Menu
  • HOME
  • TAGS

Javascript: Forloop Difference between i++ and (i+1)

javascript,loops,for-loop

The i++ is using post increment, so the value of the expression i++ is what the value was in the variable i before the increment. This code: if(sortedLetters[i] !== sortedLetters[i++]) return true; does the same thing as: if(sortedLetters[i] !== sortedLetters[i]) return true; i = i + 1; As x !==...

How to create an item list to use multiple times on a Jinja2 template page?

python,python-3.x,for-loop,flask,jinja2

As pointed out by Peter Wood in the comments, points is a generator: You need to turn it into a list: list(graph.find()) Thanks!...

Continuous to discrete cut quartile in R from for loop

r,loops,for-loop,cut,quartile

This question is more about being organized and neat with your data. There are many ways to do this. I would recommend separating out the data you want to bin into its own data.frame. x=dataset[, 50:60] then bin those columns into new columns by making a function with the parameters...

Create an object that contains an array of objects with a for loop

javascript,for-loop

This will create an array of 100 objects with id values from 1 to 100. If id needs to be calculated or pulled from somewhere, let me know and I'll update the answer. var data = { line_items_object: [] }; for (var i = 1; i <= 100; i++) data.line_items_object.push({id:...

How to remove all Objects in For Loop?

actionscript-3,for-loop,flash-cs6

Store the stars in an array when you add it. So you can refer to them later. The destroyStar-function is not best practice, because the star itself should not have the rights to change something in your main-displaylist. Better remove it directly in Main. Main public var numStars:int = 4;...

NSMutableArray adds same NSDictionary multiple times

ios,objective-c,for-loop,nsarray,nsdictionary

You need to alloc and init the array each time, so that there is new memory for it and then it wont add the same array 8 times

c# nested if/else in a for loop

c#,if-statement,for-loop

The keyword you are looking for is break; break will stop the execution of the loop it is inside. If you are inside nested loops it will only work on the innermost. The opposite of this is continue. Continue stops that iteration and moves onto the next. Here is an...

Using function “cat” with “replicate” in R

r,for-loop,cat,replicate

As an alternative, you could use sapply instead of replicate: Data <- rnorm(20,20,3) N <- 1000 f <- function(i) { Data.boot <- sample(Data, replace=TRUE) cat("\r", i, "of", N) mean(Data.boot) } outcome <- sapply(1:N, f) or alternatively, using plyr, you could use raply with the progress option (if your main purpose...

R Creating a Character Column from a Numeric Column w/o using For Loop

r,for-loop,mapping,character,lookup

I am not really sure what you are trying to do, but just looking at your last example it looks like you are trying to do something like this: set.seed(123) # good practice for reproducible answer joe <- data.frame( V1 = sample.int(5,10,replace=TRUE) ) # simpler way joe$V2 <- LETTERS[joe$V1] joe...

How to push row of two-dimensional array to object

javascript,arrays,for-loop

You can use .map, var myArray = [ [47,22,11], [28,5,1], [22,11,11] ]; var myStructure = myArray.map(function (el) { return { Pass: el[0], Warning: el[1], Fail: el[2], } }); console.log(myStructure); ...

How to dynamically name my object params in this lodash loop?

javascript,loops,for-loop,lodash

You're referring to params.term as an existing array, which is why you're getting an error. Try this instead... params["term" + index] = .... That will create a property for each index instead. You can either access it with params["term1"] or... params.term1 ...

Using for loop indices in variable generation SAS

for-loop,sas

A simple macro would do: %macro monthly_table( year, month); proc sql; create table as try_&year.&month. as select t1.var1 as var&year.&month. from t1 left join .... on... where t1.var&year.&month. is not missing; quit; %mend monthlytable; %macro reporting( year,month); %do month =1 to &month; %monthly_table( &year, &month) end; %mend reporting; In case...

Matlab: For loop with window array

arrays,matlab,math,for-loop,while-loop

In the meanSum line, you should write A(k:k+2^n-1) You want to access the elements ranging from k to k+2^n-1. Therefore you have to provide the range to the selection operation. A few suggestions: Use a search engine or a knowlegde base to gather information on the error message you received....

Loop throught list in R [on hold]

r,for-loop

Here is an answer to part 1. With R, there are usually multiple ways of accomplishing the same task. When I first started, I was lost. But by working through and struggling with the hw, I learned so much. lst <- list() for(i in 1:10) lst[[i]] <- sample(100,i^2) lst A...

Can not figure out how to print second dimension in three dimension List

c#,list,for-loop,dimensions

It looks like you're building 2 lists. The first one is 3d and the other is 2d. I would split it up like this: List<string> stuff1 = new List<string>(); List<string> stuff2 = new List<string>(); List<string> stuff3 = new List<string>(); List<string> otherStuff = new List<string>(); stuff1.Add("a1"); stuff1.Add("a2"); stuff1.Add("a3"); stuff1.Add("a4"); stuff2.Add("b1"); stuff2.Add("b2");...

Why cant I refer to a random index in my 4D list, while I know it exists?

c#,list,for-loop,dimensions

Based on your code where you're filling your 4D list: List<string> Lijst1D = new List<string>(); Lijst2D.Add(Lijst1D); Here you're creating new List<string> and adding it to parent 2D list. But Lijst1D itself doesn't contains any elements (you haven't added anything to it), so Lijst4D[0] will throw that IndexOutOfRangeException as well as...

