Search Results

Search found 4036 results on 162 pages for 'nested loops'.

Page 2/162 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Accepts Nested Attributes For - edit form displays incorrect number of items ( + !map:ActiveSupport:

    - by Brightbyte8
    Hi, I have a teacher profile model which has many subjects (separate model). I want to add subjects to the profile on the same form for creating/editing a profile. I'm using accepts_nested_attributes for and this works fine for creation. However on the edit page I am getting a very strange error - instead of seeing 3 subjects (I added three at create and a look into the console confirms this), I see 12 subjects(!). #Profile model class Profile < ActiveRecord::Base has_many :subjects accepts_nested_attributes_for :subjects end #Subject Model class Subject < ActiveRecord::Base belongs_to :profile end #Profile Controller (only showing deviations from normal RESTFUL setup) def new @profile = Profile.new 3.times do @profile.subjects.build end end #Here's 1 of three parts of the subject output of = debug @profile errors: !ruby/object:ActiveRecord::Errors base: *id004 errors: !map:ActiveSupport::OrderedHash {} subjects: - &id001 !ruby/object:Subject attributes: exam: Either name: "7" created_at: 2010-04-15 10:38:13 updated_at: 2010-04-15 10:38:13 level: Either id: "31" profile_id: "3" attributes_cache: {} # Note that 3 of these attributes are displayed despite me seeing 12 subjects on screen Other info in case it's relevant. Rails: 2.3.5 Ruby 1.8.7 p149 HAML I've never had so much difficulty with a bug before - I've already lost about 8 hours to it. Would really appreciate any help! Thanks to any courageous takers Jack

    Read the article

  • Updating nested attributes causes duplicate entries

    - by params_noob
    I have a has_many and belongs_to relationship between Job and Address. When I try to update Job and Address in the same form, it updates job but creates a duplicate entry for Address. Am I missing something here? The Edit and Update Actions from Jobs: def edit @job = Job.find(params[:id]) end def update @job = Job.find(params[:id]) if @job.update_attributes(job_params) flash[:success] = "Job Updated" redirect_to current_user else render 'edit' end end The edit form: <h1>Edit Job Information</h1> <div class="row"> <div class="span6 offset3"> <%= form_for(@job) do |f| %> <%= render 'shared/error_messages' %> <%= f.label :recipient %> <%= f.text_field :recipient %> <%= f.label :age %> <%= f.text_field :age %> <%= f.label :gender %> <%= f.text_field :gender %> <%= f.label :ethnicity %> <%= f.text_field :ethnicity %> <%= f.label :height %> <%= f.text_field :height %> <%= f.label :weight %> <%= f.text_field :weight %> <%= f.label :hair %> <%= f.text_field :hair %> <%= f.label :eyes %> <%= f.text_field :eyes %> <%= f.label :other_info %> <%= f.text_field :other_info %> <h3> Address Information </h3> <%= f.fields_for :addresses do |address| %> <%= address.label :label, "Label" %> <%= address.text_field :label %> <%= address.label :addy, "Address" %> <%= address.text_field :addy %> <%= address.label :apt, "Apt/Suite/etc" %> <%= address.text_field :apt %> <%= address.label :city, "City" %> <%= address.text_field :city %> <%= address.label :state, "State" %> <%= address.text_field :state %> <%= address.label :zip, "Zip code" %> <%= address.text_field :zip %> <% end %> <%= f.label :instructions, "Service Instructions" %> <%= f.text_field :instructions %> <%= check_box_tag(:rush) %> <%= label_tag(:rush, "Rush?") %> <%= f.submit "Update Job", class: "btn btn-large btn-primary" %> <% end %> </div> </div>

    Read the article

  • What does the English word "for" exactly mean in "for" loops?

    - by kol
    English is not my first language, but since the keywords in programming languages are English words, I usually find it easy to read source code as English sentences: if (x > 10) f(); = "If variable x is greater than 10, then call function f." while (i < 10) ++i; = "While variable i is less than 10, increase i by 1." But how a for loop is supposed to be read? for (i = 0; i < 10; ++i) f(i); = ??? I mean, I know what a for loop is and how it works. My problem is only that I don't know what the English word "for" exactly means in for loops.

    Read the article

  • Programming advice - Which Loops?

    - by GaxZE
    Theres no easy way to say this so ill just say it in the form of a story. Im looking for advice on which loops and where. Here goes: out of 200-odd fields in the database, i need to run the following against each field. extract allowed values using extract function place allowed values into an array loop the array to be inserted into a db table first check records dont already exist. if they dont exist insert into table. ive found myself playing with this for the past two days and getting tangled and tangled in loops. wondering if anybody can guide.

    Read the article

  • Nested WHILE loops not acting as expected - Javascript / Google Apps Script

    - by dthor
    I've got a function that isn't acting as intended. Before I continue, I'd like preface this with the fact that I normally program in Mathematica and have been tasked with porting over a Mathematica function (that I wrote) to JavaScript so that it can be used in a Google Docs spreadsheet. I have about 3 hours of JavaScript experience... The entire (small) project is calculating the Gross Die per Wafer, given a wafer and die size (among other inputs). The part that isn't working is where I check to see if any corner of the die is outside of the effective radius, Reff. The function takes a list of X and Y coordinates which, when combined, create the individual XY coord of the center of the die. That is then put into a separate function "maxDistance" that calculates the distance of each of the 4 corners and returns the max. This max value is checked against Reff. If the max is inside the radius, 1 is added to the die count. // Take a list of X and Y values and calculate the Gross Die per Wafer function CoordsToGDW(Reff,xSize,ySize,xCoords,yCoords) { // Initialize Variables var count = 0; // Nested loops create all the x,y coords of the die centers for (var i = 0; i < xCoords.length; i++) { for (var j = 0; j < yCoords.length, j++) { // Add 1 to the die count if the distance is within the effective radius if (maxDistance(xCoords[i],yCoords[j],xSize,ySize) <= Reff) {count = count + 1} } } return count; } Here are some examples of what I'm getting: xArray={-52.25, -42.75, -33.25, -23.75, -14.25, -4.75, 4.75, 14.25, 23.75, 33.25, 42.75, 52.25, 61.75} yArray={-52.5, -45.5, -38.5, -31.5, -24.5, -17.5, -10.5, -3.5, 3.5, 10.5, 17.5, 24.5, 31.5, 38.5, 45.5, 52.5, 59.5} CoordsToGDW(45,9.5,7.0,xArray,yArray) returns: 49 (should be 72) xArray={-36, -28, -20, -12, -4, 4, 12, 20, 28, 36, 44} yArray={-39, -33, -27, -21, -15, -9, -3, 3, 9, 15, 21, 27, 33, 39, 45} CoordsToGDW(32.5,8,6,xArray,yArray) returns: 39 (should be 48) I know that maxDistance() is returning the correct values. So, where's my simple mistake? Also, please forgive me writing some things in Mathematica notation... Edit #1: A little bit of formatting. Edit #2: Per showi, I've changed WHILE loops to FOR loops and replaced <= with <. Still not the right answer. It did clean things up a bit though... Edit #3: What I'm essentially trying to do is take [a,b] and [a,b,c] and return [[a,a],[a,b],[a,c],[b,a],[b,b],[b,c]]

    Read the article

  • Java: Combination of recursive loops which has different FOR loop inside; Output: FOR loops indexes

    - by vvinjj
    currently recursion is fresh & difficult topic for me, however I need to use it in one of my algorithms. Here is the challenge: I need a method where I specify number of recursions (number of nested FOR loops) and number of iterations for each FOR loop. The result should show me, something simmilar to counter, however each column of counter is limited to specific number. ArrayList<Integer> specs= new ArrayList<Integer>(); specs.add(5); //for(int i=0 to 5; i++) specs.add(7); specs.add(9); specs.add(2); specs.add(8); specs.add(9); public void recursion(ArrayList<Integer> specs){ //number of nested loops will be equal to: specs.size(); //each item in specs, specifies the For loop max count e.g: //First outside loop will be: for(int i=0; i< specs.get(0); i++) //Second loop inside will be: for(int i=0; i< specs.get(1); i++) //... } The the results will be similar to outputs of this manual, nested loop: int[] i; i = new int[7]; for( i[6]=0; i[6]<5; i[6]++){ for( i[5]=0; i[5]<7; i[5]++){ for(i[4] =0; i[4]<9; i[4]++){ for(i[3] =0; i[3]<2; i[3]++){ for(i[2] =0; i[2]<8; i[2]++){ for(i[1] =0; i[1]<9; i[1]++){ //... System.out.println(i[1]+" "+i[2]+" "+i[3]+" "+i[4]+" "+i[5]+" "+i[6]); } } } } } } I already, killed 3 days on this, and still no results, was searching it in internet, however the examples are too different. Therefore, posting the programming question in internet first time in my life. Thank you in advance, you are free to change the code efficiency, I just need the same results.

    Read the article

  • Add objects to Arraylist inside loop and get a list of them outside loops

    - by AgusDG
    Im already done with a method to do a shot on a board (bidimensional array). THe shot goes from the bottom to the top, and depending of the direction, it do bounces on the walls to get to the top. The thing is that I did the method to represent the trayectory with an 'x'. Now, I want to add the coordinates x and y of each position of the shot (b [x][y]) to and Arraylist of Objects Position. public Position(int row,int col) { this.row = row; this.col = col; } The thing is that the method uses a for loop and inside if loops, and I'll need to create the objects inside, and get them outside. I did that : public static ArrayList<Position> showTrayectory (char [][] b , int shotDirection, char bubble){ int row = 0, col = 0; ArrayList<Position> aListPos = new ArrayList<Position>(); Position positionsOfShot = new Position(row,col); START = ((RIGHT_WALL)/2) + shotDirection; boolean shotRight = false; if(shotDirection < 0) shotRight = false; else if(shotDirection > 0) shotRight = true; for(int y = BOTTOM,x = START ;y >= 0;y--) { if(!isOut(y,x) && !emptyCell(y,x)) break; if(x <= LEFT_WALL) shotRight = true; if(x >= RIGHT_WALL) shotRight = false; if(!isOut(y,x) && shotRight == true) { positionsOfShot = new Position(y,x); aListPos.add(positionsOfShot); b[y][x] = SHOT; ++x; } if(!isOut(y,x) && shotRight == false){ positionsOfShot = new Position(y,x); aListPos.add(positionsOfShot); b[y][x] = SHOT; --x; } } // The nested for loops below are for showing the positions // But I dont need it that way // I must get the trayectory from an ArrayList and print it from there for(int y=0;y < b.length;y++){ System.out.println(); for(int x=0;x < b[y].length;x++){ System.out.print(" "+b [y][x]+" "); } } System.out.println("\nTrayectory of the shot ["+shotDirection+"]"); System.out.println("Next bubble ["+bubble+"]"); for( Position ii : aListPos){ System.out.println("(" + positionsOfShot.getFila() + "," + positionsOfShot.getColumna()+")"); } return aListPos; } The sentence " b[y][x] = SHOT; " is still there, to see the proper trayectory of the shot (its not needed that way), but what I need, is getting the trayectory in an ArrayList, and print the trayectory from there. All that I get is a wrong position, and repeated during the number of positions the shot goes through. I need some help. I suppose the problem is that Im creating and adding Position Objects inside an ArrayList inside loops, but in a wrong way. I will need you to explain me how to do it properly ; ) Thanks in advance. I'll add the output for you see better what is that above haha *************************** y b y b g r b g o y g a a r y o y y r b y g r r o b o y y g b a r y r o a y y o o r r g r - - - x - - - - - - - - - x - - - - - - - - - x - - - - - - - - - x - - - - - - - - - x - - - - - - - - - x - - - - - - - x - - - - - - - x - - - - - - - x - - - Trayectory of the shot [1] Next bubble [y] (5,3) (5,3) (5,3) (5,3) (5,3) (5,3) (5,3) (5,3) (5,3) Action?

    Read the article

  • Python: two loops at once

    - by Stephan Meijer
    I've got a problem: I am new to Python and I want to do multiple loops. I want to run a WebSocket client (Autobahn) and I want to run a loop which shows the filed which are edited in a specific folder (pyinotify or else Watchdog). Both are running forever, Great. Is there a way to run them at once and send a message via the WebSocket connection while I'm running the FileSystemWatcher, like with callbacks, multithreading, multiprocessing or just separate files? factory = WebSocketClientFactory("ws://localhost:8888/ws", debug=False) factory.protocol = self.webSocket connectWS(factory) reactor.run() If we run this, it will have success. But if we run this: factory = WebSocketClientFactory("ws://localhost:8888/ws", debug=False) factory.protocol = self.webSocket connectWS(factory) reactor.run() # Websocket client running now,running the filewatcher wm = pyinotify.WatchManager() mask = pyinotify.IN_DELETE | pyinotify.IN_CREATE # watched events class EventHandler(pyinotify.ProcessEvent): def process_IN_CREATE(self, event): print "Creating:", event.pathname def process_IN_DELETE(self, event): print "Removing:", event.pathname handler = EventHandler() notifier = pyinotify.Notifier(wm, handler) wdd = wm.add_watch('/tmp', mask, rec=True) notifier.loop() This will create 2 loops, but since we already have a loop, the code after 'reactor.run()' will not run at all.. For your information: this project is going to be a sync client. Thanks a lot!

    Read the article

  • Efficiency of nested Loop

    - by didxga
    See the following snippet: //first nested loops for(int i=0;i<10;i++) { for(int j=1;j<1000000;j++) { //do some stuff } } //second nested loops for(int i=0;i<1000000;i++) { for(int j=1;j<10;j++) { //do some stuff } } I am wondering why the first nested loops is running slower than the second one? Regards!

    Read the article

  • Display numbers from 1 to 100 without loops or conditions

    - by Harsha
    Is there a way to print numbers from 1 to 100 without using any loops or conditions like "if"? We can easily do using recursion but that again has an if condition. Is there a way to do without using "if" as well? Also no repetitive print statements,or a single print statement containing all the numbers from 1 to 100. A solution in Java is preferable.

    Read the article

  • Enumerator problem, Any way to avoid two loops?

    - by pug
    I have a third party api, which has a class that returns an enumerator for different items in the class. I need to remove an item in that enumerator, so I cannot use "for each". Only option I can think of is to get the count by iterating over the enum and then run a normal for loop to remove the items. Anyone know of a way to avoid the two loops? Thanks

    Read the article

  • C++ non-member functions for nested template classes

    - by beldaz
    I have been writing several class templates that contain nested iterator classes, for which an equality comparison is required. As I believe is fairly typical, the comparison is performed with a non-member (and non-friend) operator== function. In doing so, my compiler (I'm using Mingw32 GCC 4.4 with flags -O3 -g -Wall) fails to find the function and I have run out of possible reasons. In the rather large block of code below there are three classes: a Base class, a Composed class that holds a Base object, and a Nested class identical to the Composed class except that it is nested within an Outer class. Non-member operator== functions are supplied for each. These classes are in templated and untemplated forms (in their own respective namespaces), with the latter equivalent to the former specialised for unsigned integers. In main, two identical objects for each class are compared. For the untemplated case there is no problem, but for the templated case the compiler fails to find operator==. What's going on? #include <iostream> namespace templated { template<typename T> class Base { T t_; public: explicit Base(const T& t) : t_(t) {} bool equal(const Base& x) const { return x.t_==t_; } }; template<typename T> bool operator==(const Base<T> &x, const Base<T> &y) { return x.equal(y); } template<typename T> class Composed { typedef Base<T> Base_; Base_ base_; public: explicit Composed(const T& t) : base_(t) {} bool equal(const Composed& x) const {return x.base_==base_;} }; template<typename T> bool operator==(const Composed<T> &x, const Composed<T> &y) { return x.equal(y); } template<typename T> class Outer { public: class Nested { typedef Base<T> Base_; Base_ base_; public: explicit Nested(const T& t) : base_(t) {} bool equal(const Nested& x) const {return x.base_==base_;} }; }; template<typename T> bool operator==(const typename Outer<T>::Nested &x, const typename Outer<T>::Nested &y) { return x.equal(y); } } // namespace templated namespace untemplated { class Base { unsigned int t_; public: explicit Base(const unsigned int& t) : t_(t) {} bool equal(const Base& x) const { return x.t_==t_; } }; bool operator==(const Base &x, const Base &y) { return x.equal(y); } class Composed { typedef Base Base_; Base_ base_; public: explicit Composed(const unsigned int& t) : base_(t) {} bool equal(const Composed& x) const {return x.base_==base_;} }; bool operator==(const Composed &x, const Composed &y) { return x.equal(y); } class Outer { public: class Nested { typedef Base Base_; Base_ base_; public: explicit Nested(const unsigned int& t) : base_(t) {} bool equal(const Nested& x) const {return x.base_==base_;} }; }; bool operator==(const Outer::Nested &x, const Outer::Nested &y) { return x.equal(y); } } // namespace untemplated int main() { using std::cout; unsigned int testVal=3; { // No templates first typedef untemplated::Base Base_t; Base_t a(testVal); Base_t b(testVal); cout << "a=b=" << testVal << "\n"; cout << "a==b ? " << (a==b ? "TRUE" : "FALSE") << "\n"; typedef untemplated::Composed Composed_t; Composed_t c(testVal); Composed_t d(testVal); cout << "c=d=" << testVal << "\n"; cout << "c==d ? " << (c==d ? "TRUE" : "FALSE") << "\n"; typedef untemplated::Outer::Nested Nested_t; Nested_t e(testVal); Nested_t f(testVal); cout << "e=f=" << testVal << "\n"; cout << "e==f ? " << (e==f ? "TRUE" : "FALSE") << "\n"; } { // Now with templates typedef templated::Base<unsigned int> Base_t; Base_t a(testVal); Base_t b(testVal); cout << "a=b=" << testVal << "\n"; cout << "a==b ? " << (a==b ? "TRUE" : "FALSE") << "\n"; typedef templated::Composed<unsigned int> Composed_t; Composed_t c(testVal); Composed_t d(testVal); cout << "c=d=" << testVal << "\n"; cout << "d==c ? " << (c==d ? "TRUE" : "FALSE") << "\n"; typedef templated::Outer<unsigned int>::Nested Nested_t; Nested_t e(testVal); Nested_t f(testVal); cout << "e=f=" << testVal << "\n"; cout << "e==f ? " << (e==f ? "TRUE" : "FALSE") << "\n"; // Above line causes compiler error: // error: no match for 'operator==' in 'e == f' } cout << std::endl; return 0; }

    Read the article

  • as3 loops and event listeners

    - by Ross
    I have an array that returns multidimensional data from an mysql database, when this is collected the createNews function creates the user interface. The problem I am having is the loop is iterating quicker than the ui is being created, is there a way to use event listeners with loops so it only continues after my function has completed its work. Any solutions or ideas are much appreciated; Thanks, R. var t:Array = responds.serverInfo.initialData; for (var i:uint = 0; i < t.length; i++) { var date = t[i][1]; var newstitle = t[i][2]; var story= t[i][3]; var image = t[i][4]; createNews(date, newstitle, story, image); }

    Read the article

  • Loops in ada and the implementation

    - by maddy
    HI all, Below is a piece of code shown and doubts are regarding the implementation of loops C := character'last; I := 1; K : loop Done := C = character'first; Count2 := I; Exit K when Done; C := character'pred(c); I := I + 1; end loop K; Can anyone please tell me what does 'K' stands for.I guess its not a variable.How does 'K' control the execution of the loop? Thanks Maddy

    Read the article

  • How to optimize MATLAB loops?

    - by striglia
    I have been working lately on a number of iterative algorithms in MATLAB, and been getting hit hard by MATLAB's performance (or lack thereof) when it comes to loops. I'm aware of the benefit of vectorizing code when possible, but are there any tools for optimization when you need the loop for your algorithm? I am aware of the MEX-file option to write small subroutines in C/C++, although given my algorithms, this can be a very painful option given the data structures required. I mainly use MATLAB for the simplicity and speed of prototyping, so a syntactically complex, statically typed language is not ideal for my situation. Are there any other suggestions? Even other languages (python?) which have relatively painless matrix tools are an option.

    Read the article

  • Avoid the use of loops (for) with R

    - by albergali
    Hi, I'm working with R and I have a code like this: i<-1 j<-1 for (i in 1:10) for (j in 1:100) if (data[i] == paths[j,1]) cluster[i,4] <- paths[j,2] where : data is a vector with 100 rows and 1 column paths is a matrix with 100 rows and 5 columns cluster is a matrix with 100 rows and 5 columns My question is: how could I avoid the use of "for" loops to iterate through the matrix? I don't know whether apply functions (lapply, tapply...) are useful in this case. This is a problem when j=10000 for example, because execution time is very long. Thank you

    Read the article

  • Implement loops for python 3

    - by Alex
    Implement this loop: total up the product of the numbers from 1 to x. Implement this loop: total up the product of the numbers from a to b. Implement this loop: total up the sum of the numbers from a to b. Implement this loop: total up the sum of the numbers from 1 to x. Implement this loop: count the number of characters in a string s. i'm very lost on implementing loops these are just some examples that i am having trouble with-- if someone could help me understand how to do them that would be awesome

    Read the article

  • Bash Nested Loops, mixture of dates and numbers

    - by Saleh
    Hi, I am trying to output a range of commands with different dates and numbers associated. for each hour eg. Output im trying to do in a loop is: shell.sh filename<number e.g. between 1-24> <date e.g. 20100928> <number e.g. between 1-24> <id> So basically the the above will generate an output done 24 times for each particular day with a unique 4 digit id. I was thinking of having a nested loop, as the batch number needs to be unique. can anyone help?

    Read the article

  • unroll nested for loops in C++

    - by Hristo
    How would I unroll the following nested loops? for(k = begin; k != end; ++k) { for(j = 0; j < Emax; ++j) { for(i = 0; i < N; ++i) { if (j >= E[i]) continue; array[k] += foo(i, tr[k][i], ex[j][i]); } } } I tried the following, but my output isn't the same, and it should be: for(k = begin; k != end; ++k) { for(j = 0; j < Emax; ++j) { for(i = 0; i+4 < N; i+=4) { if (j >= E[i]) continue; array[k] += foo(i, tr[k][i], ex[j][i]); array[k] += foo(i+1, tr[k][i+1], ex[j][i+1]); array[k] += foo(i+2, tr[k][i+2], ex[j][i+2]); array[k] += foo(i+3, tr[k][i+3], ex[j][i+3]); } if (i < N) { for (; i < N; ++i) { if (j >= E[i]) continue; array[k] += foo(i, tr[k][i], ex[j][i]); } } } } I will be running this code in parallel using Intel's TBB so that it takes advantage of multiple cores. After this is finished running, another function prints out what is in array[] and right now, with my unrolling, the output isn't identical. Any help is appreciated. Thanks, Hristo

    Read the article

  • Jquery - $(this) in in nested loops

    - by Smickie
    Hi, I can't figure out how to do something in Jquery. Let's say I have a form with many select drop-downs and do this... $('#a_form select').each(function(index) { }); When inside this loop I want to loop over each of the options, but I can't figure out how to do this, is it something like this....? $('#a_form select').each(function(index) { $(this + 'option').each(function(index) { //do things }); }); I can't quite get it to work, and advice? Cheers.

    Read the article

  • Replace Loops in R function

    - by David Hicks
    Hi, I'm new to R, and I'm having trouble figuring out how to replace the FOR loop in the function below. The function estimates a population mean. Any help at all would be much appreciated. Thank you! myFunc<- function(){ myFRAME <- read.csv(file="2008short.csv",head=TRUE,sep=",") meanTotal <- 0 for(i in 1:100) { mySample <- sample(myFRAME$TaxiIn, 100, replace = TRUE) tempMean <- mean(mySample) meanTotal <- meanTotal + tempMean } cat("Estimated Mean: ", meanTotal/100, "\n") #print result }

    Read the article

  • Variable Assignment and loops (Java)

    - by Raven Dreamer
    Greetings Stack Overflowers, A while back, I was working on a program that hashed values into a hashtable (I don't remember the specifics, and the specifics themselves are irrelevant to the question at hand). Anyway, I had the following code as part of a "recordInput" method. tempElement = new hashElement(someInt); while(in.hasNext() == true) { int firstVal = in.nextInt(); if (firstVal == -911) { break; } tempElement.setKeyValue(firstVal, 0); for(int i = 1; i<numKeyValues;i++) { tempElement.setKeyValue(in.nextInt(), i); } elementArray[placeValue] = tempElement; placeValue++; } // close while loop } // close method This part of the code was giving me a very nasty bug -- no matter how I finagled it, no matter what input I gave the program, it would always produce an array full of only a single value -- the last one. The problem, as I later determined it, was that because I had not created the tempElement variable within the loop, and because values were not being assigned to elementArray[] until after the loop had ended -- every term was defined rather as "tempElement" -- when the loop terminated, every slot in the array was filled with the last value tempElement had taken. I was able to fix this bug by moving the declaration of tempElement within the while loop. My question to you, Stackoverflow, is whether there is another (read: better) way to avoid this bug while keeping the variable declaration of tempElement outside the while loop. (suggestions for better title and tags also appreciated)

    Read the article

  • Python Beginner: Selective Printing in loops

    - by Jonathan Straus
    Hi there. I'm a very new python user (had only a little prior experience with html/javascript as far as programming goes), and was trying to find some ways to output only intermittent numbers in my loop for a basic bicycle racing simulation (10,000 lines of biker positions would be pretty excessive :P). I tried in this loop several 'reasonable' ways to communicate a condition where a floating point number equals its integer floor (int, floor division) to print out every 100 iterations or so: for i in range (0,10000): i = i + 1 t = t + t_step #t is initialized at 0 while t_step is set at .01 acceleration_rider1 = (power_rider1 / (70 * velocity_rider1)) - (force_drag1 / 70) velocity_rider1 = velocity_rider1 + (acceleration_rider1 * t_step) position_rider1 = position_rider1 + (velocity_rider1 * t_step) force_drag1 = area_rider1 * (velocity_rider1 ** 2) acceleration_rider2 = (power_rider2 / (70 * velocity_rider1)) - (force_drag2 / 70) velocity_rider2 = velocity_rider2 + (acceleration_rider2 * t_step) position_rider2 = position_rider2 + (velocity_rider2 * t_step) force_drag2 = area_rider1 * (velocity_rider2 ** 2) if t == int(t): #TRIED t == t // 1 AND OTHER VARIANTS THAT DON'T WORK HERE:( print t, "biker 1", position_rider1, "m", "\t", "biker 2", position_rider2, "m"

    Read the article

  • Perl - CodeGolf - Nested loops & SQL inserts

    - by CheeseConQueso
    I had to make a really small and simple script that would fill a table with string values according to these criteria: 2 characters long 1st character is always numeric (0-9) 2nd character is (0-9) but also includes "X" Values need to be inserted into a table on a database The program would execute: insert into table (code) values ('01'); insert into table (code) values ('02'); insert into table (code) values ('03'); insert into table (code) values ('04'); insert into table (code) values ('05'); insert into table (code) values ('06'); insert into table (code) values ('07'); insert into table (code) values ('08'); insert into table (code) values ('09'); insert into table (code) values ('0X'); And so on, until the total 110 values were inserted. My code (just to accomplish it, not to minimize and make efficient) was: use strict; use DBI; my ($db1,$sql,$sth,%dbattr); %dbattr=(ChopBlanks => 1,RaiseError => 0); $db1=DBI->connect('DBI:mysql:','','',\%dbattr); my @code; for(0..9) { $code[0]=$_; for(0..9) { $code[1]=$_; insert(@code); } insert($code[0],"X"); } sub insert { my $skip=0; foreach(@_) { if($skip==0) { $sql="insert into table (code) values ('".$_[0].$_[1]."');"; $sth=$db1->prepare($sql); $sth->execute(); $skip++; } else { $skip--; } } } exit; I'm just interested to see a really succinct & precise version of this logic.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >