List of usage examples for java.util TreeMap get
public V get(Object key)
From source file:gemlite.shell.admin.dao.AdminDao.java
/** * region//from w w w . ja v a2 s.c om * * @return * @throws IOException */ private String showRegions() throws IOException { do { System.out.println("------------------------"); Map param = new HashMap(); param.put("beanName", "ListRegionsService"); Execution execution = FunctionService.onServer(clientPool).withArgs(param); ResultCollector rc = execution.execute("REMOTE_ADMIN_FUNCTION"); Object obj = rc.getResult(); if (obj == null) { System.out.println("can't get regions list"); return null; } ArrayList list = (ArrayList) obj; if (!(list.get(0) instanceof Set)) { System.out.println(list.get(0)); return null; } TreeSet regionSet = (TreeSet) list.get(0); Iterator regionIters = regionSet.iterator(); StringBuilder sb = new StringBuilder(); TreeMap<String, String> regionMap = new TreeMap<String, String>(); int no = 1; sb.append("NO.").append("\t").append("RegionName").append("\n"); while (regionIters.hasNext()) { String fullPath = (String) regionIters.next(); sb.append(no).append("\t").append(fullPath).append("\n"); regionMap.put(String.valueOf(no), fullPath); no++; } System.out.println(sb.toString()); System.out.println( "------------------------\nRegionNames,Your choice?No.or regionName,ALL(all) means export all regions,X to exit"); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); String line = bufferedReader.readLine(); if (line == null) { System.out.println("no input regionName!"); } else if (!"x".equalsIgnoreCase(line.trim()) && !regionMap.entrySet().contains(line.trim()) && !"ALL".equalsIgnoreCase(line.trim()) && !regionMap.keySet().contains(line.trim())) { System.out.println("error input:" + line); } else { if (regionMap.keySet().contains(line.trim())) return regionMap.get(String.valueOf(line.trim())); return line.trim(); } } while (true); }
From source file:com.sfs.whichdoctor.dao.RelationshipDAOImpl.java
/** * Builds the inherited map./*from ww w . ja v a 2 s . co m*/ * * @param relationshipClass the relationship class * @param relationshipMap the relationship map * @return the tree map */ private TreeMap<Integer, RelationshipBean> buildInheritedMap(final String relationshipClass, final TreeMap<Integer, RelationshipBean> relationshipMap) { TreeMap<Integer, RelationshipBean> fullSupervisorMap = new TreeMap<Integer, RelationshipBean>(); // Load the supervisor type map TreeMap<Integer, String> types = null; try { types = loadSupervisorRelationships(relationshipClass); } catch (WhichDoctorDaoException wde) { dataLogger.error("Error loading the supervisor object types: " + wde.getMessage()); } int maxHierarchy = 0; if (types != null) { dataLogger.debug("Supervisor relationships: " + types.size()); for (Integer hierarchy : types.keySet()) { // Set the maxiumum hierarchy value by getting the last key if (hierarchy > maxHierarchy) { maxHierarchy = hierarchy; } } } dataLogger.debug("Maximum hierarchy: " + maxHierarchy); for (Integer hierarchy : types.keySet()) { final String typeName = types.get(hierarchy); if (dataLogger.isDebugEnabled()) { dataLogger.debug("Hierarchy key is: " + hierarchy); dataLogger.debug("Type is: " + typeName); } if (!relationshipMap.containsKey(hierarchy)) { // If the relationship is missing we need to find one RelationshipBean newSup = null; for (int i = 1; i < maxHierarchy + 1; i++) { dataLogger.debug("Looking up key: " + i); if (newSup == null && relationshipMap.containsKey(i)) { RelationshipBean exSup = relationshipMap.get(i); newSup = exSup.clone(); newSup.setRelationshipType(typeName); } } if (newSup != null) { if (dataLogger.isDebugEnabled()) { dataLogger.debug("Adding a new supervisor"); dataLogger.debug("GUID: " + newSup.getGUID()); dataLogger.debug("Identifier: " + newSup.getIdentifier()); dataLogger.debug("Relationship Class: " + newSup.getRelationshipClass()); dataLogger.debug("Relationship Type: " + newSup.getRelationshipType()); } fullSupervisorMap.put(hierarchy, newSup); } } else { RelationshipBean extSup = relationshipMap.get(hierarchy); if (dataLogger.isDebugEnabled()) { dataLogger.debug("Adding an existing supervisor"); dataLogger.debug("GUID: " + extSup.getGUID()); dataLogger.debug("Identifier: " + extSup.getIdentifier()); dataLogger.debug("Relationship Class: " + extSup.getRelationshipClass()); dataLogger.debug("Relationship Type: " + extSup.getRelationshipType()); } fullSupervisorMap.put(hierarchy, extSup); } } return fullSupervisorMap; }
From source file:net.spfbl.data.Block.java
public static void dropExpired() { long max = System.currentTimeMillis() - Server.DAY_TIME * 40L; TreeMap<String, Long> map = SET.getMap(); for (String token : map.keySet()) { Long time = map.get(token); if (time == null || time < max) { if (SET.dropExact(token)) { Server.logDebug("expired BLOCK '" + token + "'."); }//from w w w. j av a 2 s . co m } } }
From source file:it.uniroma2.sag.kelp.learningalgorithm.clustering.kernelbasedkmeans.KernelBasedKMeansEngine.java
@Override public ClusterList cluster(Dataset dataset, ExampleSelector seedSelector) { /*/* w w w . j av a 2 s . c o m*/ * Check consistency: the number of input examples MUST be greater or * equal to the target K */ if (dataset.getNumberOfExamples() < k) { System.err.println("Error: the number of instances (" + dataset.getNumberOfExamples() + ") must be higher than k (" + k + ")"); return null; } /* * Alphas Value are stored */ for (Example example : dataset.getExamples()) { alphas.put(example, 1.0f); } /* * Initialize seed and outputStructures */ ClusterList resClusters = new ClusterList(); List<Example> seedVector = seedSelector.select(dataset); for (int clusterId = 0; clusterId < k; clusterId++) { resClusters.add(new Cluster("cluster_" + clusterId)); if (clusterId < seedVector.size()) { KernelBasedKMeansExample kernelBasedKMeansExample = new KernelBasedKMeansExample( seedVector.get(clusterId), 0); resClusters.get(clusterId).add(kernelBasedKMeansExample); } } /* * Do Work */ // For each iteration for (int t = 0; t < maxIterations; t++) { int reassignment; logger.debug("\nITERATION:\t" + (t + 1)); TreeMap<Long, Integer> exampleIdToClusterMap = new TreeMap<Long, Integer>(); HashMap<Example, Float> minDistances = new HashMap<Example, Float>(); /* * Searching for the nearest cluster */ for (Example example : dataset.getExamples()) { float minValue = Float.MAX_VALUE; int targetCluster = -1; for (int clusterId = 0; clusterId < k; clusterId++) { float d = calculateDistance(example, resClusters.get(clusterId)); logger.debug("Distance of " + example.getId() + " from cluster " + clusterId + ":\t" + d); if (d < minValue) { minValue = d; targetCluster = clusterId; } } minDistances.put(example, minValue); exampleIdToClusterMap.put(example.getId(), targetCluster); } /* * Counting reassignments */ reassignment = countReassigment(exampleIdToClusterMap, resClusters); logger.debug("Reassigments:\t" + reassignment); /* * Updating */ for (int i = 0; i < resClusters.size(); i++) resClusters.get(i).clear(); this.thirdMemberEqBuffer.clear(); for (Example example : dataset.getExamples()) { logger.debug( "Re-assigning " + example.getId() + " to " + exampleIdToClusterMap.get(example.getId())); int assignedClusterId = exampleIdToClusterMap.get(example.getId()); float minDist = minDistances.get(example); KernelBasedKMeansExample kernelBasedKMeansExample = new KernelBasedKMeansExample(example, minDist); resClusters.get(assignedClusterId).add(kernelBasedKMeansExample); } if (t > 0 && reassignment == 0) { break; } } /* * Sort results by distance from the controid. */ for (Cluster c : resClusters) { c.sortAscendingOrder(); } return resClusters; }
From source file:com.bytelightning.opensource.pokerface.ScriptHelperImpl.java
/** * Courtesy of 'Peter' at http://stackoverflow.com/questions/6824157/parse-accept-language-header-in-java *///from w ww . j a va 2 s . c o m private void parseLocalesHeader(String value, TreeMap<Double, ArrayList<Locale>> locales) { for (String str : value.split(",")) { String[] arr = str.trim().replace("-", "_").split(";"); // Parse the q-value Double q = 1.0d; for (String s : arr) { s = s.trim(); if (s.startsWith("q=")) { try { String ds = s.substring(2).trim(); if (ds.length() > 0 && ds.length() <= 5) q = Math.rint(Double.parseDouble(ds) * 10000d) / 10000d; else q = 0d; } catch (NumberFormatException e) { q = 0.0; } break; } } if (q >= 0.00005) { // Parse the locale Locale locale; String[] l = arr[0].split("_"); switch (l.length) { case 2: locale = new Locale(l[0], l[1]); break; case 3: locale = new Locale(l[0], l[1], l[2]); break; default: locale = new Locale(l[0]); break; } ArrayList<Locale> list = locales.get(q); if (list == null) { list = new ArrayList<Locale>(); locales.put(q, list); } list.add(locale); } } }
From source file:au.org.ala.layers.web.TabulationService.java
private String[][] tabulationGridGenerator(List<Tabulation> tabulations, String fid1, String fid2, String wkt, String func) throws IOException { //determine x & y field names TreeMap<String, String> objects1 = new TreeMap<String, String>(); TreeMap<String, String> objects2 = new TreeMap<String, String>(); for (Tabulation t : tabulations) { objects1.put(t.getPid1(), t.getName1()); objects2.put(t.getPid2(), t.getName2()); }//from w w w.j a v a2s . co m int rows = Math.max(objects1.size(), objects2.size()); int columns = Math.min(objects1.size(), objects2.size()); String[][] grid = new String[rows + 1][columns + 1]; //populate grid if (objects1.size() <= objects2.size()) { //row and column sort order and labels TreeMap<String, Integer> order1 = new TreeMap<String, Integer>(); TreeMap<String, Integer> order2 = new TreeMap<String, Integer>(); int pos = 0; for (String s : objects1.keySet()) { order1.put(s, pos++); grid[0][pos] = objects1.get(s); } pos = 0; for (String s : objects2.keySet()) { order2.put(s, pos++); grid[pos][0] = objects2.get(s); } //grid for (Tabulation t : tabulations) { if (func.equals("area") || func.equals("arearow") || func.equals("areacolumn") || func.equals("areatotal")) { grid[order2.get(t.getPid2()) + 1][order1.get(t.getPid1()) + 1] = String.format("%.1f", t.getArea() / 1000000.0); //convert sqm to sqkm } else if (func.equals("occurrences") || func.equals("occurrencesrow") || func.equals("occurrencescolumn") || func.equals("occurrencestotal")) { grid[order2.get(t.getPid2()) + 1][order1.get(t.getPid1()) + 1] = String .valueOf(t.getOccurrences()); } else if (func.equals("species") || func.equals("speciesrow") || func.equals("speciescolumn") || func.equals("speciestotal")) { grid[order2.get(t.getPid2()) + 1][order1.get(t.getPid1()) + 1] = String.valueOf(t.getSpecies()); } } } else { //row and column sort order and labels TreeMap<String, Integer> order1 = new TreeMap<String, Integer>(); TreeMap<String, Integer> order2 = new TreeMap<String, Integer>(); int pos = 0; for (String s : objects1.keySet()) { order1.put(s, pos++); grid[pos][0] = objects1.get(s); } pos = 0; for (String s : objects2.keySet()) { order2.put(s, pos++); grid[0][pos] = objects2.get(s); } //grid for (Tabulation t : tabulations) { if (func.equals("area") || func.equals("arearow") || func.equals("areacolumn") || func.equals("areatotal")) { grid[order1.get(t.getPid1()) + 1][order2.get(t.getPid2()) + 1] = String.format("%.1f", t.getArea() / 1000000.0); //convert sqm to sqkm } else if (func.equals("occurrences") || func.equals("occurrencesrow") || func.equals("occurrencescolumn") || func.equals("occurrencestotal")) { grid[order1.get(t.getPid1()) + 1][order2.get(t.getPid2()) + 1] = String .valueOf(t.getOccurrences()); } else if (func.equals("species") || func.equals("speciesrow") || func.equals("speciescolumn") || func.equals("speciestotal")) { grid[order1.get(t.getPid1()) + 1][order2.get(t.getPid2()) + 1] = String.valueOf(t.getSpecies()); } } } return grid; }
From source file:com.sfs.whichdoctor.webservice.RotationServiceImpl.java
/** * Process the rotation update.//from ww w.j av a 2 s. c o m * * @param traineeMIN the trainee MIN * @param rotationGUID the rotation GUID * @param educationMIN the education MIN * @param pdaMIN the pda MIN * @return the result string * @throws Exception the exception */ private boolean processRotationUpdate(final int traineeMIN, final int rotationGUID, final int educationMIN, final int pdaMIN) throws Exception { boolean success = false; // Check that the trainee, rotation and supervisor records exist. // If not return an error loadTrainee(traineeMIN); RotationBean rotation = loadRotation(rotationGUID); PersonBean educationSpvr = loadSupervisor(educationMIN); PersonBean pdaSpvr = loadSupervisor(pdaMIN); // Process the supervisor change ArrayList<SupervisorBean> updatedSupervisorList = new ArrayList<SupervisorBean>(); // This holds the existing supervisors that maybe changed TreeMap<String, ArrayList<SupervisorBean>> supervisorsToBeChanged = new TreeMap<String, ArrayList<SupervisorBean>>(); // First build a list of existing supervisors that do not need modifying if (rotation.getSupervisors() != null) { for (SupervisorBean spvr : rotation.getSupervisors()) { // At present function only changes the Education and PDA supervisors. // Any other supervisors should be added to the updated list. String type = spvr.getRelationshipType(); if (StringUtils.equalsIgnoreCase("Education", type) || StringUtils.equalsIgnoreCase("PDA", type)) { ArrayList<SupervisorBean> spvrs = new ArrayList<SupervisorBean>(); if (supervisorsToBeChanged.containsKey(type)) { spvrs = supervisorsToBeChanged.get(type); } if (StringUtils.equalsIgnoreCase("Education", type)) { // An education supervisor - if educationMIN < 0 then unchanged if (educationMIN < 0) { updatedSupervisorList.add(spvr); } else { spvrs.add(spvr); } } if (StringUtils.equalsIgnoreCase("PDA", type)) { // An education supervisor - if pdaMIN < 0 then unchanged if (pdaMIN < 0) { updatedSupervisorList.add(spvr); } else { spvrs.add(spvr); } } supervisorsToBeChanged.put(type, spvrs); } else { updatedSupervisorList.add(spvr); } } } // WhichDoctor can store multiple education/PDA supervisors, // but the web service only accepts one of each. int educationOrder = EDUCATION_ORDER; int pdaOrder = PDA_ORDER; // Update the education supervisor (if one is provided) if (educationSpvr != null) { boolean supervisorProcessed = false; if (supervisorsToBeChanged.containsKey("Education")) { // Education supervisors currently exist - check if new or existing. ArrayList<SupervisorBean> spvrs = supervisorsToBeChanged.get("Education"); for (SupervisorBean spvr : spvrs) { if (spvr.getPersonGUID() == educationSpvr.getGUID()) { // The supervisor already exists, add the updated list updatedSupervisorList.add(spvr); supervisorProcessed = true; } } } if (!supervisorProcessed) { // The supervisor does not currently exist, create new updatedSupervisorList .add(createSupervisor(rotation.getGUID(), educationSpvr, educationOrder, "Education")); } } // Update the PDA supervisor (if one is provided) if (pdaSpvr != null) { boolean supervisorProcessed = false; if (supervisorsToBeChanged.containsKey("PDA")) { // PDA supervisors currently exist - check if new or existing. ArrayList<SupervisorBean> spvrs = supervisorsToBeChanged.get("PDA"); for (SupervisorBean spvr : spvrs) { if (spvr.getPersonGUID() == pdaSpvr.getGUID()) { // The supervisor already exists, add the updated list updatedSupervisorList.add(spvr); supervisorProcessed = true; } } } if (!supervisorProcessed) { // The supervisor does not currently exist, create new updatedSupervisorList.add(createSupervisor(rotation.getGUID(), pdaSpvr, pdaOrder, "PDA")); } } // Add the updated list of supervisors rotation.setSupervisors(updatedSupervisorList); rotation.setLogMessage("Rotation supervisors updated by web service"); // Load the privileges bean for the change PrivilegesBean privileges = null; try { privileges = privilegesDAO.load(); } catch (SFSDaoException sde) { logger.error("Error loading privileges: " + sde.getMessage()); throw new Exception("Error loading privileges"); } // Update the rotation and supervisors try { rotationDAO.modify(rotation, this.user, privileges); success = true; } catch (WhichDoctorDaoException wde) { logger.error("Error modifying rotation: " + wde.getMessage()); throw new Exception("Cannot modify rotation - " + wde.getMessage()); } return success; }
From source file:com.jtstand.swing.StatsPanel.java
public TreeMap<String, List<TestStepInstance>> getGroupedSteps(Iterator<TestStepInstance> it) { TreeMap<String, List<TestStepInstance>> groups = new TreeMap<String, List<TestStepInstance>>(); if (it == null) { return null; }//from w w w . jav a 2s . c om while (it.hasNext()) { TestStepInstance step = it.next(); String groupName = getGroupName(step); List<TestStepInstance> steps = groups.get(groupName); if (steps == null) { steps = new ArrayList<TestStepInstance>(); groups.put(groupName, steps); } steps.add(step); } return groups; }
From source file:IndexService.Indexer.java
private List<IRecord> getRange1(String indexdir, String partname, List<IRecord.IFValue> startvalue, List<IRecord.IFValue> endvalue, String indexids, int limit, int fieldnum) throws IOException { String dir = indexdir.endsWith("/") ? indexdir : (indexdir + "/"); Path partfile = new Path(dir + partname); TreeMap<String, TreeSet<Integer>> indexresult = new TreeMap<String, TreeSet<Integer>>(); HashMap<String, Boolean> iscolumn = new HashMap<String, Boolean>(); FileStatus[] fss = fs.listStatus(partfile); long time = System.currentTimeMillis(); for (FileStatus status : fss) { IFormatDataFile ifdf = new IFormatDataFile(conf); ifdf.open(status.getPath().toString()); if (ifdf.fileInfo().head().fieldMap().fieldtypes().size() < startvalue.size() + 2) { throw new IOException("input value field size is more than index can support"); }//from www.j a v a 2 s .co m for (int i = 0; i < startvalue.size(); i++) { if (ifdf.fileInfo().head().fieldMap().fieldtypes().get(i).type() != startvalue.get(i).type() .type()) { throw new IOException("input value field type is not fit the index field type"); } } HashMap<Integer, String> infos = ifdf.fileInfo().head().getUdi().infos(); List<IndexValue> res = getIndexResRange(ifdf, startvalue, endvalue, limit); for (IndexValue iv : res) { int fileid = iv.getFileindex(); String filename = infos.get(fileid); if (!indexresult.containsKey(filename)) { indexresult.put(filename, new TreeSet<Integer>()); iscolumn.put(filename, ifdf.fileInfo().head().getUdi().infos().get(123456).equals("column")); } indexresult.get(filename).add(iv.getRowid()); } ifdf.close(); } System.out.println("getIndexResRange time:\t" + (System.currentTimeMillis() - time) / 1000 + "s"); System.out.println("related file num:\t" + indexresult.size()); return getRecord(indexresult, iscolumn, indexids, limit, fieldnum); }
From source file:com.jtstand.swing.StatsPanel.java
private XYIntervalSeriesCollection createIntervalXYDatasetDistribution(boolean inverted) { //create the population map TreeMap<String, int[]> map = new TreeMap<String, int[]>(); Iterator<TestStepInstance> it = getFilteringIterator(); while (it.hasNext()) { TestStepInstance step = it.next(); String groupName = getGroupName(step); int[] population = map.get(groupName); if (population == null) { population = new int[numberOfCategories]; for (int i = 0; i < numberOfCategories; i++) { population[i] = 0;//from w w w . ja va 2s.com } map.put(groupName, population); } //Stat stat=catstats.get(groupName); Stat stat = allstat; if (stat != null) { Number num = getNumber(step); if (num != null) { double val = num.doubleValue(); int category; if (stat.getStandardDeviation() != 0) { category = (int) (numberOfCategories / 2.0 + numberOfCategories * (val - stat.getAverage()) / (getNumberOfSigmas(stat) * stat.getStandardDeviation())); } else { category = numberOfCategories / 2; } if (category >= 0 && category < numberOfCategories) { population[category]++; } // else { // System.out.println("Value: " + val + " Category: " + category); // } } } else { log.error("There is no stat for:" + groupName); } } XYIntervalSeriesCollection dataset = new XYIntervalSeriesCollection(); int cat = 0; int[] prev = new int[numberOfCategories]; for (int i = 0; i < prev.length; i++) { prev[i] = 0; } for (Iterator<String> it2 = map.keySet().iterator(); it2.hasNext(); cat++) { String groupName = it2.next(); int[] population = map.get(groupName); XYIntervalSeries pop = new XYIntervalSeries(groupName); if (inverted) { for (int i = numberOfCategories - 1; i >= 0; i--) { if (population[i] != 0) { // pop.add(midValue(i), leftValue(i, cat, map.size()), rightValue(i, cat, map.size()), population[i], prev[i], prev[i] + population[i]); pop.add(midValue(i), leftValue(i), rightValue(i), population[i], prev[i], prev[i] + population[i]); prev[i] = prev[i] + population[i]; } } } else { for (int i = 0; i < numberOfCategories; i++) { if (population[i] != 0) { // pop.add(midValue(i), leftValue(i, cat, map.size()), rightValue(i, cat, map.size()), population[i], prev[i], prev[i] + population[i]); pop.add(midValue(i), leftValue(i), rightValue(i), population[i], prev[i], prev[i] + population[i]); prev[i] = prev[i] + population[i]; } } } dataset.addSeries(pop); } return dataset; }