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

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

Introduction

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

Prototype

public BoundType lowerBoundType() 

Source Link

Document

Returns the type of this range's lower bound: BoundType#CLOSED if the range includes its lower endpoint, BoundType#OPEN if it does not.

Usage

From source file:com.basistech.tclre.ColorMap.java

/**
 * subrange - allocate new subcolors to this range of chars, fill in arcs.
 * The range will overlap existing ranges; even in the simplest case,
 * it will overlap the initial WHITE range. For each existing range that
 * it overlaps, allocate a new color, mark the range as mapping to that color,
 * and add an arc between the states for that color.
 *///w w w  . j a v  a2  s. co  m
void subrange(int from, int to, State lp, State rp) throws RegexException {
    /* Avoid one call to map.get() for each character in the range.
     * This map will usually contain one item, but in complex cases more.
     * For example, if we had [a-f][g-h] and then someone asked for [f-g], there
     * would be two. Each of these new ranges will get a new color via subcolor.
     */
    Map<Range<Integer>, Short> curColors = map.subRangeMap(Range.closed(from, to)).asMapOfRanges();
    /*
     * To avoid concurrent mod problems, we need to copy the ranges we are working from.
     */
    List<Range<Integer>> ranges = Lists.newArrayList(curColors.keySet());
    for (Range<Integer> rangeToProcess : ranges) {
        // bound management here irritating.
        int start = rangeToProcess.lowerEndpoint();
        if (rangeToProcess.lowerBoundType() == BoundType.OPEN) {
            start++;
        }
        int end = rangeToProcess.upperEndpoint();
        if (rangeToProcess.upperBoundType() == BoundType.CLOSED) {
            end++;
        }
        // allocate a new subcolor and account it owning the entire range.
        short color = subcolor(start, end - start);
        compiler.getNfa().newarc(Compiler.PLAIN, color, lp, rp);
    }
}

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);// w  ww. ja v a 2s .c o m
        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.bookkeeper.mledger.impl.ManagedLedgerOfflineBacklog.java

private long getNumberOfEntries(Range<PositionImpl> range,
        NavigableMap<Long, MLDataFormats.ManagedLedgerInfo.LedgerInfo> ledgers) {
    PositionImpl fromPosition = range.lowerEndpoint();
    boolean fromIncluded = range.lowerBoundType() == BoundType.CLOSED;
    PositionImpl toPosition = range.upperEndpoint();
    boolean toIncluded = range.upperBoundType() == BoundType.CLOSED;

    if (fromPosition.getLedgerId() == toPosition.getLedgerId()) {
        // If the 2 positions are in the same ledger
        long count = toPosition.getEntryId() - fromPosition.getEntryId() - 1;
        count += fromIncluded ? 1 : 0;/*from  ww  w .jav  a2  s .  com*/
        count += toIncluded ? 1 : 0;
        return count;
    } else {
        long count = 0;
        // If the from & to are pointing to different ledgers, then we need to :
        // 1. Add the entries in the ledger pointed by toPosition
        count += toPosition.getEntryId();
        count += toIncluded ? 1 : 0;

        // 2. Add the entries in the ledger pointed by fromPosition
        MLDataFormats.ManagedLedgerInfo.LedgerInfo li = ledgers.get(fromPosition.getLedgerId());
        if (li != null) {
            count += li.getEntries() - (fromPosition.getEntryId() + 1);
            count += fromIncluded ? 1 : 0;
        }

        // 3. Add the whole ledgers entries in between
        for (MLDataFormats.ManagedLedgerInfo.LedgerInfo ls : ledgers
                .subMap(fromPosition.getLedgerId(), false, toPosition.getLedgerId(), false).values()) {
            count += ls.getEntries();
        }

        return count;
    }
}

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

@Override
public void allocateGroup(ActorGroup group, Range<Integer> iterations, List<Core> cores, Configuration config) {
    if (group.isStateful()) {
        int minStatefulId = Integer.MAX_VALUE;
        for (Actor a : group.actors())
            if (a instanceof WorkerActor && ((WorkerActor) a).archetype().isStateful())
                minStatefulId = Math.min(minStatefulId, a.id());
        Configuration.SwitchParameter<Integer> param = config.getParameter("Group" + minStatefulId + "Core",
                Configuration.SwitchParameter.class, Integer.class);
        cores.get(param.getValue() % cores.size()).allocate(group, iterations);
        return;/*from   www . ja  v a2s  .c o m*/
    }

    Configuration.CompositionParameter param = config.getParameter("Group" + group.id() + "Cores",
            Configuration.CompositionParameter.class);
    assert iterations.lowerBoundType() == BoundType.CLOSED && iterations.upperBoundType() == BoundType.OPEN;
    int totalAvailable = iterations.upperEndpoint() - iterations.lowerEndpoint();
    int[] allocations = new int[cores.size()];
    int totalAllocated = 0;
    for (int i = 0; i < param.getLength() && i < allocations.length; ++i) {
        int allocation = DoubleMath.roundToInt(param.getValue(i) * totalAvailable, RoundingMode.HALF_EVEN);
        allocations[i] = allocation;
        totalAllocated += allocation;
    }
    //If we allocated more than we have, remove from the cores with the least.
    //Need a loop here because we might not have enough on the least core.
    while (totalAllocated > totalAvailable) {
        int least = Ints.indexOf(allocations, Ints.max(allocations));
        for (int i = 0; i < allocations.length; ++i)
            if (allocations[i] > 0 && allocations[i] < allocations[least])
                least = i;
        int toRemove = Math.min(allocations[least], totalAllocated - totalAvailable);
        allocations[least] -= toRemove;
        totalAllocated -= toRemove;
    }
    //If we didn't allocate enough, allocate on the cores with the most.
    if (totalAllocated < totalAvailable) {
        int most = Ints.indexOf(allocations, Ints.min(allocations));
        for (int i = 0; i < allocations.length; ++i)
            if (allocations[i] > allocations[most])
                most = i;
        allocations[most] += totalAvailable - totalAllocated;
        totalAllocated += totalAvailable - totalAllocated;
    }
    assert totalAllocated == totalAvailable : totalAllocated + " " + totalAvailable;

    int lower = iterations.lowerEndpoint();
    for (int i = 0; i < allocations.length; ++i)
        if (allocations[i] > 0) {
            cores.get(i).allocate(group, Range.closedOpen(lower, lower + allocations[i]));
            lower += allocations[i];
        }
}

From source file:org.eclipse.fx.ui.controls.styledtext.internal.LineNode.java

protected Range<Integer> toGlobal(Range<Integer> range) {
    int lineOffset = this.lineHelper.getOffset(index);
    return Range.range(lineOffset + range.lowerEndpoint(), range.lowerBoundType(),
            lineOffset + range.upperEndpoint(), range.upperBoundType());
}

From source file:org.eclipse.fx.ui.controls.styledtext.internal.LineNode.java

protected Range<Integer> toLocal(Range<Integer> range) {
    int lineOffset = -this.lineHelper.getOffset(index);
    return Range.range(lineOffset + range.lowerEndpoint(), range.lowerBoundType(),
            lineOffset + range.upperEndpoint(), range.upperBoundType());
}

From source file:com.pingcap.tikv.predicates.ScanBuilder.java

private List<KeyRange> buildTableScanKeyRange(TiTableInfo table, List<IndexRange> indexRanges) {
    requireNonNull(table, "Table cannot be null to encoding keyRange");
    requireNonNull(indexRanges, "indexRanges cannot be null to encoding keyRange");

    List<KeyRange> ranges = new ArrayList<>(indexRanges.size());
    for (IndexRange ir : indexRanges) {
        ByteString startKey;/*w  w  w  .j ava  2s .  c o m*/
        ByteString endKey;
        if (ir.hasAccessPoints()) {
            checkArgument(!ir.hasRange(), "Table scan must have one and only one access condition / point");

            Object v = ir.getAccessPoints().get(0);
            checkArgument(v instanceof Long, "Table scan key range must be long value");
            DataType type = ir.getTypes().get(0);
            checkArgument(type instanceof IntegerType, "Table scan key range must be long value");
            startKey = TableCodec.encodeRowKeyWithHandle(table.getId(), (long) v);
            endKey = ByteString.copyFrom(KeyUtils.prefixNext(startKey.toByteArray()));
        } else if (ir.hasRange()) {
            checkArgument(!ir.hasAccessPoints(),
                    "Table scan must have one and only one access condition / point");
            Range r = ir.getRange();
            DataType type = ir.getRangeType();
            checkArgument(type instanceof IntegerType, "Table scan key range must be long value");

            if (!r.hasLowerBound()) {
                // -INF
                // TODO: Domain and encoding should be further encapsulated
                startKey = TableCodec.encodeRowKeyWithHandle(table.getId(), Long.MIN_VALUE);
            } else {
                // Comparision with null should be filtered since it yields unknown always
                Object lb = r.lowerEndpoint();
                checkArgument(lb instanceof Long, "Table scan key range must be long value");
                long lVal = (long) lb;
                if (r.lowerBoundType().equals(BoundType.OPEN)) {
                    // TODO: Need push back?
                    if (lVal != Long.MAX_VALUE) {
                        lVal++;
                    }
                }
                startKey = TableCodec.encodeRowKeyWithHandle(table.getId(), lVal);
            }

            if (!r.hasUpperBound()) {
                // INF
                endKey = TableCodec.encodeRowKeyWithHandle(table.getId(), Long.MAX_VALUE);
            } else {
                Object ub = r.upperEndpoint();
                checkArgument(ub instanceof Long, "Table scan key range must be long value");
                long lVal = (long) ub;
                if (r.upperBoundType().equals(BoundType.CLOSED)) {
                    if (lVal != Long.MAX_VALUE) {
                        lVal++;
                    }
                }
                endKey = TableCodec.encodeRowKeyWithHandle(table.getId(), lVal);
            }
        } else {
            throw new TiClientInternalException("Empty access conditions");
        }

        ranges.add(KeyRange.newBuilder().setStart(startKey).setEnd(endKey).build());
    }

    if (ranges.isEmpty()) {
        ByteString startKey = TableCodec.encodeRowKeyWithHandle(table.getId(), Long.MIN_VALUE);
        ByteString endKey = TableCodec.encodeRowKeyWithHandle(table.getId(), Long.MAX_VALUE);
        ranges.add(KeyRange.newBuilder().setStart(startKey).setEnd(endKey).build());
    }

    return ranges;
}

