w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Deserializing nested XML list in RestSharp
In your Response class, have a property public List<Project> Projects { get; set; }. This way, it will map the <projects> to your property Projects.

Categories : C#

Gson deserializing nested objects with InstanceCreator
Just add a new InstanceCreator derived class for NewsProvider like this: public class NewsProviderInstanceCreator implements InstanceCreator<NewsProvider> { private int context; public NewsProviderInstanceCreator(int context) { this.context = context; } @Override public NewsProvider createInstance(Type type) { NewsProvider np = new NewsProvider(context); return np; } } and register it into the GsonBuilder like you have already done, like this: GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(PageItem.class, new PageItemInstanceCreator(context)); gsonBuilder.registerTypeAdapter(NewsProvider.class, new NewsProviderInstanceCreator(context)); Gson gs

Categories : Java

Deserializing nested JSON objects with ServiceStack
i tried to do this for a custom session state module, and there are many edge cases you have to consider when serializing an object that you need the type data for into JSON, which by default has no notion of type. One easy way to do it is to force ServiceStack to serialize type information into the JSON by using JSConfig.includeTypeInfo = true; In your AppHost initialize method. This will tell ServiceStack to include the "__type" property into every single object it serializes to JSON, including strings and ints and basic types. This represents a lot of overhead, especially if you are in a large project that does not need type information for every single serialization. Alternatively, you will have to implement your own type system if you want it just for this one nested object Diction

Categories : C#

