Search Results

Search found 10235 results on 410 pages for 'inner loop'.

Page 12/410 | < Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >

  • switch statement in for loop and if statement not completing

    - by user2373912
    I'm trying to find out how many of each character are in a string. I've searched around for a while and can't seem to figure out why my switch statement is stopping after the first case. function charFreq(string){ var splitUp = string.split(""); console.log(splitUp); var a; var b; var c; var v; for (var i = 0; i<splitUp.length; i++){ if (i<1){ switch (splitUp[i]){ case "a": a = 1; break; case "b": b = 1; break; case "c": c = 1; break; case "v": v = 1; break; } } else { switch (splitUp[i]){ case "a": a += 1; break; case "b": b += 1; break; case "c": c += 1; break; case "v": v += 1; break; } } } console.log("There are " + a + " A's, " + b + " B's, " + c + " C's, and " + v + " V's.") } charFreq("aaabccbbavabac"); What am I doing wrong that would make the console read: There are 6 A's, NaN B's, NaN C's, and NaN V's.

    Read the article

  • Flash AS3: position loaded images from loop based on image height

    - by HeroicNate
    I'm trying to dynamically stack images that are being pulled in via an xml file. Below is what I'm doing, and it almost works. The problem is that it only seems to fire off the event complete function on the very last one, instead of going for all of them. Is there a way to make it run the even.complete function for each image? function aboutfileLoaded(event:Event):void { aboutXML = new XML(aboutTextLoader.data); for(var l:int = 0; l < aboutXML.aboutimages.image.length(); l++) { imageLoader = new Loader(); imageSource = aboutXML.aboutimages.image[l]; if (imageSource != "") { this.imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, aboutimageLoaded); this.imageLoader.load(new URLRequest(imageSource)); //aboutBox.aboutContent.addChild(imageLoader); //imageLoader.y = imageYpos; //imageYpos = imageYpos + 50; } } } function aboutimageLoaded(event:Event):void { aboutBox.aboutContent.addChild(imageLoader); this.imageLoader.y = imageYpos; imageYpos = imageYpos + this.imageLoader.height; }

    Read the article

  • Nested for loop error with !null checking an element that doesn't exist

    - by Programatt
    I am currently using nested for loops in a 2D array of size 4,2. When I run my program, I get index out of bounds Exception on the following line else if (state[i][j+1] != null && state[i][j].getFlash() <= state[i][j].getCycleLength() && state[i][j+1].getCycleLength() == state[i][j].getCycleLength()){ } It says the index out of bounds is 2. I would understand the error if I wasn't checking to see if [i][j+1] wasn't null, but I don't understand the exception with the check? I tried moving around the !null check but the program still fails on this line. Any help would be greatly appreciated. Stack trace: Exception in thread "Timer-0" java.lang.ArrayIndexOutOfBoundsException: 2 at NatComp.data$1.run(data.java:67) at java.util.TimerThread.mainLoop(Timer.java:512) at java.util.TimerThread.run(Timer.java:462)

    Read the article

  • better for-loop syntax for detecting empty sequences?

    - by Dmitry Beransky
    Hi, Is there a better way to write the following: row_counter = 0 for item in iterable_sequence: # do stuff with the item counter += 1 if not row_counter: # handle the empty-sequence-case Please keep in mind that I can't use len(iterable_sequence) because 1) not all sequences have known lengths; 2) in some cases calling len() may trigger loading of the sequence's items into memory (as the case would be with sql query results). The reason I ask is that I'm simply curious if there is a way to make above more concise and idiomatic. What I'm looking for is along the lines of: for item in sequence: #process item *else*: #handle the empty sequence case (assuming "else" here worked only on empty sequences, which I know it doesn't)

    Read the article

  • Help with a loop to return UIImage from possible matches

    - by Canada Dev
    I am parsing a list of locations and would like to return a UIImage with a flag based on these locations. I have a string with the location. This can be many different locations and I would like to search this string for possible matches in an NSArray, and when there's a match, it should find the appropriate filename in an NSDictionary. Here's an example of the NSDictionary and NSArray: NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: @"franceFlag", @"france", @"greeceFlag", @"greece", @"spainFlag", @"spain", @"norwayFlag", @"norway", nil]; NSArray *array = [NSArray arrayWithObjects: @"france" @"greece" @"spain" @"portugal" @"ireland" @"norway", nil]; Obviously I'll have a lot more countries and flags in both. Here's what I have got to so far: -(UIImage *)flagFromOrigin:(NSString *)locationString { NSRange range; for (NSString *arrayString in countryArray) { range = [locationString rangeOfString:arrayString]; if (range.location != NSNotFound) { return [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[dictionary objectForKey: arrayString] ofType:@"png"]]; } } return nil; } Now, the above doesn't actually work. I am missing something (and perhaps not even doing it right in the first place) The issue is, the locationString could have several locations in the same country, described something like this "Barcelona, Spain", "Madrid, Spain", "North Spain", etc., but I just want to retrieve "Spain" in this case. (Also, notice caps for each country). Basically, I want to search the locationString I pass into the method for a possible match with one of the countries listed in the NSArray. If/When one is found, it should continue into the NSDictionary and grab the appropriate flag based on the correct matched string from the array. I believe the best way would then to take the string from the array, as this would be a stripped-out version of the location. Any help to point me in the right direction for the last bit is greatly appreciated.

    Read the article

  • jQuery animation loop not working

    - by Marko Ivanovski
    Hi, I'm trying to create a looping animation that starts on onmousedown and stops on onmouseout. The effect is a simple scroll that will continue looping until you release the mouse. I've created a function which performs the .animate method and it passes itself as a callback but the code only runs once. Here's the entire code: $(document).ready(function() { var $scroller = $("#scroller"); var $content = $("#content", $scroller); // lineHeight equal to 1 line of text var lineHeight = $content.css('line-height'); //Amount to scroll = 3 lines of text a time var amountToScroll = lineHeight.replace("px","")*3; var maxScroll = $content.height() - $scroller.height(); function scrollDown() { var topCoord = $content.css("top").replace("px",""); if(topCoord > -maxScroll) { if((-maxScroll-topCoord) > -amountToScroll) { $content.stop().animate({ top: -maxScroll }, 1000 ); } else { $content.stop().animate({ top: "-=" + amountToScroll }, 1000, function(){ scrollDown() } ); } } } function scrollUp() { var topCoord = $content.css("top").replace("px",""); if(topCoord < 0) { if(topCoord > -amountToScroll) { $content.stop().animate({ top: 0 }, 1000 ); } else { $content.stop().animate({ top: "+=" + amountToScroll }, 1000, function(){scrollUp()} ); } } } $("#scroll-down").mousedown(function() { scrollDown(); }); $("#scroll-down").mouseup(function() { $content.stop(); }); $("#scroll-up").mousedown(function() { scrollUp(); }); $("scroll-up").mouseup(function() { $content.stop(); }); });

    Read the article

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

    - by Aristide
    Python offers an optional loop-else clause which is executed if and only if the loop is not terminated by a break. (In other words, the condition fails for a while-loop or the iterator is exhausted for a for-loop.) Does this loop-else construct originate from another language? (Either theoretical or actually implemented.) Has it been taken up in any newer language? Maybe I should ask the former of Guido, but surely he is too busy for such a futile inquiry. ;-) Related discussion and examples: Pythonic ways to use ‘else’ in a for loop

    Read the article

  • java for loop not working

    - by Steve
    I hope this isn't a stupid question but I have looked up every example I can find and it still seems like I have this code right and it still isn't working... I enter one number and it moves on to the next line of code instead of looping. I'm using this to fill an array with user input numbers. I appreciate any help, thanks. for(i=0; i<9; i++); { System.out.println ("Please enter a number:"); Num[i] = keyboard.nextDouble(); Sum += Num[i]; Product *= Num[i]; }

    Read the article

  • JavaScript apparently waits for each AJAX call before sending another in a loop

    - by itako
    Hello. Straight to the point: I have this javascript: for(item=1;item<5;item++) { xmlhttp=new XMLHttpRequest(); xmlhttp.open("GET",'zzz.php', true); xmlhttp.send(); } And in PHP file something like this: usleep(5);die('ok'); Now the problem is javascript seems to be waiting for each ajax call to be completed before sending another one. So the first response gets back after approx. 5 seconds, next after 10 seconds and so on. That's a very simplified version of what I do, since the real script involves using cURL in PHP and jQuery as JS lib. But the problem remains the same. Why do responses come back in 5 second intervals?

    Read the article

  • JavaScript for loop index strangeness

    - by pythonBOI
    I'm relatively new to JS so this may be a common problem, but I noticed something strange when dealing with for loops and the onclick function. I was able to replicate the problem with this code: <html> <head> <script type="text/javascript"> window.onload = function () { var buttons = document.getElementsByTagName('a'); for (var i=0; i<2; i++) { buttons[i].onclick = function () { alert(i); return false; } } } </script> </head> <body> <a href="">hi</a> <br /> <a href="">bye</a> </body> </html> When clicking the links I would expect to get '0' and '1', but instead I get '2' for both of them. Why is this? BTW, I managed to solve my particular problem by using the 'this' keyword, but I'm still curious as to what is behind this behavior.

    Read the article

  • MySQL inner join different results

    - by Darryl at NetHosted
    I am trying to work out why the following two queries return different results: SELECT DISTINCT i.id, i.date FROM `tblinvoices` i INNER JOIN `tblinvoiceitems` it ON it.userid=i.userid INNER JOIN `tblcustomfieldsvalues` cf ON it.relid=cf.relid WHERE i.`tax` = 0 AND i.`date` BETWEEN '2012-07-01' AND '2012-09-31' and SELECT DISTINCT i.id, i.date FROM `tblinvoices` i WHERE i.`tax` = 0 AND i.`date` BETWEEN '2012-07-01' AND '2012-09-31' Obviously the difference is the inner join here, but I don't understand why the one with the inner join is returning less results than the one without it, I would have thought since I didn't do any cross table references they should return the same results. The final query I am working towards is SELECT DISTINCT i.id, i.date FROM `tblinvoices` i INNER JOIN `tblinvoiceitems` it ON it.userid=i.userid INNER JOIN `tblcustomfieldsvalues` cf ON it.relid=cf.relid WHERE cf.`fieldid` =5 AND cf.`value` REGEXP '[A-Za-z]' AND i.`tax` = 0 AND i.`date` BETWEEN '2012-07-01' AND '2012-09-31' But because of the different results that seem incorrect when I add the inner join (it removes some results that should be valid) it's not working at present, thanks.

    Read the article

  • collect string in loop and printout all the string outside loop

    - by user1508163
    I'm newbie here and there is some question that I want have some lesson from you guys. For example: #include <stdio.h> #include<stdlib.h> #include<ctype.h> void main() { char name[51],selection; do { printf("Enter name: "); fflush(stdin); gets(name); printf("Enter another name?(Y/N)"); scanf("%c",&selection); selection=toupper(selection); }while (selection=='Y'); //I want to printout the entered name here but dunno the coding printf("END\n"); system("pause"); } As I know when the loops perform will overwrite the variable then how I perform a coding that will printout all the name user entered? I have already ask my tutor and he is ask me to use pointer, can anyone guide me in this case?

    Read the article

  • Can a shell loop do this?

    - by helpwithshell
    Ive seen loops to unzip all zip files in a directory, however, before I run this, I would rather make sure what Im about to run will work right: for i in dir; do cd $i; unzip '*.zip'; rm -rf *.zip; cd ..; done Basically I want it to look at the output of "dir" see all the folders, for each directory cd into it, unzip all the zip archives, then remove them, then cd back and do it again until theres no more. Is this something I should do in a single command or should I consider doing this in perl?

    Read the article

  • Python for loop question

    - by Joe Dunk
    I was wondering how to achieve the following in python: for( int i = 0; cond...; i++) if cond... i++; //to skip an run-through I tried this with no luck. for i in range(whatever): if cond... : i += 1

    Read the article

  • C++ - my loop keeps on adding up to 0

    - by user1756913
    so far here's my code #include <iostream> using namespace std; int main () { int num1 = 0; int num2 = 0; int sum = 0; for(num2 = num1; num1 <= num2; num1 +=2) sum += num1; num1 = num1 / 2 == 0? num1 : num1 + 1; num2 = num2 / 2 == 0? num2 : num2 - 1; cout << "Enter the First Number:" << endl; cin >> num1; cout << "Enter the Second Number:" << endl; cin >> num2; cout << "Total Sum: " << sum << endl; } //end for but the sum keeps on adding up to 0 :/ here's the problem. Create a program that displays the sum of the even numbers between and including two numbers entered by the user. In other words, if the user enters an even number, that number should be included in the sum. For example, if the user enters the integers 2 and 7, the sum is 12 (2 + 4 + 6). If the user enters the integers 2 and 8, the sum is 20 (2 + 4 + 6 + 8 ). Display an error message if the first integer entered by the user is greater than the second integer.

    Read the article

  • Java for-loop problem

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

    Read the article

  • Nested for-loop, searching files

    - by user2961510
    I have two files: filetest.txt ============ SSISPACKAGE1.dtsx SSISPACKAGE2.dtsx SSISPACKAGE3.dtsx SSISPACKAGE4.dtsx SSISPACKAGE5.dtsx SSISPACKAGE6.dtsx SSISPACKAGE7.dtsx SSISPACKAGE8.dtsx filetest2.txt ============= \\central_test_server\SSIS_Packages\Daily.bat \\central_test_server\SSIS_Packages\Weekly.bat \\central_test_server\SSIS_Packages\Monthly.bat \\central_test_server\SSIS_Packages\Quarterly.bat \\central_test_server\SSIS_Packages\SemiAnnually.bat \\central_test_server\SSIS_Packages\Annually.bat What I need is to cycle through filetest.txt, then search the files identified in filetest2.txt for the filename and output to a file the results. I am trying to identify in well over 100 bat files where each of about 100 SSIS Packages are running. I'm doing this in Windows batch, have tried about 20 various approaches without success - any help would be greatly appreciated.

    Read the article

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

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

    Read the article

  • MySQL – How to Write Loop in MySQL

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

    Read the article

  • Reflective discovery of an inner class in an API

    - by wassup
    Let me ask you, as this bothers me for quite a while but appears to be subjectively the best solution for my problem, if reflective discovery of an inner class for API purposes is that bad idea? First, let me explain what I mean by saying "reflective discovery" and all that stuff. I am sketching an API for a Java database system, that'll be centered around block-based entities (don't ask me what that means - that's a long story), and those entities can be read and returned to the Java code as objects subclassed from the Entity class. I have an Entity.Factory class, that, by means of fluent interfaces, takes a Class<? extends Entity> argument and then, uses an instance of Section.Builder, Property.Builder, or whatever builder the entity has, to put it into the back-end storage. The idea about registering all entity types and their builders just doesn't appeal to me, so I thought that the closest solution to the problem that'd suffice my design needs would be to discover, using reflection, all inner classes of Entity classes and find one that's called Builder. Looking for some expert insight :) And if I missed some important design details (which could happen as I tried to make this question as concise as possible), just tell me and I'll add them.

    Read the article

  • How to simulate inner join on very large files in java (without running out of memory)

    - by Constantin
    I am trying to simulate SQL joins using java and very large text files (INNER, RIGHT OUTER and LEFT OUTER). The files have already been sorted using an external sort routine. The issue I have is I am trying to find the most efficient way to deal with the INNER join part of the algorithm. Right now I am using two Lists to store the lines that have the same key and iterate through the set of lines in the right file once for every line in the left file (provided the keys still match). In other words, the join key is not unique in each file so would need to account for the Cartesian product situations ... left_01, 1 left_02, 1 right_01, 1 right_02, 1 right_03, 1 left_01 joins to right_01 using key 1 left_01 joins to right_02 using key 1 left_01 joins to right_03 using key 1 left_02 joins to right_01 using key 1 left_02 joins to right_02 using key 1 left_02 joins to right_03 using key 1 My concern is one of memory. I will run out of memory if i use the approach below but still want the inner join part to work fairly quickly. What is the best approach to deal with the INNER join part keeping in mind that these files may potentially be huge public class Joiner { private void join(BufferedReader left, BufferedReader right, BufferedWriter output) throws Throwable { BufferedReader _left = left; BufferedReader _right = right; BufferedWriter _output = output; Record _leftRecord; Record _rightRecord; _leftRecord = read(_left); _rightRecord = read(_right); while( _leftRecord != null && _rightRecord != null ) { if( _leftRecord.getKey() < _rightRecord.getKey() ) { write(_output, _leftRecord, null); _leftRecord = read(_left); } else if( _leftRecord.getKey() > _rightRecord.getKey() ) { write(_output, null, _rightRecord); _rightRecord = read(_right); } else { List<Record> leftList = new ArrayList<Record>(); List<Record> rightList = new ArrayList<Record>(); _leftRecord = readRecords(leftList, _leftRecord, _left); _rightRecord = readRecords(rightList, _rightRecord, _right); for( Record equalKeyLeftRecord : leftList ){ for( Record equalKeyRightRecord : rightList ){ write(_output, equalKeyLeftRecord, equalKeyRightRecord); } } } } if( _leftRecord != null ) { write(_output, _leftRecord, null); _leftRecord = read(_left); while(_leftRecord != null) { write(_output, _leftRecord, null); _leftRecord = read(_left); } } else { if( _rightRecord != null ) { write(_output, null, _rightRecord); _rightRecord = read(_right); while(_rightRecord != null) { write(_output, null, _rightRecord); _rightRecord = read(_right); } } } _left.close(); _right.close(); _output.flush(); _output.close(); } private Record read(BufferedReader reader) throws Throwable { Record record = null; String data = reader.readLine(); if( data != null ) { record = new Record(data.split("\t")); } return record; } private Record readRecords(List<Record> list, Record record, BufferedReader reader) throws Throwable { int key = record.getKey(); list.add(record); record = read(reader); while( record != null && record.getKey() == key) { list.add(record); record = read(reader); } return record; } private void write(BufferedWriter writer, Record left, Record right) throws Throwable { String leftKey = (left == null ? "null" : Integer.toString(left.getKey())); String leftData = (left == null ? "null" : left.getData()); String rightKey = (right == null ? "null" : Integer.toString(right.getKey())); String rightData = (right == null ? "null" : right.getData()); writer.write("[" + leftKey + "][" + leftData + "][" + rightKey + "][" + rightData + "]\n"); } public static void main(String[] args) { try { BufferedReader leftReader = new BufferedReader(new FileReader("LEFT.DAT")); BufferedReader rightReader = new BufferedReader(new FileReader("RIGHT.DAT")); BufferedWriter output = new BufferedWriter(new FileWriter("OUTPUT.DAT")); Joiner joiner = new Joiner(); joiner.join(leftReader, rightReader, output); } catch (Throwable e) { e.printStackTrace(); } } } After applying the ideas from the proposed answer, I changed the loop to this private void join(RandomAccessFile left, RandomAccessFile right, BufferedWriter output) throws Throwable { long _pointer = 0; RandomAccessFile _left = left; RandomAccessFile _right = right; BufferedWriter _output = output; Record _leftRecord; Record _rightRecord; _leftRecord = read(_left); _rightRecord = read(_right); while( _leftRecord != null && _rightRecord != null ) { if( _leftRecord.getKey() < _rightRecord.getKey() ) { write(_output, _leftRecord, null); _leftRecord = read(_left); } else if( _leftRecord.getKey() > _rightRecord.getKey() ) { write(_output, null, _rightRecord); _pointer = _right.getFilePointer(); _rightRecord = read(_right); } else { long _tempPointer = 0; int key = _leftRecord.getKey(); while( _leftRecord != null && _leftRecord.getKey() == key ) { _right.seek(_pointer); _rightRecord = read(_right); while( _rightRecord != null && _rightRecord.getKey() == key ) { write(_output, _leftRecord, _rightRecord ); _tempPointer = _right.getFilePointer(); _rightRecord = read(_right); } _leftRecord = read(_left); } _pointer = _tempPointer; } } if( _leftRecord != null ) { write(_output, _leftRecord, null); _leftRecord = read(_left); while(_leftRecord != null) { write(_output, _leftRecord, null); _leftRecord = read(_left); } } else { if( _rightRecord != null ) { write(_output, null, _rightRecord); _rightRecord = read(_right); while(_rightRecord != null) { write(_output, null, _rightRecord); _rightRecord = read(_right); } } } _left.close(); _right.close(); _output.flush(); _output.close(); } UPDATE While this approach worked, it was terribly slow and so I have modified this to create files as buffers and this works very well. Here is the update ... private long getMaxBufferedLines(File file) throws Throwable { long freeBytes = Runtime.getRuntime().freeMemory() / 2; return (freeBytes / (file.length() / getLineCount(file))); } private void join(File left, File right, File output, JoinType joinType) throws Throwable { BufferedReader leftFile = new BufferedReader(new FileReader(left)); BufferedReader rightFile = new BufferedReader(new FileReader(right)); BufferedWriter outputFile = new BufferedWriter(new FileWriter(output)); long maxBufferedLines = getMaxBufferedLines(right); Record leftRecord; Record rightRecord; leftRecord = read(leftFile); rightRecord = read(rightFile); while( leftRecord != null && rightRecord != null ) { if( leftRecord.getKey().compareTo(rightRecord.getKey()) < 0) { if( joinType == JoinType.LeftOuterJoin || joinType == JoinType.LeftExclusiveJoin || joinType == JoinType.FullExclusiveJoin || joinType == JoinType.FullOuterJoin ) { write(outputFile, leftRecord, null); } leftRecord = read(leftFile); } else if( leftRecord.getKey().compareTo(rightRecord.getKey()) > 0 ) { if( joinType == JoinType.RightOuterJoin || joinType == JoinType.RightExclusiveJoin || joinType == JoinType.FullExclusiveJoin || joinType == JoinType.FullOuterJoin ) { write(outputFile, null, rightRecord); } rightRecord = read(rightFile); } else if( leftRecord.getKey().compareTo(rightRecord.getKey()) == 0 ) { String key = leftRecord.getKey(); List<File> rightRecordFileList = new ArrayList<File>(); List<Record> rightRecordList = new ArrayList<Record>(); rightRecordList.add(rightRecord); rightRecord = consume(key, rightFile, rightRecordList, rightRecordFileList, maxBufferedLines); while( leftRecord != null && leftRecord.getKey().compareTo(key) == 0 ) { processRightRecords(outputFile, leftRecord, rightRecordFileList, rightRecordList, joinType); leftRecord = read(leftFile); } // need a dispose for deleting files in list } else { throw new Exception("DATA IS NOT SORTED"); } } if( leftRecord != null ) { if( joinType == JoinType.LeftOuterJoin || joinType == JoinType.LeftExclusiveJoin || joinType == JoinType.FullExclusiveJoin || joinType == JoinType.FullOuterJoin ) { write(outputFile, leftRecord, null); } leftRecord = read(leftFile); while(leftRecord != null) { if( joinType == JoinType.LeftOuterJoin || joinType == JoinType.LeftExclusiveJoin || joinType == JoinType.FullExclusiveJoin || joinType == JoinType.FullOuterJoin ) { write(outputFile, leftRecord, null); } leftRecord = read(leftFile); } } else { if( rightRecord != null ) { if( joinType == JoinType.RightOuterJoin || joinType == JoinType.RightExclusiveJoin || joinType == JoinType.FullExclusiveJoin || joinType == JoinType.FullOuterJoin ) { write(outputFile, null, rightRecord); } rightRecord = read(rightFile); while(rightRecord != null) { if( joinType == JoinType.RightOuterJoin || joinType == JoinType.RightExclusiveJoin || joinType == JoinType.FullExclusiveJoin || joinType == JoinType.FullOuterJoin ) { write(outputFile, null, rightRecord); } rightRecord = read(rightFile); } } } leftFile.close(); rightFile.close(); outputFile.flush(); outputFile.close(); } public void processRightRecords(BufferedWriter outputFile, Record leftRecord, List<File> rightFiles, List<Record> rightRecords, JoinType joinType) throws Throwable { for(File rightFile : rightFiles) { BufferedReader rightReader = new BufferedReader(new FileReader(rightFile)); Record rightRecord = read(rightReader); while(rightRecord != null){ if( joinType == JoinType.LeftOuterJoin || joinType == JoinType.RightOuterJoin || joinType == JoinType.FullOuterJoin || joinType == JoinType.InnerJoin ) { write(outputFile, leftRecord, rightRecord); } rightRecord = read(rightReader); } rightReader.close(); } for(Record rightRecord : rightRecords) { if( joinType == JoinType.LeftOuterJoin || joinType == JoinType.RightOuterJoin || joinType == JoinType.FullOuterJoin || joinType == JoinType.InnerJoin ) { write(outputFile, leftRecord, rightRecord); } } } /** * consume all records having key (either to a single list or multiple files) each file will * store a buffer full of data. The right record returned represents the outside flow (key is * already positioned to next one or null) so we can't use this record in below while loop or * within this block in general when comparing current key. The trick is to keep consuming * from a List. When it becomes empty, re-fill it from the next file until all files have * been consumed (and the last node in the list is read). The next outside iteration will be * ready to be processed (either it will be null or it points to the next biggest key * @throws Throwable * */ private Record consume(String key, BufferedReader reader, List<Record> records, List<File> files, long bufferMaxRecordLines ) throws Throwable { boolean processComplete = false; Record record = records.get(records.size() - 1); while(!processComplete){ long recordCount = records.size(); if( record.getKey().compareTo(key) == 0 ){ record = read(reader); while( record != null && record.getKey().compareTo(key) == 0 && recordCount < bufferMaxRecordLines ) { records.add(record); recordCount++; record = read(reader); } } processComplete = true; // if record is null, we are done if( record != null ) { // if the key has changed, we are done if( record.getKey().compareTo(key) == 0 ) { // Same key means we have exhausted the buffer. // Dump entire buffer into a file. The list of file // pointers will keep track of the files ... processComplete = false; dumpBufferToFile(records, files); records.clear(); records.add(record); } } } return record; } /** * Dump all records in List of Record objects to a file. Then, add that * file to List of File objects * * NEED TO PLACE A LIMIT ON NUMBER OF FILE POINTERS (check size of file list) * * @param records * @param files * @throws Throwable */ private void dumpBufferToFile(List<Record> records, List<File> files) throws Throwable { String prefix = "joiner_" + files.size() + 1; String suffix = ".dat"; File file = File.createTempFile(prefix, suffix, new File("cache")); BufferedWriter writer = new BufferedWriter(new FileWriter(file)); for( Record record : records ) { writer.write( record.dump() ); } files.add(file); writer.flush(); writer.close(); }

    Read the article

  • Java: Non-static nested classes and instance.super()

    - by Kiv
    I'm having a hard time wrapping my head around non-static nested classes in Java. Consider the following example, which prints "Inner" and then "Child". class Outer { class Inner { Inner() { System.out.println("Inner"); } } } public class Child extends Outer.Inner { Child(Outer o) { o.super(); System.out.println("Child"); } public static void main(String args[]) { new Child(new Outer()); } } I understand that instances of Inner always have to be associated with an Outer instance, and that that applies to Child too since it extends Inner. My question is what the o.super() syntax means - why does it call the Inner constructor? I've only seen a plain super(args) used to call the superclass constructor and super.method() to call the superclass version of an overridden method, but never something of the form instance.super().

    Read the article

  • Why my inner class DO see a NON static variable?

    - by Roman
    Earlier I had a problem when an inner anonymous class did not see a field of the "outer" class. I needed to make a final variable to make it visible to the inner class. Now I have an opposite situation. In the "outer" class "ClientListener" I use an inner class "Thread" and the "Thread" class I have the "run" method and does see the "earPort" from the "outer" class! Why? import java.io.IOException; import java.net.*; import java.io.BufferedReader; import java.io.InputStreamReader; public class ClientsListener { private int earPort; // Constructor. public ClientsListener(int earPort) { this.earPort = earPort; } public void starListening() { Thread inputStreamsGenerator = new Thread() { public void run() { System.out.println(earPort); try { System.out.println(earPort); ServerSocket listeningSocket = new ServerSocket(earPort); Socket serverSideSocket = listeningSocket.accept(); BufferedReader in = new BufferedReader(new InputStreamReader(serverSideSocket.getInputStream())); } catch (IOException e) { System.out.println(""); } } }; inputStreamsGenerator.start(); } }

    Read the article

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

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

    Read the article

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