/** Constructs an empty Distribution with the specified {@link DistributionFitter}. */ public MutableDistribution(DistributionFitter distributionFitter) { this.distributionFitter = checkNotNull(distributionFitter); ImmutableSortedSet<Double> boundaries = distributionFitter.boundaries(); checkArgument(boundaries.size() > 0); checkArgument(Ordering.natural().isOrdered(boundaries)); this.intervalCounts = TreeRangeMap.create(); double[] boundariesArray = Doubles.toArray(distributionFitter.boundaries()); // Add underflow and overflow intervals this.intervalCounts.put(Range.lessThan(boundariesArray[0]), 0L); this.intervalCounts.put(Range.atLeast(boundariesArray[boundariesArray.length - 1]), 0L); // Add finite intervals for (int i = 1; i < boundariesArray.length; i++) { this.intervalCounts.put(Range.closedOpen(boundariesArray[i - 1], boundariesArray[i]), 0L); } }
/** * Applies replacements to the given string. */ private static JavaInput applyReplacements( JavaInput javaInput, TreeRangeMap<Integer, String> replacementMap) throws FormatterException { // process in descending order so the replacement ranges aren't perturbed if any replacements // differ in size from the input Map<Range<Integer>, String> ranges = replacementMap.asDescendingMapOfRanges(); if (ranges.isEmpty()) { return javaInput; } StringBuilder sb = new StringBuilder(javaInput.getText()); for (Entry<Range<Integer>, String> entry : ranges.entrySet()) { Range<Integer> range = entry.getKey(); sb.replace(range.lowerEndpoint(), range.upperEndpoint(), entry.getValue()); } return new JavaInput(sb.toString()); }
/** Applies replacements to the given string. */ private static JavaInput applyReplacements( JavaInput javaInput, TreeRangeMap<Integer, String> replacementMap) throws FormatterException { // process in descending order so the replacement ranges aren't perturbed if any replacements // differ in size from the input Map<Range<Integer>, String> ranges = replacementMap.asDescendingMapOfRanges(); if (ranges.isEmpty()) { return javaInput; } StringBuilder sb = new StringBuilder(javaInput.getText()); for (Entry<Range<Integer>, String> entry : ranges.entrySet()) { Range<Integer> range = entry.getKey(); sb.replace(range.lowerEndpoint(), range.upperEndpoint(), entry.getValue()); } return new JavaInput(sb.toString()); }
static private RangeMap<Double, String> parseDiscretize(Discretize discretize){ RangeMap<Double, String> result = TreeRangeMap.create(); List<DiscretizeBin> discretizeBins = discretize.getDiscretizeBins(); for(DiscretizeBin discretizeBin : discretizeBins){ Interval interval = discretizeBin.getInterval(); if(interval == null){ throw new MissingAttributeException(discretizeBin, PMMLAttributes.DISCRETIZEBIN_INTERVAL); } Range<Double> range = toRange(interval); String binValue = discretizeBin.getBinValue(); if(binValue == null){ throw new MissingAttributeException(discretizeBin, PMMLAttributes.DISCRETIZEBIN_BINVALUE); } result.put(range, binValue); } return result; }
public static void main(String[] args) { // define rages for checks RangeMap<Integer, Double> checkFee = TreeRangeMap.create(); checkFee.put(Range.closed(0, 19), .1); checkFee.put(Range.closed(20, 39), .8); checkFee.put(Range.closed(40, 59), .6); checkFee.put(Range.closed(60, Integer.MAX_VALUE), .4); // Create a Scanner object for keyboard input. Scanner keyboard = new Scanner(System.in); // Get the number of checks written. System.out.print("Enter the number of checks written " + "this month: "); int numChecks = keyboard.nextInt(); //close scanner keyboard.close(); // calculate total fee double total = BASE_FEE + (checkFee.get(numChecks) * numChecks); // Display the total bank fees. System.out.printf("The total fees are $%.2f\n", total); }
public RegionCache(ReadOnlyPDClient pdClient) { regionCache = new HashMap<>(); storeCache = new HashMap<>(); keyToRegionIdCache = TreeRangeMap.create(); this.pdClient = pdClient; }
/** * Finalise la création de la feuille de calcul, notamment en demandant le * redimensionnement automatique des colonnes. * * @param sheet feuilles de calcul * @param columnInfos collection contenant les informations de colonnes * @param landscapePrintSetup définit si la feuille est imprimée en paysage ou non */ protected void finalizeSheet(Sheet sheet, Collection<ColumnInformation> columnInfos, boolean landscapePrintSetup) { RangeMap<Integer, ColumnInformation> map = TreeRangeMap.create(); int index = 0; for (ColumnInformation column : columnInfos) { map.put(Range.singleton(index), column); ++index; } finalizeSheet(sheet, map, landscapePrintSetup); }
/** * Sets the dynamism levels. * @param levels At least one level must be given. The default level is * <code>.5</code>. * @return This, as per the builder pattern. */ public Builder setDynamismLevels(Iterable<Double> levels) { checkArgument(Iterables.size(levels) > 0); final RangeSet<Double> rangeSet = TreeRangeSet.create(); final Set<Range<Double>> dynamismLevelsB = new LinkedHashSet<>(); final RangeMap<Double, Double> map = TreeRangeMap.create(); for (final Double d : levels) { checkArgument(d >= 0d && d <= 1d); final Range<Double> newRange = createDynRange(d); checkArgument( rangeSet.subRangeSet(newRange).isEmpty(), "Can not add dynamism level %s, it is too close to another level.", d); rangeSet.add(newRange); dynamismLevelsB.add(newRange); map.put(newRange, d); } final SetMultimap<TimeSeriesType, Range<Double>> timeSeriesTypes = LinkedHashMultimap .<TimeSeriesType, Range<Double>>create(); for (final Range<Double> r : dynamismLevelsB) { checkArgument(DYNAMISM_MAP.get(r.lowerEndpoint()) != null); checkArgument(DYNAMISM_MAP.get(r.lowerEndpoint()) == DYNAMISM_MAP.get(r .upperEndpoint())); timeSeriesTypes.put(DYNAMISM_MAP.get(r.lowerEndpoint()), r); } dynamismLevels = ImmutableSetMultimap.copyOf(timeSeriesTypes); dynamismRangeMap = ImmutableRangeMap.copyOf(map); return this; }
private DescriptionBasedDiff(JCCompilationUnit compilationUnit) { this.compilationUnit = checkNotNull(compilationUnit); this.sourcePath = compilationUnit.getSourceFile().toUri().getPath(); this.importsToAdd = new HashSet<>(); this.importsToRemove = new HashSet<>(); this.endPosMap = JDKCompatible.getEndPosMap(compilationUnit); this.replacements = TreeRangeMap.create(); }
/** Construct replacements to fix unused imports. */ private static RangeMap<Integer, String> buildReplacements( String contents, JCCompilationUnit unit, Set<String> usedNames, Multimap<String, Range<Integer>> usedInJavadoc) { RangeMap<Integer, String> replacements = TreeRangeMap.create(); for (JCImport importTree : unit.getImports()) { String simpleName = getSimpleName(importTree); if (!isUnused(unit, usedNames, usedInJavadoc, importTree, simpleName)) { continue; } // delete the import int endPosition = importTree.getEndPosition(unit.endPositions); endPosition = Math.max(CharMatcher.isNot(' ').indexIn(contents, endPosition), endPosition); String sep = Newlines.guessLineSeparator(contents); if (endPosition + sep.length() < contents.length() && contents.subSequence(endPosition, endPosition + sep.length()).equals(sep)) { endPosition += sep.length(); } replacements.put(Range.closedOpen(importTree.getStartPosition(), endPosition), ""); // fully qualify any javadoc references with the same simple name as a deleted // non-static import if (!importTree.isStatic()) { for (Range<Integer> docRange : usedInJavadoc.get(simpleName)) { if (docRange == null) { continue; } String replaceWith = importTree.getQualifiedIdentifier().toString(); replacements.put(docRange, replaceWith); } } } return replacements; }
/** * Create {@link HomRefBlock}s which will collectively accept variants of any genotype quality * * Each individual block covers a band of genotype qualities with the splits between bands occurring at values in {@code gqPartitions}. * There will be {@code gqPartitions.size() +1} bands produced covering the entire possible range of genotype qualities from 0 to {@link VCFConstants#MAX_GENOTYPE_QUAL}. * * @param gqPartitions proposed GQ partitions * @return a list of HomRefBlocks accepting bands of genotypes qualities split at the points specified in gqPartitions */ @VisibleForTesting static RangeMap<Integer,Range<Integer>> parsePartitions(final List<Integer> gqPartitions) { Utils.nonEmpty(gqPartitions); Utils.containsNoNull(gqPartitions, "The list of GQ partitions contains a null integer"); final RangeMap<Integer, Range<Integer>> result = TreeRangeMap.create(); int lastThreshold = 0; for (final Integer value : gqPartitions) { if (value < 0) { throw new IllegalArgumentException("The list of GQ partitions contains a non-positive integer."); } else if (value > MAX_GENOTYPE_QUAL + 1) { throw new IllegalArgumentException(String.format("The value %d in the list of GQ partitions is greater than VCFConstants.MAX_GENOTYPE_QUAL + 1 = %d.", value, MAX_GENOTYPE_QUAL + 1)); } else if (value < lastThreshold) { throw new IllegalArgumentException(String.format("The list of GQ partitions is out of order. Previous value is %d but the next is %d.", lastThreshold, value)); } else if (value == lastThreshold) { throw new IllegalArgumentException(String.format("The value %d appears more than once in the list of GQ partitions.", value)); } result.put(Range.closedOpen(lastThreshold, value), Range.closedOpen(lastThreshold, value)); lastThreshold = value; } if (lastThreshold <= MAX_GENOTYPE_QUAL) { result.put(Range.closedOpen(lastThreshold, MAX_GENOTYPE_QUAL + 1), Range.closedOpen(lastThreshold,MAX_GENOTYPE_QUAL + 1)); } return result; }
@Test public void google_guava_range_map_example () { RangeMap<Integer, String> gradeScale = TreeRangeMap.create(); gradeScale.put(Range.closed(0, 60), "F"); gradeScale.put(Range.closed(61, 70), "D"); gradeScale.put(Range.closed(71, 80), "C"); gradeScale.put(Range.closed(81, 90), "B"); gradeScale.put(Range.closed(91, 100), "A"); String grade = gradeScale.get(77); assertEquals("C", grade); }
@Before public void setUp() { actual = TreeRangeMap.create(); actual.put(Range.closedOpen(380, 450), "violet"); actual.put(Range.closedOpen(450, 495), "blue"); actual.put(Range.closedOpen(495, 570), "green"); actual.put(Range.closedOpen(570, 590), "yellow"); actual.put(Range.closedOpen(590, 620), "orange"); actual.put(Range.closedOpen(620, 750), "red"); }
private MetricRetention(Pattern pattern, String function) { this.pattern = pattern; this.function = function; this.ranges = TreeRangeMap.create(); }
/** * Reorders all modifiers in the given text and within the given character ranges to be in JLS * order. */ static JavaInput reorderModifiers(JavaInput javaInput, Collection<Range<Integer>> characterRanges) throws FormatterException { if (javaInput.getTokens().isEmpty()) { // There weren't any tokens, possible because of a lexing error. // Errors about invalid input will be reported later after parsing. return javaInput; } RangeSet<Integer> tokenRanges = javaInput.characterRangesToTokenRanges(characterRanges); Iterator<? extends Token> it = javaInput.getTokens().iterator(); TreeRangeMap<Integer, String> replacements = TreeRangeMap.create(); while (it.hasNext()) { Token token = it.next(); if (!tokenRanges.contains(token.getTok().getIndex())) { continue; } Modifier mod = asModifier(token); if (mod == null) { continue; } List<Token> modifierTokens = new ArrayList<>(); List<Modifier> mods = new ArrayList<>(); int begin = token.getTok().getPosition(); mods.add(mod); modifierTokens.add(token); int end = -1; while (it.hasNext()) { token = it.next(); mod = asModifier(token); if (mod == null) { break; } mods.add(mod); modifierTokens.add(token); end = token.getTok().getPosition() + token.getTok().length(); } if (!Ordering.natural().isOrdered(mods)) { Collections.sort(mods); StringBuilder replacement = new StringBuilder(); for (int i = 0; i < mods.size(); i++) { if (i > 0) { addTrivia(replacement, modifierTokens.get(i).getToksBefore()); } replacement.append(mods.get(i).toString()); if (i < (modifierTokens.size() - 1)) { addTrivia(replacement, modifierTokens.get(i).getToksAfter()); } } replacements.put(Range.closedOpen(begin, end), replacement.toString()); } } return applyReplacements(javaInput, replacements); }
/** * 以Guava TreeRangeMap实现的, 一段范围的Key指向同一个Value的Map */ @SuppressWarnings("rawtypes") public static <K extends Comparable, V> TreeRangeMap<K, V> createRangeMap() { return TreeRangeMap.create(); }
public static List<DoubleStream> getCachedValues(String key, PeriodicRange<?> range, Function<PeriodicRange<?>, List<DoubleStream>> function) { @SuppressWarnings("unchecked") Periodicity<Period> freq = (Periodicity<Period>) range.periodicity(); String wholeKey = key + ":" + range.periodicity().code(); RangeMap<Long, CachedSeriesList> cache = null; synchronized (seriesCache) { if (range.clearCache() || !seriesCache.containsKey(wholeKey)) { seriesCache.put(wholeKey, TreeRangeMap.create()); } cache = seriesCache.get(wholeKey); } synchronized (cache) { try { Range<Long> requestedRange = Range.closed(range.start().longValue(), range.end().longValue()); Set<Range<Long>> toRemove = new HashSet<>(); List<DoubleStream> chunkData = new ArrayList<>(); long current = requestedRange.lowerEndpoint(); long chunkStart = current; Optional<Long> expirationTime = Optional.empty(); for (Map.Entry<Range<Long>, CachedSeriesList> e : cache.subRangeMap(requestedRange).asMapOfRanges() .entrySet()) { toRemove.add(e.getKey()); if(e.getValue().getExpirationTime().isPresent()) { if(System.currentTimeMillis() > e.getValue().getExpirationTime().get()) { break; } else { expirationTime = e.getValue().getExpirationTime(); } } long thisChunkStart = e.getValue().getRange().start().longValue(); long thisChunkEnd = e.getValue().getRange().end().longValue(); chunkStart = Long.min(chunkStart, thisChunkStart); if (current < thisChunkStart) { concat(chunkData, function.apply(freq.range(current, thisChunkStart - 1, false))); } concat(chunkData, e.getValue().getSeries()); current = thisChunkEnd + 1; } if (current <= requestedRange.upperEndpoint()) { concat(chunkData, function.apply(freq.range(current, requestedRange.upperEndpoint(), false))); current = requestedRange.upperEndpoint() + 1; } toRemove.stream().forEach(cache::remove); long now = freq.from(LocalDate.now()).longValue(); if(now > chunkStart) { long endOfPast = Math.min(now - 1, current - 1); cache.put(Range.closed(chunkStart, endOfPast), new CachedSeriesList(freq.range(chunkStart, endOfPast, false), dup(chunkData,0, (int) (1 + endOfPast - chunkStart)), Optional.empty())); } if(current - 1 >= now) { long startOfNow = Math.max(now, chunkStart); cache.put(Range.closed(startOfNow, current - 1), new CachedSeriesList(freq.range(startOfNow, current - 1, false), dup(chunkData, (int) (startOfNow - chunkStart), (int) (current - startOfNow)), Optional.of(expirationTime.orElse(System.currentTimeMillis() + CURRENT_DATA_TIMEOUT)))); } final long finalStart = chunkStart; return chunkData.stream() .map(s -> s.skip(requestedRange.lowerEndpoint() - finalStart).limit(range.size())) .collect(Collectors.toList()); } catch (RuntimeException re) { seriesCache.remove(wholeKey); throw re; } } }
@Override public RangeMap<RangeValue, String> load(SegmentId segmentId) throws Exception { return TreeRangeMap.create(); }
@Test public void should_fail_if_actual_is_null() { expectException(AssertionError.class, actualIsNull()); TreeRangeMap<Integer, String> actual = null; assertThat(actual).containsKeys(500, 600, 700); }