From source file:org.kiji.schema.impl.cassandra.CQLStatementCache.java

/**
 * Create a CQL statement for selecting the columns that make up the Entity ID from a Cassandra
 * Kiji Table./*from  w w  w  . j  a v a 2s. com*/
 *
 * @param table The translated Cassandra table name.
 * @param tokenRange A range of tokens to scan.
 * @return a statement that will get the single column.
 */
public Statement createEntityIDScanStatement(final CassandraTableName table, final Range<Long> tokenRange) {

    // Retrieve the prepared statement from the cache

    // We can only use the 'DISTINCT' optimization if all entity ID components are part of the
    // partition key. CQL does not allow DISTINCT over non partition-key columns.
    final boolean useDistinct = mEntityIDClusteringColumns.isEmpty();

    final Optional<BoundType> lowerBound = tokenRange.hasLowerBound() ? Optional.of(tokenRange.lowerBoundType())
            : Optional.<BoundType>absent();

    final Optional<BoundType> upperBound = tokenRange.hasUpperBound() ? Optional.of(tokenRange.upperBoundType())
            : Optional.<BoundType>absent();

    final EntityIDScanStatementKey key = new EntityIDScanStatementKey(table, lowerBound, upperBound,
            useDistinct);
    final PreparedStatement statement = mCache.getUnchecked(key);

    // Bind the parameters to the prepared statement

    // slots are for the min/max token
    final List<Object> values = Lists.newArrayListWithCapacity(2);

    if (tokenRange.hasLowerBound()) {
        values.add(tokenRange.lowerEndpoint());
    }

    if (tokenRange.hasUpperBound()) {
        values.add(tokenRange.upperEndpoint());
    }

    return statement.bind(values.toArray()).setFetchSize(ENTITY_ID_BATCH_SIZE);
}

From source file:com.pingcap.tikv.predicates.ScanBuilder.java