Array stored in array gets overwritten to the contents of the last one added

java,arrays,for-loop

You are adding the same array object dieThrown to the array thrown multiple times. Each iteration through the d for loop, you are overwriting the values in the same array, so the last iteration's values are the ones that remain. The thrown array is full of references to the same...

Batch For Do Test if exist rename url link on desktop

batch-file,for-loop

I know you are looking for help with your batch file, but I wanted to show the equivalent powershell solution. $files = Resolve-Path "C:\Users\*\Desktop\My Link With Spaces.url" $newName = "My NEW Link With Spaces.url" foreach($file in $files) { $destination = Join-Path (Split-Path $file -Parent) $newName Move-Item -Source $file -Destination $destination...

iteration (for-loop) ms Access with past value

vba,for-loop,access-vba,iteration,recordset

Following our discussion in Comments, I have updated your complete code to what it should be. Again, I don't have an Access database handy to test it but it compiles and should work: Sub vardaily() Dim db As Database Dim rs As DAO.Recordset, i As Integer, strsql As String Dim...

Matlab loop not working properly

matlab,loops,for-loop

You are not testing if largest is truly the largest with that code. As you go through the loops it is possible that a smaller palindrome will be detected after a larger one, and you are reassigning largest to it. Try this with an added test for whether a new...

php for loop of an array

php,html,arrays,for-loop

Assuming you have properly named the input values, e.g.: <input name="topay[0]" type="checkbox"> <input name="loadnum[0]" value="5"> <input name="unit[0]" value="101"> <input name="driver[0]" value="joe"> <input name="topay[1]" type="checkbox"> <input name="loadnum[1]" value="6"> <input name="unit[1]" value="103"> <input name="driver[1]" value="mike"> Take note of the topay[0] and topay[1] notation that I'm using, as opposed to your form input...

Count neighboring cells

java,function,for-loop

Your upper limit in your for statements should by checking for <= not just less-than. By testing for less-than you stop before getting to x+1 or y+1. It should look like this: for (int i = Math.max(0, x - 1); i <= Math.min(grid.getWidth()-1, x + 1); i++) { for (int...

Matlab: Writing to a file

arrays,matlab,loops,math,for-loop

If you want to get the matrices to be displayed in each column, that's going to be ugly. If I'm interpreting your request correctly, you are concatenating row vectors so that they appear as a single row. That's gonna look pretty bad. What I would suggest you do is split...

Can javascript for loop starts from negative number? [closed]

javascript,jquery,loops,for-loop

Yes, it's possible, and it works fine. for (i=-5; i<=5; i++) { ... } is the same thing as i=-5; while (i<=5) { ... } continue { i++ } The point is that any expression is allowed inside the for's first part....

Python For Loop Using Math Operators

python,for-loop

Just as a loop is introduced by for, does not imply the same behaviour for different languages. Python's for loop iterates over objects. Something like the C-for loop does not exist. The C for loop (for ( <init> ; <cond> ; <update> ) <statement>, however, is actually identical to the...

Matlab Calculating mean of distribution quantile in a for-loop

matlab,loops,for-loop,distribution,quantile

Your test variable is a three-dimensional variable, so when you do test2 = test(:,1); and then test2(:) <VaR_Calib_EVT/100 it's not the same as in your second example when you do test(:,i)<(VaR_Calib_EVT(:,i)/100) To replicate the results of your first example you could explicitly do the test2 assignment inside the loop, which...

printing an string in cross manner using c program

c,arrays,loops,for-loop,multidimensional-array

In your code, you need to change the for loop condition checking expressions, like i == lenstr and later i==0. They are not entering the loop, essentially. Instead, you can replace the whole block for(i = 0;i == lenstr;i++) { str2[i][j] = str[i]; j = j + 1; } for(i...

Java for loop only executing once

java,for-loop

The underlying problem has been identified in another answer. This answer is about avoiding the confusion that prevented the OP from seeing which loop was not executing, and therefore failing to find the bug. When an inner loop is the entire body of an outer loop, it can be unclear...

Refering to Integer inside String? Python

python,for-loop

The way I would do it is as follows. total_bugs = 0 #assuming you can't get half bugs, so we don't need a float for day in xrange(1, 8): #you don't need to declare day outside of the loop, it's declarable in the for loop itself, though can't be refernced...

Create a Triangular Matrix from a Vector performing sequential operations

r,for-loop,matrix,vector,conditional

Using sapply and ifelse : sapply(head(vv[vv>0],-1),function(y)ifelse(vv-y>0,vv-y,NA)) You loop over the positive values (you should also remove the last element), then you extract each value from the original vector. I used ifelse to replace negative values. # [,1] [,2] [,3] [,4] [,5] # [1,] NA NA NA NA NA # [2,]...

Javascript For Loop with Iterator In the Middle and Decrement Operator to the Left of i?

javascript,for-loop,syntax,decrement

In js, 0 means false, and the other values like 1 are true. why is the iteration statement in the middle for(var i = x; --i; /* optional */ ) ^^ its decrement as well as the condition loop continues until, i is 0 In fact, you can create infinite...

Display text once within for loop on the first loop

php,for-loop

Use it as below <?php $test =0 ; for($i=0;$i<sizeof($assigned_project_id);$i++){ $sql2="SELECT * FROM assign_task INNER JOIN branch ON assign_task.branch_ID=branch.branch_ID WHERE project_ID=".$assigned_project_id[$i]." AND USER_ID=1"; $query2=mysqli_query($con,$sql2); if(mysqli_num_rows($query2)>0){ if($test==0){ echo" You have Assigned following Reports"; $test++; } } while($row2=mysqli_fetch_assoc($query2)){ echo $row2['branch_ID']."&nbsp;".$row2['branch_name']."<br/>"; } } ?> ...

bash - for loop for IP range excluding certain IPs

bash,for-loop,ip,ip-address,exclude

Try this: for ip in 10.11.{32..47}.{0..255} do echo 10.11.{32..35}.{39..61} | grep -q "\<$ip\>" && continue echo "<ip>${ip}</ip>" done This of course is a simple solution which still loops through the complete set and throws away some unwanted elements. As your comment suggests, this may produce unnecessary delays during the parts...

GPA Calculator in C

loops,for-loop,do-while

There are two issues here. First, you need to discard new lines on your scanf. See here for details. Second the || operator is going to cause the whole statement to evaluate to true no matter if the user has entered Y or y. Try switching to an && operator...

Add XElement dynamically using loop in MVC 4?

c#,xml,asp.net-mvc-4,for-loop

This is the complete code [HttpPost] public ActionResult SURV_Answer_Submit(List<AnswerQuestionViewModel> viewmodel, int Survey_ID, string Language) { if (ModelState.IsValid) { var query = from r in db.SURV_Question_Ext_Model.ToList() join s in db.SURV_Question_Model on r.Qext_Question_ID equals s.Question_ID where s.Question_Survey_ID == Survey_ID && r.Qext_Language == Language orderby s.Question_Position ascending select new { r, s };...

Combining multiple for loops into one using the OR operator

c++,if-statement,for-loop

I tried your code, and it worked fine after I replaced for(int j = 0; j < myvec.size()-1; j++) with for(int j = 0; j < myvec.size(); j++) and myvec.erase(myvec.begin() + j); with myvec.erase(myvec.begin() + j--); My Testprogramm looked like this: #include <iostream> #include <string> #include <vector> using namespace std;...

VHDL average of Array through for loop

arrays,for-loop,vhdl,moving-average

It's not that efficient to add up a large number of samples each clock period like that; an adder with n inputs will consume a lot of logic resource as n starts to increase. My suggestion is to implement a memory buffer for the samples, which will have as many...

for loop vs for loop in reverse: performance

javascript,performance,for-loop

Yes, something has changed since the article was released. Firefox has gone from version 3 to version 38 for one thing. Mostly when a new version of a browser is released, the performance of several things has changed. If you try that code in different versions of different browsers on...

matlab Create growing matrix with for loop that grows by 3 per loop

matlab,loops,for-loop,matrix

Here is your problem: HSRXp(:,i*3) = [HSRXdistpR(:,i) HSRXdistpL(:,i) TocomXdistp(:,i)]; You're trying to assign an n x 3 matrix (RHS) into an n x 1 vector (LHS). It would be easier to simply use horizontal concatenation: HSRXp = [HSRXp, [HSRXdistpR(:,i) HSRXdistpL(:,i) TocomXdistp(:,i)]]; But that would mean reallocation at each step, which...

swift iterate on array

json,swift,for-loop

It would probably be best to define the JSON object initially so it produces an array with a single value, rather than this way, but otherwise you could check to see if you get a valid date, and if you don't try it another way. But looking at the API...

How to retrieve filtered data from json with double for loop

javascript,json,loops,for-loop,filter

If i understood you correctly, you need to add additional for loop for all bussen for (var i=0;i<bushalte2.length;i++) { $("#bussen").append(bushalte2[i].name + "<br/>"); for (var j=0; j <bushalte2[i].bussen.length; j++) { $("#bussen").append(bushalte2[i].bussen[j].busnummer + "<br/>"); } } here is updated jsfiddle https://jsfiddle.net/or4e8t3u/...

Converting Object Names to Strings in AS2

string,object,for-loop,actionscript-2,movieclip

Your suggestion that the objects are stored as a string is incorrect. If you try using typeof before your trace(typeof _level0[objects]) you will see that its type is movieclip and your "_level0.potato" is string They will not be equal. But you can convert object reference to string using String(...) construct....

iterating over a table passed as an argument to a function in lua

for-loop,lua,iterator,lua-table

You are creating the record table before creating the bid# tables. So when you do record = {bid1, bid2, bid3} none of the bid# variables have been created yet and so they are all nil. So that line is effectively record = {nil, nil, nil} which, obviously, doesn't give the...

Understanding the for loop in java

java,for-loop

Basically the main difference is this line: for(int y=1; y<=x; y++) resp. for(int y=1; y<=5; y++) The number of times the loop is executed is different. Namely in the first case it is variable (so the number of 'x' increases), in the second case it is fixed (5 'x' printed...

How to use list comprehensions to make a dict having list of list as values

python,list,for-loop

from operator import itemgetter from itertools import groupby a = [{'type': 'abc', 'values': 1}, {'type': 'abc', 'values': 2}, {'type': 'abc', 'values': 3}, {'type': 'xyz', 'values': 4}, {'type': 'xyz', 'values': 5}, {'type': 'pqr', 'values': 6}, {'type': 'pqr', 'values': 8}, {'type': 'abc', 'values': 9}, {'type': 'mno', 'values': 10}, {'type': 'def', 'values': 11}]...

Filling PHP array with “for” loop

php,arrays,for-loop,population

Try this Code : $maxPages = 20; $targets = array(); for ($i = 0; $i <= $maxPages; $i++) { $url = 'http://127.0.0.1/?page='.$i; $targets[$url] = array( CURLOPT_TIMEOUT => 10 ); } echo "<pre>"; print_r($targets); ...

Item not being properly indexed in PHP array inside of for loop

php,arrays,for-loop,attachment,binaryfiles

Alright, I'm posting this as an answer then, so this question can be marked as answered: This appears to be a purely visual bug. The error logs you provided seem to be incomplete, all output after any [attachment] => seems to be cut off (there should at least be closing...

R vector looping confusion [closed]

r,for-loop,vector

As indicated by comment above, the answer is to use the follwing: for (i in 1:length(x)){ } What your code does is the following: First iteration: i set to the first value in x (1), uses i to look up 1st value in x (1). Second iteration: i set to...

Why does this loop return a value that's O(n log log n) and not O(n log n)?

loops,for-loop,time-complexity,nested-loops,asymptotic-complexity

This question is tricky - there is a difference between what the runtime of the code is and what the return value is. The first loop's runtime is indeed O(log n), not O(log log n). I've reprinted it here: p = 0; for (j=n; j > 1; j=j/2) ++p; On...

For loop not only passing once

for-loop,selenium-webdriver

Please use the following code to select all options. The code you are trying to use selects the select element itself and not the options. List<WebElement> allOptions = driver.findElement(By.name("fromPort")).findElements(By.tagName("option")); ...

Java - allocation in enhanced for loop

java,for-loop,memory

No, you cannot use an enhanced for loop to initialize the elements of an array. The declared variable, here x, is a separate variable that refers to the current element in the array. It's null here because you just declared the array. You are changing x to refer to a...

Cancel last line iteration on a file

python,python-3.x,for-loop,file-io

In python3, the 'for line in file' construct is represented by an iterator internally. By definition, a value that was produced from an iterator cannot be 'put back' for later use (http://www.diveintopython3.net/iterators.html). To get the desired behaviour, you need a function that chains together two iterators, such as the chain...

concurrent modification on arraylist

java,for-loop,arraylist,concurrentmodification

This is not how to do it, to remove elements while going through a List you use an iterator. Like that : List<ServiceRequest> targets = new ArrayList<ServiceRequest>(); for(Iterator<ServiceRequest> it = targets.iterator(); it.hasNext();) { ServiceRequest currentServReq = it.next(); if(someCondition) { it.remove(); } } And you will not get ConcurrentModificationException this way...

How to stop handler.postDelayed in for-loop?

java,android,for-loop,handler,runnable

first, you should use removeCallbacks(), not removeCallbacksAndMessages() also it seems that you have pending Runnables that you should remove when your Activity says "bye bye", so try to call removeCallbacks() in onPause / onStop / onDestroy...

Matlab: Looping through an array

matlab,loops,for-loop,while-loop,do-while

You could do this using conv without loops avg_2 = mean([A(1:end-1);A(2:end)]) avg_4 = conv(A,ones(1,4)/4,'valid') avg_8 = conv(A,ones(1,8)/8,'valid') Output for the sample Input: avg_2 = 0.8445 5.9715 -0.6205 -3.5505 2.5530 6.9475 10.6100 12.5635 6.4600 avg_4 = 0.1120 1.2105 0.9662 1.6985 6.5815 9.7555 8.5350 avg_8 = 3.3467 5.4830 4.7506 Finding Standard Deviation...

Create a new loop without quotation marks

python,string,for-loop

Your item is a tuple: >>> item = ('Highest quarter rate is between', '1/1/15', 'and', '1/3/15', 'with rate:', 924.9966666666666) The string version of a tuple is its representation, for example: >>> str(item) "('Highest quarter rate is between', '1/1/15', 'and', '1/3/15', 'with rate:', 924.9966666666666)" Instead, you want to convert each element...

System.ArgumentOutOfRangeException in For loop due to entry deleted from database. Help fix it

database,vb.net,for-loop,indexing

Try going backwards - For i As Integer = (.Rows.Count - 1) to 0 Step -1. The issue is that you are deleting rows in the ReservationTableDataGridView as you try to iterate over them, thus changing the index. By going backwards you always have a valid index....

GET request inside of a loop in JavaScript

javascript,jquery,for-loop,get

The for-loop won't wait for the $.get call to finish so you need to add some async flow control around this. Check out async.eachSeries. The done callback below is the key to controlling the loop. After the success/fail of each $.get request you call done(); (or if there's an error,...

How to build a 'for' loop with input$i in R Shiny

r,loops,for-loop,shiny

Use [[ or [ if you want to subset by string names, not $. From Hadley's Advanced R, "x$y is equivalent to x[["y", exact = FALSE]]." ## Create input input <- `names<-`(lapply(landelist, function(x) sample(0:1, 1)), landelist) filterland <- c() for (landeselect in landelist) if (input[[landeselect]] == TRUE) # use `[[`...

Jekyll and Liquid for-loop

html5,for-loop,navigation,jekyll,liquid

You're comparing two counter that are not working the same way. {% assign imgIndex = {{forloop.index0}} This will count from 0 to array.size-1 {% assign naviIndex = {{forloop.index}} This will count from 1 to array.size As your not in the same "time zone", for the first image you have imgIndex...

Doubts with for loop in Unix

bash,shell,unix,for-loop

A for loop in shell scripting takes each whitespace separated string from the input and assigns it to the variable given, and runs the code once for each value. In your case b* is the input and $var is the assigned variable. The shell will also perform expansion on the...

Why does my nested for-if loops load much slonger when I dont nest this? And can I possibly fix this?

c#,excel,if-statement,for-loop,nested

This happens because the chain of if-then-elses get terminated as soon as you find a positive match, while your loop goes on to try other strings. If you find the right value within the first few constant matches most of the time, the difference may be significant. Adding a break...

How to iterate through a table in its exact order?

loops,for-loop,lua,order

You may utilize integer part of the table to store keys in order: function add(t, k, v, ...) if k ~= nil then t[k] = v t[#t+1] = k return add(t, ...) end return t end t = add({ }, "A", "hi", "B", "my", "C", "name", "D", "is") for i,k...

Set up a for loop to fill image src's

javascript,html,xml,for-loop

I'm not familiar with the API but you either: request all images, let the browser do it's work, and then fill each img element or have a queue and ask for the next image when the previous is done. The first option could be something like: var imgIds = [...

Why is my C code printing out an extra line of rows?

c,loops,for-loop,macros,printf

There is no issue with the #define, there is one issue with the conditional statement in the for loop. I believe, you'er overlooking the <= operator. You need to have only < operator. Change for(i=0;i<=rows;++i) to for(i=0;i<rows;++i) That said, the recommended signature of main() is int main(void)....

Change a Script to a For Do Done Loop

linux,bash,for-loop,awk

Turns out the code wasn't invalid (had to correct some quoting issues) but that the folder was corrupt when i tried to use it in the bash script. Here is the working code with the correct double quotes around the directory variables. #!/bin/bash #file location XMLDIR='/home/amoore19/XML/00581-001/scores' NEWXML='/home/amoore19/XML/00581-001' #this gives me...

What's the fastest way to compare point elements with each other?I have used Nested for loop to do that, but it's very slow

c++,opencv,for-loop,dictionary,vector

for 20000 random points with about 27 neighbors for each point this function gave me a speed-up. It needed about 33% less time than your original method. std::vector<std::vector<cv::Point> > findNeighborsOptimized(std::vector<cv::Point> p, float maxDistance = 3.0f) { std::vector<std::vector<cv::Point> > centerbox(p.size()); // already create a output vector for each input point /*...

Iteratively adding new columns to a list of data frames

r,list,for-loop,data.frame

You code is a concentration of things you should avoid in R: Don't use for when you can use lapply or more genrally xxapply family. Don't append row of a data.frame inside loop. This very inefficient. You should pre-allocate. Using lapply will do it for you. Don't use $ inside...

Objective C for loop delay

objective-c,for-loop,cocos2d-iphone,delay,grand-central-dispatch

The for loop will dispatch one right after the other so they will essentially delay for the same time. Instead set a different increasing delay for each: double delayInSeconds = 0.0; for(NSNumber* transaction in gainsArray) { delayInSeconds += 5.0; dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)); dispatch_after(popTime, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void)...

for of loop querySelectorAll

javascript,google-chrome,for-loop,mozilla,queryselectorall

The docs are correct, but I wouldn't call this a bug. Rather it's a "not yet implemented feature". There is no standard for this, and there is still active discussion on how the DOM should integrate with ES6. Notice that it is clear that querySelectorAll should return something iterable which...

Java print result every 10th iteration of a for loop

java,for-loop

Why would you use an if test if you can just do it simply using a for loop with a specific step, here's the code: int step = 10; for (int i = 0; i <= 100; i+=step) { Log.e("i:= ", i + ""); } The instruction will only run...

for-loop add columns using SQL in MS Access

sql,ms-access,table,for-loop,iteration

I have tested your code, I do not see any issues except for the fact, your For statement is a bit off and that you needed to set the db object. Try this code. Sub toto() Dim db As Database, i As Integer Set db = CurrentDb For i =...

How to get get max value in java? [closed]

java,for-loop,max

You can keep track of the maximum value without the need of an array. The solution is to initialize the maximum at 0, then for every number, we keep only the maximum of the previous maximum and the current number. The algorithm goes like this : double max = 0;...

Matlab Reintroduction of AR and GARCH processes

matlab,for-loop,return,time-series,volatility

I think you are a bit confused about how matrix indexing works in Matlab. If understood correctly, you have a variable TR_t with which you want to store the value for time t. You then try to do the following: TR_t = TR_{t-1} * exp(R_t); I will try to explain...

python compare items in 2 list of different length - order is important

python,list,loops,for-loop,indexing

Use the zip() function to pair up the lists, counting all the differences, then add the difference in length. zip() will only iterate over the items that can be paired up, but there is little point in iterating over the remainder; you know those are all to be counted as...

Tallying incorrect answers for Javascript game

javascript,for-loop

Add a variable to keep track of incorrect answers: var y = "You are correct!!!" var n = "You are incorrect!!!" var incorrectCount = 0; alert("Chapter 1, Human Cultural Connections. 1-10") //================================================== var Q1 = prompt("Demographers identify three different stages of life. They are children, working adults, and older adults....

Making var 's in a for-loop

c#,for-loop,var

you can use a dictionary var somethigs = new Dictionary<int, xxx.ApplicationClass>(); for (var i = 1; i < 4; i++) { somethigs[i] = new xxx.ApplicationClass(); } //access them like this somethigs[1].Name = "sheet1"; somethigs[2].Name = "sheet2"; or use an array like this var somethigs = new xxx.ApplicationClass[4]; for (var i...

Printing off the content of Array or Set using for loop

arrays,swift,for-loop,set,println

It is a playground short styled screen. In your real project you will get the exact values. No problem. Also in a playground you can see the real values by clicking the "Show Result" button and then clicking the "All Values" button in the newly produced pane. I've added a...

For Loops Not Always Updating C# [duplicate]

c#,for-loop

you are recreating the random number generator every time in the loop, create one before the loop: Random rand = new Random(); for(int i = 0; i < total.Length; i++) { ... } see also here and here, it explains why the numbers don't change...

consistent matched pairs in R

r,for-loop,matching

The problem is that you randomise the order of lalonde, but your input to GenMatch and Match are X and BalanceMat which still have the original order. When you then build your matched.data at the end, you are subsetting using indices which don't tie into lalonde any more. Try again...

looping variable in swift

swift,for-loop,uiimage

You don't need to create a new variable for each image, try this: for var i = 1; i < 8; i++ { images.append(UIImage(named: "image\(i)")) } This loop will create an array with 8 images without create the variables image1 to image8. I hope that help you!...

Run 3 variables at once in a python for loop.

python,loops,variables,csv,for-loop

zip the lists and use a for loop: def downloadData(n,i,d): for name, id, data in zip(n,i,d): URL = "http://www.website.com/data/{}".format(name) #downloads the file from the website. The last part of the URL is the name r = requests.get(URL) with open("data/{}_{}_{}.csv".format(name, id, data), "wb") as code: #create the file in the format...

For-loop does not go over all objects

python,list,for-loop

Replace for br in my_list : with for br in my_list[:] :. Thanks to that you are going to iterate over a copy of the source list.

How are the results for count different in all these three cases?

python,for-loop,while-loop,break

For Code 1, you're continuing to add on to the count. So during the first iteration, the count becomes 12 (the length of "hello, world" is 12), and then during the second iteration, you never reset the count to 0 so count is continuously added on until it reaches 24,...

How to sort multidimentional array

c++,c,sorting,for-loop

use qsort version #include <cstdio> #include <cstdlib> #define N 5 using namespace std; int cmp(const void *a, const void *b){ int *x = (int*)a; int *y = (int*)b; return (*x > *y) - (*x < *y); } int main(){ int a[N] = { 3, 6, 2, 4, 1 }; int...

Combine or merge 2 array with loop or function

c,arrays,for-loop,merge

A straightforward approach can look the following way #include <stdio.h> #define N 5 int main( void ) { int a[N] = { 3, 2, 2, 4, 5 }; int b[N] = { 6, 3, 1, 2, 9 }; int c[N][2]; for ( size_t i = 0; i < N; i++...

Retrieve index of newly added row - for loop in R

r,for-loop,indexing

This isn't very elegant, but it might work better than using two functions to fill in the rows and columns separately. Here, x is a list of all your matrices; factor is an optional list of desired row and column names fix_rc <- function(x, factors) { f <- function(x) factor(ul...

Error using range-based for loop - Eclipse CDT Luna

templates,c++11,for-loop,mingw,eclipse-luna

To use a range based for loop you'll need to use std::array instead of C-style array. I modified your code so it works. Note that you'll need to pass -std=c++11 flag to the compiler. #include <array> #include <iostream> using namespace std; template <typename T> void display (T myArray) { int...

How to stop a decreasing iteration after xth element?

php,for-loop,iteration

$j = 0; for ($i=count($array); $i>0; $i--) { if(condition) { DO SOMETHING like print the element in a decreasing manner; $j++; } if($j > 4){ break; } } ...

Time complexity of if-else statements in a for loop

if-statement,for-loop,time-complexity,asymptotic-complexity

We can start by looking at the easy case, case 2. Clearly, each time we go through the loop in case 2, one of either 2 things happens: count is incremented (which takes O(1) [except not really, but we just say it does for computers that operate on fixed-length numbers...

C++ Same name local variables keeping values between loops [closed]

c++,loops,for-loop,local-variables

The problem is here: for (int hcount = 0; hcount < height; hcount++); You end the loop with ;, which is a no-op. The hcount is in any case visible only in the scope of the loop. After the loop execution (i.e. after ;), the inner loop starts executing. Your...