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

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

Introduction

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

Prototype

public static <C extends Comparable<?>> Range<C> atLeast(C endpoint) 

Source Link

Document

Returns a range that contains all values greater than or equal to endpoint .

Usage

From source file:org.apache.druid.sql.calcite.filtration.Bounds.java

public static Range<BoundValue> toRange(final BoundDimFilter bound) {
    final BoundValue upper = bound.getUpper() != null ? new BoundValue(bound.getUpper(), bound.getOrdering())
            : null;//ww  w.j a v  a 2s .c  o  m
    final BoundValue lower = bound.getLower() != null ? new BoundValue(bound.getLower(), bound.getOrdering())
            : null;

    if (lower == null) {
        return bound.isUpperStrict() ? Range.lessThan(upper) : Range.atMost(upper);
    } else if (upper == null) {
        return bound.isLowerStrict() ? Range.greaterThan(lower) : Range.atLeast(lower);
    } else {
        return Range.range(lower, bound.isLowerStrict() ? BoundType.OPEN : BoundType.CLOSED, upper,
                bound.isUpperStrict() ? BoundType.OPEN : BoundType.CLOSED);
    }
}

From source file:net.sf.mzmine.modules.masslistmethods.shoulderpeaksfilter.peakmodels.LorentzianPeak.java

/**
 * @see net.sf.mzmine.modules.masslistmethods.shoulderpeaksfilter.peakpicking.twostep.peakmodel.PeakModel#getBasePeakWidth()
 *//*from  ww  w. j a v  a2 s.c o m*/
public Range<Double> getWidth(double partialIntensity) {

    // The height value must be bigger than zero.
    if (partialIntensity <= 0)
        return Range.atLeast(0.0);

    // Using the Lorentzian function we calculate the peak width
    double squareX = ((intensityMain / partialIntensity) - 1) * squareHWHM;

    double sideRange = (double) Math.sqrt(squareX);

    // This range represents the width of our peak in m/z terms
    Range<Double> rangePeak = Range.closed(mzMain - sideRange, mzMain + sideRange);

    return rangePeak;
}

From source file:org.asoem.greyfish.utils.collect.LinearSequences.java

/**
 * Create a crossover product between two {@code Iterables} with crossovers at given {@code indices}. This means
 * that both {@code Iterable}s in the returned product are a combination of the input iterables in such a way, that
 * the constructed iterable switches the input iterable at each given position. Both input {@code Iterable}s will be
 * zipped with {@link Products#zip(Iterable, Iterable)}. Therefore the returned {@code Iterable}s will have the same
 * size equal to the size of the input iterable with the fewest elements.
 *
 * @param x       The first Iterable/*from  w w  w  . j a  va 2s.c o m*/
 * @param y       The second Iterable
 * @param indices the indices at which to do the crossovers
 * @param <E>     the type of the elements in {@code Iterable}s
 * @return a product of Iterables with crossovers at the given indices
 */
public static <E> Product2<Iterable<E>, Iterable<E>> crossover(final Iterable<E> x, final Iterable<E> y,
        final Set<Integer> indices) {
    checkNotNull(x);
    checkNotNull(y);
    checkNotNull(indices);

    final Iterable<Product2<E, E>> zipped = Products.zip(x, y);

    if (indices.isEmpty()) {
        return Products.unzip(zipped);
    } else {
        final FunctionalList<Range<Integer>> ranges = ImmutableFunctionalList.copyOf(
                Iterables.transform(Iterables.partition(Ordering.natural().immutableSortedCopy(indices), 2),
                        new Function<List<Integer>, Range<Integer>>() {
                            @Nullable
                            @Override
                            public Range<Integer> apply(@Nullable final List<Integer> input) {
                                assert input != null;
                                return input.size() == 2 ? Range.closed(input.get(0), input.get(1))
                                        : Range.atLeast(input.get(0));
                            }
                        }));

        return Products.unzip(Iterables.transform(Products.zipWithIndex(zipped),
                new Function<Product2<Product2<E, E>, Integer>, Product2<E, E>>() {
                    @Nullable
                    @Override
                    public Product2<E, E> apply(@Nullable final Product2<Product2<E, E>, Integer> input) {
                        assert input != null;
                        return ranges.any(new Predicate<Range<Integer>>() {
                            @Override
                            public boolean apply(@Nullable final Range<Integer> range) {
                                assert range != null;
                                return range.contains(input.second());
                            }
                        }) ? Products.swap(input.first()) : input.first();
                    }
                }));
    }
}