private List<KeyRange> buildIndexScanKeyRange(TiTableInfo table, TiIndexInfo index,
        List<IndexRange> indexRanges) {
    requireNonNull(table, "Table cannot be null to encoding keyRange");
    requireNonNull(index, "Index cannot be null to encoding keyRange");
    requireNonNull(index, "indexRanges cannot be null to encoding keyRange");

    List<KeyRange> ranges = new ArrayList<>(indexRanges.size());

    for (IndexRange ir : indexRanges) {
        CodecDataOutput cdo = new CodecDataOutput();
        List<Object> values = ir.getAccessPoints();
        List<DataType> types = ir.getTypes();
        for (int i = 0; i < values.size(); i++) {
            Object v = values.get(i);
            DataType t = types.get(i);//from   w w  w .j  ava  2s  .co  m
            t.encode(cdo, DataType.EncodeType.KEY, v);
        }

        byte[] pointsData = cdo.toBytes();

        cdo.reset();
        Range r = ir.getRange();
        byte[] lPointKey;
        byte[] uPointKey;

        byte[] lKey;
        byte[] uKey;
        if (r == null) {
            lPointKey = pointsData;
            uPointKey = KeyUtils.prefixNext(lPointKey.clone());

            lKey = new byte[0];
            uKey = new byte[0];
        } else {
            lPointKey = pointsData;
            uPointKey = pointsData;

            DataType type = ir.getRangeType();
            if (!r.hasLowerBound()) {
                // -INF
                type.encodeMinValue(cdo);
                lKey = cdo.toBytes();
            } else {
                Object lb = r.lowerEndpoint();
                type.encode(cdo, DataType.EncodeType.KEY, lb);
                lKey = cdo.toBytes();
                if (r.lowerBoundType().equals(BoundType.OPEN)) {
                    lKey = KeyUtils.prefixNext(lKey);
                }
            }

            cdo.reset();
            if (!r.hasUpperBound()) {
                // INF
                type.encodeMaxValue(cdo);
                uKey = cdo.toBytes();
            } else {
                Object ub = r.upperEndpoint();
                type.encode(cdo, DataType.EncodeType.KEY, ub);
                uKey = cdo.toBytes();
                if (r.upperBoundType().equals(BoundType.CLOSED)) {
                    uKey = KeyUtils.prefixNext(lKey);
                }
            }

            cdo.reset();
        }
        TableCodec.writeIndexSeekKey(cdo, table.getId(), index.getId(), lPointKey, lKey);

        ByteString lbsKey = ByteString.copyFrom(cdo.toBytes());

        cdo.reset();
        TableCodec.writeIndexSeekKey(cdo, table.getId(), index.getId(), uPointKey, uKey);
        ByteString ubsKey = ByteString.copyFrom(cdo.toBytes());

        ranges.add(KeyRange.newBuilder().setStart(lbsKey).setEnd(ubsKey).build());
    }

    if (ranges.isEmpty()) {
        ranges.add(INDEX_FULL_RANGE);
    }
    return ranges;
}

From source file:org.apache.calcite.rex.RexSimplify.java

