Example usage for com.google.common.collect BoundType CLOSED

List of usage examples for com.google.common.collect BoundType CLOSED

Introduction

In this page you can find the example usage for com.google.common.collect BoundType CLOSED.

Prototype

BoundType CLOSED

To view the source code for com.google.common.collect BoundType CLOSED.

Click Source Link

Document

The endpoint value is considered part of the set ("inclusive").

Usage

From source file:de.bloxel.engine.data.VolumeGrid.java

public void init() {
    final int x1 = -(gridSizeX >> 1);
    final int x2 = -x1;
    final int y1 = -(gridSizeY >> 1);
    final int y2 = -y1;
    final int z1 = -(gridSizeZ >> 1);
    final int z2 = -z1;
    rangeX = range(x1, BoundType.CLOSED, x2, BoundType.CLOSED);
    rangeY = range(y1, BoundType.CLOSED, y2, BoundType.CLOSED);
    rangeZ = range(z1, BoundType.CLOSED, z2, BoundType.CLOSED);
    grid = ObjectFactory3D.sparse.make(gridSizeX + 1, gridSizeY + 1, gridSizeZ + 1);
    LOG.debug(format("Init volume grid (x:%s,y:%s,z:%s)", rangeX, rangeY, rangeZ));
}

From source file:com.google.android.apps.forscience.whistlepunk.sensordb.SensorDatabaseImpl.java

/**
 * Gets the selection string and selectionArgs based on the tag, range and resolution tier.
 *
 * @return a pair where the first element is the selection string and the second element is the
 * array of selectionArgs./*from  w w  w  .  ja  va  2 s  . c om*/
 */
private Pair<String, String[]> getSelectionAndArgs(String sensorTag, TimeRange range, int resolutionTier) {
    List<String> clauses = new ArrayList<>();
    List<String> values = new ArrayList<>();

    clauses.add(ScalarSensorsTable.Column.TAG + " = ?");
    values.add(sensorTag);

    if (resolutionTier >= 0) {
        clauses.add(ScalarSensorsTable.Column.RESOLUTION_TIER + " = ?");
        values.add(String.valueOf(resolutionTier));
    }

    Range<Long> times = range.getTimes();
    Range<Long> canonicalTimes = times.canonical(DiscreteDomain.longs());
    if (canonicalTimes.hasLowerBound()) {
        String comparator = (canonicalTimes.lowerBoundType() == BoundType.CLOSED) ? " >= ?" : " > ?";
        clauses.add(ScalarSensorsTable.Column.TIMESTAMP_MILLIS + comparator);
        values.add(String.valueOf(canonicalTimes.lowerEndpoint()));
    }
    if (canonicalTimes.hasUpperBound()) {
        String comparator = (canonicalTimes.upperBoundType() == BoundType.CLOSED) ? " =< ?" : " < ?";
        clauses.add(ScalarSensorsTable.Column.TIMESTAMP_MILLIS + comparator);
        values.add(String.valueOf(canonicalTimes.upperEndpoint()));
    }

    return new Pair<>(Joiner.on(" AND ").join(clauses), values.toArray(new String[values.size()]));
}

From source file:org.apache.mahout.math.neighborhood.ProjectionSearch.java

/**
 * Searches for the query vector returning the closest limit referenceVectors.
 *
 * @param query the vector to search for.
 * @param limit the number of results to return.
 * @return a list of Vectors wrapped in WeightedThings where the "thing"'s weight is the
 * distance./*from ww w.  java2 s.  co m*/
 */
@Override
public List<WeightedThing<Vector>> search(Vector query, int limit) {
    Set<Vector> candidates = Sets.newHashSet();

    Iterator<? extends Vector> projections = basisMatrix.iterator();
    for (TreeMultiset<WeightedThing<Vector>> v : scalarProjections) {
        Vector basisVector = projections.next();
        WeightedThing<Vector> projectedQuery = new WeightedThing<Vector>(query, query.dot(basisVector));
        for (WeightedThing<Vector> candidate : Iterables.concat(
                Iterables.limit(v.tailMultiset(projectedQuery, BoundType.CLOSED), searchSize), Iterables.limit(
                        v.headMultiset(projectedQuery, BoundType.OPEN).descendingMultiset(), searchSize))) {
            candidates.add(candidate.getValue());
        }
    }

    // If searchSize * scalarProjections.size() is small enough not to cause much memory pressure,
    // this is probably just as fast as a priority queue here.
    List<WeightedThing<Vector>> top = Lists.newArrayList();
    for (Vector candidate : candidates) {
        top.add(new WeightedThing<Vector>(candidate, distanceMeasure.distance(query, candidate)));
    }
    Collections.sort(top);
    return top.subList(0, Math.min(limit, top.size()));
}

From source file:org.cinchapi.concourse.server.model.Ranges.java

/**
 * Return a new {@link Range} that is the merger (e.g. union) of {@code a}
 * and {@code b}. The new {@link Range} maintains both the lower and higher
 * endpoint/bound between the two inputs.
 * //from   w  w w  .j a  va  2  s  .  c om
 * @param a
 * @param b
 * @return the union of {@code a} and {@code b}
 */