From source file:net.sf.mzmine.modules.masslistmethods.shoulderpeaksfilter.peakmodels.GaussPeak.java

/**
 * @see net.sf.mzmine.modules.masslistmethods.shoulderpeaksfilter.peakpicking.twostep.peakmodel.PeakModel#getBasePeakWidth()
 *//*w ww. j a  va2 s  .  c  o  m*/
public Range<Double> getWidth(double partialIntensity) {

    // The height value must be bigger than zero.
    if (partialIntensity <= 0)
        return Range.atLeast(0.0);

    // Using the Gaussian function we calculate the peak width at intensity
    // given (partialIntensity)

    double portion = partialIntensity / intensityMain;
    double ln = -1 * (double) Math.log(portion);

    double sideRange = (double) (Math.sqrt(part2C2 * ln));

    // This range represents the width of our peak in m/z
    Range<Double> rangePeak = Range.closed(mzMain - sideRange, mzMain + sideRange);

    return rangePeak;
}

From source file:com.google.devtools.build.lib.profiler.SingleStatRecorder.java

/** Create an snapshot of the the stats recorded up to now. */
public MetricData snapshot() {
    synchronized (this) {
        ImmutableList.Builder<HistogramElement> result = ImmutableList.builder();
        result.add(new HistogramElement(Range.closedOpen(0, 1), histogram[0]));
        int from = 1;
        for (int i = 1; i < histogram.length - 1; i++) {
            int to = from << 1;
            result.add(new HistogramElement(Range.closedOpen(from, to), histogram[i]));
            from = to;/*  w ww  . ja v a  2 s .c  o m*/
        }
        result.add(new HistogramElement(Range.atLeast(from), histogram[histogram.length - 1]));
        return new MetricData(description, result.build(), count, avg, Math.sqrt(m2 / (double) count), max);
    }
}

From source file:google.registry.monitoring.metrics.MutableDistribution.java

/** Constructs an empty Distribution with the specified {@link DistributionFitter}. */
public MutableDistribution(DistributionFitter distributionFitter) {
    this.distributionFitter = checkNotNull(distributionFitter);
    ImmutableSortedSet<Double> boundaries = distributionFitter.boundaries();

    checkArgument(boundaries.size() > 0);
    checkArgument(Ordering.natural().isOrdered(boundaries));

    this.intervalCounts = TreeRangeMap.create();

    double[] boundariesArray = Doubles.toArray(distributionFitter.boundaries());

    // Add underflow and overflow intervals
    this.intervalCounts.put(Range.lessThan(boundariesArray[0]), 0L);
    this.intervalCounts.put(Range.atLeast(boundariesArray[boundariesArray.length - 1]), 0L);

    // Add finite intervals
    for (int i = 1; i < boundariesArray.length; i++) {
        this.intervalCounts.put(Range.closedOpen(boundariesArray[i - 1], boundariesArray[i]), 0L);
    }/* w  ww.  j  a v  a 2s.c o  m*/
}

From source file:org.sonatype.nexus.repository.http.RangeParser.java

/**
 * Returns a list of {@link Range}s, each indicating a range of byte indices (inclusive).
 *
 * Range: bytes=0-10 (from byte 0 to byte 10)
 * Range: bytes=500-999 (from byte 500 to byte 999)
 * Range: bytes=500- (from byte 500 to the end)
 * Range: bytes=-500 (the last 500 bytes, per the RFC)
 *
 * @return {@code null} if the requested range cannot be satisfied given the size of the content, or an empty list in
 * the case of parsing errors/*from   w  w  w. ja  v a2  s  .com*/
 */
