I have difficulty processing a list a Scala:
Currently I have a list of like this
(List(JString(2437), JString(2445), JString(2428), JString(321)), CompactBuffer((4,1)))
and I would like after processing, the result will look like below:
( (2437, CompactBuffer((4,1))), (2445, CompactBuffer((4,1))), (2428, CompactBuffer((4,1))), (321, CompactBuffer((4,1))) )
Can any body help me with this issue?
Thank you very much.
Try this:
val pair = (List(JString(2437), JString(2445), JString(2428), JString(321)),
CompactBuffer((4,1)))
val result = pair._1.map((_, pair._2))
First, pair._1 gets the list from the tuple. Then, map performs the function on each element of the list. The function (_, pair._2) puts the given element from the list in a new tuple together with the second part of the pair tuple.
Related
I have spatial query for postgresql (and postgis). I use raw() function. So I have something like this:
observations = Square.objects.raw('SELECT validation_birds_square.id AS id,
validation_birds_square.identification,
Count(validation_birds_checklist.position) AS total
FROM validation_birds_square ...the rest of sql query...')
I use Square model which I defined in my models.py. Then I want serialize observations, so I make this:
return HttpResponse(serializers.serialize("json", observations), content_type='application/json')
But here is the problem. It serialize only properties of Square model, not total from sql query.
When I iterate over observations I can get that value:
for observation in observations:
print(observation.total)
Is there any better way how to put total to serialized JSON than iterate over observations and serialize it manually to JSON?
You don't have a proper queryset, so there isn't much point in using the built-in serializers. Just create a list of dicts, and use JsonResponse to return it as JSON.
data = [{'id': o.id, 'identification': o.identification, 'total': o.total} for o in observations]
return JsonResponse(data)
I have in my bucket a document containing a list of ID (childList).
I would like to query over this list and keep the result ordered like in my JSON. My query is like (using java SDK) :
String query = new StringBuilder().append("SELECT B.name, META(B).id as id ")
.append("FROM" + bucket.name() + "A ")
.append("USE KEYS $id ")
.append("JOIN" + bucket.name() + "B ON KEYS ARRAY i FOR i IN A.childList end;").toString();
This query will return rows that I will transform into my domain object and create a list like this :
n1qlQueryResult.allRows().forEach(n1qlQueryRow -> (add to return list ) ...);
The problem is the output order is important.
Any ideas?
Thank you.
here is a rough idea of a solution without N1QL, provided you always start from a single A document:
List<JsonDocument> listOfBs = bucket
.async()
.get(idOfA)
.flatMap(doc -> Observable.from(doc.content().getArray("childList")))
.concatMapEager(id -> bucket.async().get(id))
.toList()
.toBlocking().first();
You might want another map before the toList to extract the name and id, or to perform your domain object transformation even maybe...
The steps are:
use the async API
get the A document
extract the list of children and stream these ids
asynchronously fetch each child document and stream them but keeping them in original order
collect all into a List<JsonDocument>
block until the list is ready and return that List.
I'm using Postgrex in Elixir, and when it returns query results, it returns them in the following struct format:
%{columns: ["id", "email", "name"], command: :select, num_rows: 2, rows: [{1, "me#me.com", "Bobbly Long"}, {6, "email#tts.me", "Woll Smoth"}]}
It should be noted I am using Postgrex directly WITHOUT Ecto.
The columns (table headers) are returned as a collection, but the results (rows) are returned as a list of tuples. (which seems odd, as they could get very large).
I'm trying to find the best way to programmatically create JSON objects for each result in which the JSON key is the column title and the JSON value the corresponding value from the tuple.
I've tried creating maps from both, merging and then serialising to JSON objects but it seems there should be an easier/better way of doing this.
Has anyone dealt with this before? What is the best way of creating a JSON object from a separate collection and tuple?
Something like this should work:
result = Postgrex.query!(...)
Enum.map(result.rows, fn row ->
Enum.zip(result.columns, Tuple.to_list(row))
|> Enum.into(%{})
|> JSON.encode
end)
This will result in a list of json objects where each row in the resultset is a json object.
I have two arrays, array1 and array2. I need to compare both of these arrays and I want to create a third array, array3, whereby it shows the elements that are in array2, that are not in array1.
This is what I have so far:
my_buckets = Model.select("DISTINCT bucket").where(["my_id = ?", params[:user]])
all_buckets = Model.select("DISTINCT bucket").collect { |x| x.bucket }.uniq.compact
buckets_not_in_my_buckets = Model.select("DISTINCT bucket").where(["bucket NOT IN (?)", my_buckets]).collect { |x| x.bucket }.uniq.compact
For some reason, the buckets_not_in_my_buckets is always returning an empty array ([]). Is there a better way to approach this? Any help would be appreciated.
buckets_not_in_my_buckets = all_buckets - my_buckets
I'm assuming that you have the eql? operator on your buckets object working how you'd like.
Please see the Array docs for more detail.
I have a json string: {"jsonrpc":"2.0","result":[{"event":{"id":"27151641","name":"TSW Pegasus FC (Res) v Sun Hei SC (Res)","countryCode":"HK","timezone":"GMT","openDate":"2014-02-19T12:30:00.000Z"},"marketCount":14},{"event":{"id ":"27151646","name":"Humble Lions v Boys Town FC... etc etc
So the result bit is a list of event/marketcount pairs. I've used the parse method in a class module called jsonlib which I got from http://code.google.com/p/vba-json/issues/attachmentText?id=15&aid=150001000&name=jsonlib.cls&token=31ObtlGBtaGXd2KR0QLyffX_x8Y:1359742317106
This creates an object (jason_obj) which represents the result bit above. Now I want to get a list of ids for each event. I can use the for each ... construct to return each event/marketcount pair as an object, but I can't work out how to get to the id field that is somewhere in the event object. I tried to use the tostring method to get a clue, and from that this code should work but it doesn't:
For Each eventItem In jason_obj
this_eventx = eventItem("event")
this_id = this_eventx("id")
Next
Don't know much about accessing objects/collections. Can anyone help? Thanks
Objects need to be set and references should use item:
For Each eventItem In jason_obj
set this_eventx = eventItem.item("event")
this_id = this_eventx.item("id")
Next
HTH
Yes it did