Search Results

Search found 8557 results on 343 pages for 'infinite loop'.

Page 31/343 | < Previous Page | 27 28 29 30 31 32 33 34 35 36 37 38  | Next Page >

  • Distinguishing between failure and end of file in read loop

    - by celtschk
    The idiomatic loop to read from an istream is while (thestream >> value) { // do something with value } Now this loop has one problem: It will not distinguish if the loop terminated due to end of file, or due to an error. For example, take the following test program: #include <iostream> #include <sstream> void readbools(std::istream& is) { bool b; while (is >> b) { std::cout << (b ? "T" : "F"); } std::cout << " - " << is.good() << is.eof() << is.fail() << is.bad() << "\n"; } void testread(std::string s) { std::istringstream is(s); is >> std::boolalpha; readbools(is); } int main() { testread("true false"); testread("true false tr"); } The first call to testread contains two valid bools, and therefore is not an error. The second call ends with a third, incomplete bool, and therefore is an error. Nevertheless, the behaviour of both is the same. In the first case, reading the boolean value fails because there is none, while in the second case it fails because it is incomplete, and in both cases EOF is hit. Indeed, the program above outputs twice the same line: TF - 0110 TF - 0110 To solve this problem, I thought of the following solution: while (thestream >> std::ws && !thestream.eof() && thestream >> value) { // do something with value } The idea is to detect regular EOF before actually trying to extract the value. Because there might be whitespace at the end of the file (which would not be an error, but cause read of the last item to not hit EOF), I first discard any whitespace (which cannot fail) and then test for EOF. Only if I'm not at the end of file, I try to read the value. For my example program, it indeed seems to work, and I get TF - 0100 TF - 0110 So in the first case (correct input), fail() returns false. Now my question: Is this solution guaranteed to work, or was I just (un-)lucky that it happened to give the desired result? Also: Is there a simpler (or, if my solution is wrong, a correct) way to get the desired result?

    Read the article

  • How can I make an iterator that never ends?

    - by Soldier.moth
    I was just wondering what the easiest way to iterate over a set indefinitely, i.e. when it reaches the end it next(); calls the first object. I'm assuming that this is not an already predefined function in Java, so just looking for the easiest way to implement this in Java.

    Read the article

  • Using locks inside a loop

    - by Xaqron
    // Member Variable private readonly object _syncLock = new object(); // Now inside a static method foreach (var lazyObject in plugins) { if ((string)lazyObject.Metadata["key"] = "something") { lock (_syncLock) { if (!lazyObject.IsValueCreated) lazyObject.value.DoSomething(); } return lazyObject.value; } } Here I need synchronized access per loop. There are many threads iterating this loop and based on the key they are looking for, a lazy instance is created and returned. lazyObject should not be created more that one time. Although Lazy class is for doing so and despite of the used lock, under high threading I have more than one instance created (I track this with a Interlocked.Increment on a volatile shared int and log it somewhere). The problem is I don't have access to definition of Lazy and MEF defines how the Lazy class create objects. My questions: 1) Why the lock doesn't work ? 2) Should I use an array of locks instead of one lock for performance improvement ?

    Read the article

  • Scala create xhtml elements dynamically

    - by portoalet
    Given a String array val www = List("http://bloomberg.com", "http://marketwatch.com"); I want to dynamically generate <span id="span1">http://bloomberg.com</span> <span id="span2">http://marketwatch.com</span> def genSpan(web: String) = <span id="span1"> + web + </span>; www.map(genSpan); // How can I pass the loop index? How can I use scala map function to generate the ids (span1, span2), as 1 and 2 are the loop indexes ? Or is the only way is to use for comprehension?

    Read the article

  • updating a shape in scene with a for loop using javafx

    - by Susanta
    Following is a code fragment. I am updating a rectangle using a for loop when a button is pressed. This is a model for my ultimate intention of showing visualization of data model as it changes large number of times inside a for loop. It works but I see only one change. Now since I am changing the width randomly I should see large number of changes. It seems I am making a wrong assumption on something basic. The code goes below: 7 var rec: Rectangle = Rectangle { 8 x: 10, y: 10 9 width: 140, height: 90 10 fill: Color.BLACK 11 } 12 13 Stage { 14 title: "MyApp" 15 scene: Scene { 16 width: 200 17 height: 200 18 content: [ 19 rec, 20 Button { 21 text: "Button" 22 action: function () { 23 for (i in [1..999]) { 24 rec.width = 25 + java.lang.Math.random()*50; 25 } 26 } 27 } 28 ] 29 } 30 }

    Read the article

  • Substituting variables in a loop?

    - by jksl
    I am trying to write a loop in R but I think the nomenclature is not correct as it does not create the new objects, here is a simplified example of what I am trying to do: for i in (1:8) { List_i <-List colsToGrab_i <-grep(predefinedRegex_i, colnames(List_i$table)) List_i$table <- List_i$table[,predefinedRegex_i] } I have created 'predefinedRegex'es 1:8 which the grep should use to search The loop creates an object called "List_i" and then fails to find "predefinedRegex_i". I have tried putting quotes around the "i" and $ in front of the i but these do not work. Any help much appreciated. Thank you.

    Read the article

  • .bat for shutdown/reboot on xp loop problem

    - by Luca
    hello! i have a little problem... on win xp, if i write on commandline shutdown -t 00 -r -f the reboot works fine. but if i paste it, as is, in a bat file...the prompt show me an infinite loop. anyone can say me why? thanks a lot for any suggestion :)

    Read the article

  • How can use foreach to Loop Through PHP Array

    - by jtom
    How can use foreach loop to loop through the $Result? $Query = mysql_query("SELECT * FROM mytable"); $Result = array( ); while ($Row = mysql_fetch_array ( $Query) ) { $Result [ ] = $Row; } mysql_free_result($Query); print_r ($Result); ? I just have very vague idea: foreach ($Result ) { echo $row[fname] . ' ' . $row[lname] . ' ' $row[email]; } ? Could someone help please?

    Read the article

  • java nested for() loop throws ArrayIndexOutOfBoundsException

    - by Mike
    I'm working through a JPanel exercise in a Java book. I'm tasked with creating a 5x4 grid using GridLayout. When I loop through the container to add panels and buttons, the first add() throws the OOB exception. What am I doing wrong? package mineField; import java.awt.*; import javax.swing.*; @SuppressWarnings("serial") public class MineField extends JFrame { private final int WIDTH = 250; private final int HEIGHT = 120; private final int MAX_ROWS = 5; private final int MAX_COLUMNS = 4; public MineField() { super("Minefield"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container mineFieldGrid = getContentPane(); mineFieldGrid.setLayout(new GridLayout(MAX_ROWS, MAX_COLUMNS)); // loop through arrays, add panels, then add buttons to panels. for (int i = 0; i < MAX_ROWS; i++) { JPanel[] rows = new JPanel[i]; mineFieldGrid.add(rows[i], rows[i].getName()); rows[i].setBackground(Color.blue); for (int j = 0; j < MAX_COLUMNS; j++) { JButton[] buttons = new JButton[i]; rows[i].add(buttons[j], buttons[j].getName()); } } mineFieldGrid.setSize(WIDTH, HEIGHT); mineFieldGrid.setVisible(true); } public int setRandomBomb(Container con) { int bombID; bombID = (int) (Math.random() * con.getComponentCount()); return bombID; } /** * @param args */ public static void main(String[] args) { //int randomBomb; //JButton bombLocation; MineField minePanel = new MineField(); //minePanel[randomBomb] = minePanel.setRandomBomb(minePanel); } } I'm sure I'm over-engineering a simple nested for loop. Since I'm new to Java, please be kind. I'm sure I'll return the favor some day.

    Read the article

  • Java: empty ArrayLists in a foor loop

    - by Patrick
    hi, I'm reusing the same ArrayList in a for loop, and I use for loop results = new ArrayList<Integer>(); experts = new ArrayList<Integer>(); output = new ArrayList<String>(); .... to create new ones. I guess this is wrong, because I'm allocating new memory. Is this correct ? If yes, how can I empty them ? Added: another example I'm creating new variables each time I call this method. Is this good practice ? I mean to create new precision, relevantFound.. etc ? Or should I declare them in my class, outside the method to not allocate more and more memory ? public static void computeMAP(ArrayList results, ArrayList experts) { //compute MAP double precision = 0; int relevantFound = 0; double sumprecision = 0; thanks

    Read the article

  • Running for loop depending on size of string vector

    - by xbonez
    I have made a string vector vector actor_; and then added elements in it using push_back. I now want to display all of them, for which I need to run a loop according to the number of elements in the vector. For that, I need to run the following loop: for (int i = 0; i < (int)actor_.size; i++) { } but this returns the following error: error C2440: 'type cast' : cannot convert from 'unsigned int (__thiscall std::vector<_Ty::* )(void) const' to 'int' 1 with 1 [ 1 _Ty=std::string 1 ] 1 There is no context in which this conversion is possible

    Read the article

  • Partition loop understanding

    - by user1795732
    Why the loop body of the partition method never throws an ArrayIndexOutOfBounds Exception? public static int partition( int[] a, low, high ) { int k = low, m = low; /* loop invariant: * low <= k <= m <= high and * all elements in a[low..k-1] are RED (i.e., < pivot) and * all elements in a[k..m-1] are BLUE (i.e., >= pivot) */ while (m != high) { if (a[m] >= pivot) // a[m] is BLUE { } else { // a[m] is RED swap(a,k,m); k = k+1; } m = m+1; } return k; }

    Read the article

  • Commit In loop gives wrong output?

    - by Vineet
    I am trying to insert 1 to 10 numbers except 6and 8 in table messages,but when i fetch it from table mesages1, output is coming in this order 4 5 7 9 10 1 2 3 It should be like this 1 2 3 4 5 7 9 10 According to the logic ,it works fine when i omit commit or put it some where else, Please explain why it is happening? this is my code. BEGIN FOR i IN 1..10 LOOP IF i<>6 AND i<>8 THEN INSERT INTO messages1 VALUES (i); END IF; commit; END LOOP; END; select * from messages1;

    Read the article

  • Loop on enumeration values

    - by Rachel
    How awful is it - or is it perfectly acceptable - to index a loop on an enumeration? I have an enumeration defined. The values of the literals are default values. The assigned values do not have any significance, will not have any significance, and the values of any literals added in the future will also not have any significance. It's just defined to limit the allowed values and to make things easier to follow. Therefore the values will always start at 0 and increase by 1. Can I set up a loop like so: enum MyEnum { value1, value2, value3, maxValue } for(MyEnum i = value1; i < maxValue; i = static_cast<MyEnum>(i+1)){}

    Read the article

  • Wordpress meta data is written on top of page instead of the loop

    - by Fruxelot
    i'm building a wordpress webpage based on the Skeleton Wordpress theme. I have 2 posts showing on a page and each of these posts have custom fields values (meta data). Im using the shortcode from the skeleton theme to get a post-feed from a specific category and in that loop i have inserted this tag that displays the custom fields data <?php the_meta(); ?> I am getting the data - but the problem is, the data is shown on TOP of the page instead of inside the in the post. What could've ive possibly done wrong? or is it something with skeleton i am doing wrong? Webpage : http://visbyfangelse.se.preview.binero.se/rum-priser-preview/ as you can see two posts are shown - and the meta data is shown on the top of the page. Code to the loop : http://pastebin.com/mRQY5GNz As you can see i want the meta displayed in the div which i assigned this class to "my_room_meta".

    Read the article

  • How to optimize foreach loop in PHP

    - by vanneto
    First off, I know the title is generic and not fitting. I just couldn't think of a title that could describe my problem. I have a table Recipients in MySQL structured like this: id | email | status 1 foo@bar S 2 bar@baz S 3 abc@def R 4 sta@cko B I need to convert the data into the following XML, depending on the status field. For example: <Recipients> <RecipientsSent> <!-- Have the 'S' status --> <recipient>foo@bar</recipient> <recipient>bar@baz</recipient> </RecipientsSent> <RecipientsRegexError> <recipient>abc@def</recipient> </RecipientsRegexError> <RecipientsBlocked> <recipient>sta@cko</recipient> </RecipientsBlocked> </Recipients> I have this PHP code to implement this ($recipients contains an associative array of the db table): <Recipients> <RecipientsSent> <?php foreach ($recipients as $recipient): if ($recipient['status'] == 'S'): echo "<recipient>" . $recipient['email'] . "</recipient>"; endif; endforeach; ?> </RecipientsSent> <RecipientsRegexError> <?php foreach ($recipients as $recipient): if ($recipient['status'] == 'R'): echo "<recipient>" . $recipient['email'] . "</recipient>"; endif; endforeach; ?> </RecipientsRegexError> <?php /** same loop for the B status */ ?> </Recipients> So, this means that if I have 1000 entries in the table and 4 different status' that can be checked, it means that there will be 4 loops, each one executing 1000 times. How can this be done in a more efficient manner? I thought about fetching four different sets from the database, meaning 4 different queries, would that be more efficient? I'm thinking it could be done with one loop but but I can't come up with a solution. Any way this could be done with only one loop?

    Read the article

  • C# background worker and timer loop

    - by Mike
    This is my first attempt of a Timer, if someone could help me out where I am going wrong it would be awesome. I'm trying to use a while loop where if the timer hits 30 seconds try to loop it again. private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { System.Windows.Forms.Timer my_timer = new System.Windows.Forms.Timer(); my_timer = null; //int restartticker = 30000; while (true) { my_timer.Start(); if (my_timer.Equals(30000)) { watcherprocess1(); } my_timer = null; } } Object reference not set to an instance of an object. my_timer.Start();

    Read the article

  • Delay in for loop while playing mp3 file C#

    - by daniyalahmad
    I want to give delay in for loop, While in for loop there is mp3 file is playing. What I actually want to do, that every clip plays after 2 sec. There are total 10 clips. Here is my code for (int i=1; i < 10; i++) { System.Threading.Thread.Sleep(1000); WMPLib.WindowsMediaPlayer wplayer = new WMPLib.WindowsMediaPlayer(); wplayer.URL = @"D:\Project C#\A-Z\" + i + ".mp3"; }

    Read the article

  • Refactoring a nested loop

    - by user3517441
    I have the following code which I use a lot of times in the class. for (int i = 0; i < someList.size(); i++) { for (int j = 0; j < someList.size(); j++) { if (i != j) { someList.get(i).sendMessageTo(someList.get(j))); //variable action } } } The purpose of the loop is to make each element in the List to send a message (or perform another action) to every element in the list except itself. Is there any way I can create a helper method so I don't have to repeat the loop code. I want to be able to state the variable action and call the helper method. Thanks.

    Read the article

  • Resetting a while loop

    - by Patrick Beardmore
    I have found a confusing thing in a php script I am writing to generate some javascript. Here it is below, slightly simplified. The second while loop won't run unless I comment out the entire first while loop. Can anyone explain why? Many thanks. <?php $listid = 2; //DEMO ONLY $result1 = mysql_query("SELECT words.wid,words.wordmd5,words.word FROM words,instances WHERE words.wid = instances.wid AND instances.lid = \"$listid\""); $result1copy = $result1; $count1 = 1; while( $row = mysql_fetch_object( $result1 ) ) { print "words_left[$count1] = \"".$row->word."\";\n"; //Increment the array counter (starts at 1) $count1++; } ?> //Some javascript <?php $count2 = 1; while( $row = mysql_fetch_object( $result1copy ) ) { print " $count2 then $row->wordmd5 "; $count2++; } ?>

    Read the article

  • Make a loop that draws lines in processing

    - by theolc
    I have this piece of code, and i am wondering how to make a loop that will draw these lines... Every 50 pixels on the x-axis... I am curious as to how this can be done and would like to use a loop rather than manually drawing each line! The following is the code for the lines... Please any help would be much appreciated! //set sidewalk fill(255,255,255); rect(0,490,500,10); line(50,490,50,500); line(100,490,100,500); line(150,490,150,500); line(200,490,200,500); line(250,490,250,500); line(300,490,300,500); line(350,490,350,500); line(400,490,400,500); line(450,490,450,500);

    Read the article

  • C# background worker while loop

    - by Mike
    What i'm trying to create is a background worker that executes a few processes every 30seconds. But I want this while loop to execute for as long as the program is launched. here is what I am using: private void watcherprocess1() { backgroundWorker1.RunWorkerAsync(); } private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { while( Thread.Sleep(30000); specficView2(); makeFormlist2(); populateListview2(); } My main issue is ai can think of a good while loop to keep this running

    Read the article

  • Running C++ functions simultaneously

    - by user2974881
    My code is similar to the following: int main() { values(); } int values() { if (condition) { 'code' } else if (condition) { 'code' } else { 'code' } motors(); } int motors() { 'code' } motors() needs values from values() to run. What could I do so that values() and motors() run simultaneously, side by side, and keep running until the user exits out of the program?

    Read the article

  • Reboot loop after sysprep of AD machine

    - by rboarman
    Major screw-up here and I need to find out how much trouble I am in. I have an AD machine that is running Server 2008 R2, hyperv, DHCP and DNS. On the hyperv machine, I have a backup AD instance running along with a handfull of other server 2008 instances. Sysprep was run on the hyperv machine instead of one of the instances. I am attempting to bring the machine back up so I can try a system restore. When I boot the hyperv machine, I get an error that says “Windows could not complete the installation. To install windows on this computer , restart the installation” This message occurs in safe mode, AD restore mode and in last known configuration mode. How can I get my OS to boot at this point? Do I need to reinstall 2008 R2 from scratch?

    Read the article

< Previous Page | 27 28 29 30 31 32 33 34 35 36 37 38  | Next Page >