public static Range<Value> merge(Range<Value> a, Range<Value> b) {
    if (a.isConnected(b)) {
        boolean aStart = compareToLower(a, b) < 0;
        boolean aEnd = compareToUpper(a, b) > 0;
        boolean lower = getLowerBoundType(aStart ? a : b) == BoundType.CLOSED;
        boolean upper = getUpperBoundType(aStart ? a : b) == BoundType.CLOSED;
        if (lower && upper) {
            return Range.closed(getLowerEndpoint(aStart ? a : b), getUpperEndpoint(aEnd ? a : b));
        } else if (!lower && upper) {
            return Range.closedOpen(getLowerEndpoint(aStart ? a : b), getUpperEndpoint(aEnd ? a : b));
        } else if (lower && !upper) {
            return Range.openClosed(getLowerEndpoint(aStart ? a : b), getUpperEndpoint(aEnd ? a : b));
        } else {
            return Range.open(getLowerEndpoint(aStart ? a : b), getUpperEndpoint(aEnd ? a : b));
        }
    } else {
        return null;
    }
}

From source file:org.nmdp.ngs.fca.Interval.java

private BoundType reverse(final BoundType type) {
    return this.range.upperBoundType() == BoundType.OPEN ? BoundType.CLOSED : BoundType.OPEN;
}

From source file:org.apache.kylin.common.util.RangeUtil.java

public static String formatTsRange(Range<Long> tsRange) {
    if (tsRange == null)
        return null;

    StringBuilder sb = new StringBuilder();
    if (tsRange.hasLowerBound()) {
        if (tsRange.lowerBoundType() == BoundType.CLOSED) {
            sb.append("[");
        } else {/*from   www. j a v  a 2 s.c om*/
            sb.append("(");
        }
        sb.append(DateFormat.formatToTimeStr(tsRange.lowerEndpoint()));
    } else {
        sb.append("(-");
    }

    sb.append("~");

    if (tsRange.hasUpperBound()) {
        sb.append(DateFormat.formatToTimeStr(tsRange.upperEndpoint()));
        if (tsRange.upperBoundType() == BoundType.CLOSED) {
            sb.append("]");
        } else {
            sb.append(")");
        }
    } else {
        sb.append("+)");
    }
    return sb.toString();
}

From source file:net.sourceforge.ganttproject.task.algorithm.SchedulerImpl.java

