Search Results

Search found 1698 results on 68 pages for 'loops'.

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

  • Objective C loop logic

    - by Graham
    Hi guys, I'm really new to programming in Obj-C, my background is in labview which is a graphical programming language, I've worked with Visual Basic some and HTML/CSS a fair amount as well. I'm trying to figure out the logic to create an array of data for the pattern below. I need the pattern later to extract data from another 2 arrays in a specific order. I can do it by referencing a = 1, b = 2, c = 3 etc and then creating the array with a, b, c but I want to use a loop so that I don't have 8 references above the array. These references will be used to generate another generation of data so unless I can get help figuring out the logic I'll actually end up with 72 references above the array. // This is the first one which gives the pattern 0 0 0 0 (etc) // 1 1 1 1 // 2 2 2 2 NSMutableArray * expSecondRef_one = [NSMutableArray array]; int a1 = 0; while (a1 < 9) { int a2 = 0; while (a2 < 8) { NSNumber * a3 = [NSNumber numberWithInt:a1]; [expSecondRef_one addObject:a3]; a2++; } a1++; } // This is the second one which I'm stumbling over, I am looking for the pattern 1 2 3 4 5 6 7 8 // 0 2 3 4 5 6 7 8 // 0 1 3 4 5 6 7 8 // 0 1 2 4 5 6 7 8 // etc to -> // 0 1 2 3 4 5 6 7 If you run it in a line every 9th number is -1 but I don't know how to do that over a pattern of 8. Thanks in advance! Graham

    Read the article

  • Custom language - FOR loop in a clojure interpeter?

    - by Mark
    I have a basic interpreter in clojure. Now i need to implement for (initialisation; finish-test; loop-update) { statements } Implement a similar for-loop for the interpreted language. The pattern will be: (for variable-declarations end-test loop-update do statement) The variable-declarations will set up initial values for variables.The end-test returns a boolean, and the loop will end if end-test returns false. The statement is interpreted followed by the loop-update for each pass of the loop. Examples of use are: (run ’(for ((i 0)) (< i 10) (set i (+ 1 i)) do (println i))) (run ’(for ((i 0) (j 0)) (< i 10) (seq (set i (+ 1 i)) (set j (+ j (* 2 i)))) do (println j))) inside my interpreter. I will attach my interpreter code I got so far. Any help is appreciated. Interpreter (declare interpret make-env) ;; needed as language terms call out to 'interpret' (def do-trace false) ;; change to 'true' to show calls to 'interpret' ;; simple utilities (def third ; return third item in a list (fn [a-list] (second (rest a-list)))) (def fourth ; return fourth item in a list (fn [a-list] (third (rest a-list)))) (def run ; make it easy to test the interpreter (fn [e] (println "Processing: " e) (println "=> " (interpret e (make-env))))) ;; for the environment (def make-env (fn [] '())) (def add-var (fn [env var val] (cons (list var val) env))) (def lookup-var (fn [env var] (cond (empty? env) 'error (= (first (first env)) var) (second (first env)) :else (lookup-var (rest env) var)))) ;; for terms in language ;; -- define numbers (def is-number? (fn [expn] (number? expn))) (def interpret-number (fn [expn env] expn)) ;; -- define symbols (def is-symbol? (fn [expn] (symbol? expn))) (def interpret-symbol (fn [expn env] (lookup-var env expn))) ;; -- define boolean (def is-boolean? (fn [expn] (or (= expn 'true) (= expn 'false)))) (def interpret-boolean (fn [expn env] expn)) ;; -- define functions (def is-function? (fn [expn] (and (list? expn) (= 3 (count expn)) (= 'lambda (first expn))))) (def interpret-function ; keep function definitions as they are written (fn [expn env] expn)) ;; -- define addition (def is-plus? (fn [expn] (and (list? expn) (= 3 (count expn)) (= '+ (first expn))))) (def interpret-plus (fn [expn env] (+ (interpret (second expn) env) (interpret (third expn) env)))) ;; -- define subtraction (def is-minus? (fn [expn] (and (list? expn) (= 3 (count expn)) (= '- (first expn))))) (def interpret-minus (fn [expn env] (- (interpret (second expn) env) (interpret (third expn) env)))) ;; -- define multiplication (def is-times? (fn [expn] (and (list? expn) (= 3 (count expn)) (= '* (first expn))))) (def interpret-times (fn [expn env] (* (interpret (second expn) env) (interpret (third expn) env)))) ;; -- define division (def is-divides? (fn [expn] (and (list? expn) (= 3 (count expn)) (= '/ (first expn))))) (def interpret-divides (fn [expn env] (/ (interpret (second expn) env) (interpret (third expn) env)))) ;; -- define equals test (def is-equals? (fn [expn] (and (list? expn) (= 3 (count expn)) (= '= (first expn))))) (def interpret-equals (fn [expn env] (= (interpret (second expn) env) (interpret (third expn) env)))) ;; -- define greater-than test (def is-greater-than? (fn [expn] (and (list? expn) (= 3 (count expn)) (= '> (first expn))))) (def interpret-greater-than (fn [expn env] (> (interpret (second expn) env) (interpret (third expn) env)))) ;; -- define not (def is-not? (fn [expn] (and (list? expn) (= 2 (count expn)) (= 'not (first expn))))) (def interpret-not (fn [expn env] (not (interpret (second expn) env)))) ;; -- define or (def is-or? (fn [expn] (and (list? expn) (= 3 (count expn)) (= 'or (first expn))))) (def interpret-or (fn [expn env] (or (interpret (second expn) env) (interpret (third expn) env)))) ;; -- define and (def is-and? (fn [expn] (and (list? expn) (= 3 (count expn)) (= 'and (first expn))))) (def interpret-and (fn [expn env] (and (interpret (second expn) env) (interpret (third expn) env)))) ;; -- define print (def is-print? (fn [expn] (and (list? expn) (= 2 (count expn)) (= 'println (first expn))))) (def interpret-print (fn [expn env] (println (interpret (second expn) env)))) ;; -- define with (def is-with? (fn [expn] (and (list? expn) (= 3 (count expn)) (= 'with (first expn))))) (def interpret-with (fn [expn env] (interpret (third expn) (add-var env (first (second expn)) (interpret (second (second expn)) env))))) ;; -- define if (def is-if? (fn [expn] (and (list? expn) (= 4 (count expn)) (= 'if (first expn))))) (def interpret-if (fn [expn env] (cond (interpret (second expn) env) (interpret (third expn) env) :else (interpret (fourth expn) env)))) ;; -- define function-application (def is-function-application? (fn [expn env] (and (list? expn) (= 2 (count expn)) (is-function? (interpret (first expn) env))))) (def interpret-function-application (fn [expn env] (let [function (interpret (first expn) env)] (interpret (third function) (add-var env (first (second function)) (interpret (second expn) env)))))) ;; the interpreter itself (def interpret (fn [expn env] (cond do-trace (println "Interpret is processing: " expn)) (cond ; basic values (is-number? expn) (interpret-number expn env) (is-symbol? expn) (interpret-symbol expn env) (is-boolean? expn) (interpret-boolean expn env) (is-function? expn) (interpret-function expn env) ; built-in functions (is-plus? expn) (interpret-plus expn env) (is-minus? expn) (interpret-minus expn env) (is-times? expn) (interpret-times expn env) (is-divides? expn) (interpret-divides expn env) (is-equals? expn) (interpret-equals expn env) (is-greater-than? expn) (interpret-greater-than expn env) (is-not? expn) (interpret-not expn env) (is-or? expn) (interpret-or expn env) (is-and? expn) (interpret-and expn env) (is-print? expn) (interpret-print expn env) ; special syntax (is-with? expn) (interpret-with expn env) (is-if? expn) (interpret-if expn env) ; functions (is-function-application? expn env) (interpret-function-application expn env) :else 'error))) ;; tests of using environment (println "Environment tests:") (println (add-var (make-env) 'x 1)) (println (add-var (add-var (add-var (make-env) 'x 1) 'y 2) 'x 3)) (println (lookup-var '() 'x)) (println (lookup-var '((x 1)) 'x)) (println (lookup-var '((x 1) (y 2)) 'x)) (println (lookup-var '((x 1) (y 2)) 'y)) (println (lookup-var '((x 3) (y 2) (x 1)) 'x)) ;; examples of using interpreter (println "Interpreter examples:") (run '1) (run '2) (run '(+ 1 2)) (run '(/ (* (+ 4 5) (- 2 4)) 2)) (run '(with (x 1) x)) (run '(with (x 1) (with (y 2) (+ x y)))) (run '(with (x (+ 2 4)) x)) (run 'false) (run '(not false)) (run '(with (x true) (with (y false) (or x y)))) (run '(or (= 3 4) (> 4 3))) (run '(with (x 1) (if (= x 1) 2 3))) (run '(with (x 2) (if (= x 1) 2 3))) (run '((lambda (n) (* 2 n)) 4)) (run '(with (double (lambda (n) (* 2 n))) (double 4))) (run '(with (sum-to (lambda (n) (if (= n 0) 0 (+ n (sum-to (- n 1)))))) (sum-to 100))) (run '(with (x 1) (with (f (lambda (n) (+ n x))) (with (x 2) (println (f 3))))))

    Read the article

  • Android - Loop Through strings.xml file

    - by Alexis Cartier
    I was wondering if there is anyway to loop through the strings.xml file. Let's say that I have the following format: <!-- FIRST SECTION --> <string name="change_password">Change Password</string> <string name="change_server">Change URL</string> <string name="default_password">password</string> <string name="default_server">http://xxx:8080</string> <string name="default_username">testPhoneAccount</string> <!-- SECOND SECTION --> <string name="debug_settings_category">Debug Settings</string> <string name="reload_data_every_startup_pref">reload_data_every_startup</string> <string name="reload_data_on_first_startup_pref">reload_data_on_first_startup</string> Now let's say I have this: private HashMap<String,Integer> hashmapStringValues = new HashMap<String, Integer>(); Is there a way to iterate only in the second section of my xml file? Maybe wrap the section with a tag like <section2> and then iterate through it? public void initHashMap(){ for (int i=0;i< ???? ;i++) //Here I need to loop only in the second section of my xml file { String nameOfTag = ? // Here I get the name of the tag int value = R.string.nameOfTag // Here I get the associated value of the tag this.hashmapStringValues.put(nameOfTag,value); } }

    Read the article

  • Newb Question: scanf() in C

    - by riemannliness
    So I started learning C today, and as an exercise i was told to write a program that asks the user for numbers until they type a 0, then adds the even ones and the odd ones together. Here is is (don't laugh at my bad style): #include <stdio.h>; int main() { int esum = 0, osum = 0; int n, mod; puts("Please enter some numbers, 0 to terminate:"); scanf("%d", &n); while (n != 0) { mod = n % 2; switch(mod) { case 0: esum += n; break; case 1: osum += n; } scanf("%d", &n); } printf("The sum of evens:%d,\t The sum of odds:%d", esum, osum); return 0; } My question concerns the mechanics of the scanf() function. It seems that when you enter several numbers at once separated by spaces (eg. 1 22 34 2 8), the scanf() function somehow remembers each distinct numbers in the line, and steps through the while loop for each one respectively. Why/how does this happen? Example interaction within command prompt: - Please enter some numbers, 0 to terminate: 42 8 77 23 11 (enter) 0 (enter) - The sum of evens:50, The sum of odds:111 I'm running the program through the command prompt, it's compiled for win32 platforms with visual studio.

    Read the article

  • Creating nested arrays on the fly

    - by adardesign
    I am trying to do is to loop this HTML and get a nested array of this HTML values that i want to grab. It might look complex at first but is a simple question... This script is just part of a Object containing methods. html <div class="configureData"> <div title="Large"> <a href="yellow" title="true" rel="$55.00" name="sku22828"></a> <a href="green" title="true" rel="$55.00" name="sku224438"></a> <a href="Blue" title="true" rel="$55.00" name="sku22222"></a> </div> <div title="Medium"> <a href="yellow" title="true" rel="$55.00" name="sku22828"></a> <a href="green" title="true" rel="$55.00" name="sku224438"></a> <a href="Blue" title="true" rel="$55.00" name="sku22222"></a> </div> <div title="Small"> <a href="yellow" title="true" rel="$55.00" name="sku22828"></a> <a href="green" title="true" rel="$55.00" name="sku224438"></a> <a href="Blue" title="true" rel="$55.00" name="sku22222"></a> </div> </div> javascript // this is part of a script..... parseData:function(dH){ dH.find(".configureData div").each(function(indA, eleA){ colorNSize.tempSizeArray[indA] = [eleA.title,[],[],[],[]] $(eleZ).find("a").each(function(indB, eleB){ colorNSize.tempSizeArray[indA][indB+1] = eleC.title }) }) }, I expect the end array should look like this. [ ["large", ["yellow", "green", "blue"], ["true", "true", "true"], ["$55", "$55","$55"] ], ["Medium", ["yellow", "green", "blue"], ["true", "true", "true"], ["$55", "$55","$55"] ] ] // and so on....

    Read the article

  • Looping through a file in VB.NET

    - by Ousman
    I am writing a VB.NET program and I'm trying to accomplish the following: Read and loop through a text file line by line Show the event of the loop on a textbox or label until a button is pressed The loop will then stop on any number that happened to be at the loop event and When a button is pressed again the loop will continue. Code Imports System.IO Public Class Form1 'Dim nFileNum As Integer = FreeFile() ' Get a free file number Dim strFileName As String = "C:\scb.txt" Dim objFilename As FileStream = New FileStream(strFileName, _ FileMode.Open, FileAccess.Read, FileShare.Read) Dim objFileRead As StreamReader = New StreamReader(objFilename) 'Dim lLineCount As Long 'Dim sNextLine As String Private Sub btStart_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles btStart.Click Try If objFileRead.ReadLine = Nothing Then MsgBox("No Accounts Available to show!", _ MsgBoxStyle.Information, _ MsgBoxStyle.DefaultButton2 = MsgBoxStyle.OkOnly) Return Else Do While (objFileRead.Peek() > -1) Loop lblAccounts.Text = objFileRead.ReadLine() 'objFileRead.Close() 'objFilename.Close() End If Catch ex As Exception MessageBox.Show(ex.Message) Finally 'objFileRead.Close() 'objFilename.Close() End Try End Sub Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles MyBase.Load End Sub End Class Problem I'm able to read the text file but my label will only loop if I hit the start button. It goes to the next line, but I want it to continue to loop through the entire file until I hit a button telling it to stop.

    Read the article

  • JQUERY Loop from a AJAX Response

    - by nobosh
    I'm building a tagger. After a user submits a tag, ajax returns: {"returnmessage":"The Ajax operation was successful.","tagsinserted":"BLAH, BLOOOW","returncode":"0"} I want to take the tagsinserted and loop through it, and during each loop take the item in the list and insert it on the HTML page. suggestion on how to do this right? Here is the current code: $("#tag-post").click(function(){ // Post $('#tag-input').val() $.ajax({ url: '/tags/ajax/post-tag/', data: { newtaginput : $('#tag-input').val(), userid : $('#userid').val()}, success: function(data) { // After posting alert('done'); } }); });

    Read the article

  • jquery - Create a List of all LIs Name's

    - by nobosh
    Given the following block of HTML: <ul id="taglist"> <li><a name="45" href="">Product 1</a></li> <li><a name="1146" href="">Product 2</a></li> <li><a name="13437" href="">Product 3</a></li> <li><a name="51" href="">Product 4</a></li> </ul> Is it possible for JQUERY to return a STRING, one variable with the name values: alert(tagliststring); Would alert: 45,1146,13437,51 Thanks

    Read the article

  • C/C++: feedback in analyzing a code example

    - by KaiserJohaan
    Hello, I have a piece of code from an assignment I am uncertain about. I feel confident that I know the answer, but I just want to double-check with the community incase there's something I forgot. The title is basically secure coding and the question is just to explain the results. int main() { unsigned int i = 1; unsigned int c = 1; while (i > 0) { i = i*2; c++; } printf("%d\n", c); return 0; } My reasoning is this: At first glance you could imagine the code would run forever, considering it's initialized to a positive value and ever increasing. This of course is wrong because eventually the value will grow so large it will cause an integer overflow. This in turn is not entirely true either, because eventally it will force the variable 'i' to be signed by making the last bit to 1 and therefore regarded as a negative number, therefore terminating the loop. So it is not writing to unallocated memory and therefore cause integer overflow, but rather violating the data type and therefore causing the loop to terminate. I am quite sure this is the reason, but I just want to double check. Any opinions?

    Read the article

  • Creating a loop that will edit 60 TextBox names?

    - by Darkmage
    text box set1 = 1 to 30 = in the query name = br1id to br30id textbox set 2 = 1 to 30 = in the result output i dont understand how to create a loop based on 30 diffrent textbox names? i cant copy paste these lines 30 times editing the textbox names, that wold just look wrong. try { MySqlConnection mysqlCon = new MySqlConnection( "server= 195.159.253.229;" + "Database = bruker;" + "user id=bobby;" + "password=LoLOW###;"); MySqlCommand cmd1 = new MySqlCommand( "SELECT brukernavn From bruker where ID = '" + br1id.Text + "';", mysqlCon); mysqlCon.Open(); navX[0] = cmd1.ExecuteScalar().ToString(); br1txt3.Text = navX[0]; }

    Read the article

  • Pascal's repeat... until vs. C's do... while

    - by Bob
    In C there is a do while loop and pascal's (almost) equivalent is the repeat until loop, but there is a small difference between the two, while both structures will iterate at least once and check whether they need to do the loop again only in the end, in pascal you write the condition that need to met to terminate the loop (REPEAT UNTIL something) in C you write the condition that need to be met to continue the loop (DO WHILE something). Is there a reason why there is this difference or is it just an arbitrary decision?

    Read the article

  • Is it possible to convert this asp to asp.net?

    - by Phil
    I have been tasked with sifting through the worst classic asp spaghetti i've ever come across. The script runs a series of recordsets in sequence, getting 1 record at a time. As the record is built it takes the id and passes it to the next loop, which gets data, and passes on the id to the next loop. It then continues in this manner and builds an unordered list, kicking out the required html as it goes. Here are my efforts so far: have a class delivering data via sqldatareaders and output these to nested repeaters (this failed due to not being able to loop and get the id) Have a datatable populated with all the required data, then datatable.select to filter it out. have 4 datareaders looping and building the ul arraylists (I couldnt get the id's to match up) Please can you suggest the best method (with a bit of sample code if possible) to go about doing this conversion? Here is the code (sorry its long / horrible / spaghetti!!!) <% set RSMenuLevel0 = conn.execute("select id, DepartmentID, GroupingID, Heading, OrderID, Publish, moduleid, url, urltarget " &_ "from Grouping where (DepartmentID = 0 and GroupingID = 0 and Publish <> 0) order by OrderID") %> <% if session("JavaScriptEnabled") = "False" Then %> <% while not RSMenuLevel0.EOF if RSMenuLevel0("Publish") <> 0 then Menu0heading = RSMenuLevel0("Heading") Menu0id = RSMenuLevel0("id") %> <%if RSMenuLevel0("url") > "" and RSMenuLevel0("moduleid") = 0 then%> &nbsp;<a href="http://<%=RSMenuLevel0("url")%>" target="<%=RSMenuLevel0("urltarget")%>"><%=Menu0heading%></a> <%else%> &nbsp;<a href="/default.asp?id=<%=Menu0id%>"><%=Menu0heading%></a> <%end if%> <% end if RSMenuLevel0.MoveNext wend %> <% else %> <ul id="Menu1" class="MM"> <%if home <> 1 then%> <!-- <li><a href="/default.asp"><span class="item">Home</span></a> --> <%end if%> <% numone=0 while not RSMenuLevel0.EOF ' numone = numone + 1 Menu0heading = RSMenuLevel0("Heading") 'itemID = lcase(replace(Menu0heading," ","")) Menu0id = RSMenuLevel0("id") if RSMenuLevel0("url") > "" and RSMenuLevel0("moduleid") = 0 then url = RSMenuLevel0("url") if instr(url,"file:///") > 0 then %> <li><a href="<%=RSMenuLevel0("url")%>" target="<%=RSMenuLevel0("urltarget")%>" <%if numone=1 then%>class="CURRENT"<%end if%>><span class="item"><%=Menu0heading%></span></a> <%else%> <li><a href="http://<%=RSMenuLevel0("url")%>" target="<%=RSMenuLevel0("urltarget")%>" <%if numone=1 then%>class="CURRENT"<%end if%>><span class="item"><%=Menu0heading%></span></a> <%end if%> <%else%> <li><a href="/default.asp?id=<%=RSMenuLevel0("id")%>" <%if numone=1 then%>class="CURRENT"<%end if%>><span class="item"><%=Menu0heading%></span></a> <%end if%> <% set RSMenuLevel1 = conn.execute("select id, DepartmentID, GroupingID, Heading, OrderID, Publish, moduleid, url, urltarget " &_ "from Grouping where (DepartmentID = 0 and GroupingID = " & Menu0id & " and Publish <> 0) order by OrderID") if not RSMenuLevel1.EOF then %> <ul> <% while not RSMenuLevel1.EOF Menu1heading = RSMenuLevel1("Heading") Menu1id = RSMenuLevel1("id") if RSMenuLevel1("url") > "" and RSMenuLevel1("moduleid") = 0 then url = RSMenuLevel1("url") if instr(url,"file:///") > 0 then %> <li><a href="<%=RSMenuLevel1("url")%>" target="<%=RSMenuLevel1("urltarget")%>"><%=Menu1heading%></a> <%else%> <li><a href="http://<%=RSMenuLevel1("url")%>" target="<%=RSMenuLevel1("urltarget")%>"><%=Menu1heading%></a> <%end if%> <%else%> <li><a href="/default.asp?id=<%=RSMenuLevel1("id")%>"><%=Menu1heading%></a> <%end if%> <% set RSMenuLevel2 = conn.execute("select id, DepartmentID, GroupingID, Heading, OrderID, Publish, moduleid, url, urltarget " &_ "from Grouping where (DepartmentID = 0 and GroupingID = " & Menu1id & " and Publish <> 0) order by OrderID") if not RSMenuLevel2.EOF then %> <ul> <% while not RSMenuLevel2.EOF Menu2heading = RSMenuLevel2("Heading") Menu2id = RSMenuLevel2("id") if RSMenuLevel2("url") > "" and RSMenuLevel2("moduleid") = 0 then %> <li><a href="http://<%=RSMenuLevel2("url")%>" target="<%=RSMenuLevel2("urltarget")%>"><%=Menu2heading%></a> <%else%> <li><a href="/default.asp?id=<%=RSMenuLevel2("id")%>"><%=Menu2heading%></a> <%end if%> <% set RSMenuLevel3 = conn.execute("select id, DepartmentID, GroupingID, Heading, OrderID, Publish, moduleid, url, urltarget " &_ "from Grouping where (DepartmentID = 0 and GroupingID = " & Menu2id & " and Publish <> 0) order by OrderID") if not RSMenuLevel3.EOF then %> <ul> <% while not RSMenuLevel3.EOF Menu3heading = RSMenuLevel3("Heading") Menu3id = RSMenuLevel3("id") if RSMenuLevel3("url") > "" and RSMenuLevel3("moduleid") = 0 then %> <li><a href="http://<%=RSMenuLevel3("url")%>" target="<%=RSMenuLevel3("urltarget")%>"><%=Menu3heading%></a></li> <%else%> <li><a href="/default.asp?id=<%=RSMenuLevel3("id")%>"><%=Menu3heading%></a></li> <%end if%> <% RSMenuLevel3.MoveNext wend %> </ul> <% end if RSMenuLevel2.MoveNext %> </li> <% wend %> </ul> <% end if RSMenuLevel1.MoveNext %> </li> <% wend %> </ul> <% end if RSMenuLevel0.MoveNext %> </li> <% wend %> </ul> <% end if %>

    Read the article

  • fuzzy DISTINCT Values

    - by user982853
    I have a database of real estate listings and need to return a list of neighborhoods. Right now I am using mysql DISTINCT which returns all of the distinct values. My probelm is that there is a lot of neighborhoods that have similar names: example: Park View Sub 1 Park View Park View Sub 2 Park View Sub 3 Great Lake Sub 1 Great Lake Sub 2 Great Lake Great Lake Sub 3 I am looking for an easy php or mysql solution that would recognize that "Park View" and "Great Lake" already exists and ONLY return "Park View" and "Great Lake". My initial thought is to some how get the sort order by length so that the short values are at the top and then loop through using strstr. This sound like a large task I am wondering if there is a function either in mysql or php that would easily do this.

    Read the article

  • iterating through an array

    - by Farstucker
    Iterating though an array isn’t a problem but what if I only wanted to incremented only when the method is called? Im not even sure if this would work but is there an easier way of doing this int counter; string[] myArray = {"foo", "bar", "something", "else", "here"}; private string GetNext() { string myValue = string.Empty; if (counter < myArray.Length) { myValue = myArray [counter]; } else { counter = 0; } counter++; return myValue; }

    Read the article

  • Counting entries in a list of dictionaries: for loop vs. list comprehension with map(itemgetter)

    - by Dennis Williamson
    In a Python program I'm writing I've compared using a for loop and increment variables versus list comprehension with map(itemgetter) and len() when counting entries in dictionaries which are in a list. It takes the same time using a each method. Am I doing something wrong or is there a better approach? Here is a greatly simplified and shortened data structure: list = [ {'key1': True, 'dontcare': False, 'ignoreme': False, 'key2': True, 'filenotfound': 'biscuits and gravy'}, {'key1': False, 'dontcare': False, 'ignoreme': False, 'key2': True, 'filenotfound': 'peaches and cream'}, {'key1': True, 'dontcare': False, 'ignoreme': False, 'key2': False, 'filenotfound': 'Abbott and Costello'}, {'key1': False, 'dontcare': False, 'ignoreme': True, 'key2': False, 'filenotfound': 'over and under'}, {'key1': True, 'dontcare': True, 'ignoreme': False, 'key2': True, 'filenotfound': 'Scotch and... well... neat, thanks'} ] Here is the for loop version: #!/usr/bin/env python # Python 2.6 # count the entries where key1 is True # keep a separate count for the subset that also have key2 True key1 = key2 = 0 for dictionary in list: if dictionary["key1"]: key1 += 1 if dictionary["key2"]: key2 += 1 print "Counts: key1: " + str(key1) + ", subset key2: " + str(key2) Output for the data above: Counts: key1: 3, subset key2: 2 Here is the other, perhaps more Pythonic, version: #!/usr/bin/env python # Python 2.6 # count the entries where key1 is True # keep a separate count for the subset that also have key2 True from operator import itemgetter KEY1 = 0 KEY2 = 1 getentries = itemgetter("key1", "key2") entries = map(getentries, list) key1 = len([x for x in entries if x[KEY1]]) key2 = len([x for x in entries if x[KEY1] and x[KEY2]]) print "Counts: key1: " + str(key1) + ", subset key2: " + str(key2) Output for the data above (same as before): Counts: key1: 3, subset key2: 2 I'm a tiny bit surprised these take the same amount of time. I wonder if there's something faster. I'm sure I'm overlooking something simple. One alternative I've considered is loading the data into a database and doing SQL queries, but the data doesn't need to persist and I'd have to profile the overhead of the data transfer, etc., and a database may not always be available. I have no control over the original form of the data. The code above is not going for style points.

    Read the article

  • How to store local variables in jQuery click functions?

    - by Geuis
    I'm trying to figure out how to store external variable values in the functions created during jQuery's click() event. Here's a sample of the code I'm working with now. for(var i=0; i<3; i++){ $('#tmpid'+i).click(function(){ var gid = i; alert(gid); }); } <div id="tmpid0">1al</div> <div id="tmpid1">asd</div> <div id="tmpid2">qwe</div> So what's happening is that the events are attaching properly, but the value of 'gid' is always the last incremented value of 'i'. I'm not sure how to setup the private variable in this situation.

    Read the article

  • Dynamic Hierarchical Javascript Object Loop

    - by user1684586
    var treeData = {"name" : "A", "children" : [ {"name" : "B", "children": [ {"name" : "C", "children" :[]} ]} ]}; THE ARRAY BEFORE SHOULD BE EMPTY. THE ARRAY AFTER SHOULD BE POPULATED DEPENDING ON THE NUMBER OF NODES NEEDED THAT WILL BE DEFINED FROM A DYNAMIC VALUE THAT IS PASSED. I would like to build the hierarchy dynamically with each node created as a layer/level in the hierarchy having its own array of nodes. THIS SHOULD FORM A TREE STRUCTURE. This is hierarchy structure is described in the above code. This code has tree level simple for demonstrating the layout of the hierarchy of values. There should be a root node, and an undefined number of nodes and levels to make up the hierarchy size. Nothing should be fixed besides the root node. I do not need to read the hierarchy, I need to construct it. The array should start {"name" : "A", "children" : []} and every new node as levels would be created {"name" : "A", "children" : [HERE-{"name" : "A", "children" : []}]}. In the child array, going deeper and deeper. Basically the array should have no values before the call, except maybe the root node. After the function call, the array should comprise of the required nodes of a number that may vary with every call. Every child array will contain one or more node values. There should be a minimum of 2 node levels, including the root. It should initially be a Blank canvas, that is no predefined array values.

    Read the article

  • Positioning decorated series of div tags on screen using offset, DOM JQUERY RELATED

    - by Calibre2010
    Hi, I am using JQuery to position a series of div tags which basically use a class inside of the tag which decorates the divs as bars. So the div is a green box based on its css specifications to the glass. I have a list of STARTING postions, a list of left coordiantes- for the starting points I wish to position my DIV say 556, 560, 600 these automatically are generated as left positions in a list I have a list of ENDING postions, a list of left coordiantes- for the ending points I wish to position my DIV say 570, 590, 610 these automatically are generated as left positions in a list now for each start and end position, the bar(green box) i want to be drawn with its appropriate width as follows. so say f is the offset or position of the start and ff the offset or position of the end : Below draws the green box based on only one start and end position LEFT. if (f.left != 0) { $("#test").html($("<div>d</div>")).css({ position: 'absolute', left: (f.left) + "px", top: (f.top + 35) + "px", width: (ff.left - f.left) + 25 + "px" }).addClass("option1"); } I am looking to loop through the list of positons in the list and draw multiple green boxs based on the positions on the screen. The above code draws just one green box from the last offset position.

    Read the article

  • How to replace for-loops with a functional statement in C#?

    - by Lernkurve
    A colleague once said that God is killing a kitten every time I write a for-loop. When asked how to avoid for-loops, his answer was to use a functional language. However, if you are stuck with a non-functional language, say C#, what techniques are there to avoid for-loops or to get rid of them by refactoring? With lambda expressions and LINQ perhaps? If so, how? Questions So the question boils down to: Why are for-loops bad? Or, in what context are for-loops to avoid and why? Can you provide C# code examples of how it looks before, i.e. with a loop, and afterwards without a loop?

    Read the article

  • while loop in c#

    - by Nave Tseva
    I have this code: using System; namespace _121119_zionAVGfilter { class Program { static void Main(string[] args) { int cnt = 0, zion, sum = 0; double avg; Console.Write("Enter first zion \n"); zion = int.Parse(Console.ReadLine()); while (zion != -1) { while (zion < -1 || zion > 100) { Console.Write("zion can be between 0 to 100 only! \nyou can rewrite the zion here, or Press -1 to see the avg\n"); zion = int.Parse(Console.ReadLine()); } cnt++; sum = sum + zion; Console.Write("Enter next zion, if you want to exit tap -1 \n"); zion = int.Parse(Console.ReadLine()); if (cnt != 0){} } if (cnt == 0) { Console.WriteLine("something doesn't make sence"); } else { avg = (double)sum / cnt; Console.Write("the AVG is {0}", avg); } Console.ReadLine(); } } } The problem here is that if in the beginning I enter a negative or bigger than hundred number, I will get this message: "zion can be between 0 to 100 only! \nyou can rewrite the zion here, or Press -1 to see the avg\n". If I then meenter -1, this what that shows up instead of the AVG: "Enter next zion, if you want to exit tap -1 \n." How can I solve this problem so when the number is negative or bigger than hundred and than tap -1 I will see the AVG an not another message?

    Read the article

  • JavaScript Loop and wait for function

    - by Fluidbyte
    I have a simple single-dimension array, let's say: fruits = ["apples","bananas","oranges","peaches","plums"]; I can loop thru with with $.each() function: $.each(fruits, function(index, fruit) { showFruit(fruit); }); but I'm calling to another function which I need to finish before moving on to the next item. So, if I have a function like this: function showFruit(fruit){ $.getScript('some/script.js',function(){ // Do stuff }) } What's the best way to make sure the previous fruit has been appended before moving on?

    Read the article

  • How to get unique numbers using randomint python?

    - by user2519572
    I am creating a 'Euromillions Lottery generator' just for fun and I keep getting the same numbers printing out. How can I make it so that I get random numbers and never get the same number popping up: from random import randint numbers = randint(1,50) stars = randint(1,11) print "Your lucky numbers are: ", numbers, numbers, numbers, numbers, numbers print "Your lucky stars are: " , stars, stars The output is just: >>> Your lucky numbers are: 41 41 41 41 41 >>> Your lucky stars are: 8 8 >>> Good bye! How can I fix this? Regards

    Read the article

  • Why can't I roll a loop in Javascript?

    - by Carl Manaster
    I am working on a web page that uses dojo and has a number (6 in my test case, but variable in general) of project widgets on it. I'm invoking dojo.addOnLoad(init), and in my init() function I have these lines: dojo.connect(dijit.byId("project" + 0).InputNode, "onChange", function() {makeMatch(0);}); dojo.connect(dijit.byId("project" + 1).InputNode, "onChange", function() {makeMatch(1);}); dojo.connect(dijit.byId("project" + 2).InputNode, "onChange", function() {makeMatch(2);}); dojo.connect(dijit.byId("project" + 3).InputNode, "onChange", function() {makeMatch(3);}); dojo.connect(dijit.byId("project" + 4).InputNode, "onChange", function() {makeMatch(4);}); dojo.connect(dijit.byId("project" + 5).InputNode, "onChange", function() {makeMatch(5);}); and change events for my project widgets properly invoke the makeMatch function. But if I replace them with a loop: for (var i = 0; i < 6; i++) dojo.connect(dijit.byId("project" + i).InputNode, "onChange", function() {makeMatch(i);}); same makeMatch() function, same init() invocation, same everything else - just rolling my calls up into a loop - the makeMatch function is never called; the objects are not wired. What's going on, and how do I fix it? I've tried using dojo.query, but its behavior is the same as the for loop case.

    Read the article

  • Performance difference in for loop condition?

    - by CSharperWithJava
    Hello all, I have a simple question that I am posing mostly for my curiousity. What are the differences between these two lines of code? (in C++) for(int i = 0; i < N, N > 0; i++) for(int i = 0; i < N && N > 0; i++) The selection of the conditions is completely arbitrary, I'm just interested in the differences between , and &&. I'm not a beginner to coding by any means, but I've never bothered with the comma operator. Are there performance/behavior differences or is it purely aesthetic? One last note, I know there are bigger performance fish to fry than a conditional operator, but I'm just curious. Indulge me. Edit Thanks for your answers. It turns out the code that prompted this question had misused the comma operator in the way I've described. I wondered what the difference was and why it wasn't a && operator, but it was just written incorrectly. I didn't think anything was wrong with it because it worked just fine. Thanks for straightening me out.

    Read the article

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