Realm. Get subset of inner element based on outer one - realm

There is a structure:
{ "groups": [
{ "gid" : 1,
"elements" : [
{ "eid" : 1 },
{ "eid" : 2 }
]
},
{ "gid" : 2,
"elements" : [
{ "eid" : 11 },
{ "eid" : 22 }
]
}
{ "gid" : 3,
"elements" : [
{ "eid" : 21 },
{ "eid" : 32 }
]
}
]
}
I understand how to get all groups:
RealmResults<Group> all = realm.where(Group.class).findAll();
Also I could get all elements or all elements in a group.
But how could I query all element from groups that have id > 1?
RealmResults<Group> allFilteredGroups = realm.where(Group.class).greaterThan("gid", 1).findAll();
Is it possible to retrive all elements from all allFilteredGroups by one query, smth like
realm.where(Element.class).equalsTo(???, allFilteredGroups).findall() ?

I'm not quite sure what you mean by "to retrieve all elements". allFilteredGroups has all the Group objects. As they are linked to the Elements objects, you can easily iterate through them:
for(Group group : allFilteredGroups) {
for(Element element : group.getElement()) {
Log.d("TEST", "eid = " + element.eid);
}
}
There is currently no easy way to flatten the last and have all the Element objects in a single RealmResults.

Related

How I can reduce the time of a for loop in Flutter?

I have a method called getNearByPlaces(), then I have for loop that iterates over each place_id, and send a request to google API, to get the name of the place_id,
so this operation takes around 15 seconds, how I can make it faster?
Future<void> getNearByPlaces(double latitude, double longitude) async {
List results = [];
List placesId = [];
List nearbyPlaces = [];
String nearbyUrl =
"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=${latitude},${longitude}&radius=500&key=${mapKey}";
var nearbyResponse =
await RequestAssistant.getRequest(Uri.parse(nearbyUrl));
if (nearbyResponse == "Failed.") {
return;
}
results = nearbyResponse["results"];
for (int i = 0; i < results.length; i++) {
placesId.add(results[i]['place_id']);
String placeDetailsUrl =
"https://maps.googleapis.com/maps/api/place/details/json?place_id=${results[i]['place_id']}&key=$mapKey";
var response =
await RequestAssistant.getRequest(Uri.parse(placeDetailsUrl));
if (response == "Failed.") {
return;
}
if (response["status"] == "OK") {
await nearbyPlaces.add(response["result"]["name"]);
}
}
print(nearbyPlaces);
await FirebaseFirestore.instance
.collection("nearbyPlaces")
.doc(uid)
.set({'nearbyPlaces': nearbyPlaces});
}
If you just use only name in the detail result, you don't need to query again by 'place_id' because I found that there are more information in 'nearbysearch' API results.
For example, icon, name, photos and so on like below.
https://developers.google.com/maps/documentation/places/web-service/search
{
"html_attributions" : [],
"next_page_token" : "CpQCAgEAAFxg8o-eU7_uKn7Yqjana-HQIx1hr5BrT4zBaEko29ANsXtp9mrqN0yrKWhf-y2PUpHRLQb1GT-mtxNcXou8TwkXhi1Jbk-ReY7oulyuvKSQrw1lgJElggGlo0d6indiH1U-tDwquw4tU_UXoQ_sj8OBo8XBUuWjuuFShqmLMP-0W59Vr6CaXdLrF8M3wFR4dUUhSf5UC4QCLaOMVP92lyh0OdtF_m_9Dt7lz-Wniod9zDrHeDsz_by570K3jL1VuDKTl_U1cJ0mzz_zDHGfOUf7VU1kVIs1WnM9SGvnm8YZURLTtMLMWx8-doGUE56Af_VfKjGDYW361OOIj9GmkyCFtaoCmTMIr5kgyeUSnB-IEhDlzujVrV6O9Mt7N4DagR6RGhT3g1viYLS4kO5YindU6dm3GIof1Q",
"results" : [
{
"geometry" : {
"location" : {
"lat" : -33.867217,
"lng" : 151.195939
}
},
"icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/cafe-71.png",
"name" : "Biaggio Cafe - Pyrmont",
"opening_hours" : {
"open_now" : true
},
"photos" : [
{
"height" : 600,
"html_attributions" : [],
"photo_reference" : "CnRnAAAAmWmj0BqA0Jorm1_vjAvx1n6c7ZNBxyY-U9x99-oNyOxvMjDlo2npJzyIq7c3EK1YyoNXdMFDcRPzwLJtBzXAwCUFDGo_RtLRGBPJTA2CoerPdC5yvT2SjfDwH4bFf5MrznB0_YWa4Y2Qo7ABtAxgeBIQv46sGBwVNJQDI36Wd3PFYBoUTlVXa0wn-zRITjGp0zLEBh8oIBE",
"width" : 900
}
],
"place_id" : "ChIJIfBAsjeuEmsRdgu9Pl1Ps48",
"price_level" : 1,
"rating" : 3.4,
"reference" : "ChIJIfBAsjeuEmsRdgu9Pl1Ps48",
"types" : [ "cafe", "bar", "restaurant", "food", "establishment" ],
"vicinity" : "48 Pirrama Rd, Pyrmont"
},
So you just iterate 'nearbysearch' result and making 'nearbyPlaces' data.
...
results = nearbyResponse["results"];
for (int i = 0; i < results.length; i++) {
placesId.add(results[i]['place_id']);
nearbyPlaces.add(results[i]['name');
}
print(nearbyPlaces);
...

jq build string from multiple levels

I have the following JSON
{
"count": 2,
"load_arg": {
"limit": 100
},
"limit": 100,
"result": [
{
"id": 1234,
"name": "Item1",
"parts_list": {
"subattributes": {
"1234": {
"chassisid": 111236,
"part_attributes": {
"subattributes": {
"134322": {
"attribute_id": 27,
"attribute_value": 3
}
}
}
},
"1235": {
"chassisid": 76,
"part_attributes": {
"subattributes": {
"192134": {
"attribute_id": 17,
"attribute_value": "steel"
}
}
}
}
}
}
},
{
"id": 4321,
"name": "Item2",
"parts_list": {
"subattributes": {
"2212": {
"chassisid": 93245,
"part_attributes": {
"subattributes": {
"76423": {
"attribute_id": 17,
"attribute_value": "plastic"
}
}
}
},
"65": {
"chassisid": 2,
"part_attributes": {
"subattributes": {
"1285": {
"attribute_id": 27,
"attribute_value": 94
}
}
}
}
}
}
}
],
"offset": 0
}
]
and I'm trying to get jq to output the following from the results array
Item1: has a cover made of steel and requires part ID 27 to be 3
Item2: has a cover made of plastic and requires part ID 27 to be 94
I know some basic jq queries but I'm strugglig with grabbing a top level value and then building a string using some specific child values. In my JSON each result could have 10's of subattributes and not all of them are the same so I'd need to search for the attribute ID 17
Effectively I'm trying to pull (pseudo code as I know it's not right)
.[].result[].name + ": has a cover made of " + .[].result[].parts_list.subattributes[].part_attributes[][] | select(.attribute_id == 17).attribute_value + " and requires part ID 27 to be " + [].result[].parts_list.subattributes[].part_attributes[][] | select(.attribute_id == 27).attribute_value
This should get you on your way:
def id2value($id): .. | objects | select(.attribute_id == $id) | .attribute_value;
.result[]
| "\(.name): has a cover made of \(.parts_list | id2value(17))"
With your input and using the -r command-line option, the above produces:
Item1: has a cover made of steel
Item2: has a cover made of plastic

R list/dataframes to JSON array of objects

I am trying to create a JSON array of objects using jsonlite in R.
The goal is a JSON like this:
{
"top":[
{
"master1": {
"item1": "value1"
}
},
{
"master2": {
"item2": "value2"
}
}
]
}
I tried list of lists and dataframes with list column but can't get the desired output.
Apart from that, converting the above with fromJSON/toJSON results in a different format:
library(jsonlite)
txt <- '{
"top":[
{
"master1": {
"item1": "value1"
}
},
{
"master2": {
"item2": "value2"
}
}]
}'
toJSON(fromJSON(txt), pretty = T)
# Output
{
"top": [
{
"master1": {
"item1": "value1"
},
"master2": {}
},
{
"master1": {},
"master2": {
"item2": "value2"
}
}
]
}
Do I need to set a parameter for this to work?
By default, the fromJSON call converts your input to a data frame, and therefore adds NA values, which result in the empty entries in your output JSON:
$top
item1 item2
1 value1 <NA>
2 <NA> value2
You need to add simplifyDataFrame = FALSE to the fromJSON call to prevent it from creating a data frame.
toJSON(fromJSON(txt, simplifyDataFrame = FALSE), pretty = T)
gives
{
"top": [
{
"master1": {
"item1": ["value1"]
}
},
{
"master2": {
"item2": ["value2"]
}
}
]
}

