Search Results

Search found 8019 results on 321 pages for 'for loop'.

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

  • Label in PyQt4 GUI not updating with every loop of FOR loop

    - by user297920
    I'm having a problem, where I wish to run several command line functions from a python program using a GUI. I don't know if my problem is specific to PyQt4 or if it has to do with my bad use of python code. What I wish to do is have a label on my GUI change its text value to inform the user which command is being executed. My problem however, arises when I run several commands using a for loop. I would like the label to update itself with every loop, however, the program is not updating the GUI label with every loop, instead, it only updates itself once the entire loop is completed, and displays only the last command that was executed. I am using PyQt4 for my GUI environment. And I have established that the text variable for the label is indeed being updated with every loop, but, it is not actually showing up visually in the GUI. Is there a way for me to force the label to update itself? I have tried the update() and repaint() methods within the loop, but they don't make any difference. I would really appreciate any help. Thank you. Ronny. Here is the code I am using: # -*- coding: utf-8 -*- import sys, os from PyQt4 import QtGui, QtCore Gui = QtGui Core = QtCore # ================================================== CREATE WINDOW OBJECT CLASS class Win(Gui.QWidget): def __init__(self, parent = None): Gui.QWidget.__init__(self, parent) # --------------------------------------------------- SETUP PLAY BUTTON self.but1 = Gui.QPushButton("Run Commands",self) self.but1.setGeometry(10,10, 200, 100) # -------------------------------------------------------- SETUP LABELS self.label1 = Gui.QLabel("No Commands running", self) self.label1.move(10, 120) # ------------------------------------------------------- SETUP ACTIONS self.connect(self.but1, Core.SIGNAL("clicked()"), runCommands) # ======================================================= RUN COMMAND FUNCTION def runCommands(): for i in commands: win.label1.setText(i) # Make label display the command being run print win.label1.text() # This shows that the value is actually # changing with every loop, but its just not # being reflected in the GUI label os.system(i) # ======================================================================== MAIN # ------------------------------------------------------ THE TERMINAL COMMANDS com1 = "espeak 'senntence 1'" com2 = "espeak 'senntence 2'" com3 = "espeak 'senntence 3'" com4 = "espeak 'senntence 4'" com5 = "espeak 'senntence 5'" commands = (com1, com2, com3, com4, com5) # --------------------------------------------------- SETUP THE GUI ENVIRONMENT app = Gui.QApplication(sys.argv) win = Win() win.show() sys.exit(app.exec_())

    Read the article

  • How does this game loop actually work?

    - by Nicolai
    I read this playfulJS post, about ray-casting: http://www.playfuljs.com/a-first-person-engine-in-265-lines/ It looks really interested, so I decided to look at his javascript. I am no expert in javascript, so I quickly got lost. It's the game loop "object" that really gets me. I simply don't understand how it works. From the code: function GameLoop() { this.frame = this.frame.bind(this); this.lastTime = 0; this.callback = function() {}; } GameLoop.prototype.start = function(callback) { this.callback = callback; requestAnimationFrame(this.frame); }; GameLoop.prototype.frame = function(time) { var seconds = (time - this.lastTime) / 1000; this.lastTime = time; if (seconds < 0.2) this.callback(seconds); requestAnimationFrame(this.frame); }; var loop = new GameLoop(); loop.start(function frame(seconds) { map.update(seconds); player.update(controls.states, map, seconds); camera.render(player, map); }); Now, what really confuses me here, is this bind stuff and how this actually loops. I am guessing, that if less than 0.2 seconds have passed, since the last time the loop was run, it simply goes back to re-check the time. If more than 0.2 seconds have passed, it leaves the frame function, and executes the 3 lines in the loop. But, if this is true, then how does the loop.start() get called again? And what on earth is the meaning of this.frame = this.frame.bind(this);? I've looked up prototypes bind() but I really don't understand it.

    Read the article

  • In Perl, is a while loop generally faster than a for loop?

    - by Mike
    I've done a small experiment as will be shown below and it looks like that a while loop is faster than a for loop in Perl. But since the experiment was rather crude, and the subject might be a lot more complicated than it seems, I'd like to hear what you have to say about this. Thanks as always for any comments/suggestions :) In the following two small scripts, I've tried while and for loops separately to calcaulte the factorial of 100,000. The one that has the while loop took 57 minutes 17 seconds to finish while the for loop equivalent took 1 hour 7 minutes 54 seconds. Script that has while loop: use strict; use warnings; use bigint; my $now = time; my $n =shift; my $s=1; while(1){ $s *=$n; $n--; last if $n==2; } print $s*$n; $now = time - $now; printf("\n\nTotal running time: %02d:%02d:%02d\n\n", int($now / 3600), int(($now % 3600) / 60), int($now % 60)); Script that has for loop: use strict; use warnings; use bigint; my $now = time; my $n =shift; my $s=1; for (my $i=2; $i<=$n;$i++) { $s = $s*$i; } print $s; $now = time - $now; printf("\n\nTotal running time: %02d:%02d:%02d\n\n", int($now / 3600), int(($now % 3600) / 60), int($now % 60));

    Read the article

  • Help with converting foreach loop to while loop in c#

    - by James Dawson
    I had learnt by reading your great answers here, that it is not good practice deleting items from within a foreach loop, as it is (and I quote) "Sawing off the branch you're sitting on". My code currently removes the text from the dropdownlist, but the actual item remains (just without text displayed). In other words, it isn't deleting, and probably can't because you can't delete from within a foreach loop. After hours of trying I am unable to get my head around a way of doing it. //For each checked box, run the delete code for (int i = 0; i < this.organizeFav.CheckedItems.Count; i++) { //this is the foreach loop foreach (ToolStripItem mItem in favoritesToolStripMenuItem.DropDownItems) { //This rules out seperators if (mItem is ToolStripMenuItem) { ToolStripMenuItem menuItem = mItem as ToolStripMenuItem; //This matches the dropdownitems text to the CheckedItems String if (((ToolStripMenuItem)mItem).Text.ToString() == organizeFav.CheckedItems[i].ToString()) { //And deletes the item menuItem.DropDownItems.Remove(mItem); } } } } But it isn't deleting because it is within a foreach loop! I would greatly appreciate your help, and be truly amazed if anyone can get their head around this code :) Kind Regards

    Read the article

  • breaking out of for loop when running a function inside a for loop

    - by andrewj
    I'm embarrassed that I'm asking this question, but here I go: Suppose you have the following function foo. When I'm running a for loop, I'd like it to skip the remainder of foo when foo initially returns the value of 0. However, break doesn't work when it's inside a function. As it's currently written, I get an error message, no loop to break from, jumping to top level. Any suggestions? foo <- function(x) { y <- x-2 if (y==0) {break} # how do I tell the for loop to skip this z <- y + 100 z } for (i in 1:3) { print(foo(i)) }

    Read the article

  • breaking out of for loop when running a function inside a for loop in R

    - by andrewj
    I'm embarrassed that I'm asking this question, but here I go: Suppose you have the following function foo. When I'm running a for loop, I'd like it to skip the remainder of foo when foo initially returns the value of 0. However, break doesn't work when it's inside a function. As it's currently written, I get an error message, no loop to break from, jumping to top level. Any suggestions? foo <- function(x) { y <- x-2 if (y==0) {break} # how do I tell the for loop to skip this z <- y + 100 z } for (i in 1:3) { print(foo(i)) }

    Read the article

  • Need to convert this for loop to a while loop

    - by Bragaadeesh
    Hi guys, I solved a problem recently. But I have this one piece of code where I dont utilize the for loop initialization and condition check. It looks a bit odd that way for a for loop. I want to convert it into a while loop. Please help me do it. I tried many times, but somewhere something is missing. for(;;current =(current+1)%n){ if(eliminated[current%n]){ continue; }else{ inkiPinki++; if(inkiPinki == m){ eliminated[current%n] = true; printStatus(eliminated, people); remainingGuys--; break; } } } In the above code eliminiated[index] is a boolean.

    Read the article

  • for loop will not loop

    - by Bjørn Jostein Aurheim
    I have a for loop that I will use to compute time intervals to add to an ArrayList. The problem is that I can not prove that the for loop is being executed. Nothing is printed when using the system.out.println() statement, and nothing is added to the array from inside the loop ... any sugestions? // lager tidspunkter og legger disse inn i en Array kalt tider tid.setTimer(16); tid.setMinutter(0); tid.setSekunder(0); tider.add(tid.asString());// String "16:00" is added as it should System.out.println("tiden er: "+tid.asString());// gives 16:00 printed for(int i=0;i>12;i++){ System.out.println("er i løkken");// gives nothing printed tid.increaseMinutter(30); System.out.println(tid.asString());// gives nothing printed tider.add(tid.asString()); }

    Read the article

  • Rewriting .each() loop as for loop to optimize, how to replicate $(this).attr()

    - by John B
    I running into some performance issues with a jquery script i wrote when running in ie so I'm going through it trying to optimize any way possible. Apparently using for loops is way faster than using the jQuery .each method. This has led me to a question regarding the equivalent of $(this) inside a for loop. I'm simplifying what I'm doing in my loop down to just using an attr() function as it gets across my main underlying question. Im doing this with each(simplified) var existing = $('#existing'); existing.each(function(){ console.log($(this).attr('id')); }); And I've tried rewriting it as a for loop as such: var existing = $('#existing'); for(var i = 0;i < existing.length;i++) { console.log(existing[i].attr('id')); } Its throwing an error saying: Uncaught TypeError: Object #<HTMLDivElement> has no method 'attr' Thanks.

    Read the article

  • Limiting game loop to exactly 60 tics per second (Android / Java)

    - by user22241
    So I'm having terrible problems with stuttering sprites. My rendering and logic takes less than a game tic (16.6667ms) However, although my game loop runs most of the time at 60 ticks per second, it sometimes goes up to 61 - when this happens, the sprites stutter. Currently, my variables used are: //Game updates per second final int ticksPerSecond = 60; //Amount of time each update should take final int skipTicks = (1000 / ticksPerSecond); This is my current game loop @Override public void onDrawFrame(GL10 gl) { // TODO Auto-generated method stub //This method will run continuously //You should call both 'render' and 'update' methods from here //Set curTime initial value if '0' //Set/Re-set loop back to 0 to start counting again loops=0; while(System.currentTimeMillis() > nextGameTick && loops < maxFrameskip){ SceneManager.getInstance().getCurrentScene().updateLogic(); //Time correction to compensate for the missing .6667ms when using int values nextGameTick+=skipTicks; timeCorrection += (1000d/ticksPerSecond) % 1; nextGameTick+=timeCorrection; timeCorrection %=1; //Increase loops loops++; } render(); } I realise that my skipTicks is an int and therefore will come out as 16 rather that 16.6667 However, I tried changing it (and ticksPerSecond) to Longs but got the same problem). I also tried to change the timer used to Nanotime and skiptics to 1000000000/ticksPerSecond, but everything just ran at about 300 ticks per seconds. All I'm attempting to do is to limit my game loop to 60 - what is the best way to guarantee that my game updates never happen at more than 60 times a second? Please note, I do realise that very very old devices might not be able to handle 60 although I really don't expect this to happen - I've tested it on the lowest device I have and it easily achieves 60 tics. So I'm not worried about a device not being able to handle the 60 ticks per second, but rather need to limit it - any help would be appreciated.

    Read the article

  • Turn-based Strategy Loop

    - by Djentleman
    I'm working on a strategy game. It's turn-based and card-based (think Dominion-style), done in a client, with eventual AI in the works. I've already implemented almost all of the game logic (methods for calculations and suchlike) and I'm starting to work on the actual game loop. What is the "best" way to implement a game loop in such a game? Should I use a simple "while gameActive" loop that keeps running until gameActive is False, with sections that wait for player input? Or should it be managed through the UI with player actions determining what happens and when? Any help is appreciated. I'm doing it in Python (for now at least) to get my Python skills up a bit, although the language shouldn't matter for this question.

    Read the article

  • How to add more /dev/loop* devices on Fedora 19

    - by user219372
    How to add more /dev/loop* devices on Fedora 19? I do: # uname -r 3.11.2-201.fc19.x86_64 # lsmod |grep loop # ls /dev/loop* /dev/loop0 /dev/loop1 /dev/loop2 /dev/loop3 /dev/loop4 /dev/loop5 /dev/loop6 /dev/loop7 /dev/loop-control # modprobe loop max_loop=128 # ls /dev/loop* /dev/loop0 /dev/loop1 /dev/loop2 /dev/loop3 /dev/loop4 /dev/loop5 /dev/loop6 /dev/loop7 /dev/loop-control So nothing changes.

    Read the article

  • Trying to create an infinite for loop that can stop using function doIt()

    - by JoeOzz
    Hey guys, I'm new to javascript and I'm doing a project for my final in class. I need to make it so this game engine I manipulated causes the generation button to go for an infinite loop. I also need to stop it using (Reset==1). Any help? Here's the code I have so far if that helps: function generation() { for(y2=0; y2<2500; y2++) { tempmapactual[y2]=mapactual[y2]; } for (g=0;g<2500;g++) { neighbours=0; for (h=0;h<8;h++) { if (g+coords[h]>0 && g+coords[h]<2499 && mapactual[g+coords[h]]=="white.gif") {neighbours=neighbours+1;} } if (neighbours>=4 || neighbours==1 || neighbours==0) {tempmapactual[g]="black.gif";} if (neighbours==3) {tempmapactual[g]="white.gif";} } for(y3=0; y3<2500; ++y3) { if (mapactual[y3]!=tempmapactual[y3]) { mapactual[y3]=tempmapactual[y3]; document.images[y3+offset].src=mapactual[y3]; } } } </script> <script> function doIt() { for (i=0; i<X; i++) { // This is where I have trouble. What part of generation() do I call? } if (Reset==1) break; // This will kill the loop instantly. } } </script> <script> window.onload(doIt($(X).value))); </script> <form> <input type="button" value="generate" onClick="generation();"> </form> <form> <input type="text"> </form> <form> <input type="button" value="Infinite Loop!" onclick="doIt();"> </form> <form> <input type="button" value="Reset" onclick="doIt();"> </form>

    Read the article

  • PHP foreach loop through multidimensional array

    - by Muiter
    I have an multidimensional array, how can I use it? I want to use each seperate array in an for loop. I have this code <?php foreach ($calculatie_id[$i] as $value) { echo $value; } ? print_r($calculatie_id); gives Array ( [0] = Array ( [0] = 4 [1] = 6 ) [1] = Array ( [0] = 1 [1] = 5 ) [2] = Array ( [0] = 5 [1] = 6 ) [3] = ) But when using the foreach I only get 46

    Read the article

  • How to make this game loop deterministic

    - by Lanaru
    I am using the following game loop for my pacman clone: long prevTime = System.currentTimeMillis(); while (running) { long curTime = System.currentTimeMillis(); float frameTime = (curTime - prevTime) / 1000f; prevTime = curTime; while (frameTime > 0.0f) { final float deltaTime = Math.min(frameTime, TIME_STEP); update(deltaTime); frameTime -= deltaTime; } repaint(); } The thing is, I don't always get the same ghost movement every time I run the game (their logic is deterministic), so it must be the game loop. I imagine it's due to the final float deltaTime = Math.min(frameTime, TIME_STEP); line. What's the best way of modifying this to perform the exact same way every time I run it? Also, any further improvements I can make?

    Read the article

  • PHP: Loop or no loop?

    - by Joseph Robidoux
    In this situation, is it better to use a loop or not? echo "0"; echo "1"; echo "2"; echo "3"; echo "4"; echo "5"; echo "6"; echo "7"; echo "8"; echo "9"; echo "10"; echo "11"; echo "12"; echo "13"; or $number = 0; while ($number != 13) { echo $number; $number = $number + 1; }

    Read the article

  • Addind the sum of numbers using a loop statement

    - by Deonna
    I need serious help diving the positive numbers and the negative numbers. I am to accumulate the total of the negative values and separately accumulate the total of the positive values. After the loop, you are then to display the sum of the negative values and the sum of the positive values. The data is suppose to look like this: -2.3 -1.9 -1.5 -1.1 -0.7 -0.3 0.1 0.5 0.9 1.3 1.7 2.1 2.5 2.9 Sum of negative values: -7.8 Sum of positive values: 12 So far I have this: int main () { int num, num2, num3, num4, num5, sum, count, sum1; int tempVariable = 0; int numCount = 100; int newlineCount = 0, newlineCount1 = 0; float numCount1 = -2.3; while (numCount <= 150) { cout << numCount << " "; numCount += 2; newlineCount ++; if(newlineCount == 6) { cout<< " " << endl; newlineCount = 0; } } **cout << "" << endl; while (numCount1 <=2.9 ) { cout << numCount1 << " "; numCount1 += 0.4; newlineCount1 ++; } while ( newlineCount1 <= 0 && newlineCount >= -2.3 ); cout << "The sum is " << newlineCount1 << endl;** return 0; }

    Read the article

  • Recommended main loop style

    - by Frootmig-H
    I've just begun attempting an FPS with JMonkeyEngine, but I'm currently stuck as to the best way to implement the main loop - especially with regards to non-instantaneous user actions. By that, I mean things like reloading a weapon. The user starts the action, and it continues for a while with an animation and some sound, and when it completes, game state updates. (I should mention that it's not technically a loop, it's an update method, called as often as possible. Is that different? Me no understand terminology). So, far I've considered : Animation driven Player presses reload Start reload animation If user stars another action, abort animation, start new action. When the animation_complete event is received (JMonkeyEngine provides this), update ammo counters. Event driven Player presses reload Start reload animation Queue up a out-of-thread method to be called at time t + (duration of reload animation) If user starts another action, cancel both animation and queued method. When queued method executes, update ammo. This avoids relying on the animation event (JMonkeyEngine has a particular quirk), but brings in the possibility of thread problems. 'Blocking' (not sure of the correct term) Player presses reload Start reloading animation reloading = true reloadedStartTime = now while (reloading && ((now - reloadingStartTime) < reloadingDuration)) { If user starts another action, break and cancel reloading. } Update ammo counters reloading = false My main concern is that actions can interrupt each other. Reloading can be interrupted by firing, or by dropping or changing weapon, crouching can be interrupted by running, etc. What's the recommended way to handle this? What are the advantages and disadvantages of each method? I'm leaning towards event-driven, even though it requires more care; failing that, blocking.

    Read the article

  • HTML5/JS - Choppy Game Loop

    - by Rikonator
    I have been experimenting with HTML5/JS, trying to create a simple game when I hit a wall. My choice of game loop is too choppy to be actually of any use in a game. I'm trying for a fixed time step loop, rendering only when required. I simply use a requestAnimationFrame to run Game.update which finds the elapsed time since the last update, and calls State.update to update and render the current state. State.prototype.update = function(ms) { this.ticks += ms; var updates = 0; while(this.ticks >= State.DELTA_TIME && updates < State.MAX_UPDATES) { this.updateState(); this.updateFrameTicks += State.DELTA_TIME; this.updateFrames++; if(this.updateFrameTicks >= 1000) { this.ups = this.updateFrames; this.updateFrames = 0; this.updateFrameTicks -= 1000; } this.ticks -= State.DELTA_TIME; updates++; } if(updates > 0) { this.renderFrameTicks += updates*State.DELTA_TIME; this.renderFrames++; if(this.renderFrameTicks >= 1000) { this.rps = this.renderFrames; this.renderFrames = 0; this.renderFrameTicks -= 1000; } this.renderState(updates*State.DELTA_TIME); } }; But this strategy does not work very well. This is the result: http://jsbin.com/ukosuc/1 (Edit). As it is apparent, the 'game' has fits of lag, and when you tab out for a long period and come back, the 'game' behaves unexpectedly - updates faster than intended. This is either a problem due to something about game loops that I don't quite understand yet, or a problem due to implementation which I can't pinpoint. I haven't been able to solve this problem despite attempting several variations using setTimeout and requestAnimationFrame. (One such example is http://jsbin.com/eyarod/1/edit). Some help and insight would really be appreciated!

    Read the article

  • Mixing Objective-C and C++: Game Loop Parts

    - by Peteyslatts
    I'm trying to write all of my game in C++ except for drawing and game loop timing. Those parts are going to be in Objective-C for iOS. Right now, I have ViewController handling the update cycle, but I want to create a GameModel class that ViewController could update. I want GameModel to be in C++. I know how to integrate these two classes. My problem is how to have these two parts interact with the drawing and image loading. GameModel will keep track of a list of children of type GameObject. These GameObjects update every frame, and then need to pass position and visibility data to whatever class or method will handle drawing. I feel like I'm answering my own question now (talking it out helps) but would it be a good idea to put all of the visible game objects into an array at the end of the update method, return it, and use that to update graphics inside ViewController?

    Read the article

  • javascript game loop and game update design

    - by zuo
    There is a main game loop in my program, which calls game update every frame. However, to make better animation and better control, there is a need to implement a function like updateEveryNFrames(n, func). I am considering implementing a counter for each update. The counter will be added by one each frame. The update function will be invoked according to the counter % n. For example, in a sequence of sprites animation, I can use the above function to control the speed of the animation. Can some give some advice or other solutions?

    Read the article

  • Why is this PHP loop rendering every row twice?

    - by Christopher
    I'm working on a real frankensite here not of my own design. There's a rudimentary CMS and one of the pages shows customer records from a MySQL DB. For some reason, it has no probs picking up the data from the DB - there's no duplicate records - but it renders each row twice. The page PHP is viewable at http://christopher.pastebin.com/DQkjjG3s (attempted to include in this post but it was horribly mangled, think it's important to have it all in context). I'm not the world's best PHP expert but I think I can see an error in a for loop when there is one... But everything looks ok to me. You'll notice that the customer name is clickable; clicking takes you to another page where you can view their full info as held in the DB - and for both rows, the customer ID is identical, and manually checking the DB shows there's no duplicate entries. The code is definitely rendering each row twice, but for what reason I have no idea. All pointers / advice appreciated.

    Read the article

  • Passing elapsed time to the update function from the game loop

    - by Sri Harsha Chilakapati
    I want to pass the time elapsed to the update() method as this would make easy to implement the animations and time related concepts. Here's my game-loop. public void gameLoop(){ boolean running = true; long gameTime = getCurrentTime(); long elapsedTime = 0; long lastUpdateTime = 0; int loops; while (running){ loops = 0; while(getCurrentTime()>gameTime && loops<Global.MAX_FRAMESKIP){ elapsedTime = getCurrentTime() - lastUpdateTime; lastUpdateTime = getCurrentTime(); update(elapsedTime); gameTime += SKIP_STEPS; loops++; } displayGame(); } } getCurrentTime() method public long getCurrentTime(){ return (System.nanoTime()/1000000); } update() method long time = 0; public void update(long elapsedTime){ time += elapsedTime; if (time>=1000){ System.out.println("A second elapsed"); time -= 1000; } } But this is printing the message for 3 seconds. Thanks.

    Read the article

  • Which is better Java programming practice for looping up to an int value: a converted for-each loop

    - by Arvanem
    Hi folks, Given the need to loop up to an arbitrary int value, is it better programming practice to convert the value into an array and for-each the array, or just use a traditional for loop? FYI, I am calculating the number of 5 and 6 results ("hits") in multiple throws of 6-sided dice. My arbitrary int value is the dicePool which represents the number of multiple throws. As I understand it, there are two options: Convert the dicePool into an array and for-each the array: public int calcHits(int dicePool) { int[] dp = new int[dicePool]; for (Integer a : dp) { // call throwDice method } } Use a traditional for loop. public int calcHits(int dicePool) { for (int i = 0; i < dicePool; i++) { // call throwDice method } } I apologise for the poor presentation of the code above (for some reason the code button on the Ask Question page is not doing what it should). My view is that option 1 is clumsy code and involves unnecessary creation of an array, even though the for-each loop is more efficient than the traditional for loop in Option 2. Thanks in advance for any suggestions you might have.

    Read the article

  • Using foreach loop.

    - by Harikrishna
    I break the code of the for loop without using break like I have for loop given below.And when i is 1 or 2 or 3 or any else but if condition is true then loop will be terminated because i will be 5 if the condition is true.And so NO need of break is needed there.Beacause I do not want to use break.I have done like this here.It works. bool myCondition=false; for(int i=0;i<5;i++) { if(myCondition) { i=5; } } But now I want to use foreach loop and in this loop when some condition is true then I want to break the foreach loop code.So what should I do here for breaking the foreach loop code without using break ? Like in the above for loop I have initialize i to 5 when condition is true.In the foreach loop anything like that to do to avoid break.

    Read the article

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