/** * Get dependencies of a source file. * * @param path The canonical path of source file. * @return Path of dependencies. */ private ArrayList<String> getDependencies(String path) { if (!dependenceMap.containsKey(path)) { ArrayList<String> dependencies = new ArrayList<String>(); Matcher m = PATTERN_REQUIRE.matcher(read(path, charset)); while (m.find()) { // Decide which root path to use. // Path wrapped in <> is related to root path. // Path wrapped in "" is related to parent folder of the source file. String root = null; if (m.group(1).equals("<")) { root = this.root; } else { root = new File(path).getParent(); } // Get path of required file. String required = m.group(2); File f = new File(root, required); if (f.exists()) { dependencies.add(canonize(f)); } else { App.exit("Cannot find required file " + required + " in " + path); } } dependenceMap.put(path, dependencies); } return dependenceMap.get(path); }
ProcessorState(Processor p, Log log, Source source, ProcessingEnvironment env) { processor = p; contributed = false; try { processor.init(env); checkSourceVersionCompatibility(source, log); supportedAnnotationPatterns = new ArrayList<Pattern>(); for (String importString : processor.getSupportedAnnotationTypes()) { supportedAnnotationPatterns.add(importStringToPattern(importString, processor, log)); } supportedOptionNames = new ArrayList<String>(); for (String optionName : processor.getSupportedOptions()) { if (checkOptionName(optionName, log)) supportedOptionNames.add(optionName); } } catch (ClientCodeException e) { throw e; } catch (Throwable t) { throw new AnnotationProcessingError(t); } }
private InstanceList readFile() throws IOException { String NL = System.getProperty("line.separator"); Scanner scanner = new Scanner(new FileInputStream(fileName), encoding); ArrayList<Pipe> pipeList = new ArrayList<Pipe>(); pipeList.add(new CharSequence2TokenSequence(Pattern.compile("\\p{L}\\p{L}+"))); pipeList.add(new TokenSequence2FeatureSequence()); InstanceList testing = new InstanceList(new SerialPipes(pipeList)); try { while (scanner.hasNextLine()) { String text = scanner.nextLine(); text = text.replaceAll("\\x0d", ""); Pattern patten = Pattern.compile("^(.*?),(.*?),(.*)$"); Matcher matcher = patten.matcher(text); if (matcher.find()) { docIds.add(matcher.group(1)); testing.addThruPipe(new Instance(matcher.group(3), null, "test instance", null)); } } } finally { scanner.close(); } return testing; }
public void setup() { size(600, 400); smooth(); f = createFont("Georgia", 12, true); obstacles = new ArrayList(); boids = new ArrayList(); // A little algorithm to pick a bunch of random obstacles that don't overlap for (int i = 0; i < 100; i++) { float x = random(width); float y = random(height); float r = random(50 - i / 2, 50); boolean ok = true; for (int j = 0; j < obstacles.size(); j++) { Obstacle o = (Obstacle) obstacles.get(j); if (dist(x, y, o.loc.x, o.loc.y) < o.radius + r + 20) { ok = false; } } if (ok) obstacles.add(new Obstacle(x, y, r)); } // Starting with three boids boids.add(new Boid(new PVector(random(width), random(height)), 3f, 0.2f)); boids.add(new Boid(new PVector(random(width), random(height)), 3f, 0.1f)); boids.add(new Boid(new PVector(random(width), random(height)), 2f, 0.05f)); }
/** * Parse a method declaration. The declaration should be in the following format: * * <p>fully-qualified-method-name (args) * * <p>where the arguments are comma separated and all arguments other than primitives should have * fully qualified names. Arrays are indicating by trailing brackets. For example: * * <p>int int[] int[][] java.lang.String java.util.Date[] * * <p>The arguments are translated into BCEL types and a MethodDef is returned. */ private MethodDef parse_method(StrTok st) { // Get the method name String method_name = st.need_word(); // Get the opening paren st.need("("); // Read the arguments ArrayList<String> args = new ArrayList<String>(); String tok = st.nextToken(); if (tok != ")") { st.pushBack(); do { tok = st.need_word(); args.add(tok); } while (st.nextToken() == ","); st.pushBack(); st.need(")"); } // Convert the arguments to Type Type[] targs = new Type[args.size()]; for (int ii = 0; ii < args.size(); ii++) { targs[ii] = BCELUtil.classname_to_type(args.get(ii)); } return new MethodDef(method_name, targs); }
protected void checkLeaf(SimulatedArchivalUnit sau) { log.debug("checkLeaf()"); String parent = sau.getUrlRoot() + "/branch1"; CachedUrlSetSpec spec = new RangeCachedUrlSetSpec(parent); CachedUrlSet set = sau.makeCachedUrlSet(spec); Iterator setIt = set.contentHashIterator(); ArrayList childL = new ArrayList(16); while (setIt.hasNext()) { childL.add(((CachedUrlSetNode) setIt.next()).getUrl()); } String[] expectedA = new String[] { parent, parent + "/001file.html", parent + "/001file.txt", parent + "/002file.html", parent + "/002file.txt", parent + "/branch1", parent + "/branch1/001file.html", parent + "/branch1/001file.txt", parent + "/branch1/002file.html", parent + "/branch1/002file.txt", parent + "/branch1/index.html", parent + "/branch2", parent + "/branch2/001file.html", parent + "/branch2/001file.txt", parent + "/branch2/002file.html", parent + "/branch2/002file.txt", parent + "/branch2/index.html", parent + "/index.html", }; assertIsomorphic(expectedA, childL); }
/** * Returns all editors. * * @return editors */ EditorArea[] editors() { final ArrayList<EditorArea> edits = new ArrayList<EditorArea>(); for (final Component c : tabs.getComponents()) { if (c instanceof EditorArea) edits.add((EditorArea) c); } return edits.toArray(new EditorArea[edits.size()]); }
protected void checkRoot(SimulatedArchivalUnit sau) { log.debug("checkRoot()"); CachedUrlSet set = sau.getAuCachedUrlSet(); Iterator setIt = set.flatSetIterator(); ArrayList childL = new ArrayList(1); CachedUrlSet cus = null; while (setIt.hasNext()) { cus = (CachedUrlSet) setIt.next(); childL.add(cus.getUrl()); } String urlRoot = sau.getUrlRoot(); String[] expectedA = new String[1]; expectedA[0] = urlRoot; assertIsomorphic(expectedA, childL); setIt = cus.flatSetIterator(); childL = new ArrayList(7); while (setIt.hasNext()) { childL.add(((CachedUrlSetNode) setIt.next()).getUrl()); } expectedA = new String[] { urlRoot + "/001file.html", urlRoot + "/001file.txt", urlRoot + "/002file.html", urlRoot + "/002file.txt", urlRoot + "/branch1", urlRoot + "/branch2", urlRoot + "/index.html" }; assertIsomorphic(expectedA, childL); }
public static void main(String[] args) { /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ try { Scanner sc = new Scanner(new File("/home/santosh/Desktop/testData")); int testCases = sc.nextInt(); int i = 0; ArrayList<ArrayList<Integer>> inputArraysList = new ArrayList<ArrayList<Integer>>(); ArrayList<Integer> list; while (i++ < testCases) { int n = sc.nextInt(); int k = 0; list = new ArrayList<Integer>(); while (k < n) { list.add(sc.nextInt()); k++; } inputArraysList.add(list); } // System.out.println(inputArraysList.size()); for (ArrayList<Integer> arr : inputArraysList) { countPairs(arr.toArray(new Integer[arr.size()])); } } catch (Exception e) { } }
public void init() { Scanner scan = new Scanner(System.in); count = scan.nextInt(); x0 = scan.nextLong(); y0 = scan.nextLong(); int result = 0; boolean special = false; for (int i = 0; i < count; i++) { long tempx = scan.nextLong(); long tempy = scan.nextLong(); if (tempx == x0 && tempy == y0) { special = true; continue; } boolean isDuplicate = false; for (int j = 0; j < result; j++) { long x1 = xList.get(j); long y1 = yList.get(j); if ((x1 - x0) * (tempy - y0) == (y1 - y0) * (tempx - x0)) { isDuplicate = true; break; } } if (!isDuplicate) { xList.add(tempx); yList.add(tempy); result++; } } if (special && result == 0) result = 1; System.out.println(result); scan.close(); }
void handleScanFiles(JTextField field, String[] extensions) { String[] dataFiles = scanDataFolderForFilesByType(extensions); if (dataFiles == null || dataFiles.length == 0) return; String[] oldFileList = field.getText().trim().split(","); ArrayList<String> newFileList = new ArrayList<String>(); for (String c : oldFileList) { c = c.trim(); if (!c.equals("") && newFileList.indexOf(c) == -1) // TODO check exists() here? { newFileList.add(c); } } for (String c : dataFiles) { c = c.trim(); if (!c.equals("") && newFileList.indexOf(c) == -1) { newFileList.add(c); } } Collections.sort(newFileList); String finalFileList = ""; int i = 0; for (String s : newFileList) { finalFileList += (i > 0 ? ", " : "") + s; i++; } field.setText(finalFileList); }
public void trace(float x, float y) { println(x); if (frameCounter > 2 && mousePressed) { coords.add(new PVector(x, y)); frameCounter = 0; if (coordCounter > 0) { PVector tempCoord = (PVector) coords.get(coordCounter - 1); line(x, y, tempCoord.x, tempCoord.y); } coordCounter++; } // println(coordCounter); for (int i = 0; i < coords.size(); i++) { PVector tempCoordnear = (PVector) coords.get(i); float coordDist = dist(x, y, tempCoordnear.x, tempCoordnear.y); if (coordDist < distance) { stroke(255, 0, 0); line(x, y, tempCoordnear.x, tempCoordnear.y); } } frameCounter++; }
// Does a deepcopy of an array list public static ArrayList cloneArrayList(ArrayList al) { ArrayList alNew = new ArrayList(al.size()); for (int i = 0; i < al.size(); i++) { alNew.add(((CelestialObject) al.get(i)).clone()); } return alNew; }
public ArrayList getPastObjectStates() { ArrayList alPast = new ArrayList(); for (int i = intTimeIdx; i > 0 && i > intTimeIdx - 100; i--) { alPast.add(this.alObjectStateArchive.get(i)); } return alPast; }
private void parseDirective(String directive) { if (directive == null) { System.err.println("Directive is null."); return; } String[] pair = directive.split("="); if (pair == null || pair.length != 2) { System.err.println("Unable to parse directive: \"" + directive + "\" Ignored."); return; } String key = pair[0].trim(), value = pair[1].trim(); // clean these, might have too much whitespace around commas if (validKeys.indexOf(key) == FONT || validKeys.indexOf(key) == PRELOAD) { value = value.replaceAll("[\\s]*,[\\s]*", ","); } if (validKeys.indexOf(key) == -1) { System.err.println("Directive key not recognized: \"" + key + "\" Ignored."); return; } if (value.equals("")) { System.err.println("Directive value empty. Ignored."); return; } value = value.replaceAll("^\"|\"$", "").replaceAll("^'|'$", ""); // System.out.println( key + " = " + value ); boolean v; switch (validKeys.indexOf(key)) { case CRISP: v = value.toLowerCase().equals("true"); crispBox.setSelected(v); break; case FONT: fontField.setText(value); break; case GLOBAL_KEY_EVENTS: v = value.toLowerCase().equals("true"); globalKeyEventsBox.setSelected(v); break; case PAUSE_ON_BLUR: v = value.toLowerCase().equals("true"); pauseOnBlurBox.setSelected(v); break; case PRELOAD: preloadField.setText(value); break; case TRANSPARENT: v = value.toLowerCase().equals("true"); // transparentBox.setSelected(v); break; } }
// Does a deepcopy of an array list public ArrayList cloneArrayList(ArrayList al) { ArrayList alNew = new ArrayList(al.size()); for (int i = 0; i < al.size(); i++) { PVector pv = (PVector) al.get(i); alNew.add(new PVector(pv.x, pv.y)); } return alNew; }
public void avoid(ArrayList obstacles) { // Make a vector that will be the position of the object // relative to the Boid rotated in the direction of boid's velocity PVector closestRotated = new PVector(sight + 1, sight + 1); float closestDistance = 99999; Obstacle avoid = null; // Let's look at each obstacle for (int i = 0; i < obstacles.size(); i++) { Obstacle o = (Obstacle) obstacles.get(i); float d = PVector.dist(loc, o.loc); PVector dir = vel.get(); dir.normalize(); PVector diff = PVector.sub(o.loc, loc); // Now we use the dot product to rotate the vector that points from boid to obstacle // Velocity is the new x-axis PVector rotated = new PVector(diff.dot(dir), diff.dot(getNormal(dir))); // Is the obstacle in our path? if (PApplet.abs(rotated.y) < (o.radius + r)) { // Is it the closest obstacle? if ((rotated.x > 0) && (rotated.x < closestRotated.x)) { closestRotated = rotated; avoid = o; } } } // Can we actually see the closest one? if (PApplet.abs(closestRotated.x) < sight) { // The desired vector should point away from the obstacle // The closer to the obstacle, the more it should steer PVector desired = new PVector(closestRotated.x, -closestRotated.y * sight / closestRotated.x); desired.normalize(); desired.mult(closestDistance); desired.limit(maxspeed); // Rotate back to the regular coordinate system rotateVector(desired, vel.heading2D()); // Draw some debugging stuff if (debug) { stroke(0); line(loc.x, loc.y, loc.x + desired.x * 10, loc.y + desired.y * 10); avoid.highlight(true); } // Apply Reynolds steering rules desired.sub(vel); desired.limit(maxforce); acc.add(desired); } }
public void valueChanged(ListSelectionEvent evt) { if (!evt.getValueIsAdjusting()) { JFileChooser chooser = getFileChooser(); FileSystemView fsv = chooser.getFileSystemView(); JList list = (JList) evt.getSource(); int fsm = chooser.getFileSelectionMode(); boolean useSetDirectory = usesSingleFilePane && (fsm == JFileChooser.FILES_ONLY); if (chooser.isMultiSelectionEnabled()) { File[] files = null; Object[] objects = list.getSelectedValues(); if (objects != null) { if (objects.length == 1 && ((File) objects[0]).isDirectory() && chooser.isTraversable(((File) objects[0])) && (useSetDirectory || !fsv.isFileSystem(((File) objects[0])))) { setDirectorySelected(true); setDirectory(((File) objects[0])); } else { ArrayList<File> fList = new ArrayList<File>(objects.length); for (Object object : objects) { File f = (File) object; boolean isDir = f.isDirectory(); if ((chooser.isFileSelectionEnabled() && !isDir) || (chooser.isDirectorySelectionEnabled() && fsv.isFileSystem(f) && isDir)) { fList.add(f); } } if (fList.size() > 0) { files = fList.toArray(new File[fList.size()]); } setDirectorySelected(false); } } chooser.setSelectedFiles(files); } else { File file = (File) list.getSelectedValue(); if (file != null && file.isDirectory() && chooser.isTraversable(file) && (useSetDirectory || !fsv.isFileSystem(file))) { setDirectorySelected(true); setDirectory(file); if (usesSingleFilePane) { chooser.setSelectedFile(null); } } else { setDirectorySelected(false); if (file != null) { chooser.setSelectedFile(file); } } } } }
public URLFinder(String text) { Matcher matcher = dfPattern.matcher(text); urls = new ArrayList<String>(); locations = new ArrayList<Integer[]>(); while (matcher.find()) { urls.add(matcher.group(1)); locations.add(new Integer[] {matcher.start(1), matcher.end(1)}); } }
/** The only richer format supported is the file list flavor */ protected Object getRicherData(DataFlavor flavor) { if (DataFlavor.javaFileListFlavor.equals(flavor)) { ArrayList<Object> files = new ArrayList<Object>(); for (Object file : this.fileData) { files.add(file); } return files; } return null; }
public void mouseClicked() { ArrayList objects = timeline.getStatefulObjects(); for (int i = 0; i < objects.size(); i++) { CelestialObject obj = (CelestialObject) objects.get(i); if (obj.isMouseOver()) { println(obj.getName() + " clicked!"); break; } } }
public String toString() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < urls.size(); i++) { if (i > 0) { sb.append("|"); } sb.append( String.format("%d,%d=\"%s\"", locations.get(i)[0], locations.get(i)[1], urls.get(i))); } return sb.toString(); }
public String[] list(String regex) { Pattern pattern = Pattern.compile(regex); ArrayList<String> slist = new ArrayList<String>(); int count = 0; for (String s : dirList) { if (pattern.matcher(s).matches()) { count++; slist.add(s); } } return slist.toArray(new String[count]); }
public ArrayList getFutureObjectStates() { ArrayList alFutureArchive = new ArrayList(); ArrayList alFutureObjects = cloneArrayList(alStatefulObjects); for (int i = 0; i < 100; i++) { sim.calculateForces(alFutureObjects); alFutureArchive.add(cloneArrayList(alFutureObjects)); } return alFutureArchive; }
/** Update all of the Ball's and draw them */ public void update() { if (balls.size() != 0) { for (int i = 0; i < balls.size(); i++) { Ball b = (Ball) balls.get(i); b.update(); b.attract = kelly; b.drawBall(); } } }
private ArrayList GetFolderTree(String s_Dir, String s_Flag, int n_Indent, int n_TreeIndex) { String s_List = ""; ArrayList aSubFolders = new ArrayList(); File file = new File(s_Dir); File[] filelist = file.listFiles(); if (filelist != null && filelist.length > 0) { for (int i = 0; i < filelist.length; i++) { if (filelist[i].isDirectory()) { aSubFolders.add(filelist[i].getName()); } } int n_Count = aSubFolders.size(); String s_LastFlag = ""; String s_Folder = ""; for (int i = 1; i <= n_Count; i++) { if (i < n_Count) { s_LastFlag = "0"; } else { s_LastFlag = "1"; } s_Folder = aSubFolders.get(i - 1).toString(); s_List = s_List + "arr" + s_Flag + "[" + String.valueOf(n_TreeIndex) + "]=new Array(\"" + s_Folder + "\"," + String.valueOf(n_Indent) + ", " + s_LastFlag + ");\n"; n_TreeIndex = n_TreeIndex + 1; ArrayList a_Temp = GetFolderTree(s_Dir + s_Folder + sFileSeparator, s_Flag, n_Indent + 1, n_TreeIndex); s_List = s_List + a_Temp.get(0).toString(); n_TreeIndex = Integer.valueOf(a_Temp.get(1).toString()).intValue(); } } ArrayList a_Return = new ArrayList(); a_Return.add(s_List); a_Return.add(String.valueOf(n_TreeIndex)); return a_Return; }
/** * Combine seed file with its' dependencies. * * @param seed The seed file. * @return Output queue with correct dependencies order. */ public ArrayList<String> combo(File seed) { Stack<ArrayList<String>> tree = new Stack<ArrayList<String>>(); ArrayList<String> root = new ArrayList<String>(); ArrayList<String> output = new ArrayList<String>(); // Construct the initial tree. root.add(canonize(seed)); tree.add(root); // Travel the dependencies tree from the seed file. travel(tree, new Stack<String>(), output); return output; }
public static void main(String[] args) { long start = System.currentTimeMillis(); Scanner input = new Scanner(System.in); int numberOfTestCases = input.nextInt(); ArrayList<Integer> order = new ArrayList<Integer>(numberOfTestCases); int previousKey = -1; int previousValue = 0; int cycleNumber = 0; Map<Integer, Integer> testCases = new TreeMap<Integer, Integer>(); for (int i = 0; i < numberOfTestCases; i++) { int numberOfCycles = input.nextInt(); testCases.put(numberOfCycles, 1); order.add(numberOfCycles); } for (Map.Entry<Integer, Integer> entry : testCases.entrySet()) { int numberOfCycles; int initialHeight; if (previousKey == -1) { numberOfCycles = entry.getKey(); initialHeight = entry.getValue(); } else { numberOfCycles = entry.getKey() - previousKey; initialHeight = previousValue; } for (int i = 0; i < numberOfCycles; i++) { if (cycleNumber % 2 == 0) { initialHeight *= 2; } else { initialHeight += 1; } cycleNumber++; } entry.setValue(initialHeight); previousKey = entry.getKey(); previousValue = initialHeight; } for (Integer element : order) { System.out.println(testCases.get(element)); } long elapsed = System.currentTimeMillis() - start; System.out.println("time: " + elapsed); }
public static void main(String[] args) { try { BufferedReader br = new BufferedReader(new FileReader(args[0])); int tIndex = 0; int pIndex = 0; // This will probably change soon (name and implementation) NgramParser tnp = new NgramParser(args[1]); ArrayList<String> triplet = tnp.getTriplet(); ArrayList<String> polarity = tnp.getPolarity(); FileWriter sw = new FileWriter(args[2]); String line = null; while (((line = br.readLine()) != null) && (tIndex < triplet.size()) && (pIndex < polarity.size())) { if (line.matches("^[\\d]*:")) { // System.out.println(line); sw.write(line + "\n"); } else { Scanner sc = new Scanner(line); String trip = sc.findInLine(Pattern.compile("[a-zA-Z]+#[a-z]+[#]?[0-9]*")); // if (trip != null && trip.equals(triplet.get(tIndex))) { System.out.println(trip); if (trip != null && !trip.toLowerCase().contains("no#cl")) { // System.out.println(triplet.get(tIndex) + ":" +polarity.get(pIndex)); String pol = polarity.get(pIndex); sw.write(line + " " + pol + "\n"); sc.close(); tIndex++; pIndex++; } else { String pol = "neg"; sw.write("no#a#1" + " " + pol + "\n"); sc.close(); } } // sw.flush(); } sw.close(); } catch (IOException e) { e.printStackTrace(); } }
public void draw() { background(0); fill(255); if (!paused) timeline.moveForward(); if (dragging) drawOrbits(timeline.getFutureObjectStates()); else drawOrbits(timeline.getPastObjectStates()); ArrayList objects = timeline.getStatefulObjects(); for (int i = 0; i < objects.size(); i++) { CelestialObject obj = (CelestialObject) objects.get(i); obj.display(); } }