private void schedule(Node node) {
    Logger logger = GPLogger.getLogger(this);
    GPLogger.debug(logger, "Scheduling node %s", node);
    Range<Date> startRange = Range.all();
    Range<Date> endRange = Range.all();

    Range<Date> weakStartRange = Range.all();
    Range<Date> weakEndRange = Range.all();

    List<Date> subtaskRanges = Lists.newArrayList();
    List<DependencyEdge> incoming = node.getIncoming();
    GPLogger.debug(logger, ".. #incoming edges=%d", incoming.size());
    for (DependencyEdge edge : incoming) {
        if (!edge.refresh()) {
            continue;
        }// w ww .  ja v  a2s  .  com
        if (edge instanceof ImplicitSubSuperTaskDependency) {
            subtaskRanges.add(edge.getStartRange().upperEndpoint());
            subtaskRanges.add(edge.getEndRange().lowerEndpoint());
        } else {
            if (edge.isWeak()) {
                weakStartRange = weakStartRange.intersection(edge.getStartRange());
                weakEndRange = weakEndRange.intersection(edge.getEndRange());
            } else {
                startRange = startRange.intersection(edge.getStartRange());
                endRange = endRange.intersection(edge.getEndRange());
            }
        }
        if (startRange.isEmpty() || endRange.isEmpty()) {
            GPLogger.logToLogger("both start and end ranges were calculated as empty for task=" + node.getTask()
                    + ". Skipping it");
        }
    }
    GPLogger.debug(logger, "..Ranges: start=%s end=%s weakStart=%s weakEnd=%s", startRange, endRange,
            weakStartRange, weakEndRange);

    Range<Date> subtasksSpan = subtaskRanges.isEmpty()
            ? Range.closed(node.getTask().getStart().getTime(), node.getTask().getEnd().getTime())
            : Range.encloseAll(subtaskRanges);
    Range<Date> subtreeStartUpwards = subtasksSpan
            .span(Range.downTo(node.getTask().getStart().getTime(), BoundType.CLOSED));
    Range<Date> subtreeEndDownwards = subtasksSpan
            .span(Range.upTo(node.getTask().getEnd().getTime(), BoundType.CLOSED));
    GPLogger.debug(logger, "..Subtasks span=%s", subtasksSpan);

    if (!startRange.equals(Range.all())) {
        startRange = startRange.intersection(weakStartRange);
    } else if (!weakStartRange.equals(Range.all())) {
        startRange = weakStartRange.intersection(subtreeStartUpwards);
    }
    if (!endRange.equals(Range.all())) {
        endRange = endRange.intersection(weakEndRange);
    } else if (!weakEndRange.equals(Range.all())) {
        endRange = weakEndRange.intersection(subtreeEndDownwards);
    }
    if (node.getTask().getThirdDateConstraint() == TaskImpl.EARLIESTBEGIN
            && node.getTask().getThird() != null) {
        startRange = startRange
                .intersection(Range.downTo(node.getTask().getThird().getTime(), BoundType.CLOSED));
        GPLogger.debug(logger, ".. applying earliest start=%s. Now start range=%s", node.getTask().getThird(),
                startRange);
    }
    if (!subtaskRanges.isEmpty()) {
        startRange = startRange.intersection(subtasksSpan);
        endRange = endRange.intersection(subtasksSpan);
    }
    GPLogger.debug(logger, ".. finally, start range=%s", startRange);
    if (startRange.hasLowerBound()) {
        modifyTaskStart(node.getTask(), startRange.lowerEndpoint());
    }
    if (endRange.hasUpperBound()) {
        GPCalendarCalc cal = node.getTask().getManager().getCalendar();
        Date endDate = endRange.upperEndpoint();
        TimeUnit timeUnit = node.getTask().getDuration().getTimeUnit();
        if (DayMask.WORKING == (cal.getDayMask(endDate) & DayMask.WORKING)) {
            // in case if calculated end date falls on first day after holidays (say, on Monday)
            // we'll want to modify it a little bit, so that it falls on that holidays start
            // If we don't do this, it will be done automatically the next time task activities are recalculated,
            // and thus task end date will keep changing
            Date closestWorkingEndDate = cal.findClosest(endDate, timeUnit,
                    GPCalendarCalc.MoveDirection.BACKWARD, GPCalendar.DayType.WORKING);
            Date closestNonWorkingEndDate = cal.findClosest(endDate, timeUnit,
                    GPCalendarCalc.MoveDirection.BACKWARD, GPCalendar.DayType.NON_WORKING,
                    closestWorkingEndDate);
            // If there is a non-working date between current task end and closest working date
            // then we're really just after holidays
            if (closestNonWorkingEndDate != null && closestWorkingEndDate.before(closestNonWorkingEndDate)) {
                // we need to adjust-right closest working date to position to the very beginning of the holidays interval
                Date nonWorkingPeriodStart = timeUnit.adjustRight(closestWorkingEndDate);
                if (nonWorkingPeriodStart.after(node.getTask().getStart().getTime())) {
                    endDate = nonWorkingPeriodStart;
                }
            }
        }
        modifyTaskEnd(node.getTask(), endDate);
    }
}

From source file:org.assertj.guava.api.RangeAssert.java

/**
 * Verifies that the actual {@link com.google.common.collect.Range} lower bound is closed.<br>
 * <p>/*from w  w  w  . j a v a2  s .  c o m*/
 * Example :
 *
 * <pre><code class='java'> Range&lt;Integer&gt; range = Range.closed(10, 12);
 *
 * assertThat(range).hasClosedLowerBound();</code></pre>
 *
 * @return this {@link OptionalAssert} for assertions chaining.
 * @throws AssertionError if the actual {@link com.google.common.collect.Range} is {@code null}.
 * @throws AssertionError if the actual {@link com.google.common.collect.Range} lower bound is opened.
 */
public RangeAssert<T> hasClosedLowerBound() throws AssertionError {
    Objects.instance().assertNotNull(info, actual);

    if (actual.lowerBoundType() != BoundType.CLOSED) {
        throw failures.failure(info, shouldHaveClosedLowerBound(actual));
    }

    return this;
}

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;/*ww w.  j  a  v  a  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.kitesdk.data.spi.ConstraintsSerialization.java

/**
 * Deserializes an {@link Range} from the specified {@code in} stream.
 *///  w ww . j  a v  a2s  .  c om
@SuppressWarnings("unchecked")
private static Range readRangePredicate(Schema fieldSchema, ObjectInputStream in) throws IOException {
    Range range = null;

    //read in boolean indicating if there is a lower bound
    if (in.readBoolean()) {
        BoundType lowerType = in.readBoolean() ? BoundType.OPEN : BoundType.CLOSED;
        Comparable lowerBound = (Comparable) readValue(fieldSchema, in);
        if (lowerType.equals(BoundType.OPEN)) {
            range = Ranges.greaterThan(lowerBound);
        } else {
            range = Ranges.atLeast(lowerBound);
        }
    }
    //read in boolean indicating if there is an upper bound
    if (in.readBoolean()) {
        Range upperRange = null;
        BoundType upperType = in.readBoolean() ? BoundType.OPEN : BoundType.CLOSED;
        Comparable upperBound = (Comparable) readValue(fieldSchema, in);
        if (upperType.equals(BoundType.OPEN)) {
            upperRange = Ranges.lessThan(upperBound);
        } else {
            upperRange = Ranges.atMost(upperBound);
        }
        range = range == null ? upperRange : range.intersection(upperRange);
    }

    return range;
}