w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Django nested for loops: Is it possible to use the result from the first loop within the definition of the second for loop?
I would say that the collection should look more like sectList = {"Id": 1, "Section": "Home", "Identifier": {"Id": 1, "Title": "Home", "Url": "home/","Id": 2, "Title": "My Account", "Url": "account/","Id": 3, "Title": "Full List", "Url": "fullList/",}} You see - "Identifier": "homeList" is not really a link to your second list. Its just a prop. name and value.

Categories : Python

Nested For Loops, inside loop not reacting
I don't fully understand what you are trying to achieve but the code you currently have will always produce values such as 01/01/20, 02/01/20, .... Your inner loop (For i = 13 To 20) loops always replacing i until it hits 20 (as x isn't being incremented). I suspect you want to re-arrange your loops to maybe something like this: For i = 13 To 20 For x = Cells(1, Columns.Count).End(xlUp).Column To 1 Step -1 If Cells(1, x).value = y Then Columns(x).EntireColumn.Insert Columns(x).EntireColumn.Insert Columns(x).EntireColumn.Insert Cells(1, x).value = "01/01/" & i Cells(1, x).NumberFormat = "mm-yy" Cells(1, x + 1).value = "02/01/" & i Cells(1, x + 1).NumberFormat = "mm-yy" Cell

Categories : Excel