Updating list in dynamodb

How one can update a list in dynamodb. consider the following example
Section:"A",
Group:[{Name:"Albert",
Age:24},
{Name:"Antony",
Age:25}],
GroupName:"Ply"
Now I need to change Alberts age from 24 to 26, considering Section as my primary partition key
var params = {
TableName: "Add_list",
Key:{
Section:"A"
},
"UpdateExpression" : "#Key = :value",
"ConditionExpression":"#Key1 = :value1",
"ExpressionAttributeNames" : {
"#Key" : "Group",
"#Key1":"Group[0].Name"
},
"ExpressionAttributeValues" : {
":value" : [{Name:"Albert",Age:26}],
":value1" : "Albert"
}
};

get name of treeitem Javafx

I want to get name of each treeitem node and the parents for each, then put them in treemap, but when I run this sample code I get these result as values :
[TreeItem [ value: Function 12 ], TreeItem [ value: Function 13 ]]
[TreeItem [ value: Function 6 ]]
[TreeItem [ value: Function 15 ]]
[TreeItem [ value: Function 9 ], TreeItem [ value: Function 10 ]]
How can I get ride of extra things [TreeItem [ value: ] I just want the string like Function 12
ArrayList<String> kids = new ArrayList<>();
TreeMap<String, List<String>> parentChild = new TreeMap<>();
for (TreeTableColumn<String, ?> tt : treeTable.getColumns()) {
for (TreeItem node : root.getChildren()) {
if (!node.isLeaf()) {
parentChild.put(node.getValue().toString(),node.getChildren());
}
}
}
for(Entry<String, List<String>> ent : parentChild.entrySet())
System.out.println(ent.getValue());
What you are doing is the following:
parentChild.put(node.getValue().toString(),node.getChildren());
You are adding the node.getChildren(), which has the return value of an ObservableList<TreeItem<T>>. And you are adding this to a TreeMap with Value List. You should change your map to
TreeMap<String, List<TreeItem<String>>> myMap = new TreeMap<>();
After that you can loop through it later on with:
for(TreeItem node: root.getChildren(){
parentChild.put(node.getValue().toString(), node.getChildren());
}
for(Entry<String, List<TreeItem>> ent: parentChild.entrySet(){
for(TreeItem myItem : ent.getValue()){
System.out.println(myItem.getValue());
}
}
This should print your "Function X" strings.

Resources