Java Code Examples for com.google.common.collect.RangeMap

The following are top voted examples for showing how to use com.google.common.collect.RangeMap. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: martini-core   File: DefaultMixology.java   View source code 6 votes vote down vote up
protected List<Recipe> getRecipes(FeatureWrapper feature, Collection<Pickle> pickles) {
	int pickleCount = pickles.size();
	ArrayList<Recipe> recipes = Lists.newArrayListWithExpectedSize(pickleCount);
	Set<Integer> pickleLines = Sets.newHashSetWithExpectedSize(pickleCount);

	RangeMap<Integer, ScenarioDefinition> rangeMap = getRangeMap(feature);
	for (Pickle pickle : pickles) {
		List<PickleLocation> locations = pickle.getLocations();
		for (PickleLocation location : locations) {
			int line = location.getLine();
			if (!pickleLines.contains(line)) {
				pickleLines.add(line);
				Range<Integer> range = Range.singleton(line);
				RangeMap<Integer, ScenarioDefinition> subRangeMap = rangeMap.subRangeMap(range);
				Map<Range<Integer>, ScenarioDefinition> asMap = subRangeMap.asMapOfRanges();
				checkState(1 == asMap.size(), "no single range found encompassing PickleLocation %s", location);
				ScenarioDefinition definition = Iterables.getOnlyElement(asMap.values());
				Recipe recipe = new Recipe(feature, pickle, location, definition);
				recipes.add(recipe);
			}
		}
	}
	return recipes;
}
 
Example 2
Project: martini-core   File: DefaultMixology.java   View source code 6 votes vote down vote up
protected RangeMap<Integer, ScenarioDefinition> getRangeMap(FeatureWrapper feature) {
	List<ScenarioDefinition> children = Lists.newArrayList(feature.getChildren());

	ImmutableRangeMap.Builder<Integer, ScenarioDefinition> builder = ImmutableRangeMap.builder();
	while (!children.isEmpty()) {
		ScenarioDefinition child = children.remove(0);
		Location location = child.getLocation();
		Integer childStart = location.getLine();

		ScenarioDefinition sibling = children.isEmpty() ? null : children.get(0);
		Location siblingLocation = null == sibling ? null : sibling.getLocation();
		Integer siblingStart = null == siblingLocation ? null : siblingLocation.getLine();

		Range<Integer> range = null == siblingStart ? Range.atLeast(childStart) : Range.closedOpen(childStart, siblingStart);
		builder.put(range, child);
	}
	return builder.build();
}
 
Example 3
Project: Wiab.pro   File: BlockIndexImpl.java   View source code 6 votes vote down vote up
@Override
public synchronized void update(Fragment fragment) {
  RangeMap<RangeValue, String> ranges = getRanges(fragment.getSegmentId());
  Map.Entry<Range<RangeValue>, String> entry = ranges.getEntry(RangeValue.of(fragment.getStartVersion()));
  if (entry != null) {
      Preconditions.checkArgument(entry.getValue().equals(fragment.getBlock().getBlockId()),
      "New range overlaps an existing by block Id");
    Preconditions.checkArgument(fragment.getStartVersion() == entry.getKey().lowerEndpoint().get(),
      "New range overlaps an existing by start version");
    entry.getKey().upperEndpoint().set(fragment.isLast() ? Long.MAX_VALUE : fragment.getLastModifiedVersion());
  } else {
    ranges.put(Range.closed(RangeValue.of(fragment.getStartVersion()),
      RangeValue.of(fragment.isLast() ? Long.MAX_VALUE : fragment.getLastModifiedVersion())),
      fragment.getBlock().getBlockId());
  }
}
 