public List<Range<Long>> parseRangeSpec(final String rangeHeader, long size) {
    Range<Long> content = Range.closed(0L, size - 1L);

    // TODO: Current limitation: only one Range of bytes supported in forms of "-X", "X-Y" (where X<Y) and "X-".
    if (!Strings.isNullOrEmpty(rangeHeader)) {
        try {
            if (rangeHeader.startsWith("bytes=") && rangeHeader.length() > 6 && !rangeHeader.contains(",")) {
                final String rangeSpec = rangeHeader.substring(6, rangeHeader.length());
                if (rangeSpec.startsWith("-")) {
                    final long byteCount = Long.parseLong(rangeSpec.substring(1));
                    if (byteCount > size) {
                        return UNSATISFIABLE;
                    }
                    final Range<Long> suffix = Range.atLeast(size - byteCount);
                    return ensureSatisfiable(suffix, content);
                } else if (rangeSpec.endsWith("-")) {
                    final Range<Long> requested = Range
                            .atLeast(Long.parseLong(rangeSpec.substring(0, rangeSpec.length() - 1)));
                    return ensureSatisfiable(requested, content);
                } else if (rangeSpec.contains("-")) {
                    final String[] parts = rangeSpec.split("-");
                    return ensureSatisfiable(Range.closed(Long.parseLong(parts[0]), Long.parseLong(parts[1])),
                            content);
                } else {
                    log.warn("Malformed HTTP Range value: {}, ignoring it", rangeHeader);
                }
            } else {
                log.warn("Unsupported non-byte or multiple HTTP Ranges: {}; sending complete content",
                        rangeHeader);
            }
        } catch (Exception e) {
            if (log.isDebugEnabled()) {
                log.debug("Problem parsing Range value: {}, ignoring", rangeHeader, e);
            } else {
                log.warn("Problem parsing Range value: {}, ignoring: {}", rangeHeader, e.toString());
            }
        }
    }

    return WHOLE_RANGE;
}

From source file:org.sonatype.nexus.repository.partial.RangeParser.java

/**
 * Returns a list of {@link Range}s, each indicating a range of byte indices (inclusive).
 *
 * Range: bytes=0-10 (from byte 0 to byte 10)
 * Range: bytes=500-999 (from byte 500 to byte 999)
 * Range: bytes=500- (from byte 500 to the end)
 * Range: bytes=-500 (the last 500 bytes, per the RFC)
 *
 * @return {@code null} if the requested range cannot be satisfied given the size of the content, or an empty list in
 * the case of parsing errors/*from   w  w  w.ja v  a  2  s .c o m*/
 */
public List<Range<Long>> parseRangeSpec(final String rangeHeader, long size) {
    Range content = Range.closed(0L, size - 1L);

    // TODO: Current limitation: only one Range of bytes supported in forms of "-X", "X-Y" (where X<Y) and "X-".
    if (!Strings.isNullOrEmpty(rangeHeader)) {
        try {
            if (rangeHeader.startsWith("bytes=") && rangeHeader.length() > 6 && !rangeHeader.contains(",")) {
                final String rangeSpec = rangeHeader.substring(6, rangeHeader.length());
                if (rangeSpec.startsWith("-")) {
                    final long byteCount = Long.parseLong(rangeSpec.substring(1));
                    if (byteCount > size) {
                        return UNSATISFIABLE;
                    }
                    final Range<Long> suffix = Range.atLeast(size - byteCount);
                    return ensureSatisfiable(suffix, content);
                } else if (rangeSpec.endsWith("-")) {
                    final Range<Long> requested = Range
                            .atLeast(Long.parseLong(rangeSpec.substring(0, rangeSpec.length() - 1)));
                    return ensureSatisfiable(requested, content);
                } else if (rangeSpec.contains("-")) {
                    final String[] parts = rangeSpec.split("-");
                    return ensureSatisfiable(Range.closed(Long.parseLong(parts[0]), Long.parseLong(parts[1])),
                            content);
                } else {
                    log.warn("Malformed HTTP Range value: {}, ignoring it", rangeHeader);
                }
            } else {
                log.warn(
                        "Nexus does not support non-byte or multiple HTTP Ranges, sending complete content: Range value {}",
                        rangeHeader);
            }
        } catch (Exception e) {
            if (log.isDebugEnabled()) {
                log.debug("Problem parsing Range value: {}, ignoring it", rangeHeader, e);
            } else {
                log.info("Problem parsing Range value: {}, ignoring it", rangeHeader);
            }
        }
    }

    return WHOLE_RANGE;
}

From source file:org.graylog2.commands.journal.JournalDecode.java