finding loop invariant for two nested while loops java
You should work out the invariants of nested loops starting with the inner one: while (j != 0) { if (A[j] > A[k]) { k = j; } j--; } you can observe that A[k] >= A[x], for any (j < x) && (x <= i) At the end of the loop, j == 0, so using Hoare Tripple for the while loop you can state that at the end of the inner loop A[k] >= A[x], for any (0 < x <= i) This is another way of saying that A[k] is MAX(A[0:i]). Now you can proceed with the outer loop: since i proceeds from A.length down to zero, the invariant would be A[y] < A[x], for any (y >= i) for any (y < x <= Length(A)) Using Hoare Trippe once again, you derive that upon exiting the outer loop the array A is sorted in ascending order: A[y] < A[x], for any (y >=

Categories : Java

Trying to use a Nested For Loops w/ 2 variables, Keeping 1 the same while running through the first for loop
I'm assuming this part is the real problem: So Im trying to figure out how to use 2 for loops only (I have not learned dictionaries and above) to have the first for loop for the Towers themselves, then a second for loop for all the towers except the ones chosen in the first loop. So you want to loop over all of the towers except i, right? The easy way to do that is to loop over all of the towers, and just skip i. For example: for i in towers: for j in towers: if j == i: continue # do stuff with i and j Or, equivalently: for i in towers: for j in towers: if j != i: # do stuff with i and j

Categories : Python

With nested loops, in what order do the loop variables get incremented?
The code works from top to bottom in the order it appears. If it helps to see it a little better (I wouldn't recommend you code like this, but just shows the logic a bit better): for i := 1 to 5 do begin for j := 1 to 5 do begin x[i, j] := i + j; end; end; The logic starts from i = 1 and then counts the inner loop. So basically, you're doing this: x[1, 1] := 1 + 1; x[1, 2] := 1 + 2; ... x[1, 5] := 1 + 5; x[2, 1] := 2 + 1; .. x[5, 4] := 5 + 4; x[5, 5] := 5 + 5; Hopefully this helps you understand how for loops work in this case.

Categories : Delphi

Avoiding nested each loops when handling nested JSON data
JSON is "just" javascript object literals. You can skip the jQuery call, and just reference the objects and arrays directly after you parse it. obj.custom_sql_rule[0].something_else[0]; of course, your JSON is a bit oddly-formed. If at all possible, don't arbitrarily mix objects {} and arrays [] . Use the latter when you have lists of identical objects or primitive data, and the former when you have named properties. And once you have a valid javascript object, you can just iterate through its properties. for(var sqlProp in jsonObj) { if(jsonObj[sqlProp].error) { errorsContainer.append("<div>" + jsonObj[sqlProp].error + "</div>"); } }

Categories : Javascript

How to use nested for loops?
This needs to be done every time the outer loop is accessed: system.out.println(); this allows the *'s to be on different lines, also this code only does the top half of the triangle. In order to do the bottom half, you have to count down from tri.

Categories : Java

Nested "for" loops c++
You should initialize max to 0. int max = 0; Additionally there are two more bugs. int max ; should be declared before the for loop for i. (Otherwise max is defined to be 0 always) In the inner loop print i, not j.

Categories : C++

SQL nested loops
UPDATE QUESTIONNAIRE_QUESTIONS SET QUESTION_CODE = (QUESTION_NUMBER * 100) WHERE QUESTIONNAIRE_QUESTIONS.ID IN (SELECT DISTINCT QUESTIONNAIRE.ID FROM QUESTIONNAIRE, QUESTIONNAIRE_QUESTIONS WHERE QUESTIONNAIRE_QUESTIONS.ID = PARENT_QUESTION_ID) Not so sure about the 2nd question. Is that a typo?QUESTION_CODE.QUESTION_NUMBER*100

Categories : SQL

Nested for loops in OMP C
I can confirm, you have some data-race error. Without OpenMP: First number : 123456 Second number : 654321 Result :  08563613376 Calculation time = 0.005543371655221563 With OpenMP: First number : 123456 Second number : 654321 Result :  00000000825 Calculation time = 0.007188999978097854 And I don't solve the whole problem, but based on i saw, i have some remark. First i would say that you should specify the for variable in the for construct #pragma omp for schedule(dynamic) nowait for(int i=0;i<=aLength;i++) { a[i] = a[i] - 48; } And an example of the main error you made (every time) ... when you enter a parallel region you MUST take care of your variable. what is shared, what is private to each thread ? In your end loop, you don't use

Categories : C

Nested for loops, is there a better way?
To create a copy of an array, just do this: var newArray = oldArray.slice(0); That aside, I can't really think of any simpler way to filter out empty values, other than just not having them there in the first place.

Categories : Javascript

how to browse nested for loops
Alright, I think it is a bit hard to understand what is wrong in your code. I can't see anything obvious (maybe someone else will) but here are a couple points to help you find out what is going on: Have you tried to comment out all your functions in your last loop (with iterator p)? Is it working when you do so? You probably don't want to do any display in this big loop, you should build or draw everything then display only when finished. Refactoring this code would be a good idea, you may know what you're doing now but how about in 6 months? I'm not even mentioning the fact that someone else seeing this code will probably either give up understanding it or rewrite the whole thing himself even if the bug fix would have been one character.

Categories : C++

Is there a way I can avoid these nested loops?
Unless the trackslopes/trackconvolve procedures can be reduced to something simple, then there is no way to (non-trivially) remove the nested loops. The best way to see this is that each sub-loop depends on the values of at least one of its super-loops, so that unless the inner-most computation is such that the entire process can be simplified mathematically, it is already in its simplest form. If you just don't like looking at that many levels of nesting, you can try to flatten the 5-D space by using an array of indices instead of 5 distinct indices, and then you have to write a fairly ugly 1-D loop which checks the bounds of each of the 5 indices and then advances the index array appropriately.

Categories : Performance

how to exit nested loops
Don't cook spaghetti and extract your loops into the function: void foo(...) { while (...) { /* some code... */ while (...) { if ( /* this loop should stop */ ) break; if ( /* both loops should stop */ ) return; } /* more code... */ } } this decomposition will also yield cleaner code since instead of hundreds of lines of ugly procedural code, you will have neat functions at different levels of abstraction.

Categories : C++

Generalized nested for loops
I'm not 100% certain about what you want to achieve, but I believe what you would want here is polymorphism, namely inheritance and virtual functions (I dunno which language you are using but C++, for example, supports this). Basically, you would make Global government the base class, and all your other classes the derived classes which would inherit Global government (or each other). Through inheritance you can establish the hierarchy you want (for example, by making classes lower in the hierarchy inherit from classes higher up in the hierarchy). This page covers inheritance: http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming) Now for the iterative part: first, you declare functions/methods virtual (using the keyword virtual) in the base class (e.g. global governme

Categories : Java

Is there a better way to implement those nested loops?
first you need to merge all arrays char[] one = {'a', 'b', 'c'}; char[] two = {'1', '2', '3'}; char[] three = {'x', 'y', 'z'}; char[] four = {'m', 'n', 'o'}; char[][] a = new char[4][]; a[0] = one; a[1] = two; a[2] = three; a[3] = four; then you can print what you want with 2 for like this int[] index = new int[4]; for (int i = 0; i < Math.pow(3, 4); i++) { int current = i; for (int j = 0; j < 2; j++) { index[j] = current % 3; current /= 3; } int k=0; for (int j=index.length-1;j>=0;j--) { System.out.print(a[k][index[j]]+" "); k++; } System.out.println(); }

Categories : Java

Nested Parallel While Loops
Have you tried using a single loop with && ? while (toc(t_start) < trial_duration) && (check ~= 1) % Data Collection count = count +1; end

Categories : Multithreading

Vectorising Nested For Loops
So you want to vectorise this code: for k = 1:10 for l = 1:num L_Mid(k,l) = sum(LMat(k,1+in_point(l):out_point(l))); L_Sides(k,l) = sum(LMat(k,:))-L_Mid(k,l); end end First step, removing the outer loop: for l=1:num L_Mid(:,l)=sum(LMat(:,1+in_point(l):out_point(l)),2); % Using the dim input to sum L_Sides(:,l) = bsxfun(@minus,sum(LMat,2),L_Mid(:,l)); % Using bsxfun to subtract end Next step, L_Sides can be created with a single operation: for l=1:num L_Mid(:,l)=sum(LMat(:,1+in_point(l):out_point(l)),2); % Using the dim input to sum end L_Sides = bsxfun(@minus,sum(LMat,2),L_Mid); Since the length of in_point(l):out_point(l) is variable, there is no tidy way to vectorize this (that I know of; anyone got a good way I'd love to know!), and you c

Categories : Matlab

How do I create nested loops with LESS CSS?
Hm, nevermind—Found it myself. I’m leaving the answer here for posterity’s sake: @maxi: 8; .i-loop (@i) when (@i > 0) { @maxj: 8; .j-loop (@j) when (@j > 0) { .my-class-@{i}-@{j} { width: (100% / @i); height: (100% / @j); } .j-loop(@j - 1); } .j-loop (0) {} .j-loop(@maxj); .i-loop(@i - 1); } .i-loop (0) {} .i-loop(@maxi);

Categories : CSS

jQuery : nested loops
I don't know how the ajax returns the countries/cities objects but here is an example how you can create that select options var countries = ["United Kingdom", "France", "Spain"]; var cities = [["London", "Birmingham", "Bristol", "Leeds"], ["Paris", "Lille", "Calais"], ["Barcelona", "Real Madrid"] ]; $(countries).each(function(key, val){ $("#result").append('<optgroup label="'+val+'">'); $(cities[key]).each(function(k, v){ $("#result").append('<option>'+v+'</option>'); }); $("#result").append('</optgroup>'); }); EXAMPLE: http://jsfiddle.net/kC75w/

Categories : Jquery

Complicated nested loops
I think google have a lot of APIs to create charts... i found this one:Populating Data Using Server-Side Code PS:Im not a PHP programmer...i know a little only. I think it will help you ...

Categories : PHP

Nested loops in php mysql
It's a little confusing to understand without a printscreen of your page or something, but it sounds like you have a page that allows multiple checkboxes to be selected at the same time, yet you're only keeping the reference for a single checbox in your $_POST. If that's the case, you should be sending the questions' ID's through an array. Please take a look at this accepted answer to see how that can be done: PHP $_POST get data array

Categories : PHP

Nested Loops Ruby
For make the problem simple, I think it is better calculate all round multiples before update the pebble. pebbles = Array.new(10) 10.times do |i| # calculate all multiples for each index multiples = Array(1..10).select {|j| j % (i + 1) == 0} # observer that we must have to sub 1 since Ruby use 0 indexed arrays multiples.map! {|j| j - 1} # update each pebble multiples.each do |j| pebbles[j] = pebbles[j] == 'b' ? 'w' : 'b' end end puts "Black pebbles: #{pebbles.select {|p| p == 'b'}.size}"

Categories : Ruby

Nested for each loops in Objective-C
The way you do it, for each single iteration of the first loop the second loop iterates completely. I think it won't work with a for-in loop. But you said the number of items in the two arrays is the same - so you can easily do: for (i=0; i< feedsArray.count; i++) { NSDictionary subscription = feedsArray[i]; NSDictionary unreadCount = unreadCountsArray[i]; [RDInsertObjects insertFeedsWithSubscription: subscription unreadCount: unreadCount]; } This will only work, if the number of items in the array are always ever the same - if sometime they aren't, you need a modification to prevent an out-of-bounds error or it will crash!

Categories : IOS

Single Line Nested For Loops
The best source of information is the official Python tutorial on list comprehensions. List comprehensions are nearly the same as for loops (certainly any list comprehension can be written as a for-loop) but they are often faster than using a for loop. Look at this longer list comprehension from the tutorial (the if part filters the comprehension, only parts that pass the if statement are passed into the final part of the list comprehension (here (x,y)): >>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y] [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)] It's exactly the same as this nested for loop (and, as the tutorial says, note how the order of for and if are the same). >>> combs = [] >>> for x in [1,2,3]: ... for y in [3,1,4]: ...

Categories : Python

How can I simplify my nested for-loops with ReactiveCocoa?
You basically would like to create the cartesian product of the dictionaries and make a selection on it. There is no default operator in ReactiveCocoa that I know of that would do this for you. (In LINQ there are operators for this.) In RAC the simplest solution is to use the scanWithStart:combine: method to implement this operation. Once the cartesian is ready, the filter: and take:1 operations will produce the sequence of your choice. NSDictionary *adic = @{@"aa":@"vb", @"ab": @"va"}; NSDictionary *bdic = @{@"ba": @"va", @"bb":@"vb"};; RACSequence *aseq = adic.rac_keySequence; RACSequence *bseq = bdic.rac_keySequence; RACSequence *cartesian = [[aseq scanWithStart:nil combine:^id(id running, id next_a) { return [bseq scanWithStart:nil combine:^id(id running, id next_b) { re

Categories : Objective C

Storing output from nested for loops in r
Similar to how you create a ctr variable outside the scope of your for loop, if you want to retain the results of these loops you should create some sort of storage variable for the output you're trying to capture. If you can provide a reproducible example we can help you more. Here's a simple example: p=10 q=20 M=matrix(seq(1,p*q), p, q) output=matrix(NA, p,q) # storage matrix for(i in 1:p){ for(j in 1:q){ # do something output[i,j] = 2*i + j^2 } } As others have stated, it's likely that what you are trying to accomplish would be simplified by using the apply functions.

Categories : R

Nested loops for large datasets
Hmm. Well, first of all,this code is probably so heavily I/O bound that optimizing anything but disk access is probably inconsequential. You might try throwing a pointless loop to 1000 before every if-test just to see how much difference that makes. It doesn't appear like indexing would help you here, since you must access all the data when a value isn't specified, but if you are computing aggregates then caching those might help. Intersystem's DeepSee product is designed for that. But it sounds like maybe you are just running a big report printing all the data, and want to optimize what you can. In that case, I think your solution does that. As far as elegance, well, it usually isn't found in conjunction with heavy optimization. The problem with generalizing a solution is that it'

Categories : Misc

Variable Number of Nested For Loops
With the recursive method you would put one of your looping in a function pass the loop parameters to that function. Then from within the function's loop, it calls its to nest another loop. void loopFunction(ArrayList<ArrayList<String>> newWords, int level) { if (level == 0) { // terminating condition if (/* compare the indices by for example passing down a list with them in */) { newWords.get(...).add(...); } } else {// inductive condition for (int i = 0; i < len; i++) { loopFunction(newWords, level-1); } } } So for your example you need 3 levels of recursion so you would start the recursion with: loopFunction(newWords, 3); Edit Since you have been having trouble here is a working version. I

Categories : Java

Translation of nested for loops into Haskell
What exactly is the original code doing? Also, what is the type signature of my.read? I assume it would have a signature similar to Num b => (a, Int, Int) -> IO b, in which case this code will not even compile. If my . read is in the IO monad, then you could write it as: myfunc = do let indices = [(i, j, k) | i <- [0..rowsA], j <- [0..colsB], k <- [0..colsA]] -- Since `my . read` returns a value in the IO monad, -- we can't just multiply the values returned. r1 <- mapM ((i, j, k) -> (my . read) (a, i, k)) indices r2 <- mapM ((i, j, k) -> (my . read) (b, k, j)) indices -- We can multiply r1 and r2 together though, -- since they are values extracted from the IO monad

Categories : Haskell

How can I vectorize these nested for-loops in Matlab?
What about this: [kT, jT, iT] = ind2sub([size+1, size+1, size+1], [1:(size+1)^3]); for indx = 1:numel(iT) i = iT(indx) - 1; j = jT(indx) - 1; k = kT(indx) - 1; freqResult1(indx) = (c/2)*sqrt((i/L)^2+(j/W)^2+(k/H)^2); end On my PC, for size = 400, version with 3 loops takes 136s and this one takes 19s. For more "matlaby" way u could also even do as follows: [kT, jT, iT] = ind2sub([size+1, size+1, size+1], [1:(size+1)^3]); func = @(i, j, k) (c/2)*sqrt((i/L)^2+(j/W)^2+(k/H)^2); freqResult2 = arrayfun(func, iT-1, jT-1, kT-1); But for some reason, this is slower then the above version.

Categories : Performance

How to simplify nested loops and conditions?
You could do this: for (i = 0; i < data.length; i++) { if (chars.indexOf(data[i].item) != -1) { // Do something } else { // Do something else } } However, if chars is large, I would create an object whose keys are the elements of chars and use if (chars_obj[data[i].item]). This is more efficient than searching an array every time.

Categories : Javascript

Update database with nested for loops?
Don't use $x in for($x = 0; $x < sizeof($answer); $x++){ **$x** = sprintf("UPDATE exam_answers SET answer_description = '%s' WHERE answer_question_set_id = '%s'", mysql_real_escape_string($answer[$x]), mysql_real_escape_string($answerid[$x])); mysql_query($x)or die(mysql_error()); } Instead use another variable of your choice. this will complicate to your loop.

Categories : PHP

Possibilities and nested foreach loops C#
Try a recursive method. A small example : public List<Table> assignToTable(List<Person> invited, List<Table> tables) { if(!tables.HasRoom) return tables; else { assign(tables,invited) //code to add a person to a table assignToTable(invited, tables); } } If I were you I'll create a object taht represent you tables with a propertie to know if there is still some room avaiblable. This will assign to every people a table without any foreach. Then in you main you could have a method that will rearrange the tables in all the way possible : Table 1 Table 2 Table 3 Then Table 1 Table 3 Table 2 ... Table 3 Table 2 Table 1 and call the recursive method on those lists and you will have all the possibility where poeple can sit...

Categories : C#

Nested loops and array formation
You don't need a complicated code .. Just loop and use array_shift Example: print_r(cleanUp($array_1)); Function function cleanUp($array) { array_shift($array); foreach($array as $k => $var) { is_array($var) && array_shift($array[$k]); } return $array; } See Live DEMO

Categories : PHP

Cuda reduction in nested for loops
I changed the code a litte. __global__ void calcBackProjection(cuFloatComplex* fftData, cuFloatComplex* grid_magnitude, float* distance, int gridSize, int numberOfAngles, float rangeBin, int NFFT){ int gridPointIdx = threadIdx.x + blockIdx.x*blockDim.x; while(gridPointIdx < gridSize){ for(int angleIdx = 0; angleIdx < numberOfAngles; angleIdx++){ float curDistance = distance[gridPointIdx + angleIdx*gridSize]; int wantedIdx = ceil(curDistance / rangeBin) - 1; if(wantedIdx){ int fftIdx = wantedIdx + angleIdx*NFFT; int gridIdx= gridPointIdx + angleIdx*gridSize; if((fftIdx < NFFT*numberOfAngles) && (gridIdx < gridSize*numberOfAngles)){ grid_magnitude[gridIdx] = cuCaddf(

Categories : C++

How/should I use nested for loops inside of if statements?
It is difficult to tell the precise situation here, but this is how it sounds to me: defaults is almost certainly meant to be an instance of NSUserDefaults. The bolded "for" in your instructions is not suggesting a for-loop; it's giving you a hint at the method you need to use. Take a look at the NSUserDefaults reference there and see if you can find a method that might be useful for looking up a BOOL value for a named key.

Categories : Objective C

issue with two nested loops in bash
In the script there is a mistake which echoes a value of $mica_header which will be substituted only for make calls in the next outer loop run. This is caused by the second sed being run only after make. It should have been called before the inner loop. Could not this cause the confusion? Also instead of replacing one value of a parameter for another it is better to create a template of r.src file with placeholders for the parameters to be changed. This way we can be sure that for some values of the parameters there could not be conflicts with the search patterns and that a typo will not prevent substitution. Below is an improved script with considerably simpler code. The part inside if test "$Test" = 1 is just a testing code activated by Test=1. For this script just create a template fo

Categories : Bash

nested for loops in python with lists
Use the zip function, like this: list1=['a','b'] list2=['y','z'] for i, j in zip(list1, list2): print(i, j) Output: ('a', 'y') ('b', 'z')

Categories : Python

Mysql Selects in nested loops
This is very bad approach in the performance asppect. What is the correct way. it is actually not. A few primary key lookups will never do any harm. When I try to use the parent person's id as a parameter for the child people query, I get error about bind_param() function. First of all, you have not just mention the error message but read and comprehend it, as well as provide it here, full and uncut. Next, for this one it is quite easy to guess though. Use store_result() This can be done only one SQL query with JOIN operation. But I don't know how to do. A canonical text which even has been a part of mysql official docs once: Managing Hierarchical Data in MySQL (first result on google, btw)

Categories : PHP



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