Example 4
Project: Wiab.pro   File: BlockIndexImpl.java   View source code 6 votes vote down vote up
private RangeMap<RangeValue, String> getRanges(SegmentId segmentId) {
  RangeMap<RangeValue, String> ranges = rangeMap.getIfPresent(segmentId);
  if (ranges == null) {
    try {
      ranges = rangeMap.get(segmentId);
      if (serialized != null) {
        int index = serialized.getSegmentIdList().indexOf(segmentId.serialize());
        if (index != -1) {
          SegmentRanges serializedRanges = serialized.getSegmentRanges(index);
          for (ByteString serializedFragment : serializedRanges.getRawFragmentRangesList()) {
            ProtoBlockIndex.BlockIndex.FragmentRange fragment =
                ProtoBlockIndex.BlockIndex.FragmentRange.parseFrom(serializedFragment);
            ranges.put(Range.closed(RangeValue.of(fragment.getSourceVersion()),
                RangeValue.of(fragment.getTargetVersion())), fragment.getBlockId());
          }
        }
      }
    } catch (ExecutionException | InvalidProtocolBufferException ex) {
      throw new RuntimeException(ex);
    }
  }
  return ranges;
}
 
Example 5
Project: owsi-core-parent   File: AbstractExcelTableExport.java   View source code 6 votes vote down vote up
/**
 * Ajoute les en-têtes dans la feuille de calcul et cache les colonnes qui doivent l'être.
 * 
 * @param sheet feuille de calcul
 * @param rowIndex numéro de la ligne
 * @param columnInfos RangeMap contenant les informations de colonnes (valeurs) et les index sur auxquelles s'appliquent ces colonnes (clés).
 *                    Les "colonnes" s'étendant sur plus d'un index seront automatiquement fusionnées.
 */
protected void addHeadersToSheet(Sheet sheet, int rowIndex, RangeMap<Integer, ColumnInformation> columnInfos) {
	Row rowHeader = sheet.createRow(rowIndex);
	for (Map.Entry<Range<Integer>, ColumnInformation> entry : columnInfos.asMapOfRanges().entrySet()) {
		Range<Integer> range = entry.getKey();
		ColumnInformation columnInformation = entry.getValue();
		
		addHeaderCell(rowHeader, range.lowerEndpoint(), getColumnLabel(columnInformation.getHeaderKey()));
		
		for (Integer columnIndex : ContiguousSet.create(range, DiscreteDomain.integers())) {
			sheet.setColumnHidden(columnIndex, columnInformation.isHidden());
		}
		
		int beginIndex = range.lowerEndpoint();
		int endIndex = range.upperEndpoint();
		if (beginIndex != endIndex) {
			sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, beginIndex, endIndex));
		}
	}
}
 
Example 6
Project: tcl-regex-java   File: RuntimeColorMap.java   View source code 6 votes vote down vote up
private void computeBmp(RangeMap<Integer, Short> fullMap) {
    for (Map.Entry<Range<Integer>, Short> me : fullMap.asMapOfRanges().entrySet()) {
        Range<Integer> range = me.getKey();
        int min = range.lowerEndpoint();
        if (range.lowerBoundType() == BoundType.OPEN) {
            min++;
        }
        if (min < Character.MAX_VALUE) {
            int rmax = range.upperEndpoint();
            if (range.upperBoundType() == BoundType.OPEN) {
                rmax--;
            }
            int max = Math.min(Character.MAX_VALUE, rmax);
            for (int x = min; x <= max; x++) {
                this.bmpMap[x] = me.getValue();
            }
        }
    }
}
 
Example 7
Project: jpmml-evaluator   File: DiscretizationUtil.java   View source code 6 votes vote down vote up
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;
}
 
Example 8
Project: levelup-java-exercises   File: BankCharges.java   View source code 6 votes vote down vote up
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);
	}
 
Example 9
Project: ProjectAres   File: Renewable.java   View source code 5 votes vote down vote up
MaterialData chooseShuffledMaterial() {
    ImmutableRangeMap.Builder<Double, MaterialData> weightsBuilder = ImmutableRangeMap.builder();
    double sum = 0d;
    for(MaterialData material : shuffleableMaterialDeficit.materials()) {
        double weight = shuffleableMaterialDeficit.get(material);
        if(weight > 0) {
            weightsBuilder.put(Range.closedOpen(sum, sum + weight), material);
            sum += weight;
        }
    }
    RangeMap<Double, MaterialData> weights = weightsBuilder.build();
    return weights.get(match.getRandom().nextDouble() * sum);
}
 
Example 10
Project: checkstyle-backport-jre6   File: InputIndentationFromGuava2.java   View source code 5 votes vote down vote up
public V get(int index) { //indent:2 exp:2
  K key = null; //indent:4 exp:4
  int len = 0; //indent:4 exp:4
  checkElementIndex(index, len); //indent:4 exp:4
  int off; //indent:4 exp:4
  RangeMap<K, V> ranges = null; //indent:4 exp:4
  if (index == 0 || index == len - 1) { //indent:4 exp:4
    Object range; //indent:6 exp:6
    return ranges.get(key); //indent:6 exp:6
  } else { //indent:4 exp:4
    return ranges.get(key); //indent:6 exp:6
  } //indent:4 exp:4
}
 
Example 11
Project: Wiab.pro   File: BlockIndexImpl.java   View source code 5 votes vote down vote up
@Override
public synchronized ProtoBlockIndex.BlockIndex serialize() {
  ProtoBlockIndex.BlockIndex.Builder builder = ProtoBlockIndex.BlockIndex.newBuilder();
  builder.setFormatVersion(FORMAT_VERSION);
  if (serialized != null) {
    for (int i=0; i < serialized.getSegmentIdCount(); i++) {
      SegmentId segmentId = SegmentId.of(serialized.getSegmentId(i));
      if (rangeMap.getIfPresent(segmentId) == null) {
        builder.addSegmentId(serialized.getSegmentId(i));
        builder.addSegmentRanges(serialized.getSegmentRanges(i));
      }
    }
  }
  for (Map.Entry<SegmentId, RangeMap<RangeValue, String>> segmentEntry : rangeMap.asMap().entrySet()) {
    builder.addSegmentId(segmentEntry.getKey().toString());
    SegmentRanges.Builder rangesBuilder = builder.addSegmentRangesBuilder();
    Map<Range<RangeValue>, String> mapOfRanges = segmentEntry.getValue().asMapOfRanges();
    for (Map.Entry<Range<RangeValue>, String> range : mapOfRanges.entrySet()) {
      ProtoBlockIndex.BlockIndex.FragmentRange.Builder fragmentBuilder = ProtoBlockIndex.BlockIndex.FragmentRange.newBuilder();
      fragmentBuilder.setSourceVersion(range.getKey().lowerEndpoint().get());
      fragmentBuilder.setTargetVersion(range.getKey().upperEndpoint().get());
      fragmentBuilder.setBlockId(range.getValue());
      rangesBuilder.addRawFragmentRanges(fragmentBuilder.build().toByteString());
    }
  }
  Preconditions.checkArgument(lastModifiedVersion.getVersion() != 0 || rangeMap.asMap().isEmpty(),
      "Last modified version is 0 but range map is not empty");
  builder.setLastModifiedVersion(OperationSerializer.serialize(lastModifiedVersion));
  builder.setLastModifiedTime(lastModifiedTime);
  builder.setConsistent(consistent);
  return builder.build();
}
 
Example 12
Project: dex   File: Opcodes.java   View source code 5 votes vote down vote up
private Opcodes(int api, int artVersion, boolean experimental) {
    this.api = api;
    this.artVersion = artVersion;

    opcodeValues = new EnumMap<Opcode, Short>(Opcode.class);
    opcodesByName = Maps.newHashMap();

    int version;
    if (isArt()) {
        version = artVersion;
    } else {
        version = api;
    }

    for (Opcode opcode: Opcode.values()) {
        RangeMap<Integer, Short> versionToValueMap;

        if (isArt()) {
            versionToValueMap = opcode.artVersionToValueMap;
        } else {
            versionToValueMap = opcode.apiToValueMap;
        }

        Short opcodeValue = versionToValueMap.get(version);
        if (opcodeValue != null && (!opcode.isExperimental() || experimental)) {
            if (!opcode.format.isPayloadFormat) {
                opcodesByValue[opcodeValue] = opcode;
            }
            opcodeValues.put(opcode, opcodeValue);
            opcodesByName.put(opcode.name.toLowerCase(), opcode);
        }
    }
}
 
Example 13
Project: owsi-core-parent   File: AbstractExcelTableExport.java   View source code 5 votes vote down vote up
/**
 * 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);
}
 
Example 14
Project: DexTamper   File: Opcodes.java   View source code 5 votes vote down vote up
private Opcodes(int api, int artVersion, boolean experimental) {
    this.api = api;
    this.artVersion = artVersion;

    opcodeValues = new EnumMap<Opcode, Short>(Opcode.class);
    opcodesByName = Maps.newHashMap();

    int version;
    if (isArt()) {
        version = artVersion;
    } else {
        version = api;
    }

    for (Opcode opcode: Opcode.values()) {
        RangeMap<Integer, Short> versionToValueMap;

        if (isArt()) {
            versionToValueMap = opcode.artVersionToValueMap;
        } else {
            versionToValueMap = opcode.apiToValueMap;
        }

        Short opcodeValue = versionToValueMap.get(version);
        if (opcodeValue != null && (!opcode.isExperimental() || experimental)) {
            if (!opcode.format.isPayloadFormat) {
                opcodesByValue[opcodeValue] = opcode;
            }
            opcodeValues.put(opcode, opcodeValue);
            opcodesByName.put(opcode.name.toLowerCase(), opcode);
        }
    }
}
 
Example 15
Project: pdptw-dataset-generator   File: DatasetGenerator.java   View source code 5 votes vote down vote up
/**
 * 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;
}
 
Example 16
Project: refactor-faster   File: DescriptionBasedDiff.java   View source code 5 votes vote down vote up
private void addReplacement(Replacement replacement) {
  checkNotNull(replacement);
  Range<Integer> range = Range.closedOpen(replacement.startPosition, replacement.endPosition);

  RangeMap<Integer, Replacement> overlaps = replacements.subRangeMap(range);
  checkArgument(overlaps.asMapOfRanges().isEmpty(), "Replacement %s overlaps with %s",
      replacement, overlaps);

  replacements.put(range, replacement);
}
 
Example 17
Project: google-java-format   File: RemoveUnusedImports.java   View source code 5 votes vote down vote up
/** 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;
}
 
Example 18
Project: google-java-format   File: RemoveUnusedImports.java   View source code 5 votes vote down vote up
/** Applies the replacements to the given source, and re-format any edited javadoc. */
private static String applyReplacements(String source, RangeMap<Integer, String> replacements) {
  // save non-empty fixed ranges for reformatting after fixes are applied
  RangeSet<Integer> fixedRanges = TreeRangeSet.create();

  // Apply the fixes in increasing order, adjusting ranges to account for
  // earlier fixes that change the length of the source. The output ranges are
  // needed so we can reformat fixed regions, otherwise the fixes could just
  // be applied in descending order without adjusting offsets.
  StringBuilder sb = new StringBuilder(source);
  int offset = 0;
  for (Map.Entry<Range<Integer>, String> replacement : replacements.asMapOfRanges().entrySet()) {
    Range<Integer> range = replacement.getKey();
    String replaceWith = replacement.getValue();
    int start = offset + range.lowerEndpoint();
    int end = offset + range.upperEndpoint();
    sb.replace(start, end, replaceWith);
    if (!replaceWith.isEmpty()) {
      fixedRanges.add(Range.closedOpen(start, end));
    }
    offset += replaceWith.length() - (range.upperEndpoint() - range.lowerEndpoint());
  }
  String result = sb.toString();

  // If there were any non-empty replaced ranges (e.g. javadoc), reformat the fixed regions.
  // We could avoid formatting twice in --fix-imports=also mode, but that is not the default
  // and removing imports won't usually affect javadoc.
  if (!fixedRanges.isEmpty()) {
    try {
      result = new Formatter().formatSource(result, fixedRanges.asRanges());
    } catch (FormatterException e) {
      // javadoc reformatting is best-effort
    }
  }
  return result;
}
 
Example 19
Project: horizondb   File: TimeSeries.java   View source code 5 votes vote down vote up
public void write(DataBlock block,
                  ListenableFuture<ReplayPosition> future,
                  boolean replay) throws IOException, HorizonDBException {

    RangeMap<Field, DataBlock> blocks = block.split(this.definition);

    for (Entry<Range<Field>, DataBlock> entry : blocks.asMapOfRanges().entrySet()) {  
        writeToPartition(toPartitionId(entry.getKey()), entry.getValue(), future, replay);
    }
}
 
Example 20
Project: gatk   File: GVCFWriter.java   View source code 5 votes vote down vote up
/**
 * 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;
}
 
Example 21
Project: java-util-examples   File: RangeMapExample.java   View source code 5 votes vote down vote up
@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);
}
 
Example 22
Project: Refaster   File: DescriptionBasedDiff.java   View source code 5 votes vote down vote up
private void addReplacement(Replacement replacement) {
  checkNotNull(replacement);
  Range<Integer> range = Range.closedOpen(replacement.startPosition, replacement.endPosition);

  RangeMap<Integer, Replacement> overlaps = replacements.subRangeMap(range);
  checkArgument(overlaps.asMapOfRanges().isEmpty(), "Replacement %s overlaps with %s",
      replacement, overlaps);

  replacements.put(range, replacement);
}
 
Example 23
Project: checkstyle   File: InputIndentationFromGuava2.java   View source code 5 votes vote down vote up
public V get(int index) { //indent:2 exp:2
  K key = null; //indent:4 exp:4
  int len = 0; //indent:4 exp:4
  checkElementIndex(index, len); //indent:4 exp:4
  int off; //indent:4 exp:4
  RangeMap<K, V> ranges = null; //indent:4 exp:4
  if (index == 0 || index == len - 1) { //indent:4 exp:4
    Object range; //indent:6 exp:6
    return ranges.get(key); //indent:6 exp:6
  } else { //indent:4 exp:4
    return ranges.get(key); //indent:6 exp:6
  } //indent:4 exp:4
}
 
Example 24
Project: levelup-java-examples   File: RangeMapExample.java   View source code 5 votes vote down vote up
@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);
}
 
Example 25
Project: mobilitytestbed   File: ExogenousSpeedLimitSegmentInfluence.java   View source code 5 votes vote down vote up
@Override
public double computedInfluencedSpeed(GraphType graphType, long fromNodeByNodeId, long toNodeByNodeId,
		double originSpeedInmps, double influencedSpeedInmps) {

	GraphTypeAndFromToNodeKey graphTypeAndFromToNodeKey = new GraphTypeAndFromToNodeKey(graphType,
			fromNodeByNodeId, toNodeByNodeId);
	RangeMap<Long, Double> rangeMap = exogenousSpeedLimits.get(graphTypeAndFromToNodeKey);

	if (rangeMap != null && getSpeedLimit(rangeMap) != null) {
		return getSpeedLimit(rangeMap);
	}

	return influencedSpeedInmps;
}
 
Example 26
Project: pinto   File: Cache.java   View source code 4 votes vote down vote up
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;
		}
	}
}
 
Example 27
Project: checkstyle-backport-jre6   File: InputIndentationFromGuava2.java   View source code 4 votes vote down vote up
@Override //indent:2 exp:2
public void putAll(RangeMap<K, V> rangeMap) //indent:2 exp:2
{ //indent:2 exp:2

}
 
Example 28
Project: checkstyle-backport-jre6   File: InputIndentationFromGuava2.java   View source code 4 votes vote down vote up
@Override //indent:2 exp:2
public RangeMap<K, V> subRangeMap(Range<K> range) //indent:2 exp:2
{ //indent:2 exp:2
  return null; //indent:4 exp:4
}
 
Example 29
Project: JCL   File: Opcodes.java   View source code 4 votes vote down vote up
private Opcodes(int api, int artVersion) {


        if (api >= 21) {
            this.api = api;
            this.artVersion = mapApiToArtVersion(api);
        } else if (artVersion >= 0 && artVersion < 39) {
            this.api = mapArtVersionToApi(artVersion);
            this.artVersion = artVersion;
        } else {
            this.api = api;
            this.artVersion = artVersion;
        }

        opcodeValues = new EnumMap<Opcode, Short>(Opcode.class);
        opcodesByName = Maps.newHashMap();

        int version;
        if (isArt()) {
            version = this.artVersion;
        } else {
            version = this.api;
        }

        for (Opcode opcode: Opcode.values()) {
            RangeMap<Integer, Short> versionToValueMap;

            if (isArt()) {
                versionToValueMap = opcode.artVersionToValueMap;
            } else {
                versionToValueMap = opcode.apiToValueMap;
            }

            Short opcodeValue = versionToValueMap.get(version);
            if (opcodeValue != null) {
                if (!opcode.format.isPayloadFormat) {
                    opcodesByValue[opcodeValue] = opcode;
                }
                opcodeValues.put(opcode, opcodeValue);
                opcodesByName.put(opcode.name.toLowerCase(), opcode);
            }
        }
    }
 
Example 30
Project: Wiab.pro   File: BlockIndexImpl.java   View source code 4 votes vote down vote up
@Override
public RangeMap<RangeValue, String> load(SegmentId segmentId) throws Exception {
  return TreeRangeMap.create();
}
 
Example 31
Project: owsi-core-parent   File: AbstractExcelTableExport.java   View source code 4 votes vote down vote up
/**
 * @see #finalizeSheet(Sheet, RangeMap, boolean)
 */
protected void finalizeSheet(Sheet sheet, RangeMap<Integer, ColumnInformation> columnInfos) {
	// Par défaut, le format d'impression est en paysage pour les tableaux Excel
	finalizeSheet(sheet, columnInfos, true);
}
 
Example 32
Project: gondola   File: BucketManager.java   View source code 4 votes vote down vote up
public RangeMap<Integer, ShardState> getBucketMap() {
    return bucketMap;
}
 
Example 33
Project: gatk   File: GVCFWriterUnitTest.java   View source code 4 votes vote down vote up
@Test(dataProvider = "GoodBandPartitionData")
public void testGoodPartitions(final List<Integer> partitions, List<Range<Integer>> expected) {
    final RangeMap<Integer, Range<Integer>> ranges = GVCFWriter.parsePartitions(partitions);
    Assert.assertEquals(new ArrayList<>(ranges.asMapOfRanges().values()), expected);
}
 
Example 34
Project: tcl-regex-java   File: RuntimeColorMap.java   View source code 4 votes vote down vote up
/**
 * Make a runtime color map. It might be sensible for the BMP optimization
 * to be saved someplace and not recomputed here.
 * @param fullMap -- the map as built in {@link com.basistech.tclre.ColorMap}
 */
RuntimeColorMap(RangeMap<Integer, Short> fullMap) {
    this.fullMap = fullMap;
    this.bmpMap = new short[Character.MAX_VALUE + 1];
    computeBmp(fullMap);
}
 
Example 35
Project: jpmml-evaluator   File: DiscretizationUtil.java   View source code 4 votes vote down vote up
@Override
public RangeMap<Double, String> load(Discretize discretize){
	return ImmutableRangeMap.copyOf(parseDiscretize(discretize));
}
 
Example 36
Project: checkstyle   File: InputIndentationFromGuava2.java   View source code 4 votes vote down vote up
@Override //indent:2 exp:2
public void putAll(RangeMap<K, V> rangeMap) //indent:2 exp:2
{ //indent:2 exp:2

}
 
Example 37
Project: checkstyle   File: InputIndentationFromGuava2.java   View source code 4 votes vote down vote up
@Override //indent:2 exp:2
public RangeMap<K, V> subRangeMap(Range<K> range) //indent:2 exp:2
{ //indent:2 exp:2
  return null; //indent:4 exp:4
}
 
Example 38
Project: assertj-guava   File: RangeMapAssert.java   View source code 4 votes vote down vote up
protected RangeMapAssert(final RangeMap<K, V> actual) {
  super(actual, RangeMapAssert.class);
}
 
Example 39
Project: assertj-guava   File: RangeMapAssert.java   View source code 4 votes vote down vote up
protected RangeMap<K, V> getActual() {
  return actual;
}
 
Example 40
Project: assertj-guava   File: Assertions.java   View source code 4 votes vote down vote up
public static <K extends Comparable<K>, V> RangeMapAssert<K, V> assertThat(final RangeMap<K, V> actual) {
  return new RangeMapAssert<>(actual);
}