How to highlight continent - jqvmap

I have to show statistics on a continent level (Europe, Asia, etc.).
How can I pass the data? I can find only samples to pass the data on a country level like:
var sample_data0 = { "de": "10000", "at": "15000", "pl": "5000" };
I would like something like:
var sample_continent-data = { "Europe": "10000", "Asia": "15000", "northamerica": "5000" };

I know this is old but here's an answer for you....
Replace the code in your jquery.vmap.world.js file with this file (make a back up of your original):
http://www.filedropper.com/jqueryvmapworld
(There's too much data to paste it here - hence the link to a file.)
This will give you a map with continents rather than countries.
Then replace the code in jquery.vmap.sampledata.js with:
var sample_data = { "AF": "152.23", "NA": "11.58", "OC": "158.97", "AS": "85.81", "EU": "1.1", "SA": "351.02" };
That should just work now (assuming you had the basic maps working) - comment if anything has gone wrong, or the linked file has disappeared.

Related

Is there a way of reading from sub arrays?

I am currently building an iOS application that stores user added products using Google Firestore. Each product that is added is concatenated into a single, user specific "products" array (as shown below - despite having separate numbers they are part of the same array but separated in the UI by Google to show each individual sub-array more clearly)
I use the following syntax to return the data from the first sub-array of the "products" field in the database
let group_array = document["product"] as? [String] ?? [""]
if (group_array.count) == 1 {
let productName1 = group_array.first ?? "No data to display :("`
self.tableViewData =
[cellData(opened: false, title: "Item 1", sectionData: [productName1])]
}
It is returned in the following format:
Product Name: 1, Listing Price: 3, A brief description: 4, Product URL: 2, Listing active until: 21/04/2021 10:22:17
However I am trying to query each of the individual sections of this sub array, so for example, I can return "Product Name: 1" instead of the whole sub-array. As let productName1 = group_array.first is used to return the first sub-array, I have tried let productName1 = group_array.first[0] to try and return the first value in this sub-array however I receive the following error:
Cannot infer contextual base in reference to member 'first'
So my question is, referring to the image from my database (at the top of my question), if I wanted to just return "Product Name: 1" from the example sub-array, is this possible and if so, how would I extract it?
I would reconsider storing the products as long strings that need to be parsed out because I suspect there are more efficient, and less error-prone, patterns. However, this pattern is how JSON works so if this is how you want to organize product data, let's go with it and solve your problem.
let productRaw = "Product Name: 1, Listing Price: 3, A brief description: 4, Product URL: 2, Listing active until: 21/04/2021 10:22:17"
First thing you can do is parse the string into an array of components:
let componentsRaw = productRaw.components(separatedBy: ", ")
The result:
["Product Name: 1", "Listing Price: 3", "A brief description: 4", "Product URL: 2", "Listing active until: 21/04/2021 10:22:17"]
Then you can search this array using substrings but for efficiency, let's translate it into a dictionary for easier access:
var product = [String: String]()
for component in componentsRaw {
let keyVal = component.components(separatedBy: ": ")
product[keyVal[0]] = keyVal[1]
}
The result:
["Listing active until": "21/04/2021 10:22:17", "A brief description": "4", "Product Name": "1", "Product URL": "2", "Listing Price": "3"]
And then simply find the product by its key:
if let productName = product["Product Name"] {
print(productName)
} else {
print("not found")
}
There are lots of caveats here. The product string must always be uniform in that commas and colons must always adhere to this strict formatting. If product names have colons and commas, this will not work. You can modify this to handle those cases but it could turn into a bowl of spaghetti pretty quickly, which is also why I suggest going with a different data pattern altogether. You can also explore other methods of translating the array into a dictionary such as with reduce or grouping but there are big-O performance warnings. But this would be a good starting point if this is the road you want to go down.
All that said, if you truly want to use this data pattern, consider adding a delimiter to the product string. For example, a custom delimiter would greatly reduce the need for handling edge cases:
let productRaw = "Product Name: 1**Listing Price: 3**A brief description: 4**Product URL: 2**Listing active until: 21/04/2021 10:22:17"
With a delimiter like **, the values can contain commas without worry. But for complete safety (and efficiency), I would add a second delimiter so that values can contain commas or colons:
let productRaw = "name$$1**price$$3**description$$4**url$$2**expy$$21/04/2021 10:22:17"
With this string, you can much more safely parse the components by ** and the value from the key by $$. And it would look something like this:
let productRaw = "name$$1**price$$3**description$$4**url$$2**expy$$21/04/2021 10:22:17"
let componentsRaw = productRaw.components(separatedBy: "**")
var product = [String: String]()
for component in componentsRaw {
let keyVal = component.components(separatedBy: "$$")
product[keyVal[0]] = keyVal[1]
}
if let productName = product["name"] {
print(productName)
} else {
print("not found")
}

Cant figure out how to go through array in Swift and find specific data

Hello I have question about arrays.
I have an array with following data, also I have corresponding Struct for SpiritRelation():
var spiritRelations = [
SpiritRelation(relationName: "Thunder Lantern", relationSpirit1: "Razor", relationSpirit2: "Lamp Genie", relationSpirit3: "", relationSpirit4: "", relationStats: "Double resist +5%, ATK +1600", relationSpiritIcons: ["razor", "genie"]),
SpiritRelation(relationName: "Illusive Fantasy", relationSpirit1: "Heavenly Maiden", relationSpirit2: "Lamp Genie", relationSpirit3: "", relationSpirit4: "", relationStats: "Excellent strike +15%, Dmg Penetration +15%, Max HP +11500", relationSpiritIcons: ["maiden", "genie"]),
SpiritRelation(relationName: "Grand Demonlord Gathering", relationSpirit1: "Sand Golem", relationSpirit2: "Lamp Genie", relationSpirit3: "", relationSpirit4: "", relationStats: "Excellency Resist +20%, Double Dmg +5%, ATK +1600", relationSpiritIcons: ["golem", "genie"])
}
array which contains data which will be selected by user:
var selectedSpiritsForRelation = [String]()
array of type String because I put there values which corresponds to image names in Assets. I need that to display images
array where I want to keep found relations and use it to display all found relationStats in UI
var foundRelations = [SpiritRelation]()
My problems is:
lets say user has selected 2 spirits for example: selectedSpiritsForRelation["golem", "genie"]
I’m able to find and save correctly found relation by
let result3 = spiritRelations.filter{$0.relationSpiritIcons == (selectedSpiritsForRelation) } // = 3rd relation in spiritRelations[]
foundRelations.append(contentsOf: result3)
but after user select another one spirit and array become: selectedSpiritsForRelation["golem", "genie", "maiden"]
same code as for result3 does not work anymore, because how I understand it tries to filter exactly combination of 3, but my expectation is that 2nd relation from spiritRelation[] will be found also
and here is my problem, I cant figure out how to correctly go through spiritRelations[] and find all relations related to selectedSpiritsForRelation[] every time user selects new spirit
You need to use allSatisfy in your filter by checking that all relationSpiritIcons elements exists in selectedSpiritsForRelation
foundRelations = spiritRelations.filter {
$0.relationSpiritIcons.allSatisfy { icon in
selectedSpiritsForRelation.contains(icon)
}
}

How to choose one data from an array without random

I want to ask about how I can select one data from the array, and choose another without using a random function?
{
no: 1,
id_pertanyaan: "9",
pertanyaan: "Alat indra yang paling peka untuk membedakan benda panas dan benda dingin adalah?",
point: "1",
pilA: "Hidung",
pilB: "Telinga",
pilC: "Kulit",
cabang: "IPA",
jawaban: "Kulit",
keterangan: "Alat indra yang paling peka untuk membedakan benda panas dan benda dingin adalah?"
},
{
no: 2,
id_pertanyaan: "11",
pertanyaan: "Zat hijau daun disebut juga dengan?",
point: "1",
pilA: "Floem",
pilB: "Klorofil",
pilC: "Xylem",
cabang: "IPA",
jawaban: "Klorofil",
keterangan: "Zat hijau daun disebut juga dengan?"
},
And this is my function
//console.log(this.state.gagec);
var item = this.state.pertanyaande[
Math.floor(Math.random() * this.state.pertanyaande.length)
];
this.setState(
{
id_pertanyaan: item.id_pertanyaan,
pertanyaan: item.pertanyaan,
point: item.point,
pilA: item.pilA,
pilB: item.pilB,
pilC: item.pilC,
jawaban: item.jawaban,
keterangan: item.keterangan,
},
() => {
this.setTimer();
}
);
The code above is I try to be able to get the array randomly, but it raises new problems because sometimes the same data appears, I want to display data from the array only one data (not all) in a way one by one, how to get the first data in my array, then I run the script again I get the second array data?
I just had to make it not random and change it to state so if id 1 is active then if the function rerun it'll get id 2 because state+1

Getting values from json array using an array of object and keys in Python

I'm a Python newbie and I'm trying to write a script to extract json keys by passing the keys dinamically, reading them from a csv.
First of all this is my first post and I'm sorry if my questions are banals and if the code is incomplete but it's just a pseudo code to understand the problem (I hope not to complicate it...)
The following partial code retrieves the values from three key (group, user and id or username) but I'd like to load the objects and key from a csv to make them dinamicals.
Input json
{
"fullname": "The Full Name",
"group": {
"user": {
"id": 1,
"username": "John Doe"
},
"location": {
"x": "1234567",
"y": "9876543"
}
},
"color": {
"code": "ffffff",
"type" : "plastic"
}
}
Python code...
...
url = urlopen(jsonFile)
data = json.loads(url.read())
id = (data["group"]["user"]["id"])
username = (data["group"]["user"]["username"])
...
File.csv loaded into an array. Each line contains one or more keys.
fullname;
group,user,id;
group,user,username;
group,location,x;
group,location,y;
color,code;
The questions are: can I use a variable containing the object or key to be extract?
And how can I specify how many keys there are in the keys array to put them into the data([ ][ ]...) using only one line?
Something like this pseudo code:
...
url = urlopen(jsonFile)
data = json.loads(url.read())
...
keys = line.split(',')
...
# using keys[] to identify the objects and keys
value = (data[keys[0]][keys[1]][keys[2]])
...
But the line value = (data[keys[0]][keys[1]][keys[2]]) should have the exact number of the keys per line read from the csv.
Or I must to make some "if" lines like these?:
...
if len(keys) == 3:
value = (data[keys[0]][keys[1]][keys[2]])
if len(keys) == 2:
value = (data[keys[0]][keys[1]])
...
Many thanks!
I'm not sure I completely understand your question, but I would suggest you to try and play with pandas. It might be as easy as this:
import pandas as pd
df = pd.read_json(<yourJsonFile>, orient='columns')
name = df.fullname[0]
group_user = df.group.user
group_location = df.group.location
color_type = df.color.type
color_code = df.color.code
(Where group_user and group_location will be python dictionaries).

"Unable to find any mappings for the given content, keyPath=null" RestKit 0.2

So I switched to using RestKit 0.2 and CoreData and I've been having a lot of trouble trying to get the mappings correct... I don't understand why. The JSON Response of my server is like this:
{
"meta":
{
"limit": 20,
"next": null,
"offset": 0,
"previous": null,
"total_count": 2
},
"objects":
[{
"creation_date": "2012-10-15T20:16:47",
"description": "",
"id": 1,
"last_modified":
"2012-10-15T20:16:47",
"order": 1,
"other_names": "",
"primary_name": "Mixing",
"production_line": "/api/rest/productionlines/1/",
"resource_uri": "/api/rest/cells/1/"
},
{
"creation_date": "2012-10-15T20:16:47",
"description": "",
"id": 2,
"last_modified": "2012-10-15T20:16:47",
"order": 2, "other_names": "",
"primary_name": "Packaging",
"production_line": "/api/rest/productionlines/1/",
"resource_uri": "/api/rest/cells/2/"
}]
}
Then in XCode I have:
RKObjectManager *objectManager = [RKObjectManager sharedManager];
[AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
NSManagedObjectModel *managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
RKManagedObjectStore *managedObjectStore = [[RKManagedObjectStore alloc] initWithManagedObjectModel:managedObjectModel];
objectManager.managedObjectStore = managedObjectStore;
RKEntityMapping *cellMapping = [RKEntityMapping mappingForEntityForName:#"Cell" inManagedObjectStore:managedObjectStore];
cellMapping.primaryKeyAttribute = #"identifier";
[cellMapping addAttributeMappingsFromDictionary:#{
#"id": #"identifier",
#"primary_name": #"primaryName",
}];
RKResponseDescriptor *responseCell = [RKResponseDescriptor responseDescriptorWithMapping:cellMapping
pathPattern:#"/api/rest/cells/?format=json"
keyPath:#"objects"
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[objectManager addResponseDescriptorsFromArray:#[responseCell, responseUser, responseCompany]];
[managedObjectStore createPersistentStoreCoordinator];
NSString *storePath = [RKApplicationDataDirectory() stringByAppendingPathComponent:#"AppDB.sqlite"];
NSString *seedPath = [[NSBundle mainBundle] pathForResource:#"SeedDatabase" ofType:#"sqlite"];
NSError *error;
NSPersistentStore *persistentStore = [managedObjectStore addSQLitePersistentStoreAtPath:storePath fromSeedDatabaseAtPath:seedPath withConfiguration:nil options:nil error:&error];
NSAssert(persistentStore, #"Failed to add persistent store with error: %#", error);
// Create the managed object contexts
[managedObjectStore createManagedObjectContexts];
// Configure a managed object cache to ensure we do not create duplicate objects
managedObjectStore.managedObjectCache = [[RKInMemoryManagedObjectCache alloc] initWithManagedObjectContext:managedObjectStore.persistentStoreManagedObjectContext];
My request is:
[[RKObjectManager sharedManager] getObjectsAtPath:#"/api/rest/cells/?format=json" parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
RKLogInfo(#"Load complete: Table should refresh...");
[[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:#"LastUpdatedAt"];
[[NSUserDefaults standardUserDefaults] synchronize];
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
RKLogError(#"Load failed with error: %#", error);
}];
And I always get the following error:
**Error Domain=org.restkit.RestKit.ErrorDomain Code=1001 "Unable to find any mappings for the given content" UserInfo=0x1102d500 {DetailedErrors=(), NSLocalizedDescription=Unable to find any mappings for the given content, keyPath=null}**
Thanks a lot!
UPDATE: I have added cellMapping.forceCollectionMapping = YES;
but still no luck :(!
UPDATE #2: Following Blake's advice, I tried to change the path and it worked! I did /api/rest/cells/ instead of /api/rest/cells/?format=json and my server returned me everything and the mapping was successful!
Now the only problem I get is the following error:
2012-11-21 14:48:49.414 App[3125:617] W restkit.object_mapping:RKMapperOperation.m:176 Collection mapping forced but mappable objects is of type '__NSCFArray' rather than NSDictionary
It sounds like the response descriptor is failing to match for the URL requested. Two ideas:
Try removing the path pattern entirely (pass in nil) and just using a key-path based match on 'cells'
Try using a path pattern of '/api/rest/cells'
The next thing I would try is using the debugger to step through the matching. Within RKObjectManager a list of candidate response mapping is built by the RKFilteredArrayOfResponseDescriptorsMatchingPath function. If your expected response mapping is not being returned in there, then the request path to path pattern is failing to evaluate.
If things look good there, the next place a mismatch could occur is in RKResponseMapperOperation within the buildResponseMappingsDictionary method. This method evaluates the response against each response descriptor. If the response is failing to match against your response descriptor, then you'll get unexpected results here.
The final place to check is within RKResponseMapperOperation. This takes the mappings from matched descriptors and applies them. The RKMapperOperation main method should contain the deserialized response you expect and the appropriate mappings on the mappingsDictionary property.
Even when the setup seems to be right, the mapping is wrong. The information your mapping is calling is nested inside the given objects, so you've to tell the mapping to look up the values inside of the objects.
RKEntityMapping *cellMapping = [RKEntityMapping mappingForEntityForName:#"Cell" inManagedObjectStore:managedObjectStore];
cellMapping.primaryKeyAttribute = #"identifier";
[cellMapping mapKeyOfNestedDictionaryToAttribute:#"objects"];
[cellMapping mapFromKeyPath:#".id" toAttribute:"identifier"];
[cellMapping mapFromKeyPath:#"primary_name" toAttribute:"primaryName"];
For more information check the RKObjectMapping Reference.

Resources