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.
Related
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);
...
Am trying to do a simple if/then/else using JMESPath
For example: 'if the input is a string, return the string, else return the "value" property of the input'. An input of "abc" would return "abc". An input of {"value":"def"} would return "def"
With jq this is easy: if .|type == "string" then . else .value end
With JMESPath, I can get the type
type(#)
or the input:
#
or the value property:
value
but I have not found a way to combine them into an if-then-else. Is there any way to do this?
It is possible but not cleanly. The general form is to:
Make the value you are testing an array (wrap in square braces)
Apply the map function to map the filtered array to what value you want if true
At this point you have an array that is populated with one (true) item if the array filter passed, otherwise it is empty
Concat to that array one item (the false value)
Finally, take item at index 0 in this array - which will be the result of the condition
This should allow you to also derive possible transformations for both the false and true conditions
For example, if the test data is as so:
{
"test": 11
}
Depending on the value you can get either produce the results (using test data 11 and 2 as example):
"Yes, the value is 11 which is greater than 10"
OR
"No the value is 2 which is less than or equal to 10"
Like so:
[
map(
&join(' ', ['Yes, the value is', to_string(#), 'which is greater than 10']),
[test][? # > `10`]
),
join(' ', ['No the value is', to_string(test), ' which is less than or equal to 10'])
][] | #[0]
So to abstract a template:
[
map(
&<True Expression Here>,
[<Expression you are testing>][? # <Test Expression>]
),
<False Expression Here>)
][] | #[0]
people[?general.id !=100] || people
{
"people": [
{
"general": {
"id": 100,
"age": 20,
"other": "foo",
"name": "Bob"
},
"history": {
"first_login": "2014-01-01",
"last_login": "2014-01-02"
}
},
{
"general": {
"id": 101,
"age": 30,
"other": "bar",
"name": "Bill"
},
"history": {
"first_login": "2014-05-01",
"last_login": "2014-05-02"
}
}
]
}
if else condition works here
So it looks like the filter function on a Swift (2.x) dictionary returns a tuple array. My question is there an elegant solution to turning it back into a dictionary? Thanks in advance.
let dictionary: [String: String] = [
"key1": "value1",
"key2": "value2",
"key3": "value3"
]
let newTupleArray: [(String, String)] = dictionary.filter { (tuple: (key: String, value: String)) -> Bool in
return tuple.key != "key2"
}
let newDictionary: [String: String] = Dictionary(dictionaryLiteral: newTupleArray) // Error: cannot convert value of type '[(String, String)]' to expected argument type '[(_, _)]'
If you are looking for a more functional approach:
let result = dictionary.filter {
$0.0 != "key2"
}
.reduce([String: String]()) { (var aggregate, elem) in
aggregate[elem.0] = elem.1
return aggregate
}
reduce here is used to construct a new dictionary from the filtered tuples.
Edit: since var parameters has been deprecated in Swift 2.2, you need to create a local mutable copy of aggregate:
let result = dictionary.filter {
$0.0 != "key2"
}
.reduce([String: String]()) { aggregate, elem in
var newAggregate = aggregate
newAggregate[elem.0] = elem.1
return newAggregate
}
You can extend Dictionary so that it takes a sequence of tuples as initial values:
extension Dictionary {
public init<S: SequenceType where S.Generator.Element == (Key, Value)>(_ seq: S) {
self.init()
for (k, v) in seq { self[k] = v }
}
}
and then do
let newDictionary = Dictionary(newTupleArray)
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.
I have a record as
firstMap = [ name1:[ value1:10, value2:'name1', value3:150, value4:20 ],
name2:[ value1:10, value2:'name2', value3:150, value4:20 ] ]
I have a list where the values are name1, name2, etc.
I want to pull the list depending on the name1 as
[ name1:[ value1:10, value2:'name1', value3:150, value4:20 ]
firstMap.subMap(["name1"]), did work for me, but I have a list and by looping the list I need to pull the values
namesList.each{record ->
newMap = firstmap.subMap(record)
}
I have tried subMap([offer]), subMap(["offer"]), subMap(["offer?.stringValue()"]), subMap(['offer']), etc. But none of them work for me.
You don't need submap at all, that's only really useful when you want to grab a few keys at once or if you need the original key in the result
Try:
firstMap = [ name1:[ value1:10, value2:'name1', value3:150, value4:20 ],
name2:[ value1:10, value2:'name2', value3:150, value4:20 ] ]
def namesList = [ 'name1', 'name2' ]
namesList.each { name ->
println firstMap[ name ]
}
Or if you need a Map result with the original query key:
namesList.each { name ->
println firstMap.subMap( [ name ] )
}
Or indeed:
namesList.each { name ->
println( [ (name):firstMap[ name ] ] )
}
Would give you the same (ie: create a new map with the key name and the value of my first example)