@Override
protected void runCommand() {

    Range<Long> range;/*w w w .  j av  a 2 s .c o  m*/
    try {
        final List<String> offsets = Splitter.on("..").limit(2).splitToList(rangeArg);
        if (offsets.size() == 1) {
            range = Range.singleton(Long.valueOf(offsets.get(0)));
        } else if (offsets.size() == 2) {
            final String first = offsets.get(0);
            final String second = offsets.get(1);
            if (first.isEmpty()) {
                range = Range.atMost(Long.valueOf(second));
            } else if (second.isEmpty()) {
                range = Range.atLeast(Long.valueOf(first));
            } else {
                range = Range.closed(Long.valueOf(first), Long.valueOf(second));
            }
        } else {
            throw new RuntimeException();
        }
    } catch (Exception e) {
        System.err.println("Malformed offset range: " + rangeArg);
        return;
    }

    final Map<String, Codec.Factory<? extends Codec>> codecFactory = injector
            .getInstance(Key.get(new TypeLiteral<Map<String, Codec.Factory<? extends Codec>>>() {
            }));

    final Long readOffset = range.lowerEndpoint();
    final long count = range.upperEndpoint() - range.lowerEndpoint() + 1;
    final List<Journal.JournalReadEntry> entries = journal.read(readOffset, count);
    for (final Journal.JournalReadEntry entry : entries) {
        final RawMessage raw = RawMessage.decode(entry.getPayload(), entry.getOffset());
        if (raw == null) {
            System.err.println(
                    MessageFormatter.format("Journal entry at offset {} failed to decode", entry.getOffset()));
            continue;
        }

        final Codec codec = codecFactory.get(raw.getCodecName()).create(raw.getCodecConfig());
        final Message message = codec.decode(raw);
        if (message == null) {
            System.err.println(
                    MessageFormatter.format("Could not use codec {} to decode raw message id {} at offset {}",
                            new Object[] { raw.getCodecName(), raw.getId(), entry.getOffset() }));
        } else {
            message.setJournalOffset(raw.getJournalOffset());
        }

        final ResolvableInetSocketAddress remoteAddress = raw.getRemoteAddress();
        final String remote = remoteAddress == null ? "unknown address"
                : remoteAddress.getInetSocketAddress().toString();

        final StringBuffer sb = new StringBuffer();
        sb.append("Message ").append(raw.getId()).append('\n').append(" at ").append(raw.getTimestamp())
                .append('\n').append(" in format ").append(raw.getCodecName()).append('\n')
                .append(" at offset ").append(raw.getJournalOffset()).append('\n')
                .append(" received from remote address ").append(remote).append('\n').append(" (source field: ")
                .append(message == null ? "unparsed" : message.getSource()).append(')').append('\n');
        if (message != null) {
            sb.append(" contains ").append(message.getFieldNames().size()).append(" fields.");
        } else {
            sb.append("The message could not be parse by the given codec.");
        }
        System.out.println(sb);
    }

}

From source file:org.apache.kylin.storage.cache.TsConditionExtractor.java

private static Range<Long> extractTsConditionInternal(TupleFilter filter, TblColRef colRef) {
    if (filter == null) {
        return Range.all();
    }/*from  w  w  w  . j a  v a2 s .c  om*/

    if (filter instanceof LogicalTupleFilter) {
        if (filter.getOperator() == TupleFilter.FilterOperatorEnum.AND) {
            Range<Long> ret = Range.all();
            for (TupleFilter child : filter.getChildren()) {
                Range childRange = extractTsConditionInternal(child, colRef);
                if (childRange != null) {
                    if (ret.isConnected(childRange) && !ret.intersection(childRange).isEmpty()) {
                        ret = ret.intersection(childRange);
                    } else {
                        return null;
                    }
                } else {
                    return null;
                }
            }
            return ret.isEmpty() ? null : ret;
        } else {
            //for conditions like date > DATE'2000-11-11' OR date < DATE '1999-01-01'
            //we will use Ranges.all() rather than two ranges to represent them
            return Range.all();
        }
    }

    if (filter instanceof CompareTupleFilter) {
        CompareTupleFilter compareTupleFilter = (CompareTupleFilter) filter;
        if (compareTupleFilter.getColumn() == null)// column will be null at filters like " 1<>1"
            return Range.all();

        if (compareTupleFilter.getColumn().equals(colRef)) {
            Object firstValue = compareTupleFilter.getFirstValue();
            long t;
            switch (compareTupleFilter.getOperator()) {
            case EQ:
                t = DateFormat.stringToMillis((String) firstValue);
                return Range.closed(t, t);
            case LT:
                t = DateFormat.stringToMillis((String) firstValue);
                return Range.lessThan(t);
            case LTE:
                t = DateFormat.stringToMillis((String) firstValue);
                return Range.atMost(t);
            case GT:
                t = DateFormat.stringToMillis((String) firstValue);
                return Range.greaterThan(t);
            case GTE:
                t = DateFormat.stringToMillis((String) firstValue);
                return Range.atLeast(t);
            case NEQ:
            case IN://not handled for now
                break;
            default:
            }
        }
    }
    return Range.all();
}