Search Results

Search found 3425 results on 137 pages for 'polynomial math'.

Page 127/137 | < Previous Page | 123 124 125 126 127 128 129 130 131 132 133 134  | Next Page >

  • sorry for asking again the same user here help me out

    - by jazz
    i copied a game from a book which name is paratrooper i ask this question again i also provide the code of the objects which i create there i want to change the color of these objects but i didn't understand how to do that so can any one plz help me how to do that.Listen guys they are not the standard functions but i use the graphics library for these functions and i can't find the function in the library file of graphics. i hope u understand know.this code will not run properly so plz tell me something about the function which color it i can't put the image other wize i show u the image it will make alot easieer #include "graphics.h" #include "stdio.h" #include "conio.h" #include "process.h" #include "alloc.h" #include "stdlib.h" #include "math.h" #include "dos.h" main() { int gm=CGAHI, gd=CGA, key=0, area; initgraph(&gd, &gm, "C:\tc\bgi"); helidraw(246,50,-1); getch(); return 0; } helidraw ( int x, int y, int d ) { int direction, i, j ; if ( d ) direction = -1 ; else direction = 1 ; i = 3 ; j = 8 ; line ( x - j - 8, y - i - 2, x + j + 8, y - i - 2 ) ; line ( x - j + 5, y - i - 1, x + j - 5, y - i - 1 ) ; line ( x - j, y - i, x + j, y - i ) ; for ( ; i 0 ; i--, j += 2 ) { putpixel ( x - ( direction * j ), y - i, 1 ) ; line ( x + ( direction * j ), y - i, x + ( direction * ( j - 8 ) ), y - i ) ; } i = 0 ; j -= 2 ; line ( x - ( direction * j ), y - i, x - ( direction * ( j + 17 ) ), y - i ) ; line ( x - ( direction * j ), y - i + 1, x - ( direction * ( j + 7 ) ), y - i + 1 ) ; putpixel ( x - ( direction * ( j + 19 ) ), y - i - 1, 1 ) ; for ( ; i < 3 ; i++, j -= 2 ) { putpixel ( x - j, y + i, 1 ) ; putpixel ( x + j, y + i, 1 ) ; } line ( x - j, y + i, x + j, y + i ) ; putpixel ( x - j + 3, y + i + 1, 1 ) ; putpixel ( x + j - 3, y + i + 1, 1 ) ; line ( x - j - 10, y + i + 2, x + j + 10, y + i + 2 ) ; putpixel ( x + ( direction * ( j + 12 ) ), y + i + 1, 1 ) ; }

    Read the article

  • Function Point Analysis -- a seriously overestimating technique?

    - by kizzx2
    I know questions about FPA has been asked numerous times before, but this time I'm taking a more analytical angle at it, backed up with data. 1. First, some data This question is based on a tutorial. He had a "Sample Count" section where he demonstrated it step by step. You can see some screenshots of his sample application here. In the end, he calculated the unadjusted FP to be 99. There is another article on InformIT with industry data on typical hour/FP. It ranges from 2 hours/FP to 27.4 hours/FP. Let's try to stick with 2 for the moment (since SO readers are probably the more efficient crowd :p). 2. Reality check!? Now just check out the screenshots again. Do a little math here 99 * 2 = 198 hours 198 hours / 40 hours per week = 5 weeks Seriously? That sample application is going to take 5 weeks to implement? Is it just my feeling that it wouldn't take any decent programmer longer than one week (I"m not even saying weekend) to have it completed? Now let's try estimating the cost of the project. We'll use New York's minimum wage at the moment (Wikipedia), which is $7.25 198 * 7.25 = $1435.5 From what I could see from the screenshots, this application is a small excel-improvement app. I could have bought MS Office Pro for 200 bucks which gives me greater interoperability (.xls files) and flexibility (spreadsheets). (For the record, that same Web site has another article discussing productivity. It seems like they typically use 4.2 hours/FP, which gives us even more shocking stats: 99 * 4.2 = 415 hours = 10 weeks = almost 3 whopping months! 415 hours * $7.25 = $3000 zomg (That's even assuming that all our poor coders get the minimum wage!) 3. Am I missing something here? Right now, I could come up with several possible explanation: FPA is really only suited for bigger projects (1000+ FPs) so it becomes extremely inaccurate at smaller scale. The hours/FP metric fluctuates abruptly from team to team, project to project. For a small project like this, we could have used something like 0.5 hour/FP or something. (Now this kind of makes the whole estimation thing pointless, unless my firm does the same type of projects for several years with the same team, not really common.) From my experience with several software metrics, Function Point is really not a lightweight metric. If the hour/FP thing fluctuates so much, then what's the point, maybe I could have gone with User Story Points which is a lot faster to get and arguably almost as uncertain. What would be the FP experts' answers to this?

    Read the article

  • Increase efficiency for an R simulator of the Monty Hall Puzzle

    - by jahan_m
    The Monty Hall Problem is a simple puzzle involving probability that even stumps professionals in careers dealing with some heavy-duty math. Here's the basic problem: Suppose you're on a game show, and you're given the choice of three doors: Behind one door is a car; behind the others, goats. You pick a door, say No. 1, and the host, who knows what's behind the doors, opens another door, say No. 3, which has a goat. He then says to you, "Do you want to pick door No. 2?" Is it to your advantage to switch your choice? You can find numerous explanations of the solution here: http://en.wikipedia.org/wiki/Monty_Hall_problem Goal of my simulation: Prove that a switching strategy will win you the car 2/3 of the time. I got curious and wanted to write a little function that simulates the problem many times and returns the proportion of wins if you switched and the proportion of wins if you stayed with your first choice. The function then plots the cumulative wins. First and foremost, I'm interested in hearing if my simulation is indeed replicating the Monty Problem, or if some aspect of the code got it wrong. Secondly, this function takes a long time to run once I get to about 10,000 simulations. I know I don't need this many simulations to prove this but I'd love to hear some ideas on how to make it more efficient. Thanks for your feedback! Monty_Hall=function(repetitions){ doors=c('A','B','C') stay_wins=0 switch_wins=0 series=data.frame(sim_num=seq(repetitions),cum_sum_stay=replicate(repetitions,0),cum_sum_switch=replicate(repetitions,0)) for(i in seq(repetitions)){ winning_door=sample(doors,1) contestant_chooses=sample(doors,1) if(contestant_chooses==winning_door) stay_wins=stay_wins+1 else switch_wins=switch_wins+1 series[i,'cum_sum_stay']=stay_wins series[i,'cum_sum_switch']=switch_wins } plot(series$sim_num,series$cum_sum_switch,col=2,ylab='Cumulative # of wins', xlab='Simulation #',main=sprintf('%d Simulations of the Monty Hall Paradox',repetitions),type='l') lines(series$sim_num,series$cum_sum_stay,col=4) legend('topleft',legend=c('Cumulative wins from switching', 'Cumulative wins from staying'),col=c(2,4),lty=1) result=list(series=series,stay_wins=stay_wins,switch_wins=switch_wins, proportion_stay_wins=stay_wins/repetitions, proportion_switch_wins=switch_wins/repetitions) return(result) } #Theory predicts that it is to the contestant's advantage if he #switches his choice to the other door. This function simulates the game #many times, and shows you the proportion of games in which staying or #switching would win the car. It also plots the cumulative wins for each strategy. Monty_Hall(100)

    Read the article

  • Translate RoR Code to Java

    - by mnml
    Hi, for some reasons I am trying to translate the following RoR view code to a Java Groovy view: <% modulo_artists = @artists.length % 3 base = @artists.length / 3 base = base.ceil case modulo_artists when 0 cols = [base, base, base] when 1 cols = [base, base + 1, base] when 2 cols = [base + 1, base, base + 1] end counter = 0 %> <% id_hash = {"0" => "url('/images/actorsbg.png');", "1" => "url('/images/musiciansbg.png');", "2" => "url('/images/artistsbg.png') no-repeat; color: #FFF;", "3" => "url('/images/fashionbg.png')"} %> <div id="artists_<%=params[:artist_cat]%>" style="background: <%= id_hash[params[:artist_cat]] %>;" > <table border="0" width="660" height="164" cellpadding="0" cellspacing="0"> <tr valign="middle"> <% 3.times do |i| %> <td width="220" align="center" style="padding-right: 15px;"> <% cols[i].times do %> <h1><a href="/artists/show/<%= @artists[counter].urlname %>" ><%= @artists[counter].name %></a></h1> <% counter = counter + 1 %> <% end %> </td> <% end %> </tr> </table> </div> This is what I got so far: #{extends 'main.html' /} %{ modulo_artists = artists.size() % 3 base = artists.size() / 3 base = Math.ceil(base) if(modulo_artists == 0) cols = [base, base, base] else if(modulo_artists == 1) cols = [base, base + 1, base] else if(modulo_artists == 2) cols = [base + 1, base, base + 1] endif counter = 0 }% <div id="artists_${artist_cat}" style="background:${id_hash};" > <table border="0" width="660" height="164" cellpadding="0" cellspacing="0"> <tr valign="middle"> #{list items:1..3, as:'i'} <td width="220" align="center" style="padding-right: 15px;"> #{list items:cols[i]} <h1><a href="@{Artists.show(artists.get(counter).name.replaceAll(" ", "-"))}" >${artists.get(counter).name}</a></h1> %{ counter = counter + 1 }% #{/list} </td> #{/list} </tr> </table> </div> The idea is to keep the items organised in 3 columns like 1|0|1 4|5|4 or 5|4|5 for example

    Read the article

  • Is the recent trend toward widescreen (16:9) computer monitors a plus or minus for programmers?

    - by DanM
    It's almost gotten to the point where you can't buy a conventional (4:3) monitor anymore. Pretty much everything is widescreen. This is fine for watching movies or TV, but is it good or bad for programming? My initial thoughts on the issue are that widescreens are a net negative for programmers. Here are some of the disadvantages I see: Poor space utiliziation One disadvantage of widescreens you can't argue with is that they offer poor space utilization for the amount of total pixels you get. For example, my Thinkpad, which I bought just before the widescreen craze, has a 15" monitor with a native resolution of 1600 x 1200. The newer 15.4" Thinkpads run at most 1680 x 1050. So (if you do the math) you get fewer pixels in a wider (but not shorter) package. With desktop monitors, you pay a price in terms of desk space used. Two 1680 x 1050 monitors will simply take up more of your desk than two 1600 x 1200 monitors (assuming equal dot pitch). More scrolling If you compare a 1680 x 1050 monitor to a 1600 x 1200 monitor, you get 80 extra pixels of width but 150 fewer pixels of height. The height reduction means you lose approximately 11 lines of code. That's less you can see on the screen at one time and more scrolling you have to do. This harms productivity, maybe not dramatically, but insidiously. Less room for wide panels Widescreens also mean you lose space for wide but short panels common in programming environments. If you use Visual Studio, for example, your code window will be that much shorter when viewing the Find Results, Task List, or Error List (all of which I use frequently). This isn't to say the 80 pixels of extra width you get with widescreen would never be useful, but I tend to keep my lines of code short, so seeing more lines would be more valuable to me than seeing fewer, longer lines. What do you think? Do you agree/disagree? Are you now using one or more widescreen monitors for development? What resolution are you running on each? Do you ever miss the height of the traditional 4:3 monitor? Would you complain if your monitors were one inch narrower but two inches taller?

    Read the article

  • Looking for an Open Source Project in need of help

    - by hvidgaard
    Hi StackOverflow! I'm a CS student on well on my way to graduate. I have had a difficult time of finding relevant student jobs (they seems to be taken merely hours after the notice gets on the board) , so instead I'm looking for an open source project in need of help. I'm aware that I should choose one that I use, but I'm not aware of any OS-project that I use that needs help. That's why I'm asking you. I don't have any deep experience, but I here are some of my biggest projects so far: BitTorrent-ish client in Python (a subset of BitTorrent) HTTP 1.1 webserver in Java Compiler from a subset of Java to run on JRE Flash-framework project to model an iPad look and feel (not to run actual iPad programs) complete with an API for programs. Complete MySQL database for a booking system, with departure and arrival times, so you could only book valid tickets (with a Java frontend). I know, Java and languages like AS3 and C# feels natural per se, Python, and have done a fair bit of hacking around in C, but I don't feel very comfortable with it. Mostly I'm afraid to make a fuckup because I have such a high degree of control. I would like to think I'm well aware of good software design practices, but in reality what I do is ask myself "would I like to use/maintain this?", and I love to refactor my code because I see optimizations. I love algorithms and to make them run in the best possible time. I don't have any preferred domain to work in, but I wouldn't mind it to be graphics or math heavy. Ideally I'm looking for a project in C++ to learn the in's and out's of it, but I'm well aware that I don't know that language very well. I would like to have a mentor-like figure until I'm confident enough to stand on my own, not one to review all my code (I'm sure someone will to start with anyway), but to ask questions about the project and language in question. I do have a wife and two children, so don't expect me to put in 10+ hours every week. In return I can work on my own, I strive to program modular and maintainable code. Know how to read an API, use Google, StackOverflow and online resources in general. If you have any questions, shoot. I'm looking forward to your suggestions.

    Read the article

  • Flash caroussel xml parse html link

    - by Marvin
    Hello I am trying to modify a carousel script I have in flash. Its normal function is making some icons rotate and when clicked they zoom in, fade all others and display a little text. On that text I would like to have a link like a "read more". If I use CDATA it wont display a thing, if I use alt char like &#60;a href=&#34;www.google.com&#34;&#62; Read more + &#60;/a&#62; It just displays the text as: <a href="www.google.com"> Read more + </a>. The flash dynamic text box wont render it as html. I dont enough as2 to figure out how to add this. My code: var xml:XML = new XML(); xml.ignoreWhite = true; //definições do xml xml.onLoad = function() { var nodes = this.firstChild.childNodes; numOfItems = nodes.length; for(var i=0;i<numOfItems;i++) { var t = home.attachMovie("item","item"+i,i+1); t.angle = i * ((Math.PI*2)/numOfItems); t.onEnterFrame = mover; t.toolText = nodes[i].attributes.tooltip; t.content = nodes[i].attributes.content; t.icon.inner.loadMovie(nodes[i].attributes.image); t.r.inner.loadMovie(nodes[i].attributes.image); t.icon.onRollOver = over; t.icon.onRollOut = out; t.icon.onRelease = released; } } And the xml: <?xml version="1.0" encoding="UTF-8"?> <icons> <icon image="images/product.swf" tooltip="Product" content="Hello this is some random text &#60;a href=&#34;www.google.com&#34;&#62; Read More + &#60;/a&#62; "/> </icons> Any suggestions? Thanks.

    Read the article

  • Drupal incorrectly escapes tags in javascript

    - by sergdev
    I installed drupal-6.16. I applied the patch from the post http://drupal.org/node/222926#comment-930745. It works correctly in simple cases. But following code of counter is handled incorrectly and counter is now displayed on the page after drupal. Drupal modifies the string "alt='1Gb.ua counter' /><\/a>")</a></script> to "alt='1Gb.ua counter' />&lt;\/a>")</a></script> The full code of counter follows: <br><br> Text <br><br> <!-- counter.1Gb.ua --> <script language="javascript" type="text/javascript"> cgb_js="1.0"; cgb_r=""+Math.random()+"&r="+ escape(document.referrer)+"&pg="+ escape(window.location.href); document.cookie="rqbct=1; path=/"; cgb_r+="&c="+ (document.cookie?"Y":"N"); </script><script language="javascript1.1" type="text/javascript"> cgb_js="1.1";cgb_r+="&j="+ (navigator.javaEnabled()?"Y":"N")</script> <script language="javascript1.2" type="text/javascript"> cgb_js="1.2"; cgb_r+="&wh="+screen.width+ 'x'+screen.height+"&px="+ (((navigator.appName.substring(0,3)=="Mic"))? screen.colorDepth:screen.pixelDepth)</script> <script language="javascript1.3" type="text/javascript"> cgb_js="1.3"</script> <script language="javascript" type="text/javascript">cgb_r+="&js="+cgb_js; document.write("<a href='http://www.1Gb.ua?cnt=1416'>"+ "<img src='http://counter.1Gb.ua/cnt.aspx?"+ "u=1416&"+cgb_r+ "&' border=0 width=88 height=31 "+ "alt='1Gb.ua counter'><\/a>")</script> <noscript><a href='http://www.1Gb.ua?cnt=1416'> <img src="http://counter.1Gb.ua/cnt.aspx?u=1416" border=0 width="88" height="31" alt="1Gb.ua counter"></a> </noscript> <!-- /counter.1Gb.ua --> Does anybody have this code working? How can it be fixed? Thanks a lot in advance!

    Read the article

  • How are DX and DY coordinates calculated in flash?

    - by Meganlee1984
    I'm trying to update a clients site and the original developer left almost no instructions. The code is all updated through XML. Here is a sample of the code enter code here<FOLDER NAME="COMMERCIAL"> <GALLERY NAME="LOCANDA VERDE: New York"> <IMG HEIGHT="500" CAPTION="Some photo" WIDTH="393" SRC="locanda1.jpg" DX="60" DY="40" LINKTEXT="" LINKURL="" INFOTEXT="SOHO, NEW YORK"/> <IMG HEIGHT="300" CAPTION="Some photo" WIDTH="450" SRC="locanda2.jpg" DX="160" DY="80" LINKTEXT="" LINKURL="" INFOTEXT="SOHO, NEW YORK"/> <IMG HEIGHT="500" CAPTION="Some photo" WIDTH="393" SRC="locanda3.jpg" DX="80" DY="260" LINKTEXT="" LINKURL="" INFOTEXT="SOHO, NEW YORK"/> <IMG HEIGHT="500" CAPTION="Some photo" WIDTH="393" SRC="locanda4.jpg" DX="120" DY="60" LINKTEXT="" LINKURL="" INFOTEXT="SOHO, NEW YORK"/> <IMG HEIGHT="393" CAPTION="Some photo" WIDTH="500" SRC="locanda5.jpg" DX="180" DY="100" LINKTEXT="" LINKURL="" INFOTEXT="SOHO, NEW YORK"/> <IMG HEIGHT="500" CAPTION="Some photo" WIDTH="433" SRC="locanda6.jpg" DX="60" DY="140" LINKTEXT="" LINKURL="" INFOTEXT="SOHO, NEW YORK"/> <IMG HEIGHT="500" CAPTION="Some photo" WIDTH="393" SRC="locanda7.jpg" DX="100" DY="200" LINKTEXT="" LINKURL="" INFOTEXT="SOHO, NEW YORK"/> </GALLERY>`enter code here It relates to this page: http://meyerdavis.com/ Click Commercial Click Laconda Verde New York. The xml file pulls a jpg from 2 places, one is a thumb nail that are all 60 x 60 and then one is the bigger sized image. The issue that I'm having is that I can't figure out how the DX and DY coordinates are generated for each item. Any help would be much appreciated. ` Edit: Here's the code from the comment below. platformblock.expandspeed = 0.02; platformblock.h = 450 - platformblock.dy1; //platformblock.h = 402; platformblock.dy2 = 0; platformblock.onResize(); /**/ platformblock.onEnterFrame = function() { this.dy1 += (48 - this.dy1)*this.expandspeed; this.h = 450 - this.dy1; if(this.expandspeed<0.3) { this.expandspeed += 0.02; } if(Math.abs(this.dy1-48)<0.2) { this.dy1 = 48; } if(this.platform._height==402 && this.dy1==48){ this.h = null; this.onResize(); this.onEnterFrame = null; } } platformblock._resizeto(800, 402, _root.play, _root, 0.08); titleblockcontainer.play(); /**/ stop();

    Read the article

  • color objects in C or C ++ [closed]

    - by jazz
    Possible Duplicate: Colors in C language i copied a game from a book which name is paratrooper i ask this question again i also provide the code of the objects which i create there i want to change the color of these objects but i didn't understand how to do that so can any one plz help me how to do that.Listen guys they are not the standard functions but i use the graphics library for these functions and i can't find the function in the library file of graphics. i hope u understand know.this code will not run properly so plz tell me something about the function which color it i can't put the image other wize i show u the image it will make alot easieer #include "graphics.h" #include "stdio.h" #include "conio.h" #include "process.h" #include "alloc.h" #include "stdlib.h" #include "math.h" #include "dos.h" main() { int gm=CGAHI, gd=CGA, key=0, area; initgraph(&gd, &gm, "C:\\tc\\bgi"); helidraw(246,50,-1); getch(); return 0; } helidraw ( int x, int y, int d ) { int direction, i, j ; if ( d ) direction = -1 ; else direction = 1 ; i = 3 ; j = 8 ; line ( x - j - 8, y - i - 2, x + j + 8, y - i - 2 ) ; line ( x - j + 5, y - i - 1, x + j - 5, y - i - 1 ) ; line ( x - j, y - i, x + j, y - i ) ; for ( ; i > 0 ; i--, j += 2 ) { putpixel ( x - ( direction * j ), y - i, 1 ) ; line ( x + ( direction * j ), y - i, x + ( direction * ( j - 8 ) ), y - i ) ; } i = 0 ; j -= 2 ; line ( x - ( direction * j ), y - i, x - ( direction * ( j + 17 ) ), y - i ) ; line ( x - ( direction * j ), y - i + 1, x - ( direction * ( j + 7 ) ), y - i + 1 ) ; putpixel ( x - ( direction * ( j + 19 ) ), y - i - 1, 1 ) ; for ( ; i < 3 ; i++, j -= 2 ) { putpixel ( x - j, y + i, 1 ) ; putpixel ( x + j, y + i, 1 ) ; } line ( x - j, y + i, x + j, y + i ) ; putpixel ( x - j + 3, y + i + 1, 1 ) ; putpixel ( x + j - 3, y + i + 1, 1 ) ; line ( x - j - 10, y + i + 2, x + j + 10, y + i + 2 ) ; putpixel ( x + ( direction * ( j + 12 ) ), y + i + 1, 1 ) ; }

    Read the article

  • asp.net web forms best practice to retrieve dynamic server control values

    - by Andrew Florko
    I populate web form with dynamic list of exams from database. I want user to enter examination marks for each exam. There is list of exam titles and textbox near each title. I create list with repeater control: <asp:Repeater ID="rptExams" runat="server" onitemdatabound="rptExams_ItemDataBound" > <ItemTemplate> <tr> <td> <asp:Literal runat="server" ID="ltTitle"/> </td> <td> <asp:HiddenField runat="server" ID="hfId"/> <asp:Textbox runat="server" ID="tbMark"/> </td> </tr> </ItemTemplate> </asp:Repeater> And bind data to repeater on page_init: class Exam { public int Id { get; set;} public string Title { get; set;} } ... // this list is retrieved from database actually Exam[] Exams = new Exam[] { new Exam { Id = 1, Title = "Math"}, new Exam { Id = 2, Title = "History"} }; ... protected void Page_Init(object sender, EventArgs e) { rptExams.DataSource = Exams; rptExams.DataBind(); } So far so good. Then I have to retrieve data on postback. I have two ways but both of them looks ugly. Idea is to store dynamically created databounded controls on ItemDataBoundEvent in Page_Init stage, and process their values in Page_Load stage. It looks like this: private Dictionary<HiddenField, TextBox> Id2Mark = new Dictionary<HiddenField, TextBox>(); protected void rptExams_ItemDataBound(object sender, RepeaterItemEventArgs e) { ... if (IsPostBack) { var tbMark = (TextBox)e.Item.FindControl("tbMark"); var hfId = (HiddenField)e.Item.FindControl("hfId"); // store dynamically created controls Id2Mark.Add(hfId, tbMark); } ... } protected void Page_Load(object sender, EventArgs e) { if (IsPostBack) { foreach (var pair in Id2Mark) { int examId = Int32.Parse(pair.Key.Value); string mark = pair.Value.Text; // PROCESS } ... I'm completely sure there is a better way to retrieve data from dynamically created controls. Thank you in advance!

    Read the article

  • A* algorithm works OK, but not perfectly. What's wrong?

    - by Bart van Heukelom
    This is my grid of nodes: I'm moving an object around on it using the A* pathfinding algorithm. It generally works OK, but it sometimes acts wrongly: When moving from 3 to 1, it correctly goes via 2. When going from 1 to 3 however, it goes via 4. When moving between 3 and 5, it goes via 4 in either direction instead of the shorter way via 6 What can be wrong? Here's my code (AS3): public static function getPath(from:Point, to:Point, grid:NodeGrid):PointLine { // get target node var target:NodeGridNode = grid.getClosestNodeObj(to.x, to.y); var backtrace:Map = new Map(); var openList:LinkedSet = new LinkedSet(); var closedList:LinkedSet = new LinkedSet(); // begin with first node openList.add(grid.getClosestNodeObj(from.x, from.y)); // start A* var curNode:NodeGridNode; while (openList.size != 0) { // pick a new current node if (openList.size == 1) { curNode = NodeGridNode(openList.first); } else { // find cheapest node in open list var minScore:Number = Number.MAX_VALUE; var minNext:NodeGridNode; openList.iterate(function(next:NodeGridNode, i:int):int { var score:Number = curNode.distanceTo(next) + next.distanceTo(target); if (score < minScore) { minScore = score; minNext = next; return LinkedSet.BREAK; } return 0; }); curNode = minNext; } // have not reached if (curNode == target) break; else { // move to closed openList.remove(curNode); closedList.add(curNode); // put connected nodes on open list for each (var adjNode:NodeGridNode in curNode.connects) { if (!openList.contains(adjNode) && !closedList.contains(adjNode)) { openList.add(adjNode); backtrace.put(adjNode, curNode); } } } } // make path var pathPoints:Vector.<Point> = new Vector.<Point>(); pathPoints.push(to); while(curNode != null) { pathPoints.unshift(curNode.location); curNode = backtrace.read(curNode); } pathPoints.unshift(from); return new PointLine(pathPoints); } NodeGridNode::distanceTo() public function distanceTo(o:NodeGridNode):Number { var dx:Number = location.x - o.location.x; var dy:Number = location.y - o.location.y; return Math.sqrt(dx*dx + dy*dy); }

    Read the article

  • Mock Object and Interface

    - by tunl
    I'm a newbie in Unit Test with Mock Object. I use EasyMock. I try to understand this example: import java.io.IOException; public interface ExchangeRate { double getRate(String inputCurrency, String outputCurrency) throws IOException; } import java.io.IOException; public class Currency { private String units; private long amount; private int cents; public Currency(double amount, String code) { this.units = code; setAmount(amount); } private void setAmount(double amount) { this.amount = new Double(amount).longValue(); this.cents = (int) ((amount * 100.0) % 100); } public Currency toEuros(ExchangeRate converter) { if ("EUR".equals(units)) return this; else { double input = amount + cents/100.0; double rate; try { rate = converter.getRate(units, "EUR"); double output = input * rate; return new Currency(output, "EUR"); } catch (IOException ex) { return null; } } } public boolean equals(Object o) { if (o instanceof Currency) { Currency other = (Currency) o; return this.units.equals(other.units) && this.amount == other.amount && this.cents == other.cents; } return false; } public String toString() { return amount + "." + Math.abs(cents) + " " + units; } } import junit.framework.TestCase; import org.easymock.EasyMock; import java.io.IOException; public class CurrencyTest extends TestCase { public void testToEuros() throws IOException { Currency testObject = new Currency(2.50, "USD"); Currency expected = new Currency(3.75, "EUR"); ExchangeRate mock = EasyMock.createMock(ExchangeRate.class); EasyMock.expect(mock.getRate("USD", "EUR")).andReturn(1.5); EasyMock.replay(mock); Currency actual = testObject.toEuros(mock); assertEquals(expected, actual); } } So, i wonder how to Currency use ExchangeRate in toEuros(..) method. rate = converter.getRate(units, "EUR"); The behavior of getRate(..) method is not specified because ExchangeRate is an interface.

    Read the article

  • Android library to get pitch from WAV file

    - by Sakura
    I have a list of sampled data from the WAV file. I would like to pass in these values into a library and get the frequency of the music played in the WAV file. For now, I will have 1 frequency in the WAV file and I would like to find a library that is compatible with Android. I understand that I need to use FFT to get the frequency domain. Is there any good libraries for that? I found that [KissFFT][1] is quite popular but I am not very sure how compatible it is on Android. Is there an easier and good library that can perform the task I want? EDIT: I tried to use JTransforms to get the FFT of the WAV file but always failed at getting the correct frequency of the file. Currently, the WAV file contains sine curve of 440Hz, music note A4. However, I got the result as 441. Then I tried to get the frequency of G4, I got the result as 882Hz which is incorrect. The frequency of G4 is supposed to be 783Hz. Could it be due to not enough samples? If yes, how much samples should I take? //DFT DoubleFFT_1D fft = new DoubleFFT_1D(numOfFrames); double max_fftval = -1; int max_i = -1; double[] fftData = new double[numOfFrames * 2]; for (int i = 0; i < numOfFrames; i++) { // copying audio data to the fft data buffer, imaginary part is 0 fftData[2 * i] = buffer[i]; fftData[2 * i + 1] = 0; } fft.complexForward(fftData); for (int i = 0; i < fftData.length; i += 2) { // complex numbers -> vectors, so we compute the length of the vector, which is sqrt(realpart^2+imaginarypart^2) double vlen = Math.sqrt((fftData[i] * fftData[i]) + (fftData[i + 1] * fftData[i + 1])); //fd.append(Double.toString(vlen)); // fd.append(","); if (max_fftval < vlen) { // if this length is bigger than our stored biggest length max_fftval = vlen; max_i = i; } } //double dominantFreq = ((double)max_i / fftData.length) * sampleRate; double dominantFreq = (max_i/2.0) * sampleRate / numOfFrames; fd.append(Double.toString(dominantFreq)); Can someone help me out? EDIT2: I manage to fix the problem mentioned above by increasing the number of samples to 100000, however, sometimes I am getting the overtones as the frequency. Any idea how to fix it? Should I use Harmonic Product Frequency or Autocorrelation algorithms?

    Read the article

  • Do You Really Know Your Programming Languages?

    - by Kristopher Johnson
    I am often amazed at how little some of my colleagues know or care about their craft. Something that constantly frustrates me is that people don't want to learn any more than they need to about the programming languages they use every day. Many programmers seem content to learn some pidgin sub-dialect, and stick with that. If they see a keyword or construct that they aren't familiar with, they'll complain that the code is "tricky." What would you think of a civil engineer who shied away from calculus because it had "all those tricky math symbols?" I'm not suggesting that we all need to become "language lawyers." But if you make your living as a programmer, and claim to be a competent user of language X, then I think at a minimum you should know the following: Do you know the keywords of the language and what they do? What are the valid syntactic forms? How are memory, files, and other operating system resources managed? Where is the official language specification and library reference for the language? The last one is the one that really gets me. Many programmers seem to have no idea that there is a "specification" or "standard" for any particular language. I still talk to people who think that Microsoft invented C++, and that if a program doesn't compile under VC6, it's not a valid C++ program. Programmers these days have it easy when it comes to obtaining specs. Newer languages like C#, Java, Python, Ruby, etc. all have their documentation available for free from the vendors' web sites. Older languages and platforms often have standards controlled by standards bodies that demand payment for specs, but even that shouldn't be a deterrent: the C++ standard is available from ISO for $30 (and why am I the only person I know who has a copy?). Programming is hard enough even when you do know the language. If you don't, I don't see how you have a chance. What do the rest of you think? Am I right, or should we all be content with the typical level of programming language expertise? Update: Several great comments here. Thanks. A couple of people hit on something that I didn't think about: What really irks me is not the lack of knowledge, but the lack of curiosity and willingness to learn. It seems some people don't have any time to hone their craft, but they have plenty of time to write lots of bad code. And I don't expect people to be able to recite a list of keywords or EBNF expressions, but I do expect that when they see some code, they should have some inkling of what it does. Few people have complete knowledge of every dark corner of their language or platform, but everyone should at least know enough that when they see something unfamiliar, they will know how to get whatever additional information they need to understand it.

    Read the article

  • Help with method logic in Java, hw

    - by Crystal
    I have a Loan class that in its printPayment method, it prints the amortization table of a loan for a hw assignment. We are also to implement a print first payment method, and a print last payment method. Since my calculation is done in the printPayment method, I didn't know how I could get the value in the first or last iteration of the loop and print that amount out. One way I can think of is to write a new method that might return that value, but I wasn't sure if there was a better way. Here is my code: public abstract class Loan { public void setClient(Person client) { this.client = client; } public Person getClient() { return client; } public void setLoanId() { loanId = nextId; nextId++; } public int getLoanId() { return loanId; } public void setInterestRate(double interestRate) { this.interestRate = interestRate; } public double getInterestRate() { return interestRate; } public void setLoanLength(int loanLength) { this.loanLength = loanLength; } public int getLoanLength() { return loanLength; } public void setLoanAmount(double loanAmount) { this.loanAmount = loanAmount; } public double getLoanAmount() { return loanAmount; } public void printPayments() { double monthlyInterest; double monthlyPrincipalPaid; double newPrincipal; int paymentNumber = 1; double monthlyInterestRate = interestRate / 1200; double monthlyPayment = loanAmount * (monthlyInterestRate) / (1 - Math.pow((1 + monthlyInterestRate),( -1 * loanLength))); System.out.println("Payment Number | Interest | Principal | Loan Balance"); // amortization table while (loanAmount >= 0) { monthlyInterest = loanAmount * monthlyInterestRate; monthlyPrincipalPaid = monthlyPayment - monthlyInterest; newPrincipal = loanAmount - monthlyPrincipalPaid; loanAmount = newPrincipal; System.out.printf("%d, %.2f, %.2f, %.2f", paymentNumber++, monthlyInterest, monthlyPrincipalPaid, loanAmount); } } /* //method to print first payment public double getFirstPayment() { } method to print last payment public double getLastPayment() { }*/ private Person client; private int loanId; private double interestRate; private int loanLength; private double loanAmount; private static int nextId = 1; } Thanks!

    Read the article

  • help me with xor encryption in c#

    - by x86shadow
    I wrote this code in c# to encrypt a text with a key : using System; using System.Linq; using System.Collections.Generic; using System.Text; namespace ENCRYPT { class XORENC { private static int Bin2Dec(string num) { int _num = 0; for (int i = 0; i < num.Length; i++) { _num += (int)Math.Pow(2, num.Length - i - 1) * int.Parse(num[i].ToString()); } return _num; } private static string Dec2Bin(int num) { if (num < 2) return num.ToString(); return Dec2Bin(num / 2) + (num % 2).ToString(); } public static string StrXor(string str, string key) { string _str = ""; string _key = ""; string _dec = ""; string _temp = ""; for (int i = 0; i < str.Length; i++) { _temp = Dec2Bin(str[i]); for (int j = 0; j < 8 - _temp.Length + 1; j++) { _temp = '0' + _temp; } _str += _temp; } for (int i = 0; i < key.Length; i++) { _temp = Dec2Bin(key[i]); for (int j = 0; j < 8 - _temp.Length + 1; j++) { _temp = '0' + _temp; } _key += _temp; } while (_key.Length < _str.Length) { _key += _key; } if (_key.Length > _str.Length) _key = _key.Substring(0, _str.Length); for (int i = 0; i < _str.Length; i++) { if (_str[i] == _key[i]) { _dec += '0'; } else { _dec += '1'; } } _str = ""; for (int i = 0; i < _dec.Length; i = i + 8) { char _chr = (char)0; _chr = (char)Bin2Dec(_dec.Substring(i, 8)); _str += _chr; } return _str; } } } the problem is that I always get error when I want to decrypt an encryted text with this code. see the example below for more info : string enc_text = ENCRYPT.XORENC("abc","a"); //enc_text = " ??" string dec_text = ENCRYPT.XORENC(enc_text,"a"); //ERROR any one can help ?

    Read the article

  • How do I pass the value of the previous form element into an "onchange" javascript function?

    - by Jen
    Hello, I want to make some UI improvements to a page I am developing. Specifically, I need to add another drop down menu to allow the user to filter results. This is my current code: HTML file: <select name="test_id" onchange="showGrid(this.name, this.value, 'gettestgrid')"> <option selected>Select a test--></option> <option value=1>Test 1</option> <option value=2>Test 2</option> <option value=3>Test 3</option> </select> This is pseudo code for what I want to happen: <select name="test_id"> <option selected>Select a test--></option> <option value=1>Test 1</option> <option value=2>Test 2</option> <option value=3>Test 3</option> </select> <select name="statistics" onchange="showGrid(PREVIOUS.name, PREVIOUS.VALUE, THIS.value)"> <option selected>Select a data display --></option> <option value='gettestgrid'>Show averages by student</option> <option value='gethomeroomgrid'>Show averages by homeroom</option> <option value='getschoolgrid'>Show averages by school</option> </select> How do I access the previous field's name and value? Any help much appreciated, thx! Also, JS function for reference: function showGrid(name, value, phpfile) { xmlhttp=GetXmlHttpObject(); if (xmlhttp==null) { alert ("Browser does not support HTTP Request"); return; } var url=phpfile+".php"; url=url+"?"+name+"="+value; url=url+"&sid="+Math.random(); xmlhttp.onreadystatechange=stateChanged; xmlhttp.open("GET",url,true); xmlhttp.send(null); }

    Read the article

  • Simple RSA encryption (Java)

    - by jake blue
    This is simply for fun. This will not be used for any actual encryption. I'm only first year comp sci student and love cryptography. This took a long time to get working. At approximately N = 18, it begins breaking down. It won't encrypt messages properly after that point. I'm not sure why. Any insights? I'd also appreciate any links you could provide me to tutorials or interesting reading about Cryptography. import java.math.BigInteger; import java.security.SecureRandom; /** * Cryptography. * * Generates public and private keys used in encryption and * decryption * */ public class RSA { private final static BigInteger one = new BigInteger("1"); private final static SecureRandom random = new SecureRandom(); // prime numbers private BigInteger p; private BigInteger q; // modulus private BigInteger n; // totient private BigInteger t; // public key private BigInteger e; // private key private BigInteger d; private String cipherText; /** * Constructor for objects of class RSA */ public RSA(int N) { p = BigInteger.probablePrime(N/2, random); q = BigInteger.probablePrime(N/2, random); // initialising modulus n = p.multiply(q); // initialising t by euclid's totient function (p-1)(q-1) t = (p.subtract(one)).multiply(q.subtract(one)); // initialising public key ~ 65537 is common public key e = new BigInteger("65537"); } public int generatePrivateKey() { d = e.modInverse(t); return d.intValue(); } public String encrypt(String plainText) { String encrypted = ""; int j = 0; for(int i = 0; i < plainText.length(); i++){ char m = plainText.charAt(i); BigInteger bi1 = BigInteger.valueOf(m); BigInteger bi2 = bi1.modPow(e, n); j = bi2.intValue(); m = (char) j; encrypted += m; } cipherText = encrypted; return encrypted; } public String decrypt() { String decrypted = ""; int j = 0; for(int i = 0; i < cipherText.length(); i++){ char c = cipherText.charAt(i); BigInteger bi1 = BigInteger.valueOf(c); BigInteger bi2 = bi1.modPow(d, n); j = bi2.intValue(); c = (char) j; decrypted += c; } return decrypted; } }

    Read the article

  • Drupal incorrectly espaces tags in javascript

    - by sergdev
    I installed drupal-6.16. I applied the patch from the post http://drupal.org/node/222926#comment-930745. It works correctly in simple cases. But for following code for counter is handled incorrectly: <br><br> Text <br><br> <!-- counter.1Gb.ua --> <script language="javascript" type="text/javascript"> cgb_js="1.0"; cgb_r=""+Math.random()+"&r="+ escape(document.referrer)+"&pg="+ escape(window.location.href); document.cookie="rqbct=1; path=/"; cgb_r+="&c="+ (document.cookie?"Y":"N"); </script><script language="javascript1.1" type="text/javascript"> cgb_js="1.1";cgb_r+="&j="+ (navigator.javaEnabled()?"Y":"N")</script> <script language="javascript1.2" type="text/javascript"> cgb_js="1.2"; cgb_r+="&wh="+screen.width+ 'x'+screen.height+"&px="+ (((navigator.appName.substring(0,3)=="Mic"))? screen.colorDepth:screen.pixelDepth)</script> <script language="javascript1.3" type="text/javascript"> cgb_js="1.3"</script> <script language="javascript" type="text/javascript">cgb_r+="&js="+cgb_js; document.write("<a href='http://www.1Gb.ua?cnt=1416'>"+ "<img src='http://counter.1Gb.ua/cnt.aspx?"+ "u=1416&"+cgb_r+ "&' border=0 width=88 height=31 "+ "alt='1Gb.ua counter'><\/a>")</script> <noscript><a href='http://www.1Gb.ua?cnt=1416'> <img src="http://counter.1Gb.ua/cnt.aspx?u=1416" border=0 width="88" height="31" alt="1Gb.ua counter"></a> </noscript> <!-- /counter.1Gb.ua --> It modifies the string "alt='1Gb.ua counter' /><\/a>")</a></script> to "alt='1Gb.ua counter' />&lt;\/a>")</a></script> Does anybody have this code working? If so how this can be fixed? Thanks a lot in advance!

    Read the article

  • How much time should it take to find the sum of all prime numbers less than 2 million?

    - by Shahensha
    I was trying to solve this Project Euler Question. I implemented the sieve of euler as a helper class in java. It works pretty well for the small numbers. But when I input 2 million as the limit it doesn't return the answer. I use Netbeans IDE. I waited for a lot many hours once, but it still didn't print the answer. When I stopped running the code, it gave the following result Java Result: 2147483647 BUILD SUCCESSFUL (total time: 2,097 minutes 43 seconds) This answer is incorrect. Even after waiting for so much time, this isn't correct. While the same code returns correct answers for smaller limits. Sieve of euler has a very simple algo given at the botton of this page. My implementation is this: package support; import java.util.ArrayList; import java.util.List; /** * * @author admin */ public class SieveOfEuler { int upperLimit; List<Integer> primeNumbers; public SieveOfEuler(int upperLimit){ this.upperLimit = upperLimit; primeNumbers = new ArrayList<Integer>(); for(int i = 2 ; i <= upperLimit ; i++) primeNumbers.add(i); generatePrimes(); } private void generatePrimes(){ int currentPrimeIndex = 0; int currentPrime = 2; while(currentPrime <= Math.sqrt(upperLimit)){ ArrayList<Integer> toBeRemoved = new ArrayList<Integer>(); for(int i = currentPrimeIndex ; i < primeNumbers.size() ; i++){ int multiplier = primeNumbers.get(i); toBeRemoved.add(currentPrime * multiplier); } for(Integer i : toBeRemoved){ primeNumbers.remove(i); } currentPrimeIndex++; currentPrime = primeNumbers.get(currentPrimeIndex); } } public List getPrimes(){ return primeNumbers; } public void displayPrimes(){ for(double i : primeNumbers) System.out.println(i); } } I am perplexed! My questions is 1) Why is it taking so much time? Is there something wrong in what I am doing? Please suggest ways for improving my coding style, if you find something wrong.

    Read the article

  • Correlation formula explanation needed d3.js

    - by divakar
    function getCorrelation(xArray, yArray) { alert(xArray); alert(yArray); function sum(m, v) {return m + v;} function sumSquares(m, v) {return m + v * v;} function filterNaN(m, v, i) {isNaN(v) ? null : m.push(i); return m;} // clean the data (because we know that some values are missing) var xNaN = _.reduce(xArray, filterNaN , []); var yNaN = _.reduce(yArray, filterNaN , []); var include = _.intersection(xNaN, yNaN); var fX = _.map(include, function(d) {return xArray[d];}); var fY = _.map(include, function(d) {return yArray[d];}); var sumX = _.reduce(fX, sum, 0); var sumY = _.reduce(fY, sum, 0); var sumX2 = _.reduce(fX, sumSquares, 0); var sumY2 = _.reduce(fY, sumSquares, 0); var sumXY = _.reduce(fX, function(m, v, i) {return m + v * fY[i];}, 0); var n = fX.length; var ntor = ( ( sumXY ) - ( sumX * sumY / n) ); var dtorX = sumX2 - ( sumX * sumX / n); var dtorY = sumY2 - ( sumY * sumY / n); var r = ntor / (Math.sqrt( dtorX * dtorY )); // Pearson ( http://www.stat.wmich.edu/s216/book/node122.html ) var m = ntor / dtorX; // y = mx + b var b = ( sumY - m * sumX ) / n; // console.log(r, m, b); return {r: r, m: m, b: b}; } I have finding correlation between the points i plot using this function which is not written by me. my xarray=[120,110,130,132,120,118,134,105,120,0,0,0,0,137,125,120,127,120,160,120,148] yarray=[80,70,70,80,70,62,69,70,70,62,90,42,80,72,0,0,0,0,78,82,68,60,58,82,60,76,86,82,70] I can t able to understand the function perfectly. Can anybody explain it with the data i pasted here. I also wanted to remove the zeros getting calculated from this function.

    Read the article

  • Configuring a html page from an original demo page

    - by Wold
    I forked into rainyday.js through github, an awesome javascript program made by maroslaw at this link: https://github.com/maroslaw/rainyday.js. Basically I tried taking his demo page and my own photo city.jpg and changed the applicable fields so that I could run it on my own site, but only the picture loads and the script itself doesn't start to run. I'm pretty new to html and javascript so I'm probably omitting something very simple, but here is the script for the demo code: <script src="rainyday.js"></script> <script> function getURLParameter(name) { return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,''])[1].replace(/\+/g, '%20'))||null; } function demo() { var image = document.getElementById('background'); image.onload = function () { var engine = null; var preset = getURLParameter('preset') || '1'; if (preset === '1') { engine = new RainyDay({ element: 'background', blur: 10, opacity: 1, fps: 30, speed: 30 }); engine.rain([ [1, 2, 8000] ]); engine.rain([ [3, 3, 0.88], [5, 5, 0.9], [6, 2, 1] ], 100); } else if (preset === '2') { engine = new RainyDay({ element: 'background', blur: 10, opacity: 1, fps: 30, speed: 30 }); engine.VARIABLE_GRAVITY_ANGLE = Math.PI / 8; engine.rain([ [0, 2, 0.5], [4, 4, 1] ], 50); } else if (preset === '3') { engine = new RainyDay({ element: 'background', blur: 10, opacity: 1, fps: 30, speed: 30 }); engine.trail = engine.TRAIL_SMUDGE; engine.rain([ [0, 2, 0.5], [4, 4, 1] ], 100); } }; image.crossOrigin = 'anonymous'; if (getURLParameter('imgur')) { image.src = 'http://i.imgur.com/' + getURLParameter('imgur') + '.jpg'; } else if (getURLParameter('img')) { image.src = getURLParameter('img') + '.jpg'; } var youtube = getURLParameter('youtube'); if (youtube) { var div = document.getElementById('sound'); var player = document.createElement('iframe'); player.frameborder = '0'; player.height = '1'; player.width = '1'; player.src = 'https://youtube.com/embed/' + youtube + '?autoplay=1&controls=0&showinfo=0&autohide=1&loop=1'; div.appendChild(player); } } </script> This is where I am naming my background and specifying the photo from within the directory. <body onload="demo();"> <div id="sound" style="z-index: -1;"></div> <div id="parent"> <img id='background' alt="background" src="city.jpg" /> </div> </body> The actual code for the whole entire rainyday.js script can be found here: https://github.com/maroslaw/rainyday.js/blob/master/rainyday.js Thanks in advance for any help and advice!

    Read the article

  • circles and triangles problem

    - by Faken
    Hello everyone, I have an interesting problem here I've been trying to solve for the last little while: I have 3 circles on a 2D xy plane, each with the same known radius. I know the coordinates of each of the three centers (they are arbitrary and can be anywhere). What is the largest triangle that can be drawn such that each vertice of the triangle sits on a separate circle, what are the coordinates of those verticies? I've been looking at this problem for hours and asked a bunch of people but so far only one person has been able to suggest a plausible solution (though i have no way of proving it). The solution that we have come up with involves first creating a triangle about the three circle centers. Next we look at each circle individually and calculate the equation of a line that passes through the circle's center and is perpendicular to the opposite edge. We then calculate two intersection points of the circle. This is then done for the next two circles with a result of 6 points. We iterate over the 8 possible 3 point triangles that these 6 points create (the restriction is that each point of the big triangle must be on a separate circle) and find the maximum size. The results look reasonable (at least when drawn out on paper) and it passes the special case of when the centers of the circles all fall on a straight line (gives a known largest triangle). Unfortunate i have no way of proving this is correct or not. I'm wondering if anyone has encountered a problem similar to this and if so, how did you solve it? Note: I understand that this is mostly a math question and not programming, however it is going to be implemented in code and it must be optimized to run very fast and efficient. In fact, I already have the above solution in code and tested to be working, if you would like to take a look, please let me know, i chose not to post it because its all in vector form and pretty much impossible to figure out exactly what is going on (because it's been condensed to be more efficient). Lastly, yes this is for school work, though it is NOT a homework question/assignment/project. It's part of my graduate thesis (abet a very very small part, but still technically is part of it). Thanks for your help.

    Read the article

  • Create a Counter within a For-Loop?

    - by Todd Hartman
    I am a novice programmer and apologize upfront for the complicated question. I am trying to create a lexical decision task for experimental research, in which respondents must decide if a series of letters presented on the screen make a "word" or "not a word". Everything works reasonably well except for the bit where I want to randomly select a word (category A) or nonword (category B) for each of 80 trials from a separate input file (input.txt). The randomization works, but some elements from each list (category A or B) are skipped because I have used "round.catIndex = j;" where "j" is a loop for each successive trial. Because some trials randomly select from Category A and other from Category B, "j" does not move successively down the list for each category. Instead, elements from the Category A list may be selected from something like 1, 2, 5, 8, 9, 10, and so on (it varies each time because of the randomization). To make a long story short(!), how do I create a counter that will work within the for-loop for each trial, so that every word and nonword from Category A and B, respectively, will be used for the lexical decision task? Everything I have tried thus far does not work properly or breaks the javascript entirely. Below is my code snippet and the full code is available at http://50.17.194.59/LDT/trunk/LDT.js. Also, the full lexical decision task can be accessed at http://50.17.194.59/LDT/trunk/LDT.php. Thanks! function initRounds() { numlst = []; for (var k = 0; k<numrounds; k++) { if (k % 2 == 0) numlst[k] = 0; else numlst[k] = 1; } numlst.sort(function() {return 0.5 - Math.random()}) for (var j = 0; j<numrounds; j++) { var round = new LDTround(); if (numlst[j] == 0) { round.category = input.catA.datalabel; } else if (numlst[j] == 1) { round.category = input.catB.datalabel; } // pick a category & stimulus if (round.category == input.catA.datalabel) { round.itemtype = input.catA.itemtype; round.correct = 1; round.catIndex = j; } else if (round.category == input.catB.datalabel) { round.itemtype = input.catB.itemtype; round.correct = 2; round.catIndex = j; } roundArray[i].push(round); } return roundArray; }

    Read the article

< Previous Page | 123 124 125 126 127 128 129 130 131 132 133 134  | Next Page >