Search Results

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

Page 10/162 | < Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >

  • Nested Resource testing RSpec

    - by Joseph DelCioppio
    I have two models: class Solution < ActiveRecord::Base belongs_to :owner, :class_name => "User", :foreign_key => :user_id end class User < ActiveRecord::Base has_many :solutions end with the following routing: map.resources :users, :has_many => :solutions and here is the SolutionsController: class SolutionsController < ApplicationController before_filter :load_user def index @solutions = @user.solutions end private def load_user @user = User.find(params[:user_id]) unless params[:user_id].nil? end end Can anybody help me with writing a test for the index action? So far I have tried the following but it doesn't work: describe SolutionsController do before(:each) do @user = Factory.create(:user) @solutions = 7.times{Factory.build(:solution, :owner => @user)} @user.stub!(:solutions).and_return(@solutions) end it "should find all of the solutions owned by a user" do @user.should_receive(:solutions) get :index, :user_id => @user.id end end And I get the following error: Spec::Mocks::MockExpectationError in 'SolutionsController GET index, when the user owns the software he is viewing should find all of the solutions owned by a user' #<User:0x000000041c53e0> expected :solutions with (any args) once, but received it 0 times Thanks in advance for all the help. Joe

    Read the article

  • Nested Views-button aint clicking

    - by Deepika
    i have a view which has a datepicker and a button added to it. There is another view which adds the above view as subview. But the events like touchesBegan and button's action are not being clicked on the subview. Please help The code of the parent view is: iTagDatePicker *dt=[[iTagDatePicker alloc] initWithFrame:CGRectMake(0.0, 180.0, 320.0, 240.0)]; //dt.userInteractionEnabled=YES; //[dt becomeFirstResponder]; dt.backgroundColor=[UIColor clearColor]; [UIView beginAnimations:@"animation" context:nil]; [UIView setAnimationDuration:1.0]; CGPoint cntr; cntr.x=160.0; cntr.y=420.0; dt.center=cntr; [self.view addSubview:dt]; self.view.userInteractionEnabled=YES; CGPoint cntr1; cntr1.x=160.0; cntr1.y=158.0; dt.center=cntr1; [UIView commitAnimations]; [dt release]; and the code for the sub class is: - (id)initWithFrame:(CGRect)frame { if (self = [super initWithFrame:frame]) { dtPicker=[[UIDatePicker alloc] initWithFrame:CGRectMake(frame.origin.x, frame.origin.y, 320.0, 216.0)]; dtPicker.datePickerMode=UIDatePickerModeDate; dtPicker.date=[NSDate date]; [self addSubview:dtPicker]; btn=[[UIButton buttonWithType:UIButtonTypeDetailDisclosure]retain]; btn.frame=CGRectMake(110.0, 400.0, 100.0, 20.0); [btn setTitle:@"Done" forState:UIControlStateNormal]; btn.userInteractionEnabled=YES; [btn becomeFirstResponder]; [btn addTarget:self action:@selector(SelectedVal:) forControlEvents:UIControlEventTouchDown]; [self addSubview:btn]; } return self; } The button is not working

    Read the article

  • Formtastic + nested categories

    - by astropanic
    I have an article model and an category model. Category act as tree. What is the best approch to build a select list to allow the administrator to select an category from a select list to associate it later with an article ? semantic_form_for(@article) do |f| f.input :title, :as => :string f.input :content, :as => :text f.input :category, :collection => #what should go here ? end

    Read the article

  • Regex: match a non nested code block

    - by Sylvanas Garde
    I am currently writing a small texteditor. With this texteditor users are able to create small scripts for a very simple scripting engine. For a better overview I want to highlight codeblocks with the same command like GoTo(x,y) or Draw(x,y). To achieve this I want to use Regular Expresions (I am already using it to highlight other things like variables) Here is my Expression (I know it's very ugly): /(?<!GoTo|Draw|Example)(^(?:GoTo|Draw|Example)\(.+\)*?$)+(?!GoTo|Draw|Example)/gm It matches the following: lala GoTo(5656) -> MATCH 1 sdsd GoTo(sdsd) --comment -> MATCH 2 GoTo(23329); -> MATCH 3 Test() GoTo(12) -> MATCH 4 LALA Draw(23) -> MATCH 5 Draw(24) -> MATCH 6 Draw(25) -> MATCH 7 But what I want to achieve is, that the complete "blocks" of the same command are matched. In this case Match 2 & 4 and Match 5 & 6 & 7 should be one match. Tested with http://regex101.com/, the programming lanuage is vb.net. Any advise would be very useful, Thanks in advance!

    Read the article

  • xmlns='' was not expected when deserializing nested classes

    - by Mavrik
    I have a problem when attempting to serialize class on a server, send it to the client and deserialize is on the destination. On the server I have the following two classes: [XmlRoot("StatusUpdate")] public class GameStatusUpdate { public GameStatusUpdate() {} public GameStatusUpdate(Player[] players, Command command) { this.Players = players; this.Update = command; } [XmlArray("Players")] public Player[] Players { get; set; } [XmlElement("Command")] public Command Update { get; set; } } and [XmlRoot("Player")] public class Player { public Player() {} public Player(PlayerColors color) { Color = color; ... } [XmlAttribute("Color")] public PlayerColors Color { get; set; } [XmlAttribute("X")] public int X { get; set; } [XmlAttribute("Y")] public int Y { get; set; } } (The missing types are all enums). This generates the following XML on serialization: <?xml version="1.0" encoding="utf-16"?> <StatusUpdate> <Players> <Player Color="Cyan" X="67" Y="32" /> </Players> <Command>StartGame</Command> </StatusUpdate> On the client side, I'm attempting to deserialize that into following classes: [XmlRoot("StatusUpdate")] public class StatusUpdate { public StatusUpdate() { } [XmlArray("Players")] [XmlArrayItem("Player")] public PlayerInfo[] Players { get; set; } [XmlElement("Command")] public Command Update { get; set; } } and [XmlRoot("Player")] public class PlayerInfo { public PlayerInfo() { } [XmlAttribute("X")] public int X { get; set; } [XmlAttribute("Y")] public int Y { get; set; } [XmlAttribute("Color")] public PlayerColor Color { get; set; } } However, the deserializer throws an exception: There is an error in XML document (2, 2). <StatusUpdate xmlns=''> was not expected. What am I missing or doing wrong?

    Read the article

  • How to make a nested query with an Entity that doesn't really exist (many-to-many)

    - by Calou
    Hi everyone, I'm new with Doctrine2 so my question can be easy to answer (I hope so). First of all, here the SQL query that I'd want : SELECT * FROM Document WHERE id NOT IN (SELECT document_id FROM Documents_Folders) Pretty simple isn't it ? The porblem is that my table 'Documents_Folders' is not an entity. In fact, it was create because I have a many-to-many relation between my entities 'Document' and 'Folder'. I tried several queries, but none worked. Thanks.

    Read the article

  • Dynamically add data stored in php to nested json

    - by HoGo
    I am trying to dynamicaly generate data in json for jQuery gantt chart. I know PHP but am totally green with JavaScript. I have read dozen of solutions on how dynamicaly add data to json, and tried few dozens of combinations and nothing. Here is the json format: var data = [{ name: "Sprint 0", desc: "Analysis", values: [{ from: "/Date(1320192000000)/", to: "/Date(1322401600000)/", label: "Requirement Gathering", customClass: "ganttRed" }] },{ name: " ", desc: "Scoping", values: [{ from: "/Date(1322611200000)/", to: "/Date(1323302400000)/", label: "Scoping", customClass: "ganttRed" }] }, <!-- Somoe more data--> }]; now I have all data in php db result. Here it goes: $rows=$db->fetchAllRows($result); $rowsNum=count($rows); And this is how I wanted to create json out of it: var data=''; <?php foreach ($rows as $row){ ?> data['name']="<?php echo $row['name'];?>"; data['desc']="<?php echo $row['desc'];?>"; data['values'] = {"from" : "/Date(<?php echo $row['from'];?>)/", "to" : "/Date(<?php echo $row['to'];?>)/", "label" : "<?php echo $row['label'];?>", "customClass" : "ganttOrange"}; } However this does not work. I have tried without loop and replacing php variables with plain text just to check, but it did not work either. Displays chart without added items. If I add new item by adding it to the list of values, it works. So there is no problem with the Gantt itself or paths. Based on all above I assume the problem is with adding plain data to json. Can anyone please help me to fix it?

    Read the article

  • MySQL nested CASE error I need help with?

    - by AK
    What I am trying to do here is: IF the records in table todo as identified in $done have a value in the column recurinterval then THEN reset date_scheduled column ELSE just set status_id column to 6 for those records. This is the error I get from mysql_error() ... You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CASE recurinterval != 0 AND recurinterval IS NOT NULL THEN SET date_sche' at line 2 How can I make this statement work? UPDATE todo CASE recurinterval != 0 AND recurinterval IS NOT NULL THEN SET date_scheduled = CASE recurunit WHEN 'DAY' THEN DATE_ADD(date_scheduled, INTERVAL recurinterval DAY) WHEN 'WEEK' THEN DATE_ADD(date_scheduled, INTERVAL recurinterval WEEK) WHEN 'MONTH' THEN DATE_ADD(date_scheduled, INTERVAL recurinterval MONTH) WHEN 'YEAR' THEN DATE_ADD(date_scheduled, INTERVAL recurinterval YEAR) END WHERE todo_id IN ($done) ELSE SET status_id = 6 WHERE todo_id IN ($done) END The following mySQL statement worked just fine before I revised like above. UPDATE todo SET date_scheduled = CASE recurunit WHEN 'DAY' THEN DATE_ADD(date_scheduled, INTERVAL recurinterval DAY) WHEN 'WEEK' THEN DATE_ADD(date_scheduled, INTERVAL recurinterval WEEK) WHEN 'MONTH' THEN DATE_ADD(date_scheduled, INTERVAL recurinterval MONTH) WHEN 'YEAR' THEN DATE_ADD(date_scheduled, INTERVAL recurinterval YEAR) END WHERE todo_id IN ($done) AND recurinterval != 0 AND recurinterval IS NOT NULL

    Read the article

  • nested function

    - by user359179
    Hi to all of you, 1.I just came across that ANSI(ISO) aint allow nesting of function.. i want to know what makes gnu c ito implemet this functionality(why such need arise). 2.If a function say(a()) is define with in another function say(b()) then the lifetime of a() would be whole prorgramme? 3.Will the storage for a() ll be created in a stack allocated to function b().?

    Read the article

  • PHP - Nested Looping Trouble

    - by Jeremy A
    I have an HTML table that I need to populate with the values grabbed from a select statement. The table cols are populated by an array (0,1,2,3). Each of the results from the query will contain a row 'GATE' with a value of (0-3), but there will not be any predictability to those results. One query could pull 4 rows with 'GATE' values of 0,1,2,3, the next query could pull two rows with values of 1 & 2, or 1 & 3. I need to be able to populate this HTML table with values that correspond. So HTML COL 0 would have the TTL_NET_SALES of the db row which also has the GATE value of 0. <?php $gate = array(0,1,2,3); $gate_n = count($gate); /* Database = my_table.ID my_table.TT_NET_SALES my_table.GATE my_table.LOCKED */ $locked = "SELECT * FROM my_table WHERE locked = true"; $locked_n = count($locked); /* EXAMPLE RETURN Row 1: my_table['ID'] = 1 my_table['TTL_NET_SALES'] = 1000 my_table['GATE'] = 1; Row 2: my_table['ID'] = 2 my_table['TTL_NET_SALES'] = 1500 my_table['GATE'] = 3; */ print "<table border='1'>"; print "<tr><td>0</td><td>1</td><td>2</td><td>3</td>"; print "<tr>"; for ($i=0; $i<$locked_n; $i++) { for ($g=0; $g<$gate_n; $g++) { if (!is_null($locked['TTL_NET_SALES'][$i]) && $locked['GATE'][$i] == $gate[$g]) { print "<td>$".$locked['TTL_NET_SALES'][$i]."</td>"; } else { print "<td>-</td>"; } } } print "</tr>"; print "</table>"; /* What I want to see: <table border='1'> <tr> <td>0</td> <td>1</td> <td>2</td> <td>3</td> </tr> <tr> <td>-</td> <td>1000</td> <td>-</td> <td>1500</td> </tr> </table> */ ?>

    Read the article

  • Rails 3 ActiveModel Nested Class I18n

    - by Dave
    Given the following class definition in ruby: class Conversation class Message include ActiveModel::Validations attr_accessor :quantity validates :quantity, :presence => true end end How can you use i18n to customize to error message. For example the correct lookup for the class Conversation would be activemodel: errors: models: conversation: attributes: quantity: blank: "Some custom message" But what is it for the Message class? I tried: activemodel: errors: models: conversation: message: attributes: quantity: blank: "Some custom message" activemodel: errors: models: message: attributes: quantity: blank: "Some custom message" activemodel: errors: models: conversation::message: attributes: quantity: blank: "Some custom message" None of them work Any ideas or is this a bug with ActiveModel or I18n?

    Read the article

  • Elegant way to reverse order Formtastic nested objects?

    - by stephan.com
    I'm presenting a list of items to the user with a field for a new item, like this: - current_user.tasks.build - semantic_form_for current_user do |f| - f.semantic_fields_for :tasks do |t| - t.inputs do = t.input :_destroy, :as => :boolean, :label => '' - if t.object.new_record? = t.input :name, :label => false - else = t.object.name Which looks lovely and works like a charm. My only problem is I want the new record at the TOP of the list, not the bottom. Is there an elegant and easy way to do this, or am I going to have to do the new element separately, or loop through the list manually?

    Read the article

  • nested join linq-to-sql queries

    - by ile
    var result = ( from contact in db.Contacts where contact.ContactID == id join referContactID in db.ContactRefferedBies on contact.ContactID equals referContactID.ContactID join referContactName in db.Contacts on contact.ContactID equals referContactID.ContactID orderby contact.ContactID descending select new ContactReferredByView { ContactReferredByID = referContactID.ContactReferredByID, ContactReferredByName = referContactName.FirstName + " " + referContactName.LastName }).Single(); Problem is in this line: join referContactName in db.Contacts on contact.ContactID equals referContactID.ContactID where referContactID.ContactID is called from the above join line. How to nest these two joins? Thanks in advance! Ile

    Read the article

  • Howto: Access a second related model in a nested attribute builder block

    - by Joe Cairns
    I have a basic has_many through relationship: class Foo < ActiveRecord::Base has_many :bars, :dependent => :destroy has_many :wtfs :through => :bars accepts_nested_attributes_for :bars, :wtfs end On my crud forms I have a builder block for the wtf, but I need the label to come from the bar (an attribute called label for instance). What's the proper method to do this? Here's the most simple scaffold: <h1>New foo</h1> <% form_for(@foo) do |f| %> <%= f.error_messages %> <p> <%= f.label :name %><br /> <%= f.text_field :name %> </p> <h2>Bars</h2> <% f.fields_for :wtfs do |builder| %> <%= builder.hidden_field :bar_id %> <p> <%= builder.text_field :wtf_data_i_need_to_set %> </p> <% end %> <p> <%= f.submit 'Create' %> </p> <% end %> <%= link_to 'Back', foos_path %>

    Read the article

  • Getting HIERARCHY_REQUEST_ERR when using Javascript to recursively generate a nested list

    - by Mark
    I have a method that is trying to take in a list. This list can contain data and other lists. The end goal is to try to convert something like this ["a", "b", ["c", "d"]] into <ol> <li> <b>a</a> </li> <li> <b>b</a> </li> <ol> <li> <b>c</a> </li> <li> <b>d</a> </li> </ol> </ol> The code is: function $(tagName) { return document.createElement(tagName); } //returns an html element representing data //data should be an array or some sort of value function tagMaker(data) { tag = null; if(data instanceof Array) { //data is an array, represent using <ol> tag = $("ol"); for(i=0; i<data.length; i++) { //construct one <li> for each item in the array listItem = $("li"); //get the html element representing this particular item in the array child = tagMaker(data[i]); //<li>*html for child*</li> listItem.appendChild(child); //add this item to the list tag.appendChild(listItem); } } else { //data is not an array, represent using <b>data</b> tag = $("b"); tag.innerHTML = data.toString(); } return tag; } Calling tagMaker throws HIERARCHY_REQUEST_ERR: DOM Exception 3, rather than generating a helpful HTML element object which I was planning to append to document.body.

    Read the article

  • sorting nested list, allow only li to be sorted witin the same ul

    - by Y.G.J
    $(document).ready(function() { $("#test-list").sortable({ items: "> li", handle : '.handle', axis: 'y', opacity: 0.6, update : function () { var order = $('#test-list').sortable('serialize'); $("#info").load("process-sortable.asp?"+order+"&id=catid&order=orderid&table=tblCats"); } }); $("#test-sub").sortable({ containment: "ul", items: "li", handle : '.handle2', axis: 'y', opacity: 0.6, update : function () { var order = $('ul').sortable('serialize'); $("#info").load("process-sortable.asp?"+order+"&id=catid&order=orderid&table=tblCats"); } }); }); <ul id="test-list"> <li id="listItem_10">first<img align="middle" src="Themes/arrow.png" class="handle" /></li> <li id="listItem_8">second<img align="middle" src="Themes/arrow.png" class="handle" /> <ul id="test-sub"> <li id="listItem_4"><img align="middle" src="Themes/arrow.png" class="handle2" /></li> <li id="listItem_3"><img align="middle" src="Themes/arrow.png" class="handle2" /></li> <ul id="test-sub"> <li id="listItem_9"><img align="middle" src="Themes/arrow.png" class="handle2" /></li> </ul> </li> </ul> </li> </ul> the problems i have: sorting the main ul is working but not all the time - i will try to fix that my own but if there is a problem with the code here and not the one in proccess-sortable - tell me. moving li in the main ul is ok but the sub or the sub of the sub is having problem - i can drag something from one sub to it's sub or the other way too - i don't want that to happend. i want to be able to drag li and by selecting that one that only this ul group will send to proccess-sortable to be updated - how can i catch the specific ul of li i am draging?

    Read the article

  • Build model with nested model in rspec integration test

    - by user1116573
    I understand that I can do something like in rspec: let(:project) { Project.new } but in my app a project accepts_nested_attributes_for tasks and when I generate the Project form I build a task along with it using: @project = Project.new @project.tasks.build I need something like: let(:project) { Project.new.tasks.build } but that doesn't seem to work. How can I do this as a let in my rspec test?

    Read the article

  • android nested lists

    - by Raogrimm
    i'm new to programming android and i have found some useful things for my app, but i can't seem to find how to make a list filled with an string array display a new list that is going to be populated with a string array. i would like to have the user choose an item from the top_menu list and from there go to the desired area and have that array appear. this is what i have so far: public class HelloListActivity extends ListActivity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String[] top_menu = getResources().getStringArray(R.array.top_menu); setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, top_menu)); ListView lv = getListView(); lv.setTextFilterEnabled(true); lv.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { ??? } }); } all my arrays are working fine, i just don't know how to repopulate a new list with the other array depending on the choice the user made. any help is greatly appreciated

    Read the article

  • Best way to access nested data structures?

    - by Blackshark
    I would like to know what the best way (performance wise) to access a large data structure is. There are about hundred ways to do it but what is the most accessible for the compiler to optimize? One can access a value by foo[someindex].bar[indexlist[i].subelement[j]].baz[0] or create some pointer aliases like sometype_t* tmpfoo = &foo[someindex]; tmpfoo->bar[indexlist[i].subelement[j]].baz[0] or create reference aliases like sometype_t &tmpfoo = foo[someindex]; tmpfoo.bar[indexlist[i].subelement[j]].baz[0] and so forth...

    Read the article

  • Simple nested setTimeout() only runs once (JavaScript)

    - by danielfaraday
    For some reason my galleryScroll() function only runs once, even though the function calls itself using setTimeout(). I'm thinking the issue may be related to scope, but I'm not sure: http://jsfiddle.net/CYEBC/2/ $(document).ready(function() { var x = $('#box').offset().left; var y = $('#box').offset().top; galleryScroll(); function galleryScroll() { x = x + 1; y = y + 1; $('#box').offset({ left: x, top: y }); setTimeout('galleryScroll()', 100); } });? The HTML: <html> <head> </head> <body> <div id="box"> </div> </body> </html>

    Read the article

  • Nested property class

    - by user998405
    I got 1 parent property class and 3 child property class. Here is my example Parent class public class blcSalesParam { public string selectFrom { get; set; } public string pageAction { get; set; } } Child class public class blcDeliveryOrder { public int? DeliveryID { get; set; } public string DeliveryCode { get; set; }

    Read the article

  • Ubuntu 12.04 LTS loops the login screen unless you login as Guest

    - by Mário Silva
    I am running a VMWare Player with a Ubuntu 12.04 LTS Precise Pangloin as Guest on my Windows 7. Sometimes I get the shutdown blue screen error in Windows, this time it happened when I was running the Player. When I restarted everything Ubuntu gave the not so unfamiliar in this forum Login Loop in adminstrator login. I login and there's this black screen where I can only read: "piix4...smbus:0.0.0.07.3 Host Smbus controller not enabled" . When I go to the Prompt in root mode it fails to update and only upgraded, specially some plugins ( I think graphic plugins) which also appear in one an error message after quitting the prompt, but they´are successfully installed. They are not the error message. After that I have been working with the Fail/safe Mode recovery panel. When I try to update via Root I get errors like this: W:failed to fetch http://extras.ubuntu.com/ubuntu/dists/precise/release.gpg could not resolve 'extras/ubuntu.com There are 8 more like this referring to areas like: -archive/canonical.com -ppa.Launchpad.net -security.Ubuntu.com -Us.archive.ubuntu.com - release.gpg precise-updates/release.gpg precise_backport/release.gpg Final Message: some index files failed to download.....they have been ignored or old files are used. The black screens most of the time pass by too fast for me to pick up any information. But in general I think I have done everything I was able to in the recovery panel including updating network and graphic packages and recovering filesystem packages and the basic stuff ( I am a beginner regarding Linux ) in the root prompt. Now I am stuck in this screen with graphic options: - Run in low-graphics mode just for one session - Reconfigure Graphics - Troubleshoot the error - Exit to console login I am trying to choose to reconfigure graphics but the mouse disappears in the virtual machine screen and sometimes when options change ity´s only the first and last option. ut this happens from the blue without messages. This particular option menu is in the regular GUI style against a black screen in Terminal style. Really strange. Thanx in advance, all is welcome and appreciated.

    Read the article

  • how to do event checks for loops?

    - by yao jiang
    I am having some trouble getting the logic down for this. Currently, I have an app that animates the astar pathfinding algorithm. On start of the app, the ui will show the following: User can press "space" to randomly choose start/end coords, then the app will animate it. Or, user can choose the start/end by left-click/right-click. During the animation, the user can also left-click to generate blocks, or right-click to choose a new destiantion. Where I am stuck at is how to handle the events while the app is animating. Right now, I am checking events in the main loop, then when the app is animating, I do event checks again. While it works fine, I feel that I am probably doing it wrong. What is the proper way of setting up the main loop that will handle the events while the app is animating? In main loop, the app start animating once user choose start/end. In my draw function, I am putting another event checker in there. def clear(rows): for r in range(rows): for c in range(rows): if r%3 == 1 and c%3 == 1: color = brown; grid[r][c] = 1; buildCoor.append(r); buildCoor.append(c); else: color = white; grid[r][c] = 0; pick_image(screen, color, width*c, height*r); pygame.display.flip(); os.system('cls'); # draw out the grid def draw(start, end, grid, route_coord): # draw the end coords color = red; pick_image(screen, color, width*end[1],height*end[0]); pygame.display.flip(); # then draw the rest of the route for i in range(len(route_coord)): # pausing because we want animation time.sleep(speed); # get the x/y coords x,y = route_coord[i]; event_on = False; if grid[x][y] == 2: color = green; elif grid[x][y] == 3: color = blue; for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONDOWN: if event.button == 3: print "destination change detected, rerouting"; # get mouse position, px coords pos = pygame.mouse.get_pos(); # get grid coord c = pos[0] // width; r = pos[1] // height; grid[r][c] = 4; end = [r, c]; elif event.button == 1: print "user generated event"; pos = pygame.mouse.get_pos(); # get grid coord c = pos[0] // width; r = pos[1] // height; # mark it as a block for now grid[r][c] = 1; event_on = True; if check_events([x,y]) or event_on: # there is an event # mark it as a block for now grid[y][x] = 1; pick_image(screen, event_x, width*y, height*x); pygame.display.flip(); # then find a new route new_start = route_coord[i-1]; marked_grid, route_coord = find_route(new_start, end, grid); draw(new_start, end, grid, route_coord); return; # just end draw here so it wont throw the "index out of range" error elif grid[x][y] == 4: color = red; pick_image(screen, color, width*y, height*x); pygame.display.flip(); # clear route coord list, otherwise itll just add more unwanted coords route_coord_list[:] = []; clear(rows); # main loop while not done: # check the events for event in pygame.event.get(): # mouse events if event.type == pygame.MOUSEBUTTONDOWN: # get mouse position, px coords pos = pygame.mouse.get_pos(); # get grid coord c = pos[0] // width; r = pos[1] // height; # find which button pressed, highlight grid accordingly if event.button == 1: # left click, start coords if grid[r][c] == 2: grid[r][c] = 0; color = white; elif grid[r][c] == 0 or grid[r][c] == 4: grid[r][c] = 2; start = [r,c]; color = green; else: grid[r][c] = 1; color = brown; elif event.button == 3: # right click, end coords if grid[r][c] == 4: grid[r][c] = 0; color = white; elif grid[r][c] == 0 or grid[r][c] == 2: grid[r][c] = 4; end = [r,c]; color = red; else: grid[r][c] = 1; color = brown; pick_image(screen, color, width*c, height*r); # keyboard events elif event.type == pygame.KEYDOWN: clear(rows); # one way to quit program if event.key == pygame.K_ESCAPE: print "program will now exit."; done = True; # space key for random start/end elif event.key == pygame.K_SPACE: # first clear the ui clear(rows); # now choose random start/end coords buildLoc = zip(buildCoor,buildCoor[1:])[::2]; #print buildLoc; (start_x, start_y, end_x, end_y) = pick_point(); while (start_x, start_y) in buildLoc or (end_x, end_y) in buildLoc: (start_x, start_y, end_x, end_y) = pick_point(); clear(rows); print "chosen random start/end coords: ", (start_x, start_y, end_x, end_y); if (start_x, start_y) in buildLoc or (end_x, end_y) in buildLoc: print "error"; # draw the route marked_grid, route_coord = find_route([start_x,start_y],[end_x,end_y], grid); draw([start_x, start_y], [end_x, end_y], marked_grid, route_coord); # return key for user defined start/end elif event.key == pygame.K_RETURN: # first clear the ui clear(rows); # get the user defined start/end print "user defined start/end are: ", (start[0], start[1], end[0], end[1]); grid[start[0]][start[1]] = 1; grid[end[0]][end[1]] = 2; # draw the route marked_grid, route_coord = find_route(start, end, grid); draw(start, end, marked_grid, route_coord); # c to clear the screen elif event.key == pygame.K_c: print "clearing screen."; clear(rows); # go fullscreen elif event.key == pygame.K_f: if not full_sc: pygame.display.set_mode([1366, 768], pygame.FULLSCREEN); full_sc = True; rows = 15; clear(rows); else: pygame.display.set_mode(size); full_sc = False; # +/- key to change speed of animation elif event.key == pygame.K_LEFTBRACKET: if speed >= 0.1: print SPEED_UP; speed = speed_up(speed); print speed; else: print FASTEST; print speed; elif event.key == pygame.K_RIGHTBRACKET: if speed < 1.0: print SPEED_DOWN; speed = slow_down(speed); print speed; else: print SLOWEST print speed; # second method to quit program elif event.type == pygame.QUIT: print "program will now exit."; done = True; # limit to 20 fps clock.tick(20); # update the screen pygame.display.flip();

    Read the article

  • The Infinite Jukebox Creates Seamless Loops from Your Favorite Songs

    - by Jason Fitzpatrick
    Why limit yourself to simply listening to a song on repeat when The Infinite Jukebox can use algorithms to turn your song into a seamless and never ending tune? Unlike simply looping a song from the start to the end over and over, The Infinite Jukebox analyzes the song and looks for spots where it can seamlessly transition from one point in the song to a previous point to create a sense of never-ending music. Some songs worked better than others in our testing–Superstition by Stevie Wonder, for example, worked flawlessly but Gangnam Style by Psy got stuck in a short loop that sounded unnatural. Hit up the link below to play with already uploaded MP3s or upload your own to take it for a spin. The Infinite Jukebox How To Use USB Drives With the Nexus 7 and Other Android Devices Why Does 64-Bit Windows Need a Separate “Program Files (x86)” Folder? Why Your Android Phone Isn’t Getting Operating System Updates and What You Can Do About It

    Read the article

  • Prefer algorithms to hand-written loops?

    - by FredOverflow
    Which of the following to you find more readable? The hand-written loop: for (std::vector<Foo>::const_iterator it = vec.begin(); it != vec.end(); ++it) { bar.process(*it); } Or the algorithm invocation: #include <algorithm> #include <functional> std::for_each(vec.begin(), vec.end(), std::bind1st(std::mem_fun_ref(&Bar::process), bar)); I wonder if std::for_each is really worth it, given such a simple example already requires so much code. What are your thoughts on this matter?

    Read the article

< Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >