/** Compares our trees, and triggers repairs for any ranges that mismatch. */ public void run() { InetAddress local = FBUtilities.getLocalAddress(); // restore partitioners (in case we were serialized) if (ltree.partitioner() == null) ltree.partitioner(StorageService.getPartitioner()); if (rtree.partitioner() == null) rtree.partitioner(StorageService.getPartitioner()); // compare trees, and collect differences differences.addAll(MerkleTree.difference(ltree, rtree)); // choose a repair method based on the significance of the difference String format = "Endpoints " + local + " and " + remote + " %s for " + cfname + " on " + range; if (differences.isEmpty()) { logger.info(String.format(format, "are consistent")); completed(remote, cfname); return; } // non-0 difference: perform streaming repair logger.info(String.format(format, "have " + differences.size() + " range(s) out of sync")); try { performStreamingRepair(); } catch (IOException e) { throw new RuntimeException(e); } }
public static boolean testCommand( final Context context, final String command, final String contains, final List<String> arguments) { try { final List<String> commandAndArgs = new ArrayList<String>(); commandAndArgs.add(command); commandAndArgs.addAll(arguments); final ProcessBuilder pb = new ProcessBuilder(commandAndArgs); logCommand(context, pb); final Process compilation = pb.start(); final ConsumeStream result = ConsumeStream.start(compilation.getInputStream(), null); final ConsumeStream error = ConsumeStream.start(compilation.getErrorStream(), null); compilation.waitFor(); result.join(); error.join(); return error.output.toString().contains(contains) || result.output.toString().contains(contains); } catch (IOException ex) { context.log(ex.getMessage()); return false; } catch (InterruptedException ex) { context.log(ex.getMessage()); return false; } }
// Deze method maakt alle types activities aan public void makeActivities() { for (Course course : courses) { activities.addAll(createActivity(course, course.numberLectures, 0, "Hoorcollege", true)); activities.addAll( createActivity( course, course.numberWorkGroups, course.maxStudentsGroups, "Werkcollege", false)); activities.addAll( createActivity( course, course.numberPracticum, course.maxStudentsPracticum, "Practicum", false)); } /* //Print alle Activities met bijbehorende studentnummers van studenten for (int i = 0; i < activities.size(); i++) { //Stukje code die studentNumber uit lijst van Student extraheert List studentList = activities.get(i).studentGroup; List<Integer> studentNumberList = new ArrayList<>(); int studentNumber; for (int x = 0; x < studentList.size(); x++) { Student thisStudent = (Student) studentList.get(x); studentNumber = thisStudent.studentNumber; studentNumberList.add(studentNumber); } System.out.println(activities.get(i).course.name + " | Aantal " + activities.get(i).activity + ": " + activities.get(i).occurrence + " | Groep: " + activities.get(i).groupNumber + " | Aantal studenten: " + activities.get(i).studentGroup.size() + " | Studentnummers: " + studentNumberList); } */ // System.out.println("Aantal Activities: " + activities.size()); }
void test(String[] opts, String className) throws Exception { count++; System.err.println("Test " + count + " " + Arrays.asList(opts) + " " + className); Path testSrcDir = Paths.get(System.getProperty("test.src")); Path testClassesDir = Paths.get(System.getProperty("test.classes")); Path classes = Paths.get("classes." + count); classes.createDirectory(); Context ctx = new Context(); PathFileManager fm = new JavacPathFileManager(ctx, true, null); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); List<String> options = new ArrayList<String>(); options.addAll(Arrays.asList(opts)); options.addAll(Arrays.asList("-verbose", "-XDverboseCompilePolicy", "-d", classes.toString())); Iterable<? extends JavaFileObject> compilationUnits = fm.getJavaFileObjects(testSrcDir.resolve(className + ".java")); StringWriter sw = new StringWriter(); PrintWriter out = new PrintWriter(sw); JavaCompiler.CompilationTask t = compiler.getTask(out, fm, null, options, null, compilationUnits); boolean ok = t.call(); System.err.println(sw.toString()); if (!ok) { throw new Exception("compilation failed"); } File expect = new File("classes." + count + "/" + className + ".class"); if (!expect.exists()) throw new Exception("expected file not found: " + expect); long expectedSize = new File(testClassesDir.toString(), className + ".class").length(); long actualSize = expect.length(); if (expectedSize != actualSize) throw new Exception("wrong size found: " + actualSize + "; expected: " + expectedSize); }
/** * Return a List of SA Fields for all the java fields in this class, including all inherited * fields. This includes hidden fields. Thus the returned list can contain fields with the same * name. Return an empty list if there are no fields. Only designed for use in a debugging system. */ public List getAllFields() { // Contains a Field for each field in this class, including immediate // fields and inherited fields. List allFields = getImmediateFields(); // transitiveInterfaces contains all interfaces implemented // by this class and its superclass chain with no duplicates. ObjArray interfaces = getTransitiveInterfaces(); int n = (int) interfaces.getLength(); for (int i = 0; i < n; i++) { InstanceKlass intf1 = (InstanceKlass) interfaces.getObjAt(i); if (Assert.ASSERTS_ENABLED) { Assert.that(intf1.isInterface(), "just checking type"); } allFields.addAll(intf1.getImmediateFields()); } // Get all fields in the superclass, recursively. But, don't // include fields in interfaces implemented by superclasses; // we already have all those. if (!isInterface()) { InstanceKlass supr; if ((supr = (InstanceKlass) getSuper()) != null) { allFields.addAll(supr.getImmediateFields()); } } return allFields; }
public static void readExternal( final Element element, final List<ShelvedChangeList> changes, final List<ShelvedChangeList> recycled) throws InvalidDataException { changes.addAll(ShelvedChangeList.readChanges(element, false, true)); recycled.addAll(ShelvedChangeList.readChanges(element, true, true)); }
@Override public List<String> getCandidates(String word) { List<String> suggestions = new ArrayList<>(); List<List<String>> partList = splitter.getAllSplits(word); List<String> candidates = new ArrayList<>(); for (List<String> parts : partList) { candidates.addAll(super.getCandidates(parts)); } suggestions.addAll(candidates); return suggestions; }
@Override public List<DecompilerBasicBlock> getAllBasicBlocks() { List<DecompilerBasicBlock> blocks = new ArrayList<>(); blocks.add(head); for (DecompilerBlock b : thenBranch) { blocks.addAll(b.getAllBasicBlocks()); } for (DecompilerBlock b : elseBranch) { blocks.addAll(b.getAllBasicBlocks()); } return blocks; }
public static File[] getDirectoryListing(File dir) { SortedSet<File> dirSet = new TreeSet<File>(); SortedSet<File> fileSet = new TreeSet<File>(); File[] files = dir.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) dirSet.add(files[i]); else fileSet.add(files[i]); } List<File> fileList = new LinkedList<File>(); fileList.addAll(dirSet); fileList.addAll(fileSet); return fileList.toArray(new File[] {}); }
private BundleInfo[] orderingInitialConfig(List setToInitialConfig) { List notToBeStarted = new LinkedList(); List toBeStarted = new LinkedList(); for (Iterator ite2 = setToInitialConfig.iterator(); ite2.hasNext(); ) { BundleInfo bInfo = (BundleInfo) ite2.next(); if (bInfo.isMarkedAsStarted()) toBeStarted.add(bInfo); else notToBeStarted.add(bInfo); } setToInitialConfig.clear(); setToInitialConfig.addAll(notToBeStarted); setToInitialConfig.addAll(toBeStarted); return Utils.getBundleInfosFromList(setToInitialConfig); }
private static <T> Pair<List<T>, List<T>> splitData(List<T> original, double splitForSecond) { List<T> first = new ArrayList<>(); List<T> second = new ArrayList<>(); if (splitForSecond > 0.0) { Collections.shuffle(original, new Random(0L)); int numFirst = (int) ((1.0 - splitForSecond) * original.size()); first.addAll(original.subList(0, numFirst)); second.addAll(original.subList(numFirst, original.size())); } else { first.addAll(original); // second stays empty } return Tuples.pair(first, second); }
private static List<? extends StaticError> flattenErrors(Iterable<? extends StaticError> ex) { List<StaticError> result = new LinkedList<StaticError>(); for (StaticError err : ex) { result.addAll(flattenErrors(err)); } return result; }
/** * Method removes a Spring bean definition from the XML application context file. Bean definition * is identified by its id or bean name. * * @param project * @param id */ public void removeBeanDefinition(File configFile, Project project, String id) { Source xsltSource; Source xmlSource; try { xsltSource = new StreamSource(new ClassPathResource("transform/delete-bean.xsl").getInputStream()); xsltSource.setSystemId("delete-bean"); List<File> configFiles = new ArrayList<>(); configFiles.add(configFile); configFiles.addAll(getConfigImports(configFile, project)); for (File file : configFiles) { xmlSource = new StringSource(FileUtils.readToString(new FileInputStream(configFile))); // create transformer Transformer transformer = transformerFactory.newTransformer(xsltSource); transformer.setParameter("bean_id", id); // transform StringResult result = new StringResult(); transformer.transform(xmlSource, result); FileUtils.writeToFile(format(result.toString(), project.getSettings().getTabSize()), file); return; } } catch (IOException e) { throw new ApplicationRuntimeException(UNABLE_TO_READ_TRANSFORMATION_SOURCE, e); } catch (TransformerException e) { throw new ApplicationRuntimeException(FAILED_TO_UPDATE_BEAN_DEFINITION, e); } }
public String _path(String args[]) { List<String> list = new ArrayList<String>(); for (int i = 1; i < args.length; i++) { list.addAll(Processor.split(args[i])); } return Processor.join(list, File.pathSeparator); }
/** Finds the lexical items used to produce the highest scoring parse. */ public List getMaxLexEntries() { List result = new LinkedList(); for (ParseResult p : bestParses) { result.addAll(p.getLexEntries()); } return result; }
/** Finds the lexical items used to produce the highest scoring parse with semantics sem. */ public List getMaxLexEntriesFor(Exp sem) { List result = new LinkedList(); for (ParseResult p : findBestParses(allParses, sem)) { result.addAll(p.getLexEntries()); } return result; }
private static List<String> calcVCFGenotypeKeys(VariantContext vc) { Set<String> keys = new HashSet<String>(); boolean sawGoodGT = false; boolean sawGoodQual = false; boolean sawGenotypeFilter = false; for (Genotype g : vc.getGenotypes().values()) { keys.addAll(g.getAttributes().keySet()); if (g.isAvailable()) sawGoodGT = true; if (g.hasNegLog10PError()) sawGoodQual = true; if (g.isFiltered() && g.isCalled()) sawGenotypeFilter = true; } if (sawGoodQual) keys.add(VCFConstants.GENOTYPE_QUALITY_KEY); if (sawGenotypeFilter) keys.add(VCFConstants.GENOTYPE_FILTER_KEY); List<String> sortedList = ParsingUtils.sortList(new ArrayList<String>(keys)); // make sure the GT is first if (sawGoodGT) { List<String> newList = new ArrayList<String>(sortedList.size() + 1); newList.add(VCFConstants.GENOTYPE_KEY); newList.addAll(sortedList); sortedList = newList; } return sortedList; }
/** Loads streamhost address and ports from the proxies on the local server. */ private void initStreamHosts() { List<Bytestream.StreamHost> streamHosts = new ArrayList<Bytestream.StreamHost>(); Iterator it = proxies.iterator(); IQ query; PacketCollector collector; Bytestream response; while (it.hasNext()) { String jid = it.next().toString(); query = new IQ() { public String getChildElementXML() { return "<query xmlns=\"http://jabber.org/protocol/bytestreams\"/>"; } }; query.setType(IQ.Type.GET); query.setTo(jid); collector = connection.createPacketCollector(new PacketIDFilter(query.getPacketID())); connection.sendPacket(query); response = (Bytestream) collector.nextResult(SmackConfiguration.getPacketReplyTimeout()); if (response != null) { streamHosts.addAll(response.getStreamHosts()); } collector.cancel(); } this.streamHosts = streamHosts; }
/** * Obtain a new Node from a type that matches the given string. It will try to correctly detect * RealVar and constant nodes. The Node is cloned and initialized, so it can be used separatedly * * @param name The type of the requested Node. It must coincide with one of the class names of * available Nodes, unless it represents a variable or constant terminal * @param currentGlobalDepth The depth of the requested Node in the Tree */ public Node newNode(String name, int currentGlobalDepth) { System.out.println(name); Node outNode = null; if (name.startsWith("X")) { outNode = new RealVar(Integer.parseInt(name.substring("X".length(), name.length()))); } else if (name.startsWith("angle")) { outNode = new Angle(Integer.parseInt(name.substring("angle".length(), name.length()))); } else if (name.substring(0, 1).matches("\\d")) { outNode = new RealConstant(Double.parseDouble(name)); } else if (name.equals("true")) { outNode = new LogicConstant(1); } else if (name.equals("false")) { outNode = new LogicConstant(0); } else { List<Node> all = new ArrayList<Node>(); for (int i = 0; i < nodeSets.length; i++) { all.addAll(nodeSets[i].getAll()); } for (Node n : all) { if (name.equals(n.name())) { try { outNode = (Node) n.clone(); } catch (CloneNotSupportedException e) { Logger.log(e); } break; } } } outNode.setCurrentDepth(currentGlobalDepth); return outNode; }
public List<TreeNode> getChildren() { List<TreeNode> lst = new ArrayList<TreeNode>(); for (List<TreeNodeImpl> lst1 : childs.values()) { lst.addAll(lst1); } return lst; }
ActiveFile(File f, List<Thread> list) { file = f; if (list != null) { threads.addAll(list); } threads.add(Thread.currentThread()); }
public static Either<CommandResult> runCommand( final Context context, final String command, final File path, final List<String> arguments) { try { final List<String> commandAndArgs = new ArrayList<String>(); commandAndArgs.add(command); commandAndArgs.addAll(arguments); final ProcessBuilder pb = new ProcessBuilder(commandAndArgs); if (path != null) { pb.directory(path); } logCommand(context, pb); final Process compilation = pb.start(); final ConsumeStream result = ConsumeStream.start(compilation.getInputStream(), context); final ConsumeStream error = ConsumeStream.start(compilation.getErrorStream(), context); final int exitCode = compilation.waitFor(); result.join(); error.join(); if (result.exception != null) { return Either.fail(result.exception); } if (error.exception != null) { return Either.fail(error.exception); } return Either.success( new CommandResult(result.output.toString(), error.output.toString(), exitCode)); } catch (IOException ex) { return Either.fail(ex); } catch (InterruptedException ex) { return Either.fail(ex); } }
public boolean avrdude(Collection params) throws RunnerException { List commandDownloader = new ArrayList(); commandDownloader.add("avrdude"); // Point avrdude at its config file since it's in a non-standard location. if (Base.isMacOS()) { commandDownloader.add("-C" + "hardware/tools/avr/etc/avrdude.conf"); } else if (Base.isWindows()) { String userdir = System.getProperty("user.dir") + File.separator; commandDownloader.add("-C" + userdir + "hardware/tools/avr/etc/avrdude.conf"); } else { // ???: is it better to have Linux users install avrdude themselves, in // a way that it can find its own configuration file? commandDownloader.add("-C" + "hardware/tools/avrdude.conf"); } if (Preferences.getBoolean("upload.verbose")) { commandDownloader.add("-v"); commandDownloader.add("-v"); commandDownloader.add("-v"); commandDownloader.add("-v"); } else { commandDownloader.add("-q"); commandDownloader.add("-q"); } // XXX: quick hack to chop the "atmega" off of "atmega8" and "atmega168", // then shove an "m" at the beginning. won't work for attiny's, etc. commandDownloader.add( "-pm" + Preferences.get("boards." + Preferences.get("board") + ".build.mcu").substring(6)); commandDownloader.addAll(params); return executeUploadCommand(commandDownloader); }
private static List<? extends StaticError> flattenErrors(StaticError ex) { List<StaticError> result = new LinkedList<StaticError>(); if (ex instanceof MultipleStaticError) { for (StaticError err : (MultipleStaticError) ex) result.addAll(flattenErrors(err)); } else result.add(new WrappedException(ex, Debug.stackTraceOn())); return result; }
// Ast0.Block --- // Ast0.Stmt[] stmts; // // AG: // code: {stmt.c} // static List<IR0.Inst> gen(Ast0.Block n) throws Exception { List<IR0.Inst> code = new ArrayList<IR0.Inst>(); // ... need code ... for (Ast0.Stmt s : n.stmts) code.addAll(gen(s)); return code; }
public static List<Library> list(File folder) { List<Library> libraries = new ArrayList<Library>(); List<File> librariesFolders = new ArrayList<File>(); librariesFolders.addAll(discover(folder)); for (File baseFolder : librariesFolders) { libraries.add(new Library(baseFolder)); } // Support libraries inside of one level of subfolders? I believe this was // the compromise for supporting library groups, but probably a bad idea // because it's not compatible with the Manager. String[] folderNames = folder.list(junkFolderFilter); if (folderNames != null) { for (String subfolderName : folderNames) { File subfolder = new File(folder, subfolderName); if (!librariesFolders.contains(subfolder)) { List<File> discoveredLibFolders = discover(subfolder); for (File discoveredFolder : discoveredLibFolders) { libraries.add(new Library(discoveredFolder, subfolderName)); } } } } return libraries; }
// look up and apply coarts for given rels to each sign in result private void applyCoarts(List<String> coartRels, Collection<Sign> result) { List<Sign> inputSigns = new ArrayList<Sign>(result); result.clear(); List<Sign> outputSigns = new ArrayList<Sign>(inputSigns.size()); // for each rel, lookup coarts and apply to input signs, storing results in output signs for (Iterator<String> it = coartRels.iterator(); it.hasNext(); ) { String rel = it.next(); Collection<String> preds = (Collection<String>) _coartRelsToPreds.get(rel); if (preds == null) continue; // not expected Collection<Sign> coartResult = getSignsFromRelAndPreds(rel, preds); if (coartResult == null) continue; for (Iterator<Sign> it2 = coartResult.iterator(); it2.hasNext(); ) { Sign coartSign = it2.next(); // apply to each input for (int j = 0; j < inputSigns.size(); j++) { Sign sign = inputSigns.get(j); grammar.rules.applyCoart(sign, coartSign, outputSigns); } } // switch output to input for next iteration inputSigns.clear(); inputSigns.addAll(outputSigns); outputSigns.clear(); } // add results back result.addAll(inputSigns); }
private void insertAfter(JPegStmt node, JPegStmt after) { // System.out.println("node: "+node); // System.out.println("after: "+after); // System.out.println("succs of node: "+getSuccsOf(node)); // this must be done first because the succs of node will be chanaged lately List succOfAfter = new ArrayList(); succOfAfter.addAll(getSuccsOf(node)); unitToSuccs.put(after, succOfAfter); Iterator succsIt = getSuccsOf(node).iterator(); while (succsIt.hasNext()) { Object succ = succsIt.next(); List pred = getPredsOf(succ); pred.remove(node); pred.add(after); } List succOfNode = new ArrayList(); succOfNode.add(after); unitToSuccs.put(node, succOfNode); List predOfAfter = new ArrayList(); predOfAfter.add(node); unitToPreds.put(after, predOfAfter); // buildPredecessor(Chain pegChain); }
/* * return 0 is success, otherwise failure */ public final int runAdminCommandOnRemoteNode( Node thisNode, StringBuilder output, List<String> args, List<String> stdinLines) throws SSHCommandExecutionException, IllegalArgumentException, UnsupportedOperationException { String humanreadable = null; try { this.node = thisNode; dcomInfo = new DcomInfo(node); List<String> fullcommand = new ArrayList<String>(); WindowsRemoteAsadmin asadmin = dcomInfo.getAsadmin(); if (stdinLines != null && !stdinLines.isEmpty()) setupAuthTokenFile(fullcommand, stdinLines); fullcommand.addAll(args); humanreadable = dcomInfo.getNadminPath() + " " + commandListToString(fullcommand); // This is where the rubber meets the road... String out = asadmin.run(fullcommand); output.append(out); logger.info(Strings.get("remote.command.summary", humanreadable, out)); return determineStatus(args); } catch (WindowsException ex) { throw new SSHCommandExecutionException( Strings.get("remote.command.error", ex.getMessage(), humanreadable), ex); } finally { teardownAuthTokenFile(); } }
// look up and apply coarts for w to each sign in result @SuppressWarnings("unchecked") private void applyCoarts(Word w, SignHash result) throws LexException { List<Sign> inputSigns = new ArrayList<Sign>(result.asSignSet()); result.clear(); List<Sign> outputSigns = new ArrayList<Sign>(inputSigns.size()); // for each surface attr, lookup coarts and apply to input signs, storing results in output // signs for (Iterator<Pair<String, String>> it = w.getSurfaceAttrValPairs(); it.hasNext(); ) { Pair<String, String> p = it.next(); String attr = (String) p.a; if (!_indexedCoartAttrs.contains(attr)) continue; String val = (String) p.b; Word coartWord = Word.createWord(attr, val); SignHash coartResult = getSignsFromWord(coartWord, null, null, null); for (Iterator<Sign> it2 = coartResult.iterator(); it2.hasNext(); ) { Sign coartSign = it2.next(); // apply to each input for (int j = 0; j < inputSigns.size(); j++) { Sign sign = inputSigns.get(j); grammar.rules.applyCoart(sign, coartSign, outputSigns); } } // switch output to input for next iteration inputSigns.clear(); inputSigns.addAll(outputSigns); outputSigns.clear(); } // add results back result.addAll(inputSigns); }