private static RexNode processRange(RexBuilder rexBuilder, List<RexNode> terms,
        Map<String, Pair<Range, List<RexNode>>> rangeTerms, RexNode term, RexNode ref, RexLiteral constant,
        SqlKind comparison) {/*ww  w .j av  a 2  s  .  c  om*/
    final Comparable v0 = constant.getValue();
    Pair<Range, List<RexNode>> p = rangeTerms.get(ref.toString());
    if (p == null) {
        Range r;
        switch (comparison) {
        case EQUALS:
            r = Range.singleton(v0);
            break;
        case LESS_THAN:
            r = Range.lessThan(v0);
            break;
        case LESS_THAN_OR_EQUAL:
            r = Range.atMost(v0);
            break;
        case GREATER_THAN:
            r = Range.greaterThan(v0);
            break;
        case GREATER_THAN_OR_EQUAL:
            r = Range.atLeast(v0);
            break;
        default:
            throw new AssertionError();
        }
        rangeTerms.put(ref.toString(), new Pair(r, ImmutableList.of(term)));
    } else {
        // Exists
        boolean removeUpperBound = false;
        boolean removeLowerBound = false;
        Range r = p.left;
        switch (comparison) {
        case EQUALS:
            if (!r.contains(v0)) {
                // Range is empty, not satisfiable
                return rexBuilder.makeLiteral(false);
            }
            rangeTerms.put(ref.toString(), new Pair(Range.singleton(v0), ImmutableList.of(term)));
            // remove
            terms.removeAll(p.right);
            break;
        case LESS_THAN: {
            int comparisonResult = 0;
            if (r.hasUpperBound()) {
                comparisonResult = v0.compareTo(r.upperEndpoint());
            }
            if (comparisonResult <= 0) {
                // 1) No upper bound, or
                // 2) We need to open the upper bound, or
                // 3) New upper bound is lower than old upper bound
                if (r.hasLowerBound()) {
                    if (v0.compareTo(r.lowerEndpoint()) < 0) {
                        // Range is empty, not satisfiable
                        return rexBuilder.makeLiteral(false);
                    }
                    // a <= x < b OR a < x < b
                    r = Range.range(r.lowerEndpoint(), r.lowerBoundType(), v0, BoundType.OPEN);
                } else {
                    // x < b
                    r = Range.lessThan(v0);
                }

                if (r.isEmpty()) {
                    // Range is empty, not satisfiable
                    return rexBuilder.makeLiteral(false);
                }

                // remove prev upper bound
                removeUpperBound = true;
            } else {
                // Remove this term as it is contained in current upper bound
                terms.remove(term);
            }
            break;
        }
        case LESS_THAN_OR_EQUAL: {
            int comparisonResult = -1;
            if (r.hasUpperBound()) {
                comparisonResult = v0.compareTo(r.upperEndpoint());
            }
            if (comparisonResult < 0) {
                // 1) No upper bound, or
                // 2) New upper bound is lower than old upper bound
                if (r.hasLowerBound()) {
                    if (v0.compareTo(r.lowerEndpoint()) < 0) {
                        // Range is empty, not satisfiable
                        return rexBuilder.makeLiteral(false);
                    }
                    // a <= x <= b OR a < x <= b
                    r = Range.range(r.lowerEndpoint(), r.lowerBoundType(), v0, BoundType.CLOSED);
                } else {
                    // x <= b
                    r = Range.atMost(v0);
                }

                if (r.isEmpty()) {
                    // Range is empty, not satisfiable
                    return rexBuilder.makeLiteral(false);
                }

                // remove prev upper bound
                removeUpperBound = true;
            } else {
                // Remove this term as it is contained in current upper bound
                terms.remove(term);
            }
            break;
        }
        case GREATER_THAN: {
            int comparisonResult = 0;
            if (r.hasLowerBound()) {
                comparisonResult = v0.compareTo(r.lowerEndpoint());
            }
            if (comparisonResult >= 0) {
                // 1) No lower bound, or
                // 2) We need to open the lower bound, or
                // 3) New lower bound is greater than old lower bound
                if (r.hasUpperBound()) {
                    if (v0.compareTo(r.upperEndpoint()) > 0) {
                        // Range is empty, not satisfiable
                        return rexBuilder.makeLiteral(false);
                    }
                    // a < x <= b OR a < x < b
                    r = Range.range(v0, BoundType.OPEN, r.upperEndpoint(), r.upperBoundType());
                } else {
                    // x > a
                    r = Range.greaterThan(v0);
                }

                if (r.isEmpty()) {
                    // Range is empty, not satisfiable
                    return rexBuilder.makeLiteral(false);
                }

                // remove prev lower bound
                removeLowerBound = true;
            } else {
                // Remove this term as it is contained in current lower bound
                terms.remove(term);
            }
            break;
        }
        case GREATER_THAN_OR_EQUAL: {
            int comparisonResult = 1;
            if (r.hasLowerBound()) {
                comparisonResult = v0.compareTo(r.lowerEndpoint());
            }
            if (comparisonResult > 0) {
                // 1) No lower bound, or
                // 2) New lower bound is greater than old lower bound
                if (r.hasUpperBound()) {
                    if (v0.compareTo(r.upperEndpoint()) > 0) {
                        // Range is empty, not satisfiable
                        return rexBuilder.makeLiteral(false);
                    }
                    // a <= x <= b OR a <= x < b
                    r = Range.range(v0, BoundType.CLOSED, r.upperEndpoint(), r.upperBoundType());
                } else {
                    // x >= a
                    r = Range.atLeast(v0);
                }

                if (r.isEmpty()) {
                    // Range is empty, not satisfiable
                    return rexBuilder.makeLiteral(false);
                }

                // remove prev lower bound
                removeLowerBound = true;
            } else {
                // Remove this term as it is contained in current lower bound
                terms.remove(term);
            }
            break;
        }
        default:
            throw new AssertionError();
        }
        if (removeUpperBound) {
            ImmutableList.Builder<RexNode> newBounds = ImmutableList.builder();
            for (RexNode e : p.right) {
                if (e.isA(SqlKind.LESS_THAN) || e.isA(SqlKind.LESS_THAN_OR_EQUAL)) {
                    terms.remove(e);
                } else {
                    newBounds.add(e);
                }
            }
            newBounds.add(term);
            rangeTerms.put(ref.toString(), new Pair(r, newBounds.build()));
        } else if (removeLowerBound) {
            ImmutableList.Builder<RexNode> newBounds = ImmutableList.builder();
            for (RexNode e : p.right) {
                if (e.isA(SqlKind.GREATER_THAN) || e.isA(SqlKind.GREATER_THAN_OR_EQUAL)) {
                    terms.remove(e);
                } else {
                    newBounds.add(e);
                }
            }
            newBounds.add(term);
            rangeTerms.put(ref.toString(), new Pair(r, newBounds.build()));
        }
    }
    // Default
    return null;
}