List of usage examples for java.util TreeMap get
public V get(Object key)
From source file:decision_tree_learning.Matrix.java
double mostCommonValue(int col) { TreeMap<Double, Integer> tm = new TreeMap<Double, Integer>(); for (int i = 0; i < rows(); i++) { double v = get(i, col); if (v != MISSING) { Integer count = tm.get(v); if (count == null) tm.put(v, new Integer(1)); else// w w w .j ava 2s . c o m tm.put(v, new Integer(count.intValue() + 1)); } } int maxCount = 0; double val = MISSING; Iterator<Entry<Double, Integer>> it = tm.entrySet().iterator(); while (it.hasNext()) { Entry<Double, Integer> e = it.next(); if (e.getValue() > maxCount) { maxCount = e.getValue(); val = e.getKey(); } } return val; }
From source file:com.sfs.whichdoctor.dao.GroupDAOImpl.java
/** * Load identities./*from ww w. j av a2 s . c o m*/ * * @param items the group's items * * @return the tree map< string, item bean> */ private TreeMap<String, ItemBean> loadIdentities(final TreeMap<String, ItemBean> items) { for (String key : items.keySet()) { ItemBean item = items.get(key); WhichDoctorCoreIdentityBean identity = new WhichDoctorCoreIdentityBean(); identity.setGUID(item.getObject2GUID()); identity.setDescription(item.getName()); // Load the contact details for this identity try { // Load the first work address (or primary if none) identity.setAddress(this.getAddressDAO().load(identity.getGUID(), false, "Work", "Postal")); } catch (WhichDoctorDaoException wde) { dataLogger.error("Error loading identity addresses: " + wde.getMessage()); } try { // Load all the phone numbers (mobile, work phone + fax) identity.setPhone(this.getPhoneDAO().load(identity.getGUID(), true)); } catch (WhichDoctorDaoException wde) { dataLogger.error("Error loading identity phones: " + wde.getMessage()); } try { // Load the work email (or primary if none) identity.setEmail( this.getEmailDAO().load(identity.getGUID(), false, "Unsecured Email", "Work Email")); } catch (WhichDoctorDaoException wde) { dataLogger.error("Error loading identity emails: " + wde.getMessage()); } item.setIdentity(identity); items.put(key, item); } return items; }
From source file:emily.command.administrative.GuildStatsCommand.java
@Override public String execute(DiscordBot bot, String[] args, MessageChannel channel, User author, Message inputMessage) {/*ww w . ja va 2 s.c om*/ if (!bot.getContainer().allShardsReady()) { return "Not fully loaded yet!"; } if (args.length == 0) { return "Statistics! \n" + getTotalTable(bot, false) + "\nYou are on shard # " + bot.getShardId(); } SimpleRank userrank = bot.security.getSimpleRank(author, channel); switch (args[0].toLowerCase()) { case "mini": return "Statistics! \n" + getTotalTable(bot, true); case "music": return DebugUtil .sendToHastebin(getPlayingOn(bot.getContainer(), userrank.isAtLeast(SimpleRank.BOT_ADMIN) || (args.length >= 2 && args[1].equalsIgnoreCase("guilds")))); case "activity": return lastShardActivity(bot.getContainer()); case "users": if (!(channel instanceof TextChannel)) { return Templates.invalid_use.formatGuild(channel); } TreeMap<Date, Integer> map = new TreeMap<>(); Guild guild = ((TextChannel) channel).getGuild(); List<Member> joins = new ArrayList<>(guild.getMembers()); for (Member join : joins) { Date time = DateUtils.round(new Date(join.getJoinDate().toInstant().toEpochMilli()), Calendar.DAY_OF_MONTH); if (!map.containsKey(time)) { map.put(time, 0); } map.put(time, map.get(time) + 1); } List<Date> xData = new ArrayList<>(); List<Integer> yData = new ArrayList<>(); int total = 0; for (Map.Entry<Date, Integer> entry : map.entrySet()) { total += entry.getValue(); xData.add(entry.getKey()); yData.add(total); } XYChart chart = new XYChart(1024, 600); chart.setTitle("Users over time for " + guild.getName()); chart.setXAxisTitle("Date"); chart.setYAxisTitle("Users"); chart.getStyler().setTheme(new GGPlot2Theme()); XYSeries series = chart.addSeries("Users", xData, yData); series.setMarker(SeriesMarkers.CIRCLE); try { File f = new File("./Sample_Chart.png"); BitmapEncoder.saveBitmap(chart, f.getAbsolutePath(), BitmapEncoder.BitmapFormat.PNG); bot.queue.add(channel.sendFile(f), message -> f.delete()); } catch (IOException e) { e.printStackTrace(); } return ""; } return "Statistics! \n" + getTotalTable(bot, false); }
From source file:com.compomics.pride_asa_pipeline.core.logic.modification.PTMMapper.java
public PtmSettings removeDuplicateMasses(PtmSettings modProfile, double precursorMassAcc) { TreeMap<Double, String> massToModMap = new TreeMap<>(); for (String aModName : modProfile.getAllModifications()) { massToModMap.put(modProfile.getPtm(aModName).getMass(), aModName); }//www .j a v a 2 s. co m double previousMass = massToModMap.firstKey() - precursorMassAcc; for (Double aModMass : massToModMap.keySet()) { if (Math.abs(aModMass - previousMass) < precursorMassAcc) { String originalModification = massToModMap.get(previousMass); String duplicateModification = massToModMap.get(aModMass); if (originalModification != null) { System.out.println("Duplicate masses found : " + originalModification + "(" + previousMass + ")" + " vs " + duplicateModification + "(" + aModMass + ")"); if (modProfile.getFixedModifications().contains(duplicateModification)) { modProfile.removeFixedModification(duplicateModification); } else { modProfile.removeVariableModification(duplicateModification); } } } previousMass = aModMass; } return modProfile; }
From source file:au.org.ala.ecodata.IniReader.java
public void write(Map<String, String> doc, String filename) { try {/*from ww w . j a v a 2s.c om*/ PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(filename))); TreeMap<String, String> pmap = new TreeMap<String, String>(doc); Iterator<String> it = pmap.keySet().iterator(); String currentSection = ""; while (it.hasNext()) { String key = it.next(); String[] sectionkey = key.split("\\\\"); if (!currentSection.equals(sectionkey[0])) { currentSection = sectionkey[0]; out.println("\n"); out.println("[" + sectionkey[0] + "]"); } out.println(sectionkey[1] + "=" + pmap.get(key)); } out.close(); } catch (Exception e) { logger.error("Unable to write ini to " + filename); e.printStackTrace(System.out); } }
From source file:net.anthonypoon.ngram.rollingregression.RollingRegressionReducer.java
@Override protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException { TreeMap<String, Double> currElement = new TreeMap(); boolean pastThreshold = false; for (Text val : values) { String[] strArray = val.toString().split("\t"); if (Double.valueOf(strArray[1]) > threshold) { pastThreshold = true;/*from w ww . j a v a2 s .com*/ } currElement.put(strArray[0], Math.log(Double.valueOf(strArray[1]))); } if (pastThreshold) { for (Integer i = 0; i <= upbound - lowbound; i++) { if (!currElement.containsKey(String.valueOf(lowbound + i))) { if (i != 0) { currElement.put(String.valueOf(lowbound + i), currElement.get(String.valueOf(lowbound + i - 1))); } else { currElement.put(String.valueOf(lowbound + i), 0.0); } } } TreeMap<String, Double> result = new TreeMap(); for (Integer i = 0 + range; i <= upbound - lowbound - range; i++) { SimpleRegression regression = new SimpleRegression(); for (Integer l = -range; l <= range; l++) { regression.addData(l.doubleValue(), currElement.get(String.valueOf(i + lowbound + l))); } if (!Double.isNaN(regression.getSlope())) { if (!positiveOnly || regression.getSlope() > 0) { result.put(String.valueOf(lowbound + i), regression.getSlope()); } } } for (Map.Entry<String, Double> pair : result.entrySet()) { context.write(key, new Text(pair.getKey() + "\t" + String.format("%.5f", pair.getValue()))); } } }
From source file:net.triptech.buildulator.DataParser.java
/** * Parses the text data./* w w w .jav a 2s.c o m*/ * * @param text the text * * @return the tree map< integer, tree map< integer, string>> */ public static String[][] parseTextData(final String text) { TreeMap<Integer, TreeMap<Integer, String>> rowData = new TreeMap<Integer, TreeMap<Integer, String>>(); // This counter holds the maximum number of columns provided int maxNumberOfTokens = 0; if (text != null) { BufferedReader in = new BufferedReader(new StringReader(text)); String line; int lineCounter = 0; try { while ((line = in.readLine()) != null) { TreeMap<Integer, String> parsedLine = new TreeMap<Integer, String>(); SmartTokenizer tabTokenizer = new SmartTokenizer(line, "\t"); if (tabTokenizer.countTokens() > 1) { parsedLine = tokenizerToMap(tabTokenizer); } else { SmartTokenizer commaTokenizer = new SmartTokenizer(line, ","); parsedLine = tokenizerToMap(commaTokenizer); } if (parsedLine.size() > maxNumberOfTokens) { maxNumberOfTokens = parsedLine.size(); } rowData.put(lineCounter, parsedLine); lineCounter++; } } catch (IOException ioe) { // Error reading string } } String[][] parsedData = new String[rowData.size()][]; // Now cycle through all the parsed data // Ensure that each row has the same (max) number of tokens for (int rowIndex : rowData.keySet()) { TreeMap<Integer, String> parsedLine = rowData.get(rowIndex); // This map holds the final values TreeMap<Integer, String> columnTokens = new TreeMap<Integer, String>(); for (int i = 0; i < maxNumberOfTokens; i++) { String value = ""; if (parsedLine.containsKey(i)) { value = parsedLine.get(i); } columnTokens.put(i, value); } parsedData[rowIndex] = new String[columnTokens.size()]; for (int columnIndex : columnTokens.keySet()) { String value = columnTokens.get(columnIndex); parsedData[rowIndex][columnIndex] = value; } } return parsedData; }
From source file:kmi.taa.core.Crawler.java
public void crawlAll(TreeMap<Integer, String> targetUrls, String service, String proxy, String otfile) { SortedSet<Integer> results = Collections.synchronizedSortedSet(new TreeSet<Integer>()); ExecutorService pool = Executors.newFixedThreadPool(100); int howManyUrls = targetUrls.size(); System.out.println("total " + howManyUrls + " to be processed"); List<String> output = Collections.synchronizedList(new ArrayList<String>()); for (Integer targetId : targetUrls.navigableKeySet()) { String uri = targetUrls.get(targetId); pool.execute(new Explorer(targetId, uri, service, proxy, results, otfile, output)); }// www. ja v a 2 s. com pool.shutdown(); while (results.size() < howManyUrls) { System.out.println("already processed " + results.size() + " subject links"); try { Thread.sleep(1000); } catch (InterruptedException e) { log.error("crawlAll error", e); } } resultToFile(output, otfile); System.out.println("already processed " + results.size() + " subject links"); }
From source file:ch.algotrader.service.algo.VWAPOrderService.java
VWAPOrderStateVO createAlgoOrderState(final VWAPOrder algoOrder, final Date dateTime) throws OrderValidationException { Validate.notNull(algoOrder, "vwapOrder missing"); Security security = algoOrder.getSecurity(); SecurityFamily family = security.getSecurityFamily(); Exchange exchange = family.getExchange(); HistoricalDataService historicalDataService = this.applicationContext.getBean(HistoricalDataService.class); List<Bar> bars = historicalDataService.getHistoricalBars(security.getId(), // DateUtils.truncate(new Date(), Calendar.DATE), // algoOrder.getLookbackPeriod(), // TimePeriod.DAY, // algoOrder.getBucketSize(), // MarketDataEventType.TRADES, // Collections.emptyMap()); TreeMap<LocalTime, Long> buckets = new TreeMap<>(); Set<LocalDate> tradingDays = new HashSet<>(); for (Bar bar : bars) { int vol = bar.getVol(); LocalTime time = DateTimeLegacy.toLocalTime(bar.getDateTime()); tradingDays.add(DateTimeLegacy.toLocalDate(bar.getDateTime())); if (buckets.containsKey(time)) { buckets.put(time, buckets.get(time) + vol); } else {/*from www. j a v a 2s .c o m*/ buckets.put(time, (long) vol); } } // verify start and end time if (algoOrder.getStartTime() == null) { if (this.calendarService.isOpen(exchange.getId())) { algoOrder.setStartTime(dateTime); } else { Date nextOpenTime = this.calendarService.getNextOpenTime(exchange.getId()); algoOrder.setStartTime(nextOpenTime); } } Date closeTime = this.calendarService.getNextCloseTime(exchange.getId()); if (algoOrder.getEndTime() == null) { algoOrder.setEndTime(closeTime); } if (algoOrder.getStartTime().compareTo(dateTime) < 0) { throw new OrderValidationException("startTime needs to be in the future " + algoOrder); } else if (algoOrder.getEndTime().compareTo(dateTime) <= 0) { throw new OrderValidationException("endTime needs to be in the future " + algoOrder); } else if (algoOrder.getEndTime().compareTo(closeTime) > 0) { throw new OrderValidationException("endTime needs to be before next market closeTime for " + algoOrder); } else if (algoOrder.getEndTime().compareTo(algoOrder.getStartTime()) <= 0) { throw new OrderValidationException("endTime needs to be after startTime for " + algoOrder); } int historicalVolume = 0; LocalTime startTime = DateTimeLegacy.toLocalTime(algoOrder.getStartTime()); LocalTime endTime = DateTimeLegacy.toLocalTime(algoOrder.getEndTime()); LocalTime firstBucketStart = buckets.floorKey(startTime); LocalTime lastBucketStart = buckets.floorKey(endTime); SortedMap<LocalTime, Long> subBuckets = buckets.subMap(firstBucketStart, true, lastBucketStart, true); for (Map.Entry<LocalTime, Long> bucket : subBuckets.entrySet()) { long vol = bucket.getValue() / tradingDays.size(); bucket.setValue(vol); if (bucket.getKey().equals(firstBucketStart)) { LocalTime firstBucketEnd = firstBucketStart.plus(algoOrder.getBucketSize().getValue(), ChronoUnit.MILLIS); double fraction = (double) ChronoUnit.MILLIS.between(startTime, firstBucketEnd) / algoOrder.getBucketSize().getValue(); historicalVolume += vol * fraction; } else if (bucket.getKey().equals(lastBucketStart)) { double fraction = (double) ChronoUnit.MILLIS.between(lastBucketStart, endTime) / algoOrder.getBucketSize().getValue(); historicalVolume += vol * fraction; } else { historicalVolume += vol; } } double participation = algoOrder.getQuantity() / (double) historicalVolume; if (participation > MAX_PARTICIPATION) { throw new OrderValidationException("participation rate " + twoDigitFormat.format(participation * 100.0) + "% is above 50% of historical market volume for " + algoOrder); } if (LOGGER.isInfoEnabled()) { LOGGER.debug("participation of {} is {}%", algoOrder.getDescription(), twoDigitFormat.format(participation * 100.0)); } return new VWAPOrderStateVO(participation, buckets); }
From source file:mrmc.chart.ROCCurvePlot.java
/** * Creates an ROC curve that averages together the scores for all readers in * the diagonal direction/*from w ww. ja v a2 s. c om*/ * * @param treeMap Mapping of readers to points defining a curve * @return Series containing the ROC curve points */ private XYSeries generateDiagonalROC(TreeMap<String, TreeSet<XYPair>> treeMap) { XYSeries diagAvg = new XYSeries("Diagonal Average", false); TreeMap<String, TreeSet<XYPair>> rotatedData = new TreeMap<String, TreeSet<XYPair>>(); // rotate all points in data 45 degrees clockwise about origin for (String r : treeMap.keySet()) { rotatedData.put(r, new TreeSet<XYPair>()); for (XYPair point : treeMap.get(r)) { double x2 = (point.x + point.y) / Math.sqrt(2.0); double y2 = (point.y - point.x) / Math.sqrt(2.0); rotatedData.get(r).add(new XYPair(x2, y2)); } } // generate linear interpolation with new points ArrayList<InterpolatedLine> rotatedLines = new ArrayList<InterpolatedLine>(); for (String r : rotatedData.keySet()) { rotatedLines.add(new InterpolatedLine(rotatedData.get(r))); } // take vertical sample averages from x = 0 to x = 1 for (double i = 0; i <= Math.sqrt(2); i += 0.01) { double avg = 0; int counter = 0; for (InterpolatedLine line : rotatedLines) { avg += line.getYatDiag(i); counter++; } // rotate points back 45 degrees counterclockwise double x1 = i; double y1 = (avg / (double) counter); double x2 = (x1 * Math.cos(Math.toRadians(45))) - (y1 * Math.sin(Math.toRadians(45))); double y2 = (x1 * Math.sin(Math.toRadians(45))) + (y1 * Math.cos(Math.toRadians(45))); diagAvg.add(x2, y2); } diagAvg.add(1, 1); return diagAvg; }