Search Results

Search found 4036 results on 162 pages for 'nested loops'.

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

  • Nasty deep nested loop in Rails

    - by CalebHC
    I have this nested loop that goes 4 levels deep to find all the image widgets and calculate their sizes. This seems really inefficient and nasty! I have thought of putting the organization_id in the widget model so I could just call something like organization.widgets.(named_scope), but I feel like that's a bad short cut. Is there a better way? Thanks class Organization < ActiveRecord::Base ... def get_image_widget_total total_size = 0 self.trips.each do |t| t.phases.each do |phase| phase.pages.each do |page| page.widgets.each do |widget| if widget.widget_type == Widget::IMAGE total_size += widget.image_file_size end end end end end return total_size end ... end

    Read the article

  • Can a recursive function have iterations/loops?

    - by Omega
    I've been studying about recursive functions, and apparently, they're functions that call themselves, and don't use iterations/loops (otherwise it wouldn't be a recursive function). However, while surfing the web for examples (the 8-queens-recursive problem), I found this function: private boolean placeQueen(int rows, int queens, int n) { boolean result = false; if (row < n) { while ((queens[row] < n - 1) && !result) { queens[row]++; if (verify(row,queens,n)) { ok = placeQueen(row + 1,queens,n); } } if (!result) { queens[row] = -1; } }else{ result = true; } return result; } There is a while loop involved. ... so I'm a bit lost now. Can I use loops or not?

    Read the article

  • Why are Javascript for/in loops so verbose?

    - by Matthew Scharley
    I'm trying to understand the reasoning behind why the language designers would make the for (.. in ..) loops so verbose. For example: for (var x in Drupal.settings.module.stuff) { alert("Index: " + x + "\nValue: " + Drupal.settings.module.stuff[x]); } It makes trying to loop over anything semi-complex like the above a real pain as you either have to alias the value locally inside the loop yourself, or deal with long access calls. This is especially painful if you have two to three nested loops. I'm assuming there is a reason why they would do things this way, but I'm struggling with the reasoning.

    Read the article

  • Loops, Recursion and Memoization in JavaScript

    - by Ken Dason
    Originally posted on: http://geekswithblogs.net/kdason/archive/2013/07/25/loops-recursion-and-memoization-in-javascript.aspxAccording to Wikipedia, the factorial of a positive integer n (denoted by n!) is the product of all positive integers less than or equal to n. For example, 5! = 5 x 4 x 3 x 2 x 1 = 120. The value of 0! is 1. We can use factorials to demonstrate iterative loops and recursive functions in JavaScript.  Here is a function that computes the factorial using a for loop: Output: Time Taken: 51 ms Here is the factorial function coded to be called recursively: Output: Time Taken: 165 ms We can speed up the recursive function with the use of memoization.  Hence,  if the value has previously been computed, it is simply returned and the recursive call ends. Output: Time Taken: 17 ms

    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

  • javascript filter nested object based on key value

    - by murray3
    I wish to filter a nested javascript object by the value of the "step" key: var data = { "name": "Root", "step": 1, "id": "0.0", "children": [ { "name": "first level child 1", "id": "0.1", "step":2, "children": [ { "name": "second level child 1", "id": "0.1.1", "step": 3, "children": [ { "name": "third level child 1", "id": "0.1.1.1", "step": 4, "children": []}, { "name": "third level child 2", "id": "0.1.1.2", "step": 5, "children": []} ]}, ]} ] }; var subdata = data.children.filter(function (d) { return (d.step <= 2)}); This just returns the unmodified nested object, even if I put value of filter to 1. does .filter work on nested objects or do I need to roll my own function here, advise and correct code appreciated. cjm

    Read the article

  • Checking for duplicates with nested forms

    - by Cyrus
    I'm making a rails 3.2.9 app that allows users to create pages and they can embed youtube videos through a nested form. I'm trying to figure out how to make it so that I can prevent duplicate video records from being stored in my db. So I have a Video model that takes the youtube url and just parses out the video id and stores that instead of the full user submitted youtube url, which may have extraneous url query parameters. So here's the situation that I'm trying to figure out: There's page1 with video1 - url: 123 and video2 - url: abc Then another user creates page2 and submits video3 - url: def and video4 - url: 123 Currently each page has_many videos. But I think I should change it to a many-to-many relationship. But how would I make it so that the url submitted as video4 in the nested form points to video1? Also I how would I make a nested form that creates objects that are connected through a join table?

    Read the article

  • Nested class - calling the nested class from the parent class

    - by insanepaul
    I have a class whereby a method calls a nested class. I want to access the parent class properties from within the nested class. public class ParentClass { private x; private y; private z; something.something = new ChildClass public class ChildClass { need to get x, y and z; } } How do I access x,y and z from within the child class. Something to do with referencing the parent class but how? }

    Read the article

  • not able to remove nested lists in a jQuery variable

    - by Pradyut Bhattacharya
    Hi I have a nested oredered list which i m animating using this code... var $li = $("ol#update li"); function animate_li(){ $li.filter(':first') .animate({ height: 'show', opacity: 'show' }, 500, function(){ animate_li(); }); $li = $li.not(':first'); } animate_li(); now i want not to show or animate the nested lists(ol s) or the li s in the ols take a look at the example here The structure of my ols are <ol> <li class="bar248"> <div class="nli"> <div class="pic"> <img src="dir/anonymous-thumb.png"alt="image" /> </div> <div align="left" class="text"> <span> <span class="delete_button"><a href="#" id="test" class="delete_update">R</a></span> test shouted <span class="timestamp"> 2010/02/24 18:34:26 </span> <br /> this </span> </div> <div class="clear"></div> </div> <div class="padd"> </div> <ol class="comment"> <li> <div>Testing </div> </li> <li> <div>Another Test </div> </li> </ol> </li> </ol> I m able to hide the nested ols using this code... $("ol#update li ol").hide(); But still time is being consumed in animating them although they are hidden I m not able to remove the nested li s using this code var $li = $("ol#update li").not("ol#update li ol"); $li = $li.not("ol#update li ol"); Take a look at this here Any help thanks < br Pradyut

    Read the article

  • Nested Row problem

    - by Patrick
    Hi, I'm using the 1kb css grid framework for a site, and although nested rows are apparently supported by the framework, when I try to drop in a nested row it doesn't work! Sorry not to explain it better - the site's here, may be easier to just look at the source: http://2605.co.uk/saf/build/ the grid: /grid.css the stylesheet: /style.css I'm a graphic designer hacking his way through a site he shouldn't be having to build but there's no budget to speak of! Cheers for any help, Patrick

    Read the article

  • MYSQL join - reference external field from nested select?

    - by PHP thinker
    Is it allowed to reference external field from nested select? E.g. SELECT FROM ext1 LEFT JOIN (SELECT * FROM int2 WHERE int2.id = ext1.some_id ) as x ON 1=1 in this case, this is referencing ext1.some_id in nested select. I am getting errors in this case that field ext1.some_id is unknow. Is it possible? Is there some other way?

    Read the article

  • Look for match in a nested list in Python

    - by elfuego1
    Hello everybody, I have two nested lists of different sizes: A = [[1, 7, 3, 5], [5, 5, 14, 10]] B = [[1, 17, 3, 5], [1487, 34, 14, 74], [1487, 34, 3, 87], [141, 25, 14, 10]] I'd like to gather all nested lists from list B if A[2:4] == B[2:4] and put it into list L: L = [[1, 17, 3, 5], [141, 25, 14, 10]] Additionally if the match occurs then I want to change last element of sublist B into first element of sublist A so the final solution would look like this: L1 = [[1, 17, 3, 1], [141, 25, 14, 5]]

    Read the article

  • PYTHON: Look for match in a nested list

    - by elfuego1
    Hello everybody, I have two nested lists of different sizes: A = [[1, 7, 3, 5], [5, 5, 14, 10]] B = [[1, 17, 3, 5], [1487, 34, 14, 74], [1487, 34, 3, 87], [141, 25, 14, 10]] I'd like to gather all nested lists from list B if A[2:4] == B[2:4] and put it into list L: L = [[1, 17, 3, 5], [141, 25, 14, 10]] Would you help me with this?

    Read the article

  • Are nested functions a bad thing in gcc ?

    - by LB
    Hi, I know that nested functions are not part of the standard C, but since they're present in gcc (and the fact that gcc is the only compiler i care about), i tend to use them quite often. Is this a bad thing ? If so, could you show me some nasty examples ? What's the status of nested functions in gcc ? Are they going to be removed ? thanks

    Read the article

  • An observation on .NET loops – foreach, for, while, do-while

    It’s very common that .NET programmers use “foreach” loop for iterating through collections. Following is my observation whilst I was testing simple scenario on loops. “for” loop is 30% faster than “foreach” and “while” loop is 50% faster than “foreach”. “do-while” is bit faster than “while”. Someone may feel that how does it make difference if I’m iterating only 1000 times in a loop. This test case is only for simple iteration. According to the "Data structure" concepts, best and worst cases are completely based on the data we provide to the algorithm. so we can not conclude that a "foreach" algorithm is not good. All I want to tell that we need to be little cautious even choosing the loops. Example:- You might want to chose quick sort when you want to sort more numbers. At the same time bubble sort may be effective than quick sort when you want to sort less numbers. Take a simple scenario, a request of a simple web application fetches the data of 10000 (10K) rows and iterating them for some business logic. Think, this application is being accessed by 1000 (1K) people simultaneously. In this simple scenario you are ending up with 10000000 (10Million or 1 Crore) iterations. below is the test scenario with simple console application to test 100 Million records. using System;using System.Collections.Generic;using System.Diagnostics;namespace ConsoleApplication1{ class Program { static void Main(string[] args) { var sw = new Stopwatch(); var numbers = GetSomeNumbers(); sw.Start(); foreach (var item in numbers) { } sw.Stop(); Console.WriteLine( String.Format("\"foreach\" took {0} milliseconds", sw.ElapsedMilliseconds)); sw.Reset(); sw.Start(); for (int i = 0; i < numbers.Count; i++) { } sw.Stop(); Console.WriteLine( String.Format("\"for\" loop took {0} milliseconds", sw.ElapsedMilliseconds)); sw.Reset(); sw.Start(); var it = 0; while (it++ < numbers.Count) { } sw.Stop(); Console.WriteLine( String.Format("\"while\" loop took {0} milliseconds", sw.ElapsedMilliseconds)); sw.Reset(); sw.Start(); var it2 = 0; do { } while (it2++ < numbers.Count); sw.Stop(); Console.WriteLine( String.Format("\"do-while\" loop took {0} milliseconds", sw.ElapsedMilliseconds)); } #region Get me 10Crore (100 Million) numbers private static List<int> GetSomeNumbers() { var lstNumbers = new List<int>(); var count = 100000000; for (var i = 1; i <= count; i++) { lstNumbers.Add(i); } return lstNumbers; } #endregion Get me some numbers }} In above example, I was just iterating through 100 Million numbers. You can see the time to execute various  loops provided in .NET Output "foreach" took 1108 milliseconds "for" loop took 727 milliseconds "while" loop took 596 milliseconds "do-while" loop took 594 milliseconds   Press any key to continue . . . So I feel we need to be careful while choosing the looping strategy. Please comment your thoughts. span.fullpost {display:none;}

    Read the article

  • Input handling between game loops

    - by user48023
    This may be obvious and trivial for you but as I am a newbie in programming I come with a specific question. I have three loops in my game engine which are input-loop, update-loop and render-loop. Update-loop is set to 10 ticks per second with a fixed timestep, render-loop is capped at around 60 fps and the input-loop runs as fast as possible. I am using one of the Javascript frameworks which provide such things but it doesn't really matter. Let's say I am rendering a tile map and the view of which elements are rendered depends on camera-like movement variables which are modified during key pressing. This is only about camera/viewport and rendering, no game physics involved here. And now, how can I handle input events among these loops to keep consistent engine reaction? Am I supposed to read the current variable modified with input and do some needed calculations in a update-loop and share the result so it could be interpolated in a render-loop? Or read the input effect directly inside the render-loop and put needed calculations inside? I thought interpreting user input inside an update-loop with a low tick rate would be inaccurate and kind of unresponsive while rendering with interpolation in the final view. How it is done properly in games overall?

    Read the article

  • Achieving NHibernate Nested Transactions Behavior

    - by jfneis
    Hi all, I'm trying to achieve some kind of nested transaction behavior using NHibernate's transaction control and FlushMode options, but things got a little bit confusing after too much reading, so any confirmation about the facts I list below will be very usefull. What I want is to open one big transaction that splits in little transactions. Imagine the following scenario: TX1 opens a TX and inserts a Person's record; TX2 opens a TX and updates this Person's name to P2; TX2 commits; TX3 opens a TX and updates this Person's name to P3; TX3 rollbacks; TX1 commits; I'd like to see NH sending the INSERT and the TX2 UPDATE to the database, just ignoring what TX3, as it was rolled back. I tried to use FlushMode = Never and only flushing the session after the proper Begins/Commits/Rollbacks have been demanded, but NH always update the database with the object's final state, independent of commits and rollbacks. Is that normal? Does NH really ignores transactional control when working with FlushMode = Never? I've also tried to use FlushMode = Commit and openning the nested transactions, but I discovered that, because ADO.NET, the nested transactions are, actually, always the same transaction. Note that I'm not trying to achieve a "all or nothing" behavior. I'm looking more to a savepoint way of working. Is there a way to do that (savepoints) with NH? Thank you in advance. Filipe

    Read the article

  • "Public" nested classes or not

    - by Frederick
    Suppose I have a class 'Application'. In order to be initialised it takes certain settings in the constructor. Let's also assume that the number of settings is so many that it's compelling to place them in a class of their own. Compare the following two implementations of this scenario. Implementation 1: class Application { Application(ApplicationSettings settings) { //Do initialisation here } } class ApplicationSettings { //Settings related methods and properties here } Implementation 2: class Application { Application(Application.Settings settings) { //Do initialisation here } class Settings { //Settings related methods and properties here } } To me, the second approach is very much preferable. It is more readable because it strongly emphasises the relation between the two classes. When I write code to instantiate Application class anywhere, the second approach is going to look prettier. Now just imagine the Settings class itself in turn had some similarly "related" class and that class in turn did so too. Go only three such levels and the class naming gets out out of hand in the 'non-nested' case. If you nest, however, things still stay elegant. Despite the above, I've read people saying on StackOverflow that nested classes are justified only if they're not visible to the outside world; that is if they are used only for the internal implementation of the containing class. The commonly cited objection is bloating the size of containing class's source file, but partial classes is the perfect solution for that problem. My question is, why are we wary of the "publicly exposed" use of nested classes? Are there any other arguments against such use?

    Read the article

  • How do I do nested transactions in NHibernate?

    - by Gavin Schultz-Ohkubo
    Can I do nested transactions in NHibernate, and how do I implement them? I'm using SQL Server 2008, so support is definitely in the DBMS. I find that if I try something like this: using (var outerTX = UnitOfWork.Current.BeginTransaction()) { using (var nestedTX = UnitOfWork.Current.BeginTransaction()) { ... do stuff nestedTX.Commit(); } outerTX.Commit(); } then by the time it comes to outerTX.Commit() the transaction has become inactive, and results in a ObjectDisposedException on the session AdoTransaction. Are we therefore supposed to create nested NHibernate sessions instead? Or is there some other class we should use to wrap around the transactions (I've heard of TransactionScope, but I'm not sure what that is)? I'm now using Ayende's UnitOfWork implementation (thanks Sneal). Forgive any naivety in this question, I'm still new to NHibernate. Thanks! EDIT: I've discovered that you can use TransactionScope, such as: using (var transactionScope = new TransactionScope()) { using (var tx = UnitOfWork.Current.BeginTransaction()) { ... do stuff tx.Commit(); } using (var tx = UnitOfWork.Current.BeginTransaction()) { ... do stuff tx.Commit(); } transactionScope.Commit(); } However I'm not all that excited about this, as it locks us in to using SQL Server, and also I've found that if the database is remote then you have to worry about having MSDTC enabled... one more component to go wrong. Nested transactions are so useful and easy to do in SQL that I kind of assumed NHibernate would have some way of emulating the same...

    Read the article

  • Rails nested models and data separation by scope

    - by jobrahms
    I have Teacher, Student, and Parent models that all belong to User. This is so that a Teacher can create Students and Parents that can or cannot log into the app depending on the teacher's preference. Student and Parent both accept nested attributes for User so a Student and User object can be created in the same form. All four models also belong to Studio so I can do data separation by scope. The current studio is set in application_controller.rb by looking up the current subdomain. In my students controller (all of my controllers, actually) I'm using @studio.students.new instead of Student.new, etc, to scope the new student to the correct studio, and therefore the correct subdomain. However, the nested User does not pick up the studio from its parent - it gets set to nil. I was thinking that I could do something like params[:student][:user_attributes][:studio_id] = @student.studio.id in the controller, but that would require doing attr_accessible :studio_id in User, which would be bad. How can I make sure that the nested User picks up the same scope that the Student model gets when it's created? student.rb class Student < ActiveRecord::Base belongs_to :studio belongs_to :user, :dependent => :destroy attr_accessible :user_attributes accepts_nested_attributes_for :user, :reject_if => :all_blank end students_controller.rb def create @student = @studio.students.new @student.attributes = params[:student] if @student.save redirect_to @student, :notice => "Successfully created student." else render :action => 'new' end end user.rb class User < ActiveRecord::Base belongs_to :studio accepts_nested_attributes_for :studio attr_accessible :email, :password, :password_confirmation, :remember_me, :studio_attributes devise :invitable, :database_authenticatable, :recoverable, :rememberable, :trackable end

    Read the article

  • Break the nested(double) loop in python

    - by prosseek
    I use the following method to break the double loop in Python. for word1 in buf1: find = False for word2 in buf2: ... if res == res1: print "BINGO " + word1 + ":" + word2 find = True if find: break Is there better way to break the double loop?

    Read the article

  • php nested for statements?

    - by Dashiell0415
    I'm trying to process a for loop within a for loop, and just a little wary of the syntax... Will this work? Essentially, I want to run code for every 1,000 records while the count is equal to or less than the $count... Will the syntax below work, or is there a better way? for($x = 0; $x <= 700000; $x++) { for($i = 0; $i <= 1000; $i++) { //run the code } }

    Read the article

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