I have sqlite database with table 'data' as
uid type name value
1 abc North 10
1 abc South 0
1 abc East 0
1 abc West 0
1 abc Total 10
1 xyz Total 20
1 xyz Open 10
1 xyz Close 10
Using select query I am able to get this table data, now I need to create response object having following structure
DataModel(String type, Arraylist<Data> data)
Data(String name, String value)
expected output json will be
{"data":[{"type":"abc", "values":[{"name":"North", "value":"10"}, {"name":"South", "value":"0"}...]},
{"type":"xyz", "values":[{"name":"total", "value":"20"}, {"name":"open", "value":"10"}...]}]}
for now I tried this kotlin code in android studio & its working well 'result' Arraylist contains above table data
val dataList: ArrayList<DashboardDataModel> = ArrayList()
val typeAyyList: ArrayList<String> = ArrayList()
for(res in result){
typeAyyList.add(res.type)
}
val distinct = typeAyyList.toSet().toList()
for(type in distinct) {
val values: ArrayList<DashboardData> = ArrayList()
for (res in result) {
if (type == res.type) {
val dash=DashboardData()
dash.name=res.name
dash.value=res.value
values.add(dash)
}
}
val data = DashboardDataModel()
data.type=type
data.values=values
dataList.add(data)
}
Is there any better solution available?
Any help/suggestion please?
Related
I have a csv file that holds country names and years they won on the eurovision:
country, year
Israel, 1998
Sweden, 2012
Sweden, 2015
United Kingdom, 1997
and my csv (using tototoshi):
object CountryEurovision {
def countrEurovisionYearFile: File = new File("conf/countryEurovision.csv")
lazy val countrEurovisionYearMap: Map[String, String] = getConvertData
private def getConvertData: Map[String, String] = {
implicit object CodesFormat extends CSVFormat {
val delimiter: Char = ','
val quoteChar: Char = '"'
val escapeChar: Char = '"'
val lineTerminator: String = "\r\n"
val quoting: Quoting = QUOTE_NONNUMERIC
val treatEmptyLineAsNil: Boolean = false
}
val csvDataReader = CSVReader.open(countrEurovisionYearFile, "UTF-8")(CodesFormat)
val linesIterator = csvDataReader.iteratorWithHeaders
val convertedData = linesIterator.map {
row => row("Country") -> row("Year")
}.toMap
csvDataReader.close()
convertedData
}
}
now, since the country and year is not unique, cause a country can have several years when they won, so when I get Sweden:
CountryEurovision.countrEurovisionYearMap.get("Sweden")
I only get option res0: Option[String] = Some(2015)
which I would expect to be the list of years per country... even if it's a country of just one year I will get a list, and in case of Sweden I will get list of 2012 and 2015...
How can I change my setup for that behavior?
When you transform linesIterator.map { row => row("Country") -> row("Year") } into a Map with .toMap, for duplicated keys only the last one will be kept as it will override the previous one.
You can change this by having a unique element per key (country) by grouping values (dates) per key (before applying toMap) and modifying the value of your Map to be a List:
linesIterator
.map { row => row("Country") -> row("Year") } // List(("Sweden", 1997), ("France", 2008), ("Sweden", 2017))
.groupBy(_._1) // Map(France -> List((France,2008)), Sweden -> List((Sweden,1997), (Sweden,2017)))
.mapValues(_.map(_._2)) // Map(France -> List(2008), Sweden -> List(1997, 2017))
.toMap
which produces:
Map(France -> List(2008), Sweden -> List(1997, 2017))
This way, .get("Sweden") will return Some(List(1997, 2017)).
I am having these list of data from the database
Level 1
Level 2
Level 3
will get 100 points
will get 200 points
will get 300 points
My java code:
List ln5 = readDB(iStepNumber, status, query5);
Iterator itr5 = ln5.iterator();
while (itr5.hasNext()) {
String Levels1 = (String) itr5.next();
String LevelsDescription1 = (String) itr5.next();
String Levels2 = (String) itr5.next();
String LevelsDescription2 = (String) itr5.next();
String Levels3 = (String) itr5.next();
String LevelsDescription3 = (String) itr5.next();
}
I need to get the data as follows,
Level 1
will get 100 points
Level 2
will get 200 points
Level 3
will get 300 points
Any Suggestion Plz?
Suggestion 1 : Change the way you stock your datas. It's a strange way to do it
Suggestion 2 : If you can't change, then use a for on the list
for(int i = 0;i< ln5.size()/2;i++){
System.out.println(ln5.get(i));
System.out.println(ln5.get(i+ln5.size()/2));
}
After I load a json file with:
df = sqlContext.read().json(path);
I will get my DataFrame in Java Spark. I have for example the next DF:
id item1 item2 item3 ....
id1 0 3 4
id2 1 0 2
id3 3 3 0
...
I want to transform it in the most easy way to (probably of Object of the class Rating, id and item then to Integer by .hashCode())
id item ranking
id1 item1 0
id1 item2 3
id1 item3 4
....
id2 item1 1
id2 item2 0
id1 item1 2
...
PS Some first attempt to create the flatMap function:
void transformTracks() {
JavaRDD<Rating> = df.flatMap(new Function<Row, Rating>(){
public Rating call(Row r) {
for (String i : r) {
return Rating(1, 1, r.apply(Double.parseDouble(i)));
}
}
})
}
You have to forgive me if the syntax is slightly off - I program in Scala nowadays and it's been a while since I used Java - but something along the lines of:
DataFrame df = sqlContext.read().json(path);
String[] columnNames = df.columns;
DataFrame newDF = df.flatMap(row -> {
ArrayList list = new ArrayList<>(columnNames.length);
String id = (String)row.get(0);
for (int i = 1; i < columnNames.length, i++) {
list.add(id, columnNames[i], (int)row.get(i));
}
return list;
}).toDF("id", "item", "ranking");
in below two sql query sql1 not selecting any row, and sql2 selecting only 1 for 111#k2.com
var ids="'111#k2.com','222#k2.com','333#k2.com','444#k2.com','555#k2.com','666#k2.com'"
val sql1 = SQL("SELECT id,point,privacy FROM `pointTable` WHERE state=1 and id in ({users})").on("users" -> ids)
sql1().map { row =>
val point = if (row[Boolean]("privacy")) { row[Double]("point").toString } else { "0" }
println(write(Map("id" -> row[String]("id"), "point" -> point)))
}
val sql2 = SQL("SELECT id,point,privacy FROM `pointTable` WHERE state=1 and id in (" + ids + ")")
sql2().map { row =>
val point = if (row[Boolean]("privacy")) { row[Double]("point").toString } else { "0" }
println(write(Map("id" -> row[String]("id"), "point" -> point)))
}
in phpmyadmin when i run this query manualy it returns 6 rows then why not working perfectly here.
i am using play framework 2.2 with scala 2.1
That's not going to work. Passing users though on is going to escape the entire string, so it's going to appear as one value instead of a list. Anorm in Play 2.3 actually allows you to pass lists as parameters, but here you'll have to work around that.
val ids: List[String] = List("111#k2.com", "222#k2.com", "333#k2.com")
val indexedIds: List[(String, Int)] = ids.zipWithIndex
// Create a bunch of parameter tokens for the IN clause.. {id_0}, {id_1}, ..
val tokens: String = indexedIds.map{ case (id, index) => s"{id_${index}}" }.mkString(", ")
// Create the parameter bindings for the tokens
val parameters = indexedIds.map{ case (id, index) => (s"id_${index}" -> toParameterValue(id)) }
val sql1 = SQL(s"SELECT id,point,privacy FROM `pointTable` WHERE state=1 and id in (${tokens})")
.on(parameters: _ *)
I have two arrays: in one i inserted all the Questions ID's from my SELECT and in the other array i want insert the sames ID'S but NON repetead this time. My code in the second array don't works and i don't know why. I can't use DISTINCT in my SELECT because don't works (rows are diferents) and i don't wanna use two selects for this.
$query_slidersanswers= "SELECT A.QuestionIDFK, A.AnswerIDPK, A.AnswerValue, A.SortOrder
FROM tblquestionset AS QS
INNER JOIN tblquestion AS Q ON QS.QuestionIDFKPK = Q.QuestionIDPK
INNER JOIN tblanswer AS A ON Q.QuestionIDPK = A.QuestionIDFK
WHERE QS.QuestionSetIDPK = '0'
AND QS.OnPage = '1'
AND Q.Constructor = '".$_session['slider']."'";
$Query_Sliders= mysql_query($query_slidersanswers);
$currentQuestionID= 0;
while($row_Slider=mysql_fetch_array($Query_Sliders)){
$QuestionID=$row_Slider['QuestionIDFK'] ;
$AnswerID=$row_Slider['AnswerIDPK'] ;
$AnswerValue=$row_Slider['AnswerValue'] ;
$SortOrder=$row_Slider['SortOrder'] ;
$tableslidersqid[] = array($QuestionID);
if($QuestionID != $currentQuestionID){
//I DO THIS FOR OBTAIN other array with THE UNIQUES ID'S (non repeated)
$tableslidersREALqid[] = array($QuestionID);
$CurrentQuestionID = $QuestionID;
}
}
Suppose that your array for question id is as below
$input = array( "19", "55", "19", "55", "78" );
$result = array_unique($input);
print_r($result);
The above example will output:
Array
(
[0] => 19
[1] => 55
[4] => 78
)
array_unique($array) will detect the same values in the array and only give the first occured value, rest are skipped.
EDITED :
while($row_Slider=mysql_fetch_array($Query_Sliders)){
$QuestionID[]=$row_Slider['QuestionIDFK']; //used $QuestionID[], instead of $QuestionID
//$AnswerID=$row_Slider['AnswerIDPK'] ;
//$AnswerValue=$row_Slider['AnswerValue'] ;
//$SortOrder=$row_Slider['SortOrder'] ;
//$tableslidersqid[] = array($QuestionID);
//if($QuestionID != $currentQuestionID){
//$tableslidersREALqid[] = array($QuestionID);
//$CurrentQuestionID = $QuestionID;
//}
}
$result = array_unique($QuestionID); //make array unique here, after all the ids are in the array