Search Results

Search found 9667 results on 387 pages for 'parallel loop'.

Page 11/387 | < Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >

  • Good input validation loop using cin - C++

    - by Alex
    Hi there, I'm in my second OOP class, and my first class was taught in C#, so I'm new to C++ and currently I am practicing input validation using cin. So here's my question: Is this loop I constructed a pretty good way of validating input? Or is there a more common/accepted way of doing it? Thanks! Code: int taxableIncome; int error; // input validation loop do { error = 0; cout << "Please enter in your taxable income: "; cin >> taxableIncome; if (cin.fail()) { cout << "Please enter a valid integer" << endl; error = 1; cin.clear(); cin.ignore(80, '\n'); } }while(error == 1);

    Read the article

  • C - is it possible to decrement the max value of a for loop from within the for loop?

    - by hatorade
    for example: void decrement(int counter) { counter--; } int counter = 20; for (int i = 0; i < counter; i++) { for (int j = 0; j < counter, j++) { decrement(counter); } } ideally, what i'd like to see is the counter var being decremented every time the for loop is run, so that it runs fewer than 20 iterations. but gdb shows that within decrement() counter is decremented, but that going back to the for loop counter actually stays the same.

    Read the article

  • PHP - Loop thru recordset and fire event each n rows

    - by Luciano
    I'm looking for the right logic to loop thru a recordset and fire an event each n times. Searching on Google i've found some discussion on similar situations, but it seems that solutions don't fits my needs. Let's say i have a recordset of 22 rows. I want to loop thru each row and launch a function on the 4th, the 8th, the 12th and so on... Using the modulus operator as shown in this answer, if($i % 4 == 0), i get the event fired each 4 rows, but 22 its not a multiple of 4 so the event is fired till the 20th row and then nothing. Maybe i need to make a division counting rows in 'excess'? Since the recordset will be between 50 and 200 rows i think its not necessary run multiple query of 4 rows, am I wrong? Thanks in advance!

    Read the article

  • Drupal and Login Toboggan -- infinite redirect loop

    - by Ian Silber
    I'm getting a redirect loop when using Login Toboggan. It doesn't happen all of the time and I think I've narrowed it down to something with the session, specifically the active-tabs[last-active-href] value. Since it's intermittent, I was able to print out a session of a working copy and a non-working copy. Here are both: WORKS -- Array ( [active-tabs] = Array ( [last-active-href] = index ) ) toboggan/denied DOESN'T WORK -- Array ( [active-tabs] = Array ( [last-active-href] = user/register [user] = user/register ) [wantsEvents] = [wantsResources] = [wantsSupport] = ) toboggan/denied I've also noticed that if I comment out the following line the redirection loop stops (although no page loads): $return = menu_execute_active_handler('user/register'); Any ideas? I'm at my wits end.

    Read the article

  • zsh for loop exclusion

    - by ABach
    This is somewhat of a simple question, but for the life of me, I cannot figure out how to exclude something from a zsh for loop. For instance, let's say we have this: for $package in /home/user/settings/* do # do stuff done Let's say that in /home/user/settings/, there is a particular directory ("os") that I want to ignore. Logically, I tried the following variations: for $package in /home/user/settings/^os (works w/ "ls", but not with a foor loop) for $package in /home/user/settings/*^os for $package in /home/user/settings/^os* ...but none of those seem to work. Could someone steer my syntax in the right direction?

    Read the article

  • Stuck in Infinite Loop while PostInvalidating

    - by Nicholas Roge
    I'm trying to test something, however, the loop I'm using keeps getting stuck while running. It's just a basic lock thread while doing something else before continuing kind of loop. I've double checked that I'm locking AND unlocking the variable I'm using, but regardless it's still stuck in the loop. Here are the segments of code I have that cause the problem: ActualGame.java: Thread thread=new Thread("Dialogue Thread"){ @Override public void run(){ Timer fireTimer=new Timer(); int arrowSequence=0; gameHandler.setOnTouchListener( new OnTouchListener(){ @Override public boolean onTouch(View v, MotionEvent me) { //Do something. if(!gameHandler.fireTimer.getActive()){ exitLoop=true; } return false; } } ); while(!exitLoop){ while(fireTimer.getActive()||!gameHandler.drawn); c.drawBitmap(SpriteSheet.createSingleBitmap(getResources(), R.drawable.dialogue_box,240,48),-48,0,null); c.drawBitmap(SpriteSheet.createSingleBitmap(getResources(),R.drawable.dialogue_continuearrow,32,16,8,16,arrowSequence,0),-16,8,null); gameHandler.drawn=false; gameHandler.postInvalidate(); if(arrowSequence+1==4){ arrowSequence=0; exitLoop=true; }else{ arrowSequence++; } fireTimer.startWait(100); } gameHandler.setOnTouchListener(gameHandler.defaultOnTouchListener); } }; thread.run(); And the onDraw method of GameHandler: canvas.scale(scale,scale); canvas.translate(((screenWidth/2)-((terrainWidth*scale)/2))/scale,((screenHeight/2)-((terrainHeight*scale)/2))/scale); canvas.drawColor(Color.BLACK); for(int layer=0;layer(less than)tiles.length;layer++){ if(layer==playerLayer){ canvas.drawBitmap(playerSprite.getCurrentSprite(), playerSprite.getPixelLocationX(), playerSprite.getPixelLocationY(), null); continue; } for(int y=0;y(less than)tiles[layer].length;y++){ for(int x=0;x(less than)tiles[layer][y].length;x++){ if(layer==0&&tiles[layer][y][x]==null){ tiles[layer][y][x]=nullTile; } if(tiles[layer][y][x]!=null){ runningFromTileEvent=false; canvas.drawBitmap(tiles[layer][y][x].associatedSprite.getCurrentSprite(),x*tiles[layer][y][x].associatedSprite.spriteWidth,y*tiles[layer][y][x].associatedSprite.spriteHeight,null); } } } } for(int i=0;i(less than)canvasEvents.size();i++){ if(canvasEvents.elementAt(i).condition(this)){ canvasEvents.elementAt(i).run(canvas,this); } } Log.e("JapaneseTutor","Got here.[1]"); drawn=true; Log.e("JapaneseTutor","Got here.[2]"); If you need to see the Timer class, or the full length of the GameHandler or ActualGame classes, just let me know.

    Read the article

  • Struggling with a loop

    - by Emil
    Hey. I am trying to make an integer match another integer by adding a number to one of them. I have tried several loop types, but none has worked. Take a look at the code: int favoriteLoop = [favoriteThing intValue]; if (favoriteLoop != [[[array objectAtIndex:favoriteLoop] description] intValue]){ NSLog(@"%d", [[[array objectAtIndex:favoriteLoop] description] intValue]); int favTemp = favoriteLoop; for (int x = favTemp; (favoriteLoop == [[[array objectAtIndex:favoriteLoop] description] intValue]); x++) { NSLog(@"Still not there.."); } } Could anyone help me clear up this mess? It just won't work! Could it have something to do with it allready being inside a for-loop?

    Read the article

  • Erlang message loops

    - by Roger Alsing
    How does message loops in erlang work, are they sync when it comes to processing messages? As far as I understand, the loop will start by "receive"ing a message and then perform something and hit another iteration of the loop. So that has to be sync? right? If multiple clients send messages to the same message loop, then all those messages are queued and performed one after another, or? To process multiple messages in parallell, you would have to spawn multiple message loops in different processes, right? Or did I misunderstand all of it?

    Read the article

  • Strange behaviour with fputs and a loop.

    - by Jonathan
    When running the following code I get no output but I cannot work out why. # include <stdio.h> int main() { fputs("hello", stdout); while (1); return 0; } Without the while loop it works perfectly but as soon as I add it in I get no output. Surely it should output before starting the loop? Is it just on my system? Do I have to flush some sort of buffer or something? Thanks in advance.

    Read the article

  • In .NET which loop runs faster for or foreach

    - by Binoj Antony
    In c#/VB.NET/.NET which loop runs faster for or foreach? Ever since I read that for loop works faster than foreach a long time ago I assumed it stood true for all collections, generic collection all arrays etc. I scoured google and found few articles but most of them are inconclusive (read comments on the articles) and open ended. What would be ideal is to have each scenarios listed and the best solution for the same e.g: (just example of how it should be) for iterating an array of 1000+ strings - for is better than foreach for iterating over IList (non generic) strings - foreach is better than for Few references found on the web for the same: Original grand old article by Emmanuel Schanzer CodeProject FOREACH Vs. FOR Blog - To foreach or not to foreach that is the question asp.net forum - NET 1.1 C# for vs foreach [Edit] Apart from the readability aspect of it I am really interested in facts and figures, there are applications where the last mile of performance optimization squeezed do matter.

    Read the article

  • Using a Loop to add objects to a list(python)

    - by Will
    Hey guys so im trying to use a while loop to add objects to a list. Heres bascially what i want to do: (ill paste actually go after) class x: blah blah choice = raw_input(pick what you want to do) while(choice!=0): if(choice==1): Enter in info for the class: append object to list (A) if(choice==2): print out length of list(A) if(choice==0): break ((((other options)))) as im doing this i can get the object to get added to the list, but i am stuck as to how to add multiple objects to the list in the loop. Here is my actual code i have so far... print "Welcome to the Student Management Program" class Student: def init (self, name, age, gender, favclass): self.name = name self.age = age self.gender = gender self.fac = favclass choice = int(raw_input("Make a Choice: " )) while (choice !=0): if (guess==1): print("STUDENT") namer = raw_input("Enter Name: ") ager = raw_input("Enter Age: ") sexer = raw_input("Enter Sex: ") faver = raw_input("Enter Fav: ") elif(guess==2): print "TESTING LINE" elif(guess==3): print(len(a)) guess=int(raw_input("Make a Choice: ")) s = Student(namer, ager, sexer, faver) a =[]; a.append(s) raw_input("Press enter to exit") any help would be greatly appreciated!

    Read the article

  • Technical non-terminating condition in a loop

    - by Snarfblam
    Most of us know that a loop should not have a non-terminating condition. For example, this C# loop has a non-terminating condition: any even value of i. This is an obvious logic error. void CountByTwosStartingAt(byte i) { // If i is even, it never exceeds 254 for(; i < 255; i += 2) { Console.WriteLine(i); } } Sometimes there are edge cases that are extremely unlikeley, but technically constitute non-exiting conditions (stack overflows and out-of-memory errors aside). Suppose you have a function that counts the number of sequential zeros in a stream: int CountZeros(Stream s) { int total = 0; while(s.ReadByte() == 0) total++; return total; } Now, suppose you feed it this thing: class InfiniteEmptyStream:Stream { // ... Other members ... public override int Read(byte[] buffer, int offset, int count) { Array.Clear(buffer, offset, count); // Output zeros return count; // Never returns -1 (end of stream) } } Or more realistically, maybe a stream that returns data from external hardware, which in certain cases might return lots of zeros (such as a game controller sitting on your desk). Either way we have an infinite loop. This particular non-terminating condition stands out, but sometimes they don't. A completely real-world example as in an app I'm writing. An endless stream of zeros will be deserialized into infinite "empty" objects (until the collection class or GC throws an exception because I've exceeded two billion items). But this would be a completely unexpected circumstance (considering my data source). How important is it to have absolutely no non-terminating conditions? How much does this affect "robustness?" Does it matter if they are only "theoretically" non-terminating (is it okay if an exception represents an implicit terminating condition)? Does it matter whether the app is commercial? If it is publicly distributed? Does it matter if the problematic code is in no way accessible through a public interface/API? Edit: One of the primary concerns I have is unforseen logic errors that can create the non-terminating condition. If, as a rule, you ensure there are no non-terminating conditions, you can identify or handle these logic errors more gracefully, but is it worth it? And when? This is a concern orthogonal to trust.

    Read the article

  • Mystery regarding for-loop.

    - by primalpop
    Hi, I am stuck with this mystery regarding for loop. int abc[3], i, j; for(j=0; j<3; j++); printf("%d\n", j); abc[j] = abc[j] + 3; printf("%d \n", j); Output: 3 6 Output should have been 3,3 as I've not changed value of j. Adding 3 to the jth value of abc has resulted in change of value of j by 3. This happens only while exiting from a for loop and then trying to change the value of abc[j]. Maybe I am missing something pretty obvious. Any help would be much appreciated.

    Read the article

  • int and float increment condition in for loop [on hold]

    - by Mazaya Jamil
    I am doing a program that involves integer and float number.Let say I want to calculate atx={1,1/2,2,3,4} and want to use for-loop. But I know the condition of increment for(x=1;x<=4;x++) as x++=x+1. I want to find the iteration at x={1,2,3,4} and at x={1/2}. But I do not have idea how to modify the for-loop statement; either to make the increment of 0.5 or 1. But if I set 0.5, I will get the answers for 5/2 and 7/2 instead.

    Read the article

  • Problems with 'while' loop and 'for' loop when reading through file

    - by David Beckham
    I wasted plenty of hours trying to figure out the problem but no luck. Tried asking the TA at my school, but he was useless. I am a beginner and I know there are a lot of mistakes in it, so it would be great if I can get some detail explanation as well. Anyways, basically what I am trying to do with the following function is: Use while loop to check and see if random_string is in TEXT, if not return NoneType if yes, then use a for loop to read lines from that TEXT and put it in list, l1. then, write an if statement to see if random_string is in l1. if it is, then do some calculations. else read the next line Finally, return the calculations as a whole. TEXT = open('randomfile.txt') def random (TEXT, random_string): while random_string in TEXT: for lines in TEXT: l1=TEXT.readline().rsplit() if random_string in l1: ''' do some calculations ''' else: TEXT.readline() #read next line??? return #calculations return None

    Read the article

  • while(true) and loop-breaking - anti-pattern?

    - by KeithS
    Consider the following code: public void doSomething(int input) { while(true) { TransformInSomeWay(input); if(ProcessingComplete(input)) break; DoSomethingElseTo(input); } } Assume that this process involves a finite but input-dependent number of steps; the loop is designed to terminate on its own as a result of the algorithm, and is not designed to run indefinitely (until cancelled by an outside event). Because the test to see if the loop should end is in the middle of a logical set of steps, the while loop itself currently doesn't check anything meaningful; the check is instead performed at the "proper" place within the conceptual algorithm. I was told that this is bad code, because it is more bug-prone due to the ending condition not being checked by the loop structure. It's more difficult to figure out how you'd exit the loop, and could invite bugs as the breaking condition might be bypassed or omitted accidentally given future changes. Now, the code could be structured as follows: public void doSomething(int input) { TransformInSomeWay(input); while(!ProcessingComplete(input)) { DoSomethingElseTo(input); TransformInSomeWay(input); } } However, this duplicates a call to a method in code, violating DRY; if TransformInSomeWay were later replaced with some other method, both calls would have to be found and changed (and the fact that there are two may be less obvious in a more complex piece of code). You could also write it like: public void doSomething(int input) { var complete = false; while(!complete) { TransformInSomeWay(input); complete = ProcessingComplete(input); if(!complete) { DoSomethingElseTo(input); } } } ... but you now have a variable whose only purpose is to shift the condition-checking to the loop structure, and also has to be checked multiple times to provide the same behavior as the original logic. For my part, I say that given the algorithm this code implements in the real world, the original code is the most readable. If you were going through it yourself, this is the way you'd think about it, and so it would be intuitive to people familiar with the algorithm. So, which is "better"? is it better to give the responsibility of condition checking to the while loop by structuring the logic around the loop? Or is it better to structure the logic in a "natural" way as indicated by requirements or a conceptual description of the algorithm, even though that may mean bypassing the loop's built-in capabilities?

    Read the article

  • Parallel port with C#

    - by Michael S.
    Hello, I am trying to send data to LPT1 port with a C# program, unfortunately with no success.. I am using windows 7 x64. I tried both x86 and x64 (inpoutx64.dll) dll's.. With the x64 dll when I send: Output(888, 255); It just continues the program as everything went ok, but i can't see anything on my multimeter (only the static 0.02V).. I also tried the following with C++: int main () { int val = 0; printf("Enter a value\n"); scanf("%d", &val); _outp(0x378, val); getchar(); _outp(0x378, 0); return 0; } But it throws an exception: Unhandled exception at 0x01281428 in ppac.exe: 0xC0000096: Privileged instruction. I remember once I made something like this work on xp, I hope it's possible on win7 too.. Please help me with this. Thanks.

    Read the article

  • Parallel programming patterns for C#?

    - by VoidDweller
    With Intel's launch of a Hexa-Core processor for the desktop, it looks like we can no longer wait for Microsoft to make many-core programming "easy". I just order a copy of Joe Duffy's book Concurrent Programming on Windows. This looks like a great place to start, though, I am hoping some of you who have been targeting multi/many core systems would point me to some good resources that have or would have helped on your projects?

    Read the article

  • Multithreading or task parallel library

    - by Bruce Adams
    I have an application which performs 30 independent tasks simultaneously using multithreading, each task retrieves data over http, performs a calculation and returns a result to the ui thread. Can I use tpl to perform the same tasks? Does tpl create 30 new threads and spread them over all the available cores, or does it just split the tasks over the available cores and use one thread per core? Will there be a performance boost using tpl over multithreading in this case?

    Read the article

  • parallel-python error: RuntimeError("Socket connection is broken")

    - by user288558
    I am using a simple program to send a function: import pp nodes=('mosura02','mosura03','mosura04','mosura05','mosura06', 'mosura09','mosura10','mosura11','mosura12') nodes=('miner:60001',) def pptester(): js=pp.Server(ppservers=nodes) js.set_ncpus(0) tmp=[] for i in range(200): tmp.append(js.submit(ppworktest,(),(),('os',))) return tmp def ppworktest(): import os return os.system("uname -a") the result is: wkerzend@mosura:/home/wkerzend/tmp/ppython_test>ssh miner "source ~/coala_python_setup.sh;ppserver.py -d -p 60001" 2010-04-12 00:50:48,162 - pp - INFO - Creating server instance (pp-1.6.0) 2010-04-12 00:50:52,732 - pp - INFO - pp local server started with 32 workers 2010-04-12 00:50:52,732 - pp - DEBUG - Strarting network server interface=0.0.0.0 port=60001 Exception in thread client_socket: Traceback (most recent call last): File "/usr/lib64/python2.6/threading.py", line 525, in __bootstrap_inner self.run() File "/usr/lib64/python2.6/threading.py", line 477, in run self.__target(*self.__args, **self.__kwargs) File "/home/wkerzend/python_coala/bin/ppserver.py", line 161, in crun ctype = mysocket.receive() File "/home/wkerzend/python_coala/lib/python2.6/site-packages/pptransport.py", line 178, in receive raise RuntimeError("Socket connection is broken") RuntimeError: Socket connection is broken

    Read the article

  • Recommendations for Open Source Parallel programming IDE

    - by Andrew Bolster
    What are the best IDE's / IDE plugins / Tools, etc for programming with CUDA / MPI etc? I've been working in these frameworks for a short while but feel like the IDE could be doing more heavy lifting in terms of scaling and job processing interactions. (I usually use Eclipse or Netbeans, and usually in C/C++ with occasional Java, and its a vague question but I can't think of any more specific way to put it)

    Read the article

  • ksh : Need to delete multiple directories in parallel

    - by priya
    Hi , I have many directories and need to delete them periodically with minimum time. Additionally for each directories delete status need to know i.e whether deleted successfully or not. I need to write on the ksh . Could you please help me out. The sample code which I am using is not working. for var1 in 1...10 rm -rf & pid[var1]=$! done my_var=1 for my_var in 1...var1 wait $pid[my_var] if [ $? -eq 1 ] then echo falied else echo passed fi done

    Read the article

  • Task Parallel Library exception handling

    - by user1680766
    When handling exceptions in TPL tasks I have come across two ways to handle exceptions. The first catches the exception within the task and returns it within the result like so: var task = Task<Exception>.Factory.StartNew( () => { try { // Do Something return null; } catch (System.Exception e) { return e; } }); task.ContinueWith( r => { if (r.Result != null) { // Handle Exception } }); The second is the one shown within the documentation and I guess the proper way to do things: var task = Task.Factory.StartNew( () => { // Do Something }); task.ContinueWith( r => { if (r.Exception != null) { // Handle Aggregate Exception r.Exception.Handle(y => true); } }); I am wondering if there is anything wrong with the first approach? I have received 'unhandled aggregate exception' exceptions every now and again using this technique and was wondering how this can happen?

    Read the article

  • Parallel computation of the median of a large array

    - by recipriversexclusion
    I got asked this question once and still haven't been able to figure it out: You have an array of N integers, where N is large, say, a billion. You want to calculate the median value of this array. Assume you have m+1 machines (m workers, one master) to distribute the job to. How would you go about doing this? Since the median is a nonlinear operator, you can't just find the median in each machine and then take the median of those values.

    Read the article

< Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >