List of usage examples for java.util TreeSet iterator
public Iterator<E> iterator()
From source file:ImageIOTest.java
/** * Gets a set of "preferred" format names of all image writers. The preferred format name is the * first format name that a writer specifies. * @return the format name set// w w w .j a v a 2 s . c om */ public static Set<String> getWriterFormats() { TreeSet<String> writerFormats = new TreeSet<String>(); TreeSet<String> formatNames = new TreeSet<String>(Arrays.asList(ImageIO.getWriterFormatNames())); while (formatNames.size() > 0) { String name = formatNames.iterator().next(); Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName(name); ImageWriter writer = iter.next(); String[] names = writer.getOriginatingProvider().getFormatNames(); String format = names[0]; if (format.equals(format.toLowerCase())) format = format.toUpperCase(); writerFormats.add(format); formatNames.removeAll(Arrays.asList(names)); } return writerFormats; }
From source file:eu.ggnet.dwoss.report.assist.ReportUtil.java
/** * Returns a set containing only non reportable lines that are not of the RETURNS type. * It's not allowed to have a null value in the collection. * <p>//from w w w . ja v a2 s .c om * @param allLines * @param reportAble * @return */ public static NavigableSet<ReportLine> filterActiveInfo(Collection<ReportLine> allLines, Collection<ReportLine> reportAble) { TreeSet<ReportLine> treeSet = new TreeSet<>(allLines); treeSet.removeAll(reportAble); for (Iterator<ReportLine> it = treeSet.iterator(); it.hasNext();) { ReportLine reportLine = it.next(); if (reportLine.getDocumentType() == DocumentType.RETURNS) it.remove(); } return treeSet; }
From source file:org.openhab.binding.network.service.NetworkService.java
/** * Takes the interfaceIPs and fetches every IP which can be assigned on their network * * @param networkIPs The IPs which are assigned to the Network Interfaces * @return Every single IP which can be assigned on the Networks the computer is connected to */// w ww . j a va2 s.c o m private static LinkedHashSet<String> getNetworkIPs(TreeSet<String> interfaceIPs) { LinkedHashSet<String> networkIPs = new LinkedHashSet<String>(); for (Iterator<String> it = interfaceIPs.iterator(); it.hasNext();) { try { // gets every ip which can be assigned on the given network SubnetUtils utils = new SubnetUtils(it.next()); String[] addresses = utils.getInfo().getAllAddresses(); for (int i = 0; i < addresses.length; i++) { networkIPs.add(addresses[i]); } } catch (Exception ex) { } } return networkIPs; }
From source file:DecorateMutationsSNP.java
/** * The procedure updates the SNPs of all populations that are directly connected to the ancestral population in input. * There can be at most two populations directly connected to an ancestral one. The procedure updates their SNPs based on the SNPs of the ancestral population that are transmitted * @param pop_up instance of the class PopulationARG that represents the ARG of a single population (in this case an ancestral population) * @see PopulationARG/*from w w w . jav a 2 s . com*/ */ public static void updateMutationsForTheBottomPop(PopulationARG pop_up) { if (pop_up.getKind() == 1 || pop_up.getKind() == 2) { //Add all mutations to the mutation set Iterator<Integer> it_map = pop_up.getMaps_leaves_roots().keySet().iterator(); //System.out.println("**** UPDATING MUTATIONS FROM POPULATION "+pop_up.getId_pop()+" ****"); while (it_map.hasNext()) { Integer key_pop = it_map.next(); PopulationARG pop_buttom = GenerateAdmixturePopulations.getPopulations().get(key_pop); //System.out.println("------- Mapping with Population "+key_pop+" --------- \n"); HashMap<Integer, Integer> map_nodes = pop_up.getMaps_leaves_roots().get(key_pop); Iterator<Integer> it_mapping_nodes = map_nodes.keySet().iterator(); while (it_mapping_nodes.hasNext()) { Integer node_buttom = it_mapping_nodes.next(); Integer node_up = map_nodes.get(node_buttom); //System.out.println("node_up - node_buttom\n"); //System.out.println(node_up+" - "+node_buttom+"\n"); TreeSet<Integer> leaves_from_node_buttom = computeLeaves(node_buttom, pop_buttom); //for each mutation in node_up TreeSet<Double> muts = pop_up.getNodeSet().get(node_up).getMutation_set(); Iterator<Double> it_muts = muts.iterator(); while (it_muts.hasNext()) { //Prendo la mutazione Double mut_id = it_muts.next(); Mutation mut_up = pop_up.getMutationSet().get(mut_id); Mutation mut = new Mutation(); mut.setPositionID(mut_up.getPositionID()); mut.setSegment(mut_up.getSegment()); mut.setLeaves(leaves_from_node_buttom); mut.setIDfather(mut_up.getIDfather()); mut.setIDson(mut_up.getIDson()); mut.setID_original_pop(mut_up.getID_original_pop()); pop_buttom.getSNPpositionsList().add(mut.getPositionID()); pop_buttom.getMutationSet().put(mut.getPositionID(), mut); //For each leaf (in the treeset) that has the mutation mut, add mut to the leaf TreeSet<Integer> leaves = mut.getLeaves(); Iterator<Integer> it_leaves = leaves.iterator(); while (it_leaves.hasNext()) { int l = it_leaves.next(); pop_buttom.getNodeSet().get(l).getMutation_set().add(mut.getPositionID()); } } } //System.out.println("------------------------ End mapping ------------------------------- \n"); } } }
From source file:org.apache.hadoop.hbase.loadtest.MultiThreadedReader.java
static void debugMismatchResults(TreeSet<KeyValue> noDuplicateResultSet, TreeSet<KeyValue> kvExpected) { if (noDuplicateResultSet.size() != kvExpected.size()) { LOG.info("Expected size was: " + kvExpected.size() + " but result set was of size: " + noDuplicateResultSet.size()); }//w w w .jav a 2 s .c om Iterator<KeyValue> expectedIterator = kvExpected.iterator(); Iterator<KeyValue> returnedIterator = noDuplicateResultSet.iterator(); while (expectedIterator.hasNext() || returnedIterator.hasNext()) { KeyValue expected = null; KeyValue returned = null; if (expectedIterator.hasNext()) { expected = expectedIterator.next(); } if (returnedIterator.hasNext()) { returned = returnedIterator.next(); } if (returned == null || expected == null) { LOG.info("MISMATCH!! Expected was : " + expected + " but got " + returned); } else if (KeyValue.COMPARATOR.compare(expected, returned) != 0) { LOG.info("MISMATCH!! Expected was : " + expected + " but got " + returned); } else { LOG.info("Expected was : " + expected + " and got " + returned); } } }
From source file:DecorateMutationsSNP.java
/** * The procedure computes for each edge of the ARG the number of mutations occurred in that period of time (length of the edge) by means of Poisson and Normal distributions * @param mu real value that is SNP mutation rate * @param arg instance of the class PopulationARG representing the ARG of a single population * @throws ErrorTimesInputFileException this exception is thrown if there is an inconsistency in time parameters setting * @see PopulationARG/*w w w . ja v a2 s . c o m*/ */ public static void decoratingWithMutations(double mu, PopulationARG arg) throws ErrorTimesInputFileException { //For each leaf of arg create a set of mutations in the node for (int j = 0; j < arg.getExtantUnits(); j++) { arg.getNodeSet().get(j).setLeaf(true); arg.getNodeSet().get(j).setMutation_set(new TreeSet<Double>()); } Iterator<Integer> it_edges = arg.getGraphEdges().keySet().iterator(); double lamda = 0; //System.out.println("------- SNPs Decoration of Population "+arg.getId_pop()+" ------------ "); //For each edge in the ARG, compute the number of mutations and decorate the solids while (it_edges.hasNext()) { Integer keyE = it_edges.next(); if (arg.getGraphEdges().get(keyE).getId_fath() != -1) { double density = arg.getGraphEdges().get(keyE).computeDensity(); double time = arg.getGraphEdges().get(keyE).getTime(); //*** if time is negative then throw the exception that //there is probably an error in how the time parameters are specified in the input file ***// if (time <= 0) { throw new ErrorTimesInputFileException(); } //System.out.println("Time: "+arg.getGraphEdges().get(keyE).getTime()); double n = arg.getG() * density; double p = mu * arg.getN() * time; //******* Compute the # of mutations by Poisson Distribution ****** lamda = n * p; PoissonDistribution Prand = new PoissonDistribution(lamda); int randomPois = Prand.sample(); arg.getGraphEdges().get(keyE).setnMut(randomPois); if (randomPois == 0) GenerateAdmixturePopulations .setNum_edges_without_mut(GenerateAdmixturePopulations.getNum_edges_without_mut() + 1); else GenerateAdmixturePopulations.setNum_edges_more_than_one_mut( GenerateAdmixturePopulations.getNum_edges_more_than_one_mut() + 1); //For each mutation we assign a position for (int i = 0; i < arg.getGraphEdges().get(keyE).getnMut(); i++) { //maps the real solids in (0,1) in an interval (0,densityTotal) //by creating a new list of segments. double start = 0; ArrayList<Interval> tempSegs = new ArrayList<Interval>(); for (int j = 0; j < arg.getGraphEdges().get(keyE).getSegments().size(); j++) { double lengthInt = arg.getGraphEdges().get(keyE).getSegments().get(j).getEnd() - arg.getGraphEdges().get(keyE).getSegments().get(j).getStart(); tempSegs.add(new Interval(start, start + lengthInt)); start = start + lengthInt; } double x = Math.random() * arg.getGraphEdges().get(keyE).getDensity(); boolean found = false; int index = 0; while (!found && index < tempSegs.size()) { if (x >= tempSegs.get(index).getStart() && x < tempSegs.get(index).getEnd()) { found = true; } else { index++; } } double offset = x - tempSegs.get(index).getStart(); double posMutation = arg.getGraphEdges().get(keyE).getSegments().get(index).getStart() + offset; arg.getGraphEdges().get(keyE).getSegments().get(index).getPosMutations().add(posMutation); //add the mutation to the set of the all mutations GenerateAdmixturePopulations.getAllMutations().add(new Double(posMutation)); //Create the mutation object Mutation mut = new Mutation(); mut.setPositionID(posMutation); mut.setIDfather(arg.getGraphEdges().get(keyE).getId_fath()); mut.setIDson(arg.getGraphEdges().get(keyE).getId_son()); mut.setSegment(arg.getGraphEdges().get(keyE).getSegments().get(index)); mut.setLeaves(computeLeaves(arg.getGraphEdges().get(keyE).getId_son(), arg)); mut.setID_original_pop(arg.getId_pop()); arg.getSNPpositionsList().add(posMutation); arg.getMutationSet().put(posMutation, mut); GenerateAdmixturePopulations.getAllmutationSet().put(mut.getPositionID(), mut); //For each leaf (in the set), that has the mutation mut, add mut to the leaf TreeSet<Integer> leaves = mut.getLeaves(); Iterator<Integer> it_leaves = leaves.iterator(); while (it_leaves.hasNext()) { int l = it_leaves.next(); arg.getNodeSet().get(l).getMutation_set().add(mut.getPositionID()); } } //end of computing the exact position of each mutation } //end if the edge has a father } //end while for each edge of the ARG //System.out.println("------- End of SNPs Decoration of Population "+arg.getId_pop()+" ------------ "); }
From source file:ch.entwine.weblounge.common.url.UrlUtils.java
/** * Sorts the given urls by path.// w w w.j av a2 s . c o m * * @param urls * the urls to sort * @return the sorted urls */ public static String[] sort(String[] urls) { TreeSet<String> set = new TreeSet<String>(); for (int i = 0; i < urls.length; i++) set.add(urls[i]); String[] result = new String[urls.length]; Iterator<String> i = set.iterator(); int index = 0; while (i.hasNext()) { result[index++] = i.toString(); } return result; }
From source file:org.apache.hadoop.hive.ql.optimizer.calcite.druid.DruidIntervalUtils.java
protected static List<Range> condenseRanges(List<Range> ranges) { if (ranges.size() <= 1) { return ranges; }/* w w w. j a va 2s. co m*/ Comparator<Range> startThenEnd = new Comparator<Range>() { @Override public int compare(Range lhs, Range rhs) { int compare = 0; if (lhs.hasLowerBound() && rhs.hasLowerBound()) { compare = lhs.lowerEndpoint().compareTo(rhs.lowerEndpoint()); } else if (!lhs.hasLowerBound() && rhs.hasLowerBound()) { compare = -1; } else if (lhs.hasLowerBound() && !rhs.hasLowerBound()) { compare = 1; } if (compare != 0) { return compare; } if (lhs.hasUpperBound() && rhs.hasUpperBound()) { compare = lhs.upperEndpoint().compareTo(rhs.upperEndpoint()); } else if (!lhs.hasUpperBound() && rhs.hasUpperBound()) { compare = -1; } else if (lhs.hasUpperBound() && !rhs.hasUpperBound()) { compare = 1; } return compare; } }; TreeSet<Range> sortedIntervals = Sets.newTreeSet(startThenEnd); sortedIntervals.addAll(ranges); List<Range> retVal = Lists.newArrayList(); Iterator<Range> intervalsIter = sortedIntervals.iterator(); Range currInterval = intervalsIter.next(); while (intervalsIter.hasNext()) { Range next = intervalsIter.next(); if (currInterval.encloses(next)) { continue; } if (mergeable(currInterval, next)) { currInterval = currInterval.span(next); } else { retVal.add(currInterval); currInterval = next; } } retVal.add(currInterval); return retVal; }
From source file:uk.ac.soton.itinnovation.ecc.service.utils.MetricCalculator.java
public static float calcORDINALMedianValuePosition(MeasurementSet mSet) { float result = Float.NaN; if (mSet != null) { // Check semantics before trying calculation Metric metric = mSet.getMetric(); if (metric != null && metric.getMetricType() == MetricType.ORDINAL && !metric.getMetaType().equals("Unknown")) { // Initialise scale map HashMap<String, Integer> ordMap = new HashMap<>(); String[] orderedItems = metric.getMetaContent().split(","); int index = 0; for (String ordItem : orderedItems) { ordMap.put(ordItem, index); ++index;/*from w ww .ja va 2 s . c om*/ } // Create distribution map of values TreeSet<Integer> medMap = new TreeSet<>(); for (Measurement m : mSet.getMeasurements()) { Integer order = ordMap.get(m.getValue()); if (order != null) medMap.add(order); } // Create sorted list of results ArrayList<Integer> medList = new ArrayList(); Iterator<Integer> medIt = medMap.iterator(); while (medIt.hasNext()) medList.add(medIt.next()); // If we have items to work with, find the median if (!medList.isEmpty()) { int medListSize = medList.size(); // Single item --------------------------------------------- if (medListSize == 1) result = medList.get(0); // Two items ----------------------------------------------- else if (medListSize == 2) { // If the values are the same, return the index if (medList.get(0).compareTo(medList.get(1)) == 0) result = medList.get(0); else // Otherwise return point in the middle result = (float) medList.get(1) / (float) medList.get(0); } // More than two items ------------------------------------- else { int middle = medListSize / 2; // Even number of items means checking centre two values if (medListSize % 2 == 0) { // If the values are the same, return the index if (medList.get(middle).compareTo(medList.get(middle - 1)) == 0) result = medList.get(middle); else // Otherwise return point in the middle result = (float) medList.get(middle) / (float) medList.get(middle - 1); } // Odd number of items resolves to centre else result = middle; } } } } return result; }
From source file:org.unitime.timetable.test.BatchStudentSectioningTest.java
public static void batchSectioning(DataProperties cfg) { StudentSectioningModel model = new StudentSectioningModel(cfg); DefaultSingleAssignment<Request, Enrollment> assignment = new DefaultSingleAssignment<Request, Enrollment>(); try {//from w w w . j a va2 s.c om new BatchStudentSectioningLoader(model, assignment).load(); } catch (Exception e) { sLog.error("Unable to load problem, reason: " + e.getMessage(), e); return; } Solver solver = new Solver(cfg); Solution solution = new Solution(model, assignment, 0, 0); solver.setInitalSolution(solution); solver.addSolverListener(new SolverListener<Request, Enrollment>() { public boolean variableSelected(Assignment<Request, Enrollment> assignment, long iteration, Request variable) { return true; } public boolean valueSelected(Assignment<Request, Enrollment> assignment, long iteration, Request variable, Enrollment value) { return true; } public boolean neighbourSelected(Assignment<Request, Enrollment> assignment, long iteration, Neighbour<Request, Enrollment> neighbour) { sLog.debug("Select[" + iteration + "]: " + neighbour); return true; } public void neighbourFailed(Assignment<Request, Enrollment> assignment, long iteration, Neighbour<Request, Enrollment> neighbour) { } }); solution.addSolutionListener(new SolutionListener() { public void solutionUpdated(Solution solution) { } public void getInfo(Solution solution, java.util.Map info) { } public void getInfo(Solution solution, java.util.Map info, java.util.Collection variables) { } public void bestCleared(Solution solution) { } public void bestSaved(Solution solution) { StudentSectioningModel m = (StudentSectioningModel) solution.getModel(); Assignment<Request, Enrollment> a = solution.getAssignment(); sLog.debug("**BEST** V:" + m.nrAssignedVariables(a) + "/" + m.variables().size() + " - S:" + m.getContext(a).nrComplete() + "/" + m.getStudents().size() + " - TV:" + sDF.format(m.getTotalValue(a))); } public void bestRestored(Solution solution) { } }); try { new StudentSectioningXMLSaver(solver) .save(new File(new File(cfg.getProperty("General.Output", ".")), "input.xml")); } catch (Exception e) { sLog.error("Unable to save input data, reason: " + e.getMessage(), e); } solver.start(); try { solver.getSolverThread().join(); } catch (InterruptedException e) { } solution = solver.lastSolution(); solution.restoreBest(); model = (StudentSectioningModel) solution.getModel(); try { File outDir = new File(cfg.getProperty("General.Output", ".")); outDir.mkdirs(); CourseConflictTable cct = new CourseConflictTable((StudentSectioningModel) solution.getModel()); cct.createTable(assignment, true, false, true).save(new File(outDir, "conflicts-lastlike.csv")); cct.createTable(assignment, false, true, true).save(new File(outDir, "conflicts-real.csv")); DistanceConflictTable dct = new DistanceConflictTable((StudentSectioningModel) solution.getModel()); dct.createTable(assignment, true, false, true).save(new File(outDir, "distances-lastlike.csv")); dct.createTable(assignment, false, true, true).save(new File(outDir, "distances-real.csv")); if (cfg.getPropertyBoolean("Test.InevitableStudentConflictsCheck", false)) { InevitableStudentConflicts ch = new InevitableStudentConflicts(model); if (!ch.check(assignment)) ch.getCSVFile().save(new File(outDir, "inevitable-conflicts.csv")); } } catch (IOException e) { sLog.error(e.getMessage(), e); } solution.saveBest(); model.computeOnlineSectioningInfos(assignment); new OverlapCheck((StudentSectioningModel) solution.getModel()).check(assignment); new SectionLimitCheck((StudentSectioningModel) solution.getModel()).check(assignment); sLog.info("Best solution found after " + solution.getBestTime() + " seconds (" + solution.getBestIteration() + " iterations)."); sLog.info("Number of assigned variables is " + solution.getModel().nrAssignedVariables(assignment)); sLog.info("Number of students with complete schedule is " + model.getContext(assignment).nrComplete()); sLog.info("Total value of the solution is " + solution.getModel().getTotalValue(assignment)); sLog.info("Average unassigned priority " + sDF.format(model.avgUnassignPriority(assignment))); sLog.info("Average number of requests " + sDF.format(model.avgNrRequests())); sLog.info("Unassigned request weight " + sDF.format(model.getUnassignedRequestWeight(assignment)) + " / " + sDF.format(model.getTotalRequestWeight())); sLog.info("Info: " + ToolBox.dict2string(solution.getExtendedInfo(), 2)); PrintWriter pw = null; try { pw = new PrintWriter( new FileWriter(new File(new File(cfg.getProperty("General.Output", ".")), "info.properties"))); TreeSet entrySet = new TreeSet(new Comparator() { public int compare(Object o1, Object o2) { Map.Entry e1 = (Map.Entry) o1; Map.Entry e2 = (Map.Entry) o2; return ((Comparable) e1.getKey()).compareTo(e2.getKey()); } }); entrySet.addAll(solution.getExtendedInfo().entrySet()); for (Iterator i = entrySet.iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry) i.next(); pw.println(entry.getKey().toString().toLowerCase().replace(' ', '.') + "=" + entry.getValue()); } pw.flush(); } catch (IOException e) { sLog.error("Unable to save info, reason: " + e.getMessage(), e); } finally { if (pw != null) pw.close(); } try { new StudentSectioningXMLSaver(solver) .save(new File(new File(cfg.getProperty("General.Output", ".")), "solution.xml")); } catch (Exception e) { sLog.error("Unable to save solution, reason: " + e.getMessage(), e); } try { new BatchStudentSectioningSaver(solver).save(); } catch (Exception e) { sLog.error("Unable to save solution, reason: " + e.getMessage(), e); } }