Search Results

Search found 12044 results on 482 pages for 'foreach loop'.

Page 15/482 | < Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >

  • Java for-loop problem

    - by Dan
    OK so here's my code: http://so.pastebin.com/9swaiuRy The problem is that I am trying to make certain tiles blocked so the player cannot walk on them. However, it's only reading the FIRST tile which is board[0][0] and everything else is not checked.... What am I doing wrong? :( Thank you.

    Read the article

  • how to change a while sql query loop into an array loop

    - by Mac Taylor
    hey guys i record number of queries of my website and in page the below script runs , 40 extra queries added to page . how can I change this sql connection into a propper and light one function tree_set($index) { //global $menu; Remove this. $q=mysql_query("select id,name,parent from cats where parent='$index'"); if(mysql_num_rows($q) === 0) { return; } // User $tree instead of the $menu global as this way there shouldn't be any data duplication $tree = $index > 0 ? '<ul>' : ''; // If we are on index 0 then we don't need the enclosing ul while($arr=mysql_fetch_assoc($q)) { $subFileCount=mysql_query("select id,name,parent from cats where parent='{$arr['id']}'"); if(mysql_num_rows($subFileCount) > 0) { $class = 'folder'; } else { $class = 'file'; } $tree .= '<li>'; $tree .= '<span class="'.$class.'">'.$arr['name'].'</span>'; $tree .=tree_set("".$arr['id'].""); $tree .= '</li>'."\n"; } $tree .= $index > 0 ? '</ul>' : ''; // If we are on index 0 then we don't need the enclosing ul return $tree; } i heard , this can be done by changing it into an array , but i don't know how to do so thanks in advance

    Read the article

  • MySQL – How to Write Loop in MySQL

    - by Pinal Dave
    Since, I have written courses on MySQL, I quite often get emails about MySQL courses. Here is the question, which I have received quite often. “How do I loop queries in MySQL?” Well, currently MySQL does not allow to write loops with the help of ad-hoc SQL. You have to write stored procedure (routine) for the same. Here is the example, how we can create a procedure in MySQL which will look over the code. In this example I have used SELECT 1 statement and looped over it. In reality you can put there any code and loop over it. This procedure accepts one parameter which is the number of the count the loop will iterate itself. delimiter // CREATE PROCEDURE doiterate(p1 INT) BEGIN label1: LOOP SET p1 = p1 - 1; IF p1 > 0 THEN SELECT 1; ITERATE label1; END IF; LEAVE label1; END LOOP label1; END// delimiter ; CALL doiterate(100); You can also use WHILE to loop as well, we will see that in future blog posts. Reference: Pinal Dave (http://blog.sqlauthority.com)Filed under: MySQL, PostADay, SQL, SQL Authority, SQL Query, SQL Tips and Tricks, T SQL

    Read the article

  • How can I use an Ant foreach iteration with values from a file?

    - by Egon Willighagen
    In our Ant build environment, I have to do the same task for a number of items. The AntContrib foreach task is useful for that. However, the list is in a parameter, where I actually have the list in a file. How can I iterate over items in a file in an foreach-like way in Ant? Something like (pseudo-code): <foreach target="compile-module" listFromFile="$fileWithModules"/> I'm happy to write a custom Task, and welcome any suggestion on possible solutions.

    Read the article

  • PHP: Is there an elegant way to foreach through multiple items (groups) at a time?

    - by acheong87
    Given an array of N items: $arr = array('a', 'b', 'c', 'd', 'e', 'f'); What's the most elegant way to loop through in groups of M items (assuming N is divisible by M)? I tried foreach (array_chunk($arr, 2) as list($first, $second)) { // do stuff with $first and $second } but this resulted in a syntax error. In other words, I want to emulate what in Tcl would look like this: set arr [a b c d e f] foreach {first second} $arr { // do stuff with $first and $second } For now I've resorted to the obvious measure: foreach (array_chunk($arr, 2) as $group) { $first = $group[0]; $second = $group[1]; // do stuff with $first and $second } But I'm hoping someone has a more elegant method...

    Read the article

  • How can I use foreach and fork together to do something in parallel?

    - by kaushalmodi
    This question is not UVM specific but the example that I am working on is UVM related. I have an array of agents in my UVM environment and I would like to launch a sequence on all of them in parallel. If I do the below: foreach (env.agt[i]) begin seq.start(env.agt[i].sqr); end , the sequence seq first executes on env.agt[0].sqr. Once that gets over, it then executes on env.agt[1].sqr and so on. I want to implement a foreach-fork statement so that seq is executed in parallel on all agt[i] sequencers. No matter how I order the fork-join and foreach, I am not able to achieve that. Can you please help me get that parallel sequence launching behavior? Thanks.

    Read the article

  • how to change the while loop condition depending on stuff?

    - by linkcool
    by this question what i mean is that if, by example, someone's username is "bob" then the while loop condition will be ($i < 10), and if the username is something else then the while loop condition will be ($i 10) if($username == "bob") { //make this while loop condition: ($i < 10) // it means: while($i <10){ so stuff} } else { //make the while loop condition: ($i >10) }

    Read the article

  • how ot change the while loop condition depending on stuff?

    - by linkcool
    by this question what i mean is that if, by example, someone's username is "bob" then the while loop condition will be ($i < 10), and if the username is something else then the while loop condition will be ($i 10) if($username == "bob") { //make this while loop condition: ($i < 10) // it means: while($i <10){ so stuff} } else { //make the while loop condition: ($i >10) }

    Read the article

  • How can I create a horizontal table in a single foreach loop in MVC?

    - by GenericTypeTea
    Is there any way, in ASP.Net MVC, to condense the following code to a single foreach loop? <table class="table"> <tr> <td> Name </td> <% foreach (var item in Model) { %> <td> <%= item.Name %> </td> <% } %> </tr> <tr> <td> Item </td> <% foreach (var item in Model) { %> <td> <%= item.Company %> </td> <% } %> </tr> </table> Where model is a simple object: public class SomeObject { public virtual Name {get;set;} public virtual Company {get;set;} } This would output a table as follows: Name | Bob | Sam | Bill | Steve | Company | Builder | Fireman | MS | Apple | I know I could probably use an extension method to write out each row, but is it possible to build all rows using a single iteration over the model? This is a follow on from this question as I'm unhappy with my accepted answer and cannot believe I've provided the best solution.

    Read the article

  • How do I keep a count of undefined strings within a loop using PHP?

    - by mike
    I'm using a loop within a loop to try to generate keyword combinations and also find the ones that have been used the most. My outside loop just queries a list of keywords (lets use "chicago" as our first keyword, 3 records were found). The inside loop finds all the records in the "posts" table where keyword = "chicago". Within this loop, I need to generate strings based on info I found in the database. Which, would look something like "chicago bulls", "chicago bears", "chicago cubs" etc... I know how to do everything up until this point, but how do I temporary hold these generated strings and count how many times they have been found within the 3 records?

    Read the article

  • "Optimal" game loop for 2D side-scroller

    - by MrDatabase
    Is it possible to describe an "optimal" (in terms of performance) layout for a 2D side-scroller's game loop? In this context the "game loop" takes user input, updates the states of game objects and draws the game objects. For example having a GameObject base class with a deep inheritance hierarchy could be good for maintenance... you can do something like the following: foreach(GameObject g in gameObjects) g.update(); However I think this approach can create performance issues. On the other hand all game objects' data and functions could be global. Which would be a maintenance headache but might be closer to an optimally performing game loop. Any thoughts? I'm interested in practical applications of near optimal game loop structure... even if I get a maintenance headache in exchange for great performance.

    Read the article

  • How to print index in a 'for-loop' being executed in remote host through SSH?

    - by YShin
    I want to ssh into a remote host, and then execute a for loop that goes through sequence of numbers to control number of different nodes. ssh user@host /bin/bash << EOF for i in {1..10} do echo $i done EOF If I do this, the output is just 10 blank lines, instead of printing out numbers from 1 through 10. If I execute same code on my local machine, I get the desired output which is ten lines each line printing from 1 through 10. How would one achieve the intended functionality, that is accessing the index in a for loop that is being executed in SSH?

    Read the article

  • How to avoid loop limitation in a openvz container?

    - by mat.viguier
    On a openVZ containing Deb7 I need to lock the maximum size of a folder, which is used to upload on a php based web server. The directory is synced, so I have to lock the maxsize. MAXSIZE should be upgradable by adding some physical disk later ... I want to use a file as a block device for a file system. So I have done : dd if=/dev/zero of=/disk2/filesystem.dat bs=1M count=100 Then, I made the filesystem on it mkfs.ext4 filesystem.dat Then I tried to mount it : mkdir /opt/filesystem ; mount /disk2/filesystem.dat /opt/filesystem My OpenVZ (it is on a VPS) has no loop module in the kernerl. So I got Could not find any loop device as usual under OpenVz So i think I have to use FUSE, but I really do not know HOW .... Any idea on locking the size of directory under OpenVZ ?

    Read the article

  • Why doesn't my Perl code work when I put it in a foreach loop?

    - by foxhop
    This code outputs the scalars in the row array properly: $line = "This is my favorite test"; @row = split(/ /, $line); print $row[0]; print $row[1]; The same code inside a foreach loop doesn't print any scalar values: foreach $line (@lines){ @row = split(/ /, $line); print $row[0]; print $row[1]; } What could cause this to happen? I am new to Perl coming from python. I need to learn Perl for my new position.

    Read the article

  • Does lamda in List.ForEach leads to memory leaks and performance problems ?

    - by Monomachus
    I have a problem which I could solve using something like this sortedElements.ForEach((XElement el) => PrintXElementName(el,i++)); And this means that I have in ForEach a lambda which permits using parameters like int i. I like that way of doing it, but i read somewhere that anonymous methods and delegates with lambda leads to a lot of memory leaks because each time when lambda is executed something is instantiated but is not released. Something like that. Could you please tell me if this is true in this situation and if it is why?

    Read the article

  • Perl, Array called by scalar doesn't work in foreach loop.

    - by foxhop
    This code outputs the scalars in the row array properly: $line = "This is my favorite test"; @row = split(/ /, $line); print $row[0]; print $row[1]; The same code inside a foreach loop doesn't print any scalar values: foreach $line (@lines){ @row = split(/ /, $line); print $row[0]; print $row[1]; } What could cause this to happen? I am new to perl coming from python. I need to learn perl for my new position.

    Read the article

  • How to Create an Array from a Single Variable and Form Multiple Foreach Loops?

    - by matphoto
    I'm fairly proficient in HTML/CSS, but very new when it comes to the likes of PHP and Javascript. I've jumped headfirst into coding Wordpress shortcodes (basically php functions), and so far, through trial and error and seemingly endless browser refreshes, I've been able to figure everything out. I just hit a huge wall though, hence why I'm here. Basically, I'm trying to give an attribute a list of values like: attr="23, 95, 136, ect" The function then needs to take that attribute variable and create an array with it: $arr = array($attr); To me that seems as if it would work, but the array takes the whole list as one value instead. After doing that I want to create a foreach loop that parses each number from the list, possibly through yet another foreach loop if possible, and returns a section of code for each one, and I'm not quite sure how to pull that off either. Any feedback would be greatly appreciated.

    Read the article

  • Foreach loop with 2d array of objects

    - by Jacob Millward
    I'm using a 2D array of objects to store data about tiles, or "blocks" in my gameworld. I initialise the array, fill it with data and then attempt to invoke the draw method of each object. foreach (Block block in blockList) { block.Draw(spriteBatch); } I end up with an exception being thrown "Object reference is not set to an instance of an object". What have I done wrong? EDIT: This is the code used to define the array Block[,] blockList; Then blockList = new Block[screenRectangle.Width, screenRectangle.Height]; // Fill with dummy data for (int x = 0; x <= screenRectangle.Width / texture.Width; x++) { for (int y = 0; y <= screenRectangle.Height / texture.Width; y++) { if (y >= screenRectangle.Height / (texture.Width*2)) { blockList[x, y] = new Block(1, new Rectangle(x * 16, y * 16, texture.Width, texture.Height), texture); } else { blockList[x, y] = new Block(0, new Rectangle(x * 16, y * 16, texture.Width, texture.Height), texture); } } }

    Read the article

  • Is there a more elegant way to act on the first and last items in a foreach enumeration than count++

    - by Edward Tanguay
    Is there a more elegant way to act on the first and last items when iterating through a foreach loop than incrementing a separate counter and checking it each time? For instance, the following code outputs: >>> [line1], [line2], [line3], [line4] <<< which requires knowing when you are acting on the first and last item. Is there a more elegant way to do this now in C# 3 / C# 4? It seems like I could use .Last() or .First() or something like that. using System; using System.Collections.Generic; using System.Text; namespace TestForNext29343 { class Program { static void Main(string[] args) { StringBuilder sb = new StringBuilder(); List<string> lines = new List<string> { "line1", "line2", "line3", "line4" }; int index = 0; foreach (var line in lines) { if (index == 0) sb.Append(">>> "); sb.Append("[" + line + "]"); if (index < lines.Count - 1) sb.Append(", "); else sb.Append(" <<<"); index++; } Console.WriteLine(sb.ToString()); Console.ReadLine(); } } }

    Read the article

  • Foreach is crashing script, but no errors reported.

    - by ILMV
    So I've created this smarty function to get images from my flickr photostream using SimplePie... simple really, or so it should be. The problem I'm having is the foreach will crash the script, this doesn't happen if I put an exit after the closing foreach, of course because of this the rest of my script doesn't execute. The problem also completely subsides if I remove the foreach, I've tested it and it's not the contents of the foreach, but the loop itself. Error reporting is turned on but I don't get any, I also tried messing with the memory_limit, with no luck. Anyone know why this foreach is killing my script? Thanks! function smarty_function_flickr ($params, &$smarty) { require_once('system/library/SimplePie/simplepie.inc'); require_once('system/library/SimplePie/idn/idna_convert.class.php'); $flickr=new flickr(); /** * Set up SimplePie with all default values using shorthand syntax. */ $feed = new SimplePie($params['feed'], 'system/library/SimplePie/cache', '600'); $feed->handle_content_type(); /** * What sizes should we use? * Choices: square, thumb, small, medium, large. */ $thumb = 'square'; $full = 'medium'; $output = array(); $counter=0; // If I comment this foreach out the problem subsides, I know it is not the code within the foreach foreach ($feed->get_items() as $item) { $url = $flickr->image_from_description($item->get_description()); $output[$counter]['title'] = $item->get_title(); $output[$counter]['image'] = $flickr->select_image($url, $full); $output[$counter]['thumb'] = $flickr->select_image($url, $thumb); $counter++; } // Set template variables and template $smarty->assign('flickr',$output); $smarty->display('forms/'.$params['template'].'.tpl'); }

    Read the article

  • Games development with a game loop that's abstracted away

    - by Davy8
    Most game development happens with a main game loop. Are there any good articles/blog posts/discussions about games without a game loop? I imagine they'd mostly be web games, but I'd be interested in hearing otherwise. (As a side note, I think it's really interesting that the concept is almost exclusively used in gaming as far as I'm aware, perhaps that may be another question.) Edit: I realize there's probably a redraw loop somewhere. I guess what I really mean is a loop that is hidden to you. Frames are something you as the developer are not concerned with as you're working on a higher level of abstraction. E.g. someLootItem.moveTo(inventory, someAnimatationType) and that will move from the loot box to your inventory using the specified animation type without the game developer having to worry about the implementation details of that animation. Maybe that's how "real" games end up working, but from reading most tutorials they seem to imply a much more granular level of control is used, but that might just be an artifact of being a tutorial. Edit2: I think most people are misunderstanding what I'm trying to ask, likely because I'm having trouble describing exactly what I'm trying to ask. After some more thinking perhaps what I'm referring to is more along the lines of what I believe is referred to as "scripting" where you're working at a very high level and having some game engine take care of the low level details. For example, take custom maps in Starcraft II or Warcraft III. Many of the "maps" have gameplay that deviates enough from the primary game that they could be considered a separate game written on the same engine. What I'm referring to then is along those lines. I may be wrong because I only dabbed in the Warcraft III editor, but as far as I remember no where in the map editor do you control the game loop, and yet you can create many different games out of it. In my mind, these are games in their own right. If you're playing DotA you don't say you're playing Warcraft III, you say you're playing DotA because that's the actual game you're playing. Such a system may impose limitations that don't exist if you're creating a game from scratch, but it greatly reduces development time because much of the "hard" work has already been done for you. Hopefully that clarifies what I'm asking. Another example of what is I mean, is when you write a web app, of course it communicates through sockets and TCP. But does the average web developer doesn't explicitly write code for connecting sockets. They just need to know about receiving a request and sending a response. There are unique scenarios where you do occasionally need to use raw sockets, but it's generally rare in web development. In a similar fashion, it's very possible to write a game without directly using the game loop, even though one is used behind the scenes. Probably not a AAA title, but there must be hundreds of smaller scale games that can and possibly are written this way. Are there any good resources on writing these "simpler" games?

    Read the article

  • How can I loop through posts as well as child pages to display them all by date in Wordpress 2.9

    - by Craig Dennis
    Some background info -- In wordpress I have my portfolio as a parent page with each item of work a child page. I also have a blog. I want to display the most recent 6 items on the homepage whether they are from my portfolio or my blog. I have a loop that displays the posts and on another page I have a loop that displays the child pages of a specific parent page. I only need to display the_title and the_post_thumbnail. Is it possible to loop through both the posts and the child pages and display them in order of date (recent first). So the final display would be a mixture of posts and child pages. Could it be done by having a separate loop for pages and one for posts, then somehow adding the results to an array and then pull them out in date order (recent first). Any help would be greatful. Thanks

    Read the article

  • How do I make this nested for loop, testing sums of cubes, more efficient?

    - by Brian J. Fink
    I'm trying to iterate through all the combinations of pairs of positive long integers in Java and testing the sum of their cubes to discover if it's a Fibonacci number. I'm currently doing this by using the value of the outer loop variable as the inner loop's upper limit, with the effect being that the outer loop runs a little slower each time. Initially it appeared to run very quickly--I was up to 10 digits within minutes. But now after 2 full days of continuous execution, I'm only somewhere in the middle range of 15 digits. At this rate it may end up taking a whole year just to finish running this program. The code for the program is below: import java.lang.*; import java.math.*; public class FindFib { public static void main(String args[]) { long uLimit=9223372036854775807L; //long maximum value BigDecimal PHI=new BigDecimal(1D+Math.sqrt(5D)/2D); //Golden Ratio for(long a=1;a<=uLimit;a++) //Outer Loop, 1 to maximum for(long b=1;b<=a;b++) //Inner Loop, 1 to current outer { //Cube the numbers and add BigDecimal c=BigDecimal.valueOf(a).pow(3).add(BigDecimal.valueOf(b).pow(3)); System.out.print(c+" "); //Output result //Upper and lower limits of interval for Mobius test: [c*PHI-1/c,c*PHI+1/c] BigDecimal d=c.multiply(PHI).subtract(BigDecimal.ONE.divide(c,BigDecimal.ROUND_HALF_UP)), e=c.multiply(PHI).add(BigDecimal.ONE.divide(c,BigDecimal.ROUND_HALF_UP)); //Mobius test: if integer in interval (floor values unequal) Fibonacci number! if (d.toBigInteger().compareTo(e.toBigInteger())!=0) System.out.println(); //Line feed else System.out.print("\r"); //Carriage return instead } //Display final message System.out.println("\rDone. "); } } Now the use of BigDecimal and BigInteger was delibrate; I need them to get the necessary precision. Is there anything other than my variable types that I could change to gain better efficiency?

    Read the article

  • Inspiration and influence of the else clause of loop statements in Python?

    - by Aristide
    Python offers an optional else clause in loop statements, which is executed if and only if the loop is not terminated by a break. For an interesting discussion about this neglected commodity, see this question. Here, I just wanted to know: if the very concept of this loop-else construct originates from another language (either theoretical or actually implemented), conversely, if it was taken up in any newer language. May be I should ask the former to Guido, but he surely is a too busy guy for such a futile inquiry. ;-)

    Read the article

< Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >