Example usage for com.google.common.collect Range closedOpen

List of usage examples for com.google.common.collect Range closedOpen

Introduction

In this page you can find the example usage for com.google.common.collect Range closedOpen.

Prototype

public static <C extends Comparable<?>> Range<C> closedOpen(C lower, C upper) 

Source Link

Document

Returns a range that contains all values greater than or equal to lower and strictly less than upper .

Usage

From source file:com.google.googlejavaformat.java.ModifierOrderer.java

/**
 * Reorders all modifiers in the given text and within the given character ranges to be in JLS
 * order.// w ww .j  a  v a  2 s. c  om
 */
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);
}

From source file:edu.mit.streamjit.impl.compiler2.DescendingShareAllocationStrategy.java

@Override
public void allocateGroup(ActorGroup group, Range<Integer> iterations, List<Core> cores, Configuration config) {
    List<Float> shares = new ArrayList<>(cores.size());
    for (int core = 0; core < cores.size(); ++core) {
        String name = String.format("node%dcore%diter", group.id(), core);
        Configuration.FloatParameter parameter = config.getParameter(name, Configuration.FloatParameter.class);
        if (parameter == null)
            shares.add(0f);// ww w.  j  a v  a 2 s  .c  om
        else
            shares.add(parameter.getValue());
    }

    assert iterations.lowerBoundType() == BoundType.CLOSED && iterations.upperBoundType() == BoundType.OPEN;
    int totalAvailable = iterations.upperEndpoint() - iterations.lowerEndpoint();
    while (!iterations.isEmpty()) {
        int max = CollectionUtils.maxIndex(shares);
        float share = shares.get(max);
        if (share == 0)
            break;
        int amount = DoubleMath.roundToInt(share * totalAvailable, RoundingMode.HALF_EVEN);
        int done = iterations.lowerEndpoint();
        Range<Integer> allocation = group.isStateful() ? iterations
                : iterations.intersection(Range.closedOpen(done, done + amount));
        cores.get(max).allocate(group, allocation);
        iterations = Range.closedOpen(allocation.upperEndpoint(), iterations.upperEndpoint());
        shares.set(max, 0f); //don't allocate to this core again
    }

    //If we have iterations left over not assigned to a core, spread them
    //evenly over all cores.
    if (!iterations.isEmpty()) {
        int perCore = IntMath.divide(iterations.upperEndpoint() - iterations.lowerEndpoint(), cores.size(),
                RoundingMode.CEILING);
        for (int i = 0; i < cores.size() && !iterations.isEmpty(); ++i) {
            int min = iterations.lowerEndpoint();
            Range<Integer> allocation = group.isStateful() ? iterations
                    : iterations.intersection(Range.closedOpen(min, min + perCore));
            cores.get(i).allocate(group, allocation);
            iterations = Range.closedOpen(allocation.upperEndpoint(), iterations.upperEndpoint());
        }
    }
    assert iterations.isEmpty();
}

From source file:org.apache.drill.exec.store.AffinityCalculator.java

/**
 * For a given RowGroup, calculate how many bytes are available on each on drillbit endpoint
 *
 * @param rowGroup the RowGroup to calculate endpoint bytes for
 *//*from  ww w. j av a  2 s.c  om*/
public void setEndpointBytes(ParquetGroupScan.RowGroupInfo rowGroup) {
    Stopwatch watch = new Stopwatch();
    watch.start();
    String fileName = rowGroup.getPath();
    if (!blockMapMap.containsKey(fileName)) {
        buildBlockMap(fileName);
    }

    ImmutableRangeMap<Long, BlockLocation> blockMap = blockMapMap.get(fileName);
    HashMap<String, Long> hostMap = new HashMap<>();
    HashMap<DrillbitEndpoint, Long> endpointByteMap = new HashMap();
    long start = rowGroup.getStart();
    long end = start + rowGroup.getLength();
    Range<Long> rowGroupRange = Range.closedOpen(start, end);

    // Find submap of ranges that intersect with the rowGroup
    ImmutableRangeMap<Long, BlockLocation> subRangeMap = blockMap.subRangeMap(rowGroupRange);

    // Iterate through each block in this submap and get the host for the block location
    for (Map.Entry<Range<Long>, BlockLocation> block : subRangeMap.asMapOfRanges().entrySet()) {
        String[] hosts;
        Range<Long> blockRange = block.getKey();
        try {
            hosts = block.getValue().getHosts();
        } catch (IOException ioe) {
            throw new RuntimeException("Failed to get hosts for block location", ioe);
        }
        Range<Long> intersection = rowGroupRange.intersection(blockRange);
        long bytes = intersection.upperEndpoint() - intersection.lowerEndpoint();

        // For each host in the current block location, add the intersecting bytes to the corresponding endpoint
        for (String host : hosts) {
            DrillbitEndpoint endpoint = getDrillBitEndpoint(host);
            if (endpointByteMap.containsKey(endpoint)) {
                endpointByteMap.put(endpoint, endpointByteMap.get(endpoint) + bytes);
            } else {
                if (endpoint != null)
                    endpointByteMap.put(endpoint, bytes);
            }
        }
    }

    rowGroup.setEndpointBytes(endpointByteMap);
    rowGroup.setMaxBytes(endpointByteMap.size() > 0 ? Collections.max(endpointByteMap.values()) : 0);
    logger.debug("Row group ({},{}) max bytes {}", rowGroup.getPath(), rowGroup.getStart(),
            rowGroup.getMaxBytes());
    watch.stop();
    logger.debug("Took {} ms to set endpoint bytes", watch.elapsed(TimeUnit.MILLISECONDS));
}

From source file:com.google.googlejavaformat.java.GoogleJavaFormatter.java

private List<Range<Integer>> rangesFromRegions(IRegion[] regions) {
    List<Range<Integer>> ranges = new ArrayList<>();
    for (IRegion region : regions) {
        ranges.add(Range.closedOpen(region.getOffset(), region.getOffset() + region.getLength()));
    }/*w  ww  .  ja  va2s.com*/
    return ranges;
}

From source file:it.units.malelab.ege.ge.mapper.BitsSGEMapper.java

@Override
public Node<T> map(BitsGenotype genotype, Map<String, Object> report) throws MappingException {
    int[] bitUsages = new int[genotype.size()];
    //transform genotypes in ints
    if (genotype.size() < overallSize) {
        throw new MappingException(String.format("Short genotype (%d<%d)", genotype.size(), overallSize));
    }/*  www  .  j  av a  2s  .c o m*/
    Map<Pair<T, Integer>, List<Range<Integer>>> codonRanges = new LinkedHashMap<>();
    List<Range<Integer>> nonTerminalRanges = Utils.slices(Range.closedOpen(0, genotype.size()),
            nonTerminalSizes);
    for (int i = 0; i < nonTerminals.size(); i++) {
        //int codonSize = (int) Math.max(Math.ceil(Math.log10(nonRecursiveGrammar.getRules().get(nonTerminals.get(i)).size()) / Math.log10(2)), 1);
        List<Range<Integer>> boundaries = Utils.slices(nonTerminalRanges.get(i),
                nonTerminalCodonsNumbers.get(i));
        codonRanges.put(nonTerminals.get(i), boundaries);
    }
    //map
    Multiset<Pair<T, Integer>> expandedSymbols = LinkedHashMultiset.create();
    Node<Pair<T, Integer>> tree = new Node<>(nonRecursiveGrammar.getStartingSymbol());
    while (true) {
        Node<Pair<T, Integer>> nodeToBeReplaced = null;
        for (Node<Pair<T, Integer>> node : tree.leafNodes()) {
            if (nonRecursiveGrammar.getRules().keySet().contains(node.getContent())) {
                nodeToBeReplaced = node;
                break;
            }
        }
        if (nodeToBeReplaced == null) {
            break;
        }
        //get codon
        Range<Integer> range = codonRanges.get(nodeToBeReplaced.getContent())
                .get(expandedSymbols.count(nodeToBeReplaced.getContent()));
        List<List<Pair<T, Integer>>> options = nonRecursiveGrammar.getRules()
                .get(nodeToBeReplaced.getContent());
        int codonSize = (int) Math.max(Math.ceil(Math.log10(options.size()) / Math.log10(2)), 1);
        int codonValue = genotype.slice(range).compress(codonSize).toInt();
        int optionIndex = codonValue % options.size();
        //update usages
        for (int i = range.lowerEndpoint(); i < range.upperEndpoint(); i++) {
            bitUsages[i] = bitUsages[i] + 1;
        }
        //add children
        for (Pair<T, Integer> p : options.get(optionIndex)) {
            Node<Pair<T, Integer>> newChild = new Node<>(p);
            nodeToBeReplaced.getChildren().add(newChild);
        }
        expandedSymbols.add(nodeToBeReplaced.getContent());
    }
    report.put(BIT_USAGES_INDEX_NAME, bitUsages);
    //transform tree
    return transform(tree);
}

From source file:com.github.fge.largetext.range.LongRange.java

/**
 * Return this range as a Guava {@link Range}
 *
 * @return a Guava range//w ww.ja  v a2s.c o  m
 * @see RangeMap
 */
public Range<Long> asGuavaRange() {
    return Range.closedOpen(lowerBound, upperBound);
}

From source file:com.pingcap.tikv.Snapshot.java

public List<KvPair> batchGet(List<ByteString> keys) {
    Region curRegion = null;// ww  w  .ja  v  a  2  s. c  om
    Range<ByteBuffer> curKeyRange = null;
    Pair<Region, Store> lastPair = null;
    List<ByteString> keyBuffer = new ArrayList<>();
    List<KvPair> result = new ArrayList<>(keys.size());
    for (ByteString key : keys) {
        if (curRegion == null || !curKeyRange.contains(key.asReadOnlyByteBuffer())) {
            Pair<Region, Store> pair = regionCache.getRegionStorePairByKey(key);
            lastPair = pair;
            curRegion = pair.first;
            curKeyRange = Range.closedOpen(curRegion.getStartKey().asReadOnlyByteBuffer(),
                    curRegion.getEndKey().asReadOnlyByteBuffer());
            if (lastPair != null) {
                try (RegionStoreClient client = RegionStoreClient.create(lastPair.first, lastPair.second,
                        getSession())) {
                    List<KvPair> partialResult = client.batchGet(keyBuffer, version.getVersion());
                    for (KvPair kv : partialResult) {
                        // TODO: Add lock check
                        result.add(kv);
                    }
                } catch (Exception e) {
                    throw new TiClientInternalException("Error Closing Store client.", e);
                }
                keyBuffer = new ArrayList<>();
            }
            keyBuffer.add(key);
        }
    }
    return result;
}

From source file:com.wealdtech.collect.TreeRangedMap.java

@Override
public void put(final Range<K> key, final V value) {
    validateRange(key);/* w w w . java2s .  c om*/
    K resultantStart = key.lowerEndpoint();
    K resultantEnd = key.upperEndpoint();

    // Truncate or coalesce anything which overlaps the start of our new entry
    final Map.Entry<K, TwoTuple<Range<K>, V>> prior = getEntry(key.lowerEndpoint());
    if (prior != null) {
        if (prior.getValue().getT().equals(value)) {
            // Values are the same so we can coalesce.
            if (resultantEnd.compareTo(prior.getValue().getS().upperEndpoint()) < 0) {
                // Existing entry already covers this; we don't have to do anything more
                return;
            }
            underlying.remove(prior.getKey());
            // Set our start to the start of the prior entry
            resultantStart = prior.getKey();
        } else {
            // Values are different; truncate prior item
            underlying.put(prior.getKey(),
                    new TwoTuple<>(Range.closedOpen(prior.getKey(), resultantStart), prior.getValue().getT()));
            // If the prior entry stretches beyond the new entry we also need to put in our remaining item
            if (resultantEnd.compareTo(prior.getValue().getS().upperEndpoint()) < 0) {
                underlying.put(resultantEnd,
                        new TwoTuple<>(Range.closedOpen(resultantEnd, prior.getValue().getS().upperEndpoint()),
                                prior.getValue().getT()));
            }

        }
    }

    // Remove any items which are covered by our new entry, and truncate or coalesce anything which overlaps the end of it
    Map.Entry<K, TwoTuple<Range<K>, V>> potentialVictim = underlying.ceilingEntry(resultantStart);
    while (potentialVictim != null) {
        if (key.encloses(potentialVictim.getValue().getS())) {
            // Totally enclosed; remove it
            underlying.remove(potentialVictim.getKey());
            potentialVictim = underlying.ceilingEntry(resultantStart);
        } else if (key.contains(potentialVictim.getKey())) {
            // Partial overlap
            if (potentialVictim.getValue().getT().equals(value)) {
                // Values are the same so we can coalesce.  Remove the entry and update our bounds accordingly
                resultantEnd = potentialVictim.getValue().getS().upperEndpoint();
                underlying.remove(potentialVictim.getKey());
            } else {
                // Values are different; truncate victim item
                underlying.remove(potentialVictim.getKey());
                underlying.put(resultantEnd,
                        new TwoTuple<>(
                                Range.closedOpen(resultantEnd,
                                        potentialVictim.getValue().getS().upperEndpoint()),
                                potentialVictim.getValue().getT()));
            }
            potentialVictim = null;
        } else {
            // No relationship
            potentialVictim = null;
        }
    }

    // Write out our final result
    underlying.put(resultantStart, new TwoTuple<>(Range.closedOpen(resultantStart, resultantEnd), value));
}

From source file:com.pingcap.tikv.RegionManager.java

private static Range<ByteBuffer> makeRange(ByteString startKey, ByteString endKey) {
    return Range.closedOpen(startKey.asReadOnlyByteBuffer(), endKey.asReadOnlyByteBuffer());
}

From source file:com.wealdtech.jackson.modules.DateTimeRangeDeserializer.java

public static Range<DateTime> deserialize(final String txt) throws IOException {
      final int txtLen = txt.length();

      final int firstDateChar;
      boolean lowerClosed;
      if (txt.charAt(0) == '[') {
          firstDateChar = 1;//from   w  w w  .  j a v a2  s. co m
          lowerClosed = true;
      } else if (txt.charAt(0) == '(') {
          firstDateChar = 1;
          lowerClosed = false;
      } else if (txt.charAt(0) >= '0' && txt.charAt(0) <= '9') {
          // Lazy version
          firstDateChar = 0;
          lowerClosed = true;
      } else {
          throw new DataError.Bad("Unexpected first character in range \"" + txt + "\"");
      }

      boolean upperClosed;
      if (txt.charAt(txtLen - 1) == ']') {
          upperClosed = true;
      } else if (txt.charAt(txtLen - 1) == ')') {
          upperClosed = false;
      } else if (firstDateChar == 0) {
          upperClosed = false;
      } else {
          throw new DataError.Bad("Unexpected last character in range \"" + txt + "\"");
      }

      final Iterator<String> dateTimes;
      if (txt.indexOf(WEALD_SPLITTER_CHAR) != -1) {
          dateTimes = WEALD_SPLITTER.split(txt.substring(firstDateChar, txtLen - firstDateChar)).iterator();
      } else if (txt.indexOf(GUAVA_SPLITTER_CHAR) != -1) {
          dateTimes = GUAVA_SPLITTER.split(txt.substring(firstDateChar, txtLen - firstDateChar)).iterator();
      } else {
          throw new DataError.Bad("Cannot find a range separator in range \"" + txt + "\"");
      }
      String start = dateTimes.next();
      String end = dateTimes.next();

      boolean lowerBound;
      final DateTime lowerPoint;
      if (start.equals(NEGATIVE_INFINITY)) {
          lowerBound = false;
          lowerPoint = null;
      } else {
          lowerBound = true;
          lowerPoint = DateTimeDeserializer.deserialize(start);
      }

      boolean upperBound;
      final DateTime upperPoint;
      if (end.equals(POSITIVE_INFINITY)) {
          upperBound = false;
          upperPoint = null;
      } else {
          upperBound = true;
          upperPoint = DateTimeDeserializer.deserialize(end);
      }

      if (lowerBound == false && upperBound == false) {
          return Range.all();
      } else if (lowerBound == false) {
          // Upper present
          if (upperClosed == true) {
              return Range.lessThan(upperPoint);
          } else {
              return Range.atMost(upperPoint);
          }
      } else if (upperBound == false) {
          // Lower present
          if (lowerClosed == true) {
              return Range.atLeast(lowerPoint);
          } else {
              return Range.greaterThan(lowerPoint);
          }
      } else {
          // Both present
          if (lowerClosed == true) {
              if (upperClosed == true) {
                  return Range.closed(lowerPoint, upperPoint);
              } else {
                  return Range.closedOpen(lowerPoint, upperPoint);
              }
          } else {
              if (upperClosed == true) {
                  return Range.openClosed(lowerPoint, upperPoint);
              } else {
                  return Range.open(lowerPoint, upperPoint);
              }
          }
      }
  }