w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Find piece of string inside array and do something if I can find it
First, you probably want $(this).text() rather than .html(), in case you have nested spans or something (though you shouldn't). But that shouldn't cause the problem you're getting. You must have a difference in the html between the two examples or something.

Categories : Javascript

How to do a find iterating in a array field
You can do a bit more logic to efficiently grab the users as a batch using the $in operator. var mongodb = require('mongodb') , MongoClient = require('mongodb').MongoClient , Server = require('mongodb').Server; MongoClient.connect('mongodb://127.0.0.1:27017/test', function (err, db) { if (err) throw err; var tvs = db.collection('tvs'); var users = db.collection('users'); var userNames = {}; var tvId = new mongodb.ObjectID("5203af83396d285ea2ecff8f"); // hard-code // find a TV tvs.findOne({ _id : tvId }, function (err, tv) { var allUserIds = []; if (tv && tv.comments) { // build a list of all user IDs used in comments // this doesn't filter duplicates right now allUserIds = tv.comments.map(

Categories : Mongodb

Passing order-dependent array into ActiveRecord's find() method
Instead of returning ids from your query you can return the views itself. @most_viewed = View.where('created_at < ?', Time.now - 1.week) .group(:person_id).order('count_person_id desc').includes(:person) Now you have the persons ordered, but you just have to access them through @most_viewed variable. @most_viewed.each do |view| # do something with view.person end Edit: If the solution above is not working for you, you can order the persons in this way Person.find([6, 1, 2]).index_by(&:id).slice(*[6, 1, 2]).values But the order is happening in ruby, not in the query.

Categories : Mysql

Find the order of numbers which will give the largest number in an array
A lexicographic sort is a good start. However, the difficulty comes in when considering that, for example, [854, 854853, 854855] needs to be sorted to [854855, 854, 854853]. One way to fix this is to define a comparator that compares concatenated versions of the numbers (i.e. comparing abc and def translates to comparing abcdef and defabc). The simplest version: // processing numbers as strings List<String> array = Arrays.asList("854", "854853", "854855"); Collections.sort(array, new Comparator<String>() { @Override public int compare(String o1, String o2) { // negative since we want biggest first return -(o1+o2).compareTo(o2+o1); } }); Test. The compare function without the overhead of actually having to concatenate the numbers, just doing the ch

Categories : Java

Android: Find a value inside an Array with a "a like" value
.contains method will check whether the object is present in the ArrayList or not. Here in your case objects are : "name=NAME","add=ADD","age=AGE", "gender=GENDER" which are of String type. So it is obvious that it returns false. For you, better practice is to create a class named Person which has attributes like name,add,age and gender. Then store the object of it in ArrayList and you can check whether object is in ArrayList of not using .contains() function. Like below : class Person{ String name; String add; int age; String gen; // All getters and setters methods will be here. } public static void main(String[] args){ Person p = new Person(); //Here you can set the properties of person using p.setXXX() methods //Now suppose you have ArrayList of Person object named

Categories : Java

Using WHERE clause to only retrieve results where array field has only ONE element inside
Use array_length(): SELECT * FROM attr_lookup WHERE array_length(target_tcode, 1) = 1;

Categories : SQL

What is the syntax for std::array as a field, and objects inside must be constructed with ctor that takes parameters?
The problem is that Bar doesn't have a default constructor, so std::array<Bar> doesn't have one either. If you add a default constructor to Bar, std::array<Bar> will have one too: #include <array> using namespace std; typedef int var1, var2; class Bar { public: Bar() {} // <--------- HERE Bar( var1 v1, var2 v2 ) { // setup Bar fields } // bar fields }; class Foo { Foo() : mArray() { } std::array<Bar, 3> mArray; };

Categories : C++

Use regex inside Array.indexof in c#.net to find the index of element
Try this : var match = Regex.Match(String.Join(String.Empty, myList.ToArray()), @"3s*-s*6"); if (match.Success) { // match.Index to get the index // match.Value to get the value }

Categories : C#

Hard to find JSON.stringify bug: Don't parse inside array
You are missing brackets for the objects. [ {12387192837: test_object_a}, {12387192838: test_object_b} ] Other than that the stringify works for me.

Categories : Arrays

mongoid update elements within array
Looks like I found the answer in a github issue discussion. The solution for me was: User.elem_match(activities: { type: "redemption" }).elem_match(activities: { uuid: uuid }).update("$set" => {"activities.$.submitted" => true })

Categories : Arrays

Mongoid returning object as array
1. Logger is your homie. I would recommend printing this wherever your logic exists so you can see exactly what array you are returning. Something like this: # your logic here @your_array = ..set logger.debug "MY ARRAY: #{@your_array}" This will give you at least a good look at what you are dealing with if you can take a look at Webrick or whatever setup you have. 2+3. Mongoid stores Documents as an array of hashes so that is what you are probably looking at (but I haven't seen the exact code). I dont believe there is anything wrong with your document definitions but I would take a better look at the [Relations Sections] of the Mongoid docs1 More specifically to question 2: take a look at the operations section.

Categories : Ruby On Rails

pushing item in mongoid array
I just found how to do a push on a mongoid array. In the API documentation they give an example (mongoid 3.x) : Model#push person.push(:aliases, "007") I'm using mongoid 4.0.0 and they changed the method definition, now we have to use the new syntax so I had to write : foo.push(aliases: "test") Problem solved so.

Categories : Ruby On Rails

Associate Array / Key Pair Array In Javascript arranged in with random order of keys.
Looks to me as if your using an object. The sorting of an object's properties is never guaranteed. I don't think internet explorer (at least the old versions) sorts the properties but chrome does by default. Your code is invalid, it should have the properties as strings if they are not numbers. And you would have to use an object a = {}; a["T1001"] ="B" a["T1005"] = "A" a["T1003"] ="C" You can either use two arrays to store your properties and the value if you want to preserve the ordering, or you cannot guarantee the ordering if you insist on using an object. Two arrays a1 = []; a2 = [] a1[0] = "T1001"; a2[0] = "B"; a1[1] = "T1005"; a2[1] = "A"; a1[2] = "T1003"; a2[2] = "C"; EDIT: Unless I guessed at what you meant wrong and that T1001, etc are variables containing numbers.

Categories : Javascript

need soting multi dimensional array based on another array displaying order
I hope this will help :) $array1 = array(name=>'JK',age=>'20',place=>'India',year=>array(marks1=>array(sub1=>50,sub3=>70,sub7=>65,sub5=>75,sub4=>35), marks2=>array(sub8=>50,sub10=>70,sub12=>75,sub9=>35,sub11=>65)); $array2 = array(name=>1,year=>2,age=>3,place=>4,sub1=>5,sub3=>6,sub4=>7,sub5=>8,sub7=>9,sub8=>10,sub9=>11,sub10=>12,sub11=>13,sub12=>14); //final array $final_array = array(); //for each value in sorting array foreach ($array2 as $key => $value) { //store result in final array $final_array[$value] = $array1[$key]; } //display array for check result var_dump($final_array);

Categories : PHP

How to update $scope.items array order in response to user re-sorting the DOM array using Angular-UI ui-sortable directive
You are Missing ng:model <ul ui:sortable ng:model="list"> <li ng:repeat="item in list" class="item">{{item}}</li> </ul> Please check below working example Demo It display the updated array <div ng:repeat="item in list">{{item}}</div> Array is updated automatically by the directive

Categories : Angularjs

iOS sort one array based on order of strings in another array
That sort order isn't something that could be easily replicated (i.e. it's not alpha, etc). Instead, you should just use that original NSArray as a guide to match data from the NSDictionary from Twitter. For example: [twitterDictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { NSInteger index = [yourLocalArray indexOfObject:obj]; if (index != NSNotFound) { // You have a match, do something. } }];

Categories : IOS

CakePHP: creating an array field that holds the count of specific values from another array
Replace those with these three: 'SUM(CASE PanelPref.panel_rating_id WHEN 3 THEN 1 ELSE 0 END) AS rated_three', 'SUM(CASE PanelPref.panel_rating_id WHEN 2 THEN 1 ELSE 0 END) AS rated_two', 'SUM(CASE PanelPref.panel_rating_id WHEN 1 THEN 1 ELSE 0 END) AS rated_one' Those items are part of the "fields" array, which correspond to the SELECT area of a generic T-SQL code block. What it looks like you want is a count of ratings for the item, and so this sum of case is the sort of hacky workaround for this.

Categories : Arrays

MongoDB - select document where all values in field array are present in a given array
Basically there are some ways to match array. There is no exact solution for your need. Considering you have documents like : { "_id" : ObjectId("51b05a712961f4704684d901"), "x" : [ 6, 7, 8, 9 ] } { "_id" : ObjectId("51b05a712961f4704684d902"), "x" : [ 7, 8, 9, 10 ] } { "_id" : ObjectId("51b05a712961f4704684d903"), "x" : [ 8, 9, 10, 11 ] } You can use query1 like: db.collection.find({x:[3,4,5,6]}) The result is exact match only for arrays like x result1: { "_id" : ObjectId("51b05a712961f4704684d8fe"), "x" : [ 3, 4, 5, 6 ] } query1 will not match : { "_id" : ObjectId("51b05a712961f4704684d8fe"), "x" : [ 3, 4, 5] } { "_id" : ObjectId("51b05a712961f4704684d8fe"), "x" : [ 3, 4, 5, 6, 7] } You can use : query2 like: db.t.find({x:{$all:[3,4]}}) result2 can be: { "_id" : ObjectI

Categories : Database

Deal array values to a single field of a structure array (in Matlab)
deal does what it is expected to do. It distributes the input arguments among the outputs, and if it has only one argument (the vector 1:2) it replicates it as many times as the number of output arguments. You were probably looking for: [b(1:2).a] = deal(1, 2); %// or simply [b.a] = deal(1, 2) In the general case, you'll probably have to create a cell array from your values (e.g using num2cell) and use a comma-separated list, for instance: C = num2cell(v); %// v stores the values [b.a] = deal(C{:});

Categories : Arrays

Sorting array numerically based on EYE_SIZE inside array's arrays
You could use usort and write your own comparison function. function cmp($a, $b) { return strcmp($a["EYE_SIZE"], $b["EYE_SIZE"]); } usort($your_array, "cmp"); or with a closure usort($your_array, function($a, $b){ return strcmp($a["EYE_SIZE"], $b["EYE_SIZE"]); });

Categories : PHP

How to make array inside array data for custom jQuery Function?
That's called an object, not an array, and you can just access it object1.object2_name.object3_name. (function($) { $.fn.myPlugin = function(data) { console.log(data); return this.each(function() { console.log(data.data_first + ' blah - ' + data.data_second.first_word); }); } })(jQuery);

Categories : Javascript

How to loop through array inside an array in handlebar with Node.js + express
You must choose between object or array interation: { outer:[{ Key1:"ID001", Key2:{ innerKey1:"Myvalue1", innerKey2:"Myvalue2" }, Key3:[ "Myvalue4", "Myvalue5" ] }] } <div> {{#each outer}} key1: {{this.Key1}} <br/> {{#each this.Key2}} {{@key}}: {{this}} {{/each}} <br/> {{#each this.Key3}} {{@index}}: {{this}} {{/each}} {{/each}} </div> outputs: key1: ID001 innerKey1: Myvalue1 innerKey2: Myvalue2 0: Myvalue4 1: Myvalue5 http://codepen.io/rafaelcastrocouto/pen/qgrFE

Categories : Node Js

Find and search for a double in an array and return its indices? Is this an array element swap method?)
A few things to fix in your first example: Right now, j < circles[0].length means that only one column is being searched: column 0. You'll want j < circles[i].length to search every column by row. if (temp == r) means you're comparing a Circle and a double. I'm not familiar with the circle class, but I believe you'll want to replace instead of Circle temp = circles[i][j] with double temp = circles[i][j].getRadius();. You want to return as soon as you find the matching Circle, so you have some things a little backwards. With my new revisions, if (temp == r) will now activate the code if you have found the correct radius. That means below that if statement, you'll want return {i, j};. That will return the current circle's (which has the correct radius) indicies. The last statement wi

Categories : Java

VB6 - Populate User Defined Type Array from Stored Procedure then Find Item in Array
If you are using ADO you can cache results by querying into a static cursor client-side Recordset and then disconnecting it. You can use Sort, Find, Filter, etc. and move through the rows as needed. You can even improve searches by building a local index within the Recordset after opening and disconnecting it by using the Field object's Optimize dynamic property. See: Optimize Property-Dynamic (ADO)

Categories : Arrays

How can I do an order by of a field inside and another object?
orderBy takes an expression which can be the name of the field as string, you need to quote the number like this: <li data-ng-repeat="question in modal.data.questions | orderBy: 'number'"> The expression can be a string: An Angular expression which evaluates to an object to order by, such as 'name' to sort by a property called 'name'. Optionally prefixed with + or - to control ascending or descending sort order (for example, +name or -name).

Categories : Angularjs

MySQL php array - find values from array that do not match query
This query returns rows that doesn't have the job id you specified but has the user_id, $query="SELECT job_id FROM table WHERE job_id NOT IN('$job_id') AND user_id='$user_id'"; if you want the job ids that doesn't have the user id then use. $query="SELECT job_id FROM table WHERE job_id IN('$job_id') AND user_id!='$user_id'";

Categories : PHP

In Javascript without jQuery, I am to find if any value in one array exists in a separate array
You need to break or return once you've found a value that matches. Otherwise, the else case overwrites isInArray if it was already true. Alternately, initialize isInArray to false, and only assign it to true in the loop. Here's how I'd do it: function isInArray(itemArray, categoryArray) { for(var z=0; z<itemArray.length; z++) { for(var y=0; y<categoryArray.length; y++) { if(itemArray[z] == categoryArray[y]) return true; } } return false; } I prefer early return in cases such as this.

Categories : Javascript

ActiveRecord find by model's array attribute containing a value (not association array)
Since Rails serializes arrays using YAML by default, it's difficult to do a "contains a value" query. If your values are unique and part of a fixed set, (e.g. a roles column with ['User', 'Admin', 'Guest']), you could do something like this: User.where("roles ilike '% - Guest %'") since that will match on the YAML of --- - User - Admin Guest . Alternatively, you could use the native array type in Postgres. In Rails 3, you would need to use the activerecord-postgres-array gem (though I don't know how well maintained this is); in Rails 4, it's supported natively. You would set up your column as such: t.string :roles_array, :array => true, :length => 30 Then you could query against it: User.where("'Guest' = ANY(roles_array)")

Categories : SQL

Nested foreach inside a while loop, array is not an array after first while
foreach($clicklist as $key => $clicklist) Is where your problem is. Do not reuse the name, change it for something such as foreach($clicklist as $key => $cl) otherwise by the end of your loop, $clicklist will be overwritten as the last element that was iterated. Edit: on a related note, avoid accessing your array without quotes, such as in $clicklist[clickdate]. This could later on turn into a bug if you ever encounter a constant that has been defined with that same name. Use $clicklist['clickdate'] instead.

Categories : PHP

2D Array inside an Array to Excel Output using Range
Answer after your edited question. Dim sheetNo As Integer sheetNo = 1 Sheets(sheetNo).Select Dim startRow As Integer Dim endRow As Integer Dim startCol As Integer Dim endCol As Integer Dim totCols As Integer Dim lastCol As Integer Dim firstCol As Integer totCols = 5 startRow = 2 endRow = 5 firstCol = 3 For curRow = startRow To endRow lastCol = firstCol For a = 1 To 3 startCol = lastCol + 1 endCol = startCol + totCols For curCol = startCol To endCol ActiveSheet.Cells(curRow, curCol).Value = a Next endCol = endCol + 1 If (a < 3) Then ActiveSheet.Cells(curRow, endCol).Value = "-" End If lastCol = endCol Next Next

Categories : Excel

retry a statement inside an array loop in php but with the next value of the array
Maybe something like: $result = ""; while ($result == "") { foreach ($proxyList as $key => $value) { if (!isUrlAvailable($key)) { $errorCounter++; } else { $result = callThisProxy($key); } } } // Now check $result, which should contain the first successful callThisProxy() // result, or nothing if none of the keys worked.

Categories : PHP

jquery ajax array inside data array
Assuming your server is expecting JSON, you need to stringify it: jQuery.ajax({ url: ajax_url, type: "POST", data: JSON.stringify({ fields: { id: id, name: name } }), contentType: "application/json; charset=utf-8" }); Make sure you include json2.js if you need this to work on old browsers. When you attempt to post without stringifying your javascript object and marking the contentType, it writes the request as URL-encoded parameters, which get all funky on complex object types. Take a look at the request body in your browser dev tools or Fiddler to see what I mean.

Categories : Jquery

access an array stored inside another array excel vba
To print the contents of arrA you'll have to iterate through it like this: For i = 1 to UBound(arrB(1)) For j = LBound(arrB(1), 2) To UBound(arrB(1), 2) Debug.Print arrB(1)(i, j) Next Next The 2nd argument of the LBound/UBound functions is used to choose the dimension that we want; in this case, we want the 2nd one because the outer For is already going through the 1st.

Categories : Excel

Array of strings of unknown size inside array
I like doing this: var multidimArray = [[],[]]; and then for all the extra arrays i want to append after that I do this: array = []; for(c = 0; c < x.length; c++){ array.push(x[c]); } multidimArray.push(array) alternatively you could just append FormData Objects to the array

Categories : Javascript

How to compare values in array to find one or more matches in another array?
In the each callback this points to a object, not to the value var products = [2, 5, 6, 7, 200]; var item_id = [2, 1, 6, 200]; $.each(item_id, function(idx, value) { if ($.inArray(value, products) !== -1) { console.log('Match Prod: ' + value); } else { console.log('Not Match: ' + value); } }); Demo: Fiddle

Categories : Jquery

CodeIgniter 2.1, PHP - find a day in array, take that day plus six more and remove the rest from the array
I think you should look at another way of doing whatever it is you want to do. But here is a solution for what you asked: $days = range(1, date('t')); $days_forward = 6; $key = array_search(date('j'), $days); if($key === FALSE) die('Date not found in array'); $days = array_slice($days, $key, $days_forward + 1); print_r($days); Output: Array ( [0] => 19 [1] => 20 [2] => 21 [3] => 22 [4] => 23 [5] => 24 [6] => 25 )

Categories : PHP

Fast way to find index of array in array of arrays
If you perform search more than one time and you don't mind to use extra memory, you can create set from you array (I'm using list here, but it's almost the same code): >>> elem = [1, 2, 3, 4] >>> elements = [[ 1, 15, 0, 0], [ 30, 10, 0, 0], [1, 2, 3, 4]] >>> index = set([tuple(x) for x in elements]) >>> True if tuple(elem) in index else False True

Categories : Python

Load a few records from database given an array of integers and keep the order as the array without loading all records to memory
You could turn it around. Make the selection of ids from your array Fetch only the records that you actually need Project the fetched records back on your id selection/order. Like this: Given I have a list of 100 album id's. Take 15 of those id's, let's say, descending order. var ids = Enumerable.Range(1, 100); var subsetOfIds = ids.OrderByDescending(i => i).Take(15); var dbresults = Albums.Where(a => subsetOfIds.Contains(a.AlbumId)).ToArray(); var results = subsetOfIds.Select(id => new { IdFromArray = id, record = dbresults.First(album => album.AlbumId == id) }).ToArray(); Now I only fetched those 15 records from the database and still have them back in the order that I want them to be.

Categories : C#

How to count the elements of an array inside an array?
The array you are showing is nested inside another array. So the outer array is of length 1, the inner array is what you want. To get it you have to first get the first element of the outer array using [0] or first testList[0].length testList.first.length I am not sure why your getHotelsList method returns a nested array, it doesn't appear to need it.

Categories : Ruby

How do I use an array variable inside an array of structures?
There's an extra * in the example you quote. The malloc is needed only because of that, in your example inputs is an array of 10 pointers to char while here name is a buffer holding 10 chars. You don't need any malloc in your code. Your structure looks like this in memory (assuming 4-bytes ints): Your student array from main looks like: As you see, fields are laid out one after another. Thus, to read the name of the first student you have to write into student[0].name (using strncpy to ensure that there's no overflow). To change the third letter of the name of the second student you'll use student[1].name[2].

Categories : C



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