Properly deserializing a nested JSON feed with NSJSONSerialization?
Your videoTypes dictionary does not have any nested data. You want something like this: NSDictionary *videoTypes = [[playlistitems objectForKey:@"videos"] objectForKey:@"ds700"]; NSString *url = videoTypes[@"uri"]; NSLog(@"Val: %@", uri); If you really want to iterate over the keys of the dictionary, you can do: NSDictionary *videoTypes = [[playlistitems objectForKey:@"videos"] objectForKey:@"ds700"]; NSLog(@"String: %@", videoTypes); for (NSString *videoTypeKey in [videoTypes allKeys]) { NSLog(@"ds700 Key: %@", videoTypeKey); NSLog(@"Val : %@", videoTypesItems[videoTypeKey]); //error caused here }

Categories : IOS

Jackson incorrectly deserializing nested object's values into parent
My guess is that the problem comes from ComponentDependency not being static. As it is not declared static, it means it can only be instantiated with an existing instance of ComponentDescription. For more details, see here.

Categories : Java

Concatenate arrays from foreach loop into single variable of nested arrays
Use this: $allimagesizes[] = $imagesizes; Putting [] after the array name means to add a new element to the end of the array. Also, in the assignment to $imagesizes, you should use =, not .=. The latter is for appending to a string.

Categories : PHP

create a PHP function that works for simple arrays and nested arrays
Try this: <?php /** * Applies callback function recursively to every element of the given array. * * If the array contains inner arrays or objects, the callback is also applied * to these. * * Caution: If $arrayOfObject is an object, only public members are processed. * * @param callback $func * @param array|object $array * * @return array */ public static function array_map_recursive($func, $arrayOrObject) { $array = is_array($arrayOrObject) ? $arrayOrObject : get_object_vars($arrayOrObject); foreach ($array as $key => $val) { $array[$key] = is_array($val) || is_object($val) ? self::array_map_recursive($func, $val)

Categories : PHP

How Can I Convert Nested YAML to nested Arrays and OpenStructs in Ruby
There is the solution (https://github.com/jsuchal/hashugar) i often use. opts = Hashugar.new({:a => 1, 'b' => {:c => 2, :d => [3, 4, {:e => 5}]}}) But you also need to do: opts.b.d.last.e I do not understand how do you want to name array's getters. As Arup Rakshit sayed: give us yaml example and expected output or behavior.

Categories : Ruby

nested arrays in d3.js
After reading over your post again, I think I know what your trying to do. If you want to access the weights column with something like d3.max, you can use an accessor function. An accessor function specifies how you want to look through an item in the array. In your case, you want a function that looks at the weight field in each link in dataset.links. With the link as an input, this function is quite simple: function getWeight(link){return link.weight} We can then use this function as the accessor function to get the max of the weight fields in dataset.links, as follows: var maxWeight = d3.max(dataset.links, getWeight) This uses the general form of the d3.max command, d3.max(array [,accessorFcn]). I've set up a fiddle that does this and then alerts the max weight.

Categories : Javascript

Querying against nested arrays
$ in tags.$.tag_name should help: db.users.find({'tags.posts.post_id':'000000'}, {'tags.$.tag_name':1}) EDIT: ok, I read your update. In this case I see a solution in aggregation framework. We can try build pipeline like this: db.col.aggregate( {$match: {'tags.posts.post_id':'000000'}}, {$unwind: '$tags'}, {$match: {'tags.posts.post_id':'000000'}}, {$group: {_id:'$_id', tags: {$push: '$tags'}}} ) result will be: { "_id" : ObjectId("5209f5e4ef21a864f6f6ed54"), "tags" : [ { "tag_name" : "java", "posts" : [ { "post_id" : "000000" }, { "post_id" : "111111" } ] }, { "tag_name" : "ruby", "posts" : [

Categories : Mongodb

Arrays and nested foreach
Assuming they have matching keys for the loop: foreach( $name as $key => $value) { echo $value[$key] . $family[$key] . '<br />'; } This will go through each match for $name and print it out, and then print out the corresponding $family with it. I don't think you want to hardcode [1]. If you do, I'm a little confused and would like to see a var_dump of both $name and $family for clarification.

Categories : PHP

Using NSPredicate with nested arrays ios
here problem with array. ( ( { name = "What is the opposite of up?"; questionpicture = "101q.png"; }, { name = "What is the opposite of front?"; questionpicture = "102q.png"; } ), ( { name = "Name a common pet?"; questionpicture = "201q.png"; }, { name = "Name a common bird?"; questionpicture = "202q.png"; } ), ( { name = "List 3 rooms in your house?"; questionpicture = "301q.png"; } ) ) for working your above predicate then array must be like this, ( { name = "What is the opposite of up?";

Categories : Iphone

Nested arrays in JSON
I'm not sure what is the question, but an object like that would be this: { X : [ { id: "1", name: "Student z", }, { id: "2", name: "Student b", } ], N : [ { id: "3", name: "Student c", }, { id: "4", name: "Student a", } ] } Is that what you wanted?

Categories : PHP

Javascript nested arrays
I would suggest moving the name to the top level of the array and switching it to an associated array of strings to arrays: var recipes = { "pizza": [ "tomato", "cheese", "meat" ] } Then you can call each recipe by name and get the iterable list of ingredients.

Categories : Javascript

PHP Compare two nested arrays to get a new array
$ar1 = array(0 => array('id' => 43, 'quantity' => 4)); $ar2 = array(0 => array('id' => 43, 'quantity' => 2)); $new_array = array(); foreach($ar1 as $key => $value) { $new_array[$key] = array('id' => $value['id'], 'quantity' => ($value['quantity'] - $ar2[$key]['quantity'])); } Array ( [0] => Array ( [id] => 43 [quantity] => 2 ) )

Categories : PHP

Comparing Arrays with nested loops
The if/else is being tested for every iteration of your inner loop. I think what you're after is testing if you have a match after the inner loop has run. Something like: var getkeywords = ["John","Frank","Sarah"]; var captionarray = ["Jim","Joe","Lee","Steve","John","Michelle","Brad"]; var matchFound; for (k = 0; k < getkeywords.length; k++) { matchFound = false; for (l = 0; l < captionarray.length; l++) { if (getkeywords[k] == captionarray[l]){ matchFound = true; break; } } if(matchFound){ alert('Found > ' + getkeywords[k] + ':filter image'); }else{ alert('not found > ' + getkeywords[k] + ':filter image'); } }

Categories : Javascript

Deserialize deep-nested arrays
It seems there's no built-in way of de-/serializing deep-nested json into anything other than JObject/JArray. So I use strings instead. I suppose one could write a converter to handle everything, however not needed in my case. public class NestedArrayConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (value.GetType() == typeof(List<string>)) { var list = (List<string>)value; writer.WriteStartArray(); foreach (var str in list) writer.WriteRawValue(str); writer.WriteEndArray(); } else { writer.WriteValue(value); } } public override object ReadJson(JsonReader reader,

Categories : C#

Looping through nested arrays in Javascript
This is simply a question of mapping your data to the desired format: var final = response.data.map(function(item) { return [item.number, item.calls]; }); console.log(final); Here is a demo: http://jsfiddle.net/c8UQg/ EDIT: I didn't realise you were looking for a string representation (I thought you wanted an array). If that is the case, please disregard the above.

Categories : Javascript

Nested float arrays in Python
Use list.extend not list.append: The difference between extend and append is that append appends the object passed to it as it is. While extend expects that item passed to it to be an iterable(list, tuple,string, etc) and appends it's items to the list. Using append we can append any type of object; i.e iterable or non-iterable. >>> lis = [1,2,3] >>> lis.append(4) #non-iterable >>> lis.append('foo') #iterable >>> lis [1, 2, 3, 4, 'foo'] But extend behaves differently and actually appends the individual items from the iterable to the list. >>> lis = [1,2,3] >>> lis.extend('foo') #string is an iterable in python >>> lis [1, 2, 3, 'f', 'o', 'o'] #extend appends individual characters to the list >>>

Categories : Python

How do I use a nested arrays to draw a grid?
You're selecting the same <rect> elements in both the father and the mother cases. Since you aren't providing a key function in the data bind the key defaults to array index, which will be the same for both the mother and father array. Same nodes plus same bind key means you're updating the father nodes with mother data (and the enter() selection will be empty). If you add a "father" class to the father nodes and a "mother" class to the mother nodes, you can keep them separate in your selection. For example: var motherrects = svg.selectAll("rect.mother") .data(mother) .enter() .append("rect") .attr("class", "mother"); Another option is to pass a key function into the data call, but this will involve modifying your data so it contains something you can use a

Categories : D3 Js

Nested Arrays in Mongoose with ObjectId
I think your problem stems from your schema. You should try to define a schema in which the keys are not dynamically changing. MongoDB does not support queries on the keys of documents, just the values. I think that using a dynamic "ObjectID" as the key in your schema above is leading to weirdness with Mongoose, and causing your issue. But, even if your query were propagated properly to MongoDB, it would still not produce the output you desire. The reason for this is that MongoDB will interpret "postID" as a String, regardless of whether you've defined some postID variable to hold a dynamic value. This is the output if you run the query from the mongo shell, using a variable postID: > var postID = 1234 > db.users.update( {twitterID : 102016704}, {$push : {votedPosts : {postID

Categories : Javascript

How to Predicate through Nested Arrays with Keys
"artist" is an array, therefore you have to use "ANY" in the predicate: [NSPredicate predicateWithFormat:@"ANY %K.%K CONTAINS[c] %@", @"artist",@"name",searchText]; Note that instead of building the "union" of the search results manually, you can use a "compound predicate": NSPredicate *predicate = [NSCompoundPredicate orPredicateWithSubpredicates: @[predicateEventsByName, predicateEventsByArtistName]]; self.filteredEventsArray = [self.eventsArray filteredArrayUsingPredicate:predicate];

Categories : IOS

How to set and get nested arrays in a PHP registry class
The array could be defined as public: public static $vars; And then you will be able to access directly: ClassName::$vars['a']['b'] = 'somevalue'; $myvalue = ClassName::$vars['a']['b'];

Categories : PHP

JSON PHP cant navigate through nested arrays
The false is being treated as a boolean and not a string when you read in the value. PHP shows nothing when you try to echo out a boolean false (e.g. try a print false;). You could also verify this further by comparing the print_r output to var_dump output, e.g.: Interactive shell php > var_dump(false); bool(false) php > print_r(false); php > See this question for a possible solution: How to Convert Boolean to String The basic overview is that you need to test the value, then output a string.

Categories : PHP

Removing duplicate nested arrays
Closing, there was no duplicity, the to and from fields are not the same. The solution I came up with was removing and re-adding message attributes, which took those fields out of the programs logic, then re attaching them further down the line by matching up removed hashes to the current keys. Cheers, hope this helps someone. protected $patterns = array( '/((?=_).*?)@.*/', // replacing all @'s with leading underscore '/_+/i', // replacing first occurrence of underscore with @ '/.*//i', // Group chat modifier to multiple people, same from ); protected $replace = array( '$1', // replace with look back '@', // replace with (at) '', // replace with bl

Categories : PHP

How to create nested arrays? Javascript
Just change items.push.apply(items, item) to items.push(item). When you use apply like that you are effectively doing the same thing as Array.prototype.concat.

Categories : Javascript

Laravel 4 Validation - Nested Indexed Arrays?
At this time, the Validator class isn't meant to iterate over array data. While it can traverse through a nested array to find a specific value, it expects that value to be a single (typically string) value. The way I see it, you have a few options: 1: Create rules with the array key in the field name. Basically essentially what you're doing already, except you'd need to figure out exactly how many values your ['stuff']['item'] array has. I did something like this with good results: $data = [ 'stuff' => [ 'item' => [ ['title' => 'flying_lotus'], ['title' => 'various_cheeses'], ['title' => ''], ['title' => 'welsh_cats'], ] ] ]; $rules = []; for ($i = 0, $c = count($data['stuff']['item']); $i <

Categories : PHP

ElasticSearch: Searching fields in nested arrays
Nested fields should be searched using nested query: echo "Deleting old ElasticSearch index..." curl -XDELETE 'localhost:9200/arrtest' echo echo "Creating new ElasticSearch index..." curl -XPUT 'localhost:9200/arrtest/?pretty=1' -d '{ "mappings" : { "cust2" : { "properties" : { "firstName" : { "type" : "string", "analyzer" : "string_lowercase" }, "lastName" : { "type" : "string", "analyzer" : "string_lowercase" }, "paymentInfos": { "properties": { "billingZip": { "type": "string", "analyzer": "string_lowercase" }, "paypalEmail": {

Categories : Elasticsearch

Php regex returning repeats in nested arrays
Use get_included_files(), or the built-in tokenizer if the script is not included I'm searching through a string of another files contents and not the current file Then your best bet is the tokenizer. Try this: $scriptPath = '/full/path/to/your/script.php'; $tokens = token_get_all(file_get_contents($scriptPath)); $matches = array(); $incMode = null; foreach($tokens as $token){ // ";" should end include stm. if($incMode && ($token === ';')){ $matches[] = $incMode; $incMode = array(); } // keep track of the code if inside include statement if($incMode){ $incMode[1] .= is_array($token) ? $token[1] : $token; continue; } if(!is_array($token)) continue; // start of include stm. if(in_array($token[0], array(T_INCLUDE, T_INCLUDE_ONCE, T

Categories : PHP

PHP - How to modify deeply nested associative arrays?
If you want to pass something by reference use =& like this: $rootSection = array(); $currentSection =& $rootSection; $currentSection['foo'] = 'bar'; print_r($rootSection); // Outputs: Array ( [foo] => bar ) I've also seen the syntax like this $currentSection = &$rootSection; but they're functionally the same.

Categories : PHP

Convert a nested array to plain Arrays
Like this?: var arr = [["a", "b"],[1],[5,6]]; var convert2PlainArray = function(array){ var totalLength = 1, plainArray = []; for(var i=0;i<array.length; i++){ totalLength*=array[i].length; } for(var i=0;i<array.length; i++){ var currentElementLength = totalLength/array[i].length, tempArray = []; for(var e=0;e<array[i].length; e++){ for(var l=0;l<currentElementLength; l++)tempArray.push(array[i][e]); } plainArray.push(tempArray); } return plainArray; } alert(JSON.stringify(convert2PlainArray(arr))); Test it on fiddle: http://jsfiddle.net/GMJzW/

Categories : Javascript

How are Java Nested Arrays implemented in memory?
In a word references. Arrays themselves are likely to be contiguous blocks, but it's unlikely that the Objects the elements refer to are. This article sums it up nicely http://java.dzone.com/articles/what-does-java-array-look

Categories : Java

Android - GenericJson with nested info and arrays
The object that your are serializing/deserializing is a ParameterizedType (i.e. contains at least one type parameter and may be an array) then you must use the toJson(Object, Type) or fromJson(String, Type) method. Here is an example for serializing and deserialing a ParameterizedType: Type listType = new TypeToken<LinkedList>() {}.getType(); List target = new LinkedList(); target.add("blah"); Gson gson = new Gson(); String json = gson.toJson(target, listType); List target2 = gson.fromJson(json, listType); Knowing that Type typeOfCollectionOfFoo = new TypeToken<Collection<Foo>>(){}.getType()

Categories : Java

working with nested arrays hashes ruby
Restaurant[:waiters].reject!{|h| h[:name] == "Jack"} Restaurant # => { :name=>"McDonalds", :location=>"NYC", :chefs=>[{:name=>"Sunny", :food=>"fries"}, {:name=>"Brooklyn", :food=>"burgers"}, {:name=>"Mac", :food=>"burgers"}], :waiters=>[{:name=>"Jess", :role=>"senior manager"}, {:name=>"Sam", :role=>"manager"}, {:name=>"Mary", :role=>"server"}] } Restaurant[:waiters].select{|h| h[:role] == "server"} # => [{:name=>"Mary", :role=>"server"}]

Categories : Ruby

Optimizing logical operations on nested numpy arrays
I can think of two broad approaches, either pad your arrays so that you can a single 2d array instead of nested arrays, or treat your nested arrays as a list of arrays. The first would look something like this: import numpy as np a = np.array([1,2,3]) b = np.array([4,5, -99]) c = np.array([a, b]) print c.shape # (2, 3) print c > 0 # [[ True True True] # [ True True False]] Or do something like: import numpy as np a = np.array([1,2,3]) b = np.array([4,5]) c = np.array([a, b]) out = [i > 0 for i in c] print out # [array([ True, True, True], dtype=bool), array([ True, True], dtype=bool)] If padding is not an option, you might in fact find that lists of arrays are better behaved than arrays of arrays.

Categories : Python

C language: Referencing char arrays in nested struct
pkeys->uk[i] is a struct KEY, not a pointer. You are passing the entire struct by value into printf, which probably tried to interpret it as a pointer (with bad results). Try printf("key=%s ", pkeys->uk[i].k); to pass a pointer to the contained char array.

Categories : C

Computed observables in nested arrays with mapping plugin
I think you are trying to get the length of questions before it has been fully instantiated - can you try to change your computed to the following - model.numberOfQuestions = ko.computed(function () { if (!self.questions()) {return 0;} return self.questions().length; // error: self.questions() is not a function }); but also it looks like you may have some scope issues - function formViewModel(data) { var self = this; self.mapping = { // do stuff }; } Check out this answer for more info on properly establishing scope in a nested map. I bet if you console.log(self) before your self.questions().length it isn't what you are looking for, or it isn't yet at least. Map JSON data to Knockout observableArray with specific view model type

Categories : Knockout Js

how to read values from JSON nested in multiple arrays
use the following code: for(var i = 0; i < listEditions.length; i++) { var arrayItem=item.listEditions[i].listInsertion; //get colorType value alert(arrayItem[0].colorType); //get color value alert(arrayItem[0].color) } i think it will meet your demand.you can see the example:http://jsfiddle.net/rayhan/x2H5W/

Categories : Java

Need to validate nested json arrays in play 2.1 in scala
First of all, ensure you are using the latest Play 2.1.1 releases. There was an issue with earlier versions when validating case classes with a single field. After that, it should all work - please see below for an example: object JsonTest { case class SecondStructure(index: Int) case class EntryStructure(field1: String, muSecondJsonArray: List[SecondStructure]) case class MyJsonArray(allEntries: List[EntryStructure]) // Use the macro "inception" feature to automatically build your Readers. implicit val ssReads = Json.reads[SecondStructure] implicit val esReads = Json.reads[EntryStructure] implicit val arrayReads = Json.reads[MyJsonArray] // Defining an example instance... val testArray = MyJsonArray( List( EntryStructure("foo", List(SecondStructure(1), Sec

Categories : Scala

Consolidate nested arrays and erase the subarrays that have been consolidated?
It looks like after ary.delete_at(i) the size of array is decreased by one, hence i is better than i+1: # ary.delete_at(i+1) ary.delete_at(i)

Categories : Ruby



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.