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

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

Introduction

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

Prototype

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

Source Link

Document

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

Usage

From source file:edu.cmu.sphinx.api.SpeechAligner.java

private void checkedOffer(List<String> transcript, Queue<List<String>> texts, Queue<TimeFrame> timeFrames,
        Queue<Range<Integer>> ranges, int start, int end, long timeStart, long timeEnd) {

    double wordDensity = ((double) (timeEnd - timeStart)) / (end - start);

    // Skip range if it's too short, average word is less than 10
    // milliseconds
    if (wordDensity < 10.0) {
        logger.info("Skipping text range due to a high density " + transcript.subList(start, end).toString());
        return;/*w w  w. j  a v  a2s  .  com*/
    }

    texts.offer(transcript.subList(start, end));
    timeFrames.offer(new TimeFrame(timeStart, timeEnd));
    ranges.offer(Range.closed(start, end - 1));
}

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

/**
 * Convert a set of (start-token, host) pairs into a set of (token-range, host) pairs.
 *
 * Package private for testing.// w  w  w  .  j  av  a 2 s. c  o  m
 *
 * @param startTokens The set of start tokens with hosts.
 * @return The token corresponding token ranges.
 */
static Map<Range<Long>, InetAddress> getTokenRanges(final SortedMap<Long, InetAddress> startTokens) {

    ImmutableMap.Builder<Range<Long>, InetAddress> tokenRangesBldr = ImmutableMap.builder();

    final PeekingIterator<Entry<Long, InetAddress>> startTokensItr = Iterators
            .peekingIterator(startTokens.entrySet().iterator());

    // Add a range for [-, firstStartToken) owned by the final key (the wrap-around range).
    // For more information on Casandra VNode token ranges:
    //    http://www.datastax.com/dev/blog/virtual-nodes-in-cassandra-1-2
    tokenRangesBldr.put(Range.lessThan(startTokens.firstKey()), startTokens.get(startTokens.lastKey()));

    while (startTokensItr.hasNext()) {
        Entry<Long, InetAddress> startToken = startTokensItr.next();
        if (!startTokensItr.hasNext()) {
            // The final start token
            // Add a range for [lastStartToken, )
            tokenRangesBldr.put(Range.atLeast(startToken.getKey()), startToken.getValue());
        } else {
            // Add a range for [thisStartToken, nextStartToken)
            tokenRangesBldr.put(Range.closedOpen(startToken.getKey(), startTokensItr.peek().getKey()),
                    startToken.getValue());
        }
    }

    final Map<Range<Long>, InetAddress> tokenRanges = tokenRangesBldr.build();

    // Check that the returned ranges are coherent; most importantly that all possible tokens fall
    // within the returned range set.

    if (startTokens.size() + 1 != tokenRanges.size()) {
        throw new InternalKijiError(
                String.format("Unexpected number of token ranges. start-tokens: %s, token-ranges: %s.",
                        startTokens.size(), tokenRanges.size()));
    }

    final RangeSet<Long> ranges = TreeRangeSet.create();
    for (Range<Long> tokenRange : tokenRanges.keySet()) {
        ranges.add(tokenRange);
    }

    if (!ranges.encloses(Range.closed(Long.MIN_VALUE, Long.MAX_VALUE))) {
        throw new InternalKijiError("Token range does not include all possible tokens.");
    }

    return tokenRanges;
}

From source file:org.robotframework.red.nattable.painter.RedTableTextPainter.java

private RangeSet<Integer> getHyperlinks(final TableCellStringData data, final String text,
        final String originalText) {
    final List<TableCellStringData> datas = data == null ? new ArrayList<>()
            : Lists.<TableCellStringData>newArrayList(data);
    final List<Range<Integer>> hyperlinkRanges = datas.stream().map(TableCellStringData::getHyperlinkRegion)
            .filter(notNull()).collect(toList());

    final RangeSet<Integer> hyperlinksRanges = mapOriginalRangesToCurrentLabel(hyperlinkRanges, text,
            originalText);/*w  w  w .  ja v a 2s  .  c o m*/
    if (hyperlinksRanges.isEmpty()) {
        hyperlinksRanges.add(Range.closed(-1, -1));
    }
    return hyperlinksRanges;
}

From source file:net.sf.mzmine.modules.masslistmethods.chromatogrambuilder.Chromatogram.java

public void finishChromatogram() {

    int allScanNumbers[] = Ints.toArray(dataPointsMap.keySet());
    Arrays.sort(allScanNumbers);/*ww  w.  jav  a 2s.c o m*/

    // Calculate median m/z
    double allMzValues[] = new double[allScanNumbers.length];
    for (int i = 0; i < allScanNumbers.length; i++) {
        allMzValues[i] = dataPointsMap.get(allScanNumbers[i]).getMZ();
    }
    mz = MathUtils.calcQuantile(allMzValues, 0.5f);

    // Update raw data point ranges, height, rt and representative scan
    height = Double.MIN_VALUE;
    for (int i = 0; i < allScanNumbers.length; i++) {

        DataPoint mzPeak = dataPointsMap.get(allScanNumbers[i]);

        // Replace the MzPeak instance with an instance of SimpleDataPoint,
        // to reduce the memory usage. After we finish this Chromatogram, we
        // don't need the additional data provided by the MzPeak

        dataPointsMap.put(allScanNumbers[i], mzPeak);

        if (i == 0) {
            rawDataPointsIntensityRange = Range.singleton(mzPeak.getIntensity());
            rawDataPointsMZRange = Range.singleton(mzPeak.getMZ());
        } else {
            rawDataPointsIntensityRange = rawDataPointsIntensityRange
                    .span(Range.singleton(mzPeak.getIntensity()));
            rawDataPointsMZRange = rawDataPointsMZRange.span(Range.singleton(mzPeak.getMZ()));
        }

        if (height < mzPeak.getIntensity()) {
            height = mzPeak.getIntensity();
            rt = dataFile.getScan(allScanNumbers[i]).getRetentionTime();
            representativeScan = allScanNumbers[i];
        }
    }

    // Update area
    area = 0;
    for (int i = 1; i < allScanNumbers.length; i++) {
        // For area calculation, we use retention time in seconds
        double previousRT = dataFile.getScan(allScanNumbers[i - 1]).getRetentionTime() * 60d;
        double currentRT = dataFile.getScan(allScanNumbers[i]).getRetentionTime() * 60d;
        double previousHeight = dataPointsMap.get(allScanNumbers[i - 1]).getIntensity();
        double currentHeight = dataPointsMap.get(allScanNumbers[i]).getIntensity();
        area += (currentRT - previousRT) * (currentHeight + previousHeight) / 2;
    }

    // Update fragment scan
    fragmentScan = ScanUtils.findBestFragmentScan(dataFile, dataFile.getDataRTRange(1), rawDataPointsMZRange);

    if (fragmentScan > 0) {
        Scan fragmentScanObject = dataFile.getScan(fragmentScan);
        int precursorCharge = fragmentScanObject.getPrecursorCharge();
        if (precursorCharge > 0)
            this.charge = precursorCharge;
    }

    // Victor Trevio
    // using allScanNumbers : rawDataPointsRTRange = new
    // Range(dataFile.getScan(allScanNumbers[0]).getRetentionTime(),
    // dataFile.getScan(allScanNumbers[allScanNumbers.length-1]).getRetentionTime());
    rawDataPointsRTRange = Range.closed(minTime, maxTime); // using the
                                                           // "cached"
                                                           // values

    // Discard the fields we don't need anymore
    buildingSegment = null;
    lastMzPeak = null;

}

From source file:com.rockhoppertech.music.fx.cmn.model.MeasureSymbolManager.java

/**
 * Clear out the existing shapes, then calculate and add new ones. Draws a
 * simple representation. Does not pay any attention to the note's start
 * time. That what the MeasureCanvas will do when finished.
 */// www. ja  va  2  s . com
public void refresh() {
    logger.debug("refreshing");

    if (model == null) {
        return;
    }
    shapes.clear();
    symbols.clear();
    //
    // double x = model.getStartX() + 1d
    // * model.getFontSize();

    double x = model.getBeginningBarlineX();

    // this will be at model startx
    // sets first note x
    x = createStaves();
    // x = this.model.getStartX();

    if (this.drawTimeSignature) {
        if (!this.drawKeySignature)
            x += model.getFontSize() / 2d;
        x = addTimeSignature(x, 4, 4);
    }

    // model.setFirstNoteX(x);
    this.createBeatRectangles();

    if (noteList == null) {
        return;
    }

    if (noteList.isEmpty()) {
        return;
    }
    logger.debug("notelist {}", this.noteList);

    // TODO this doesn't cover initial rests i.e. when start beat > 1
    // TODO rests > 5 beats long don't work well
    MIDINote previousNote = noteList.get(0);
    MIDINote firstNote = noteList.get(0);
    double gap = firstNote.getStartBeat() - 1d;
    double eb = 1d;

    double beats = (double) measure.getTimeSignature().getNumerator();
    RangeSet<Double> durSet = TreeRangeSet.create();
    durSet.add(Range.closed(1d, beats));
    logger.debug("initial durSet {} beats {}", durSet, beats);

    for (MIDINote note : noteList) {

        Range<Double> noteRange = Range.closed(note.getStartBeat(), note.getEndBeat());
        durSet.remove(noteRange);
        logger.debug("durSet {} after removing {}", durSet, noteRange);

        logger.debug("beat {} beat in measure {}", note.getStartBeat(), measure.getBeatInMeasure(note));

        // figure out if there is a rest
        double sb = note.getStartBeat();
        if (sb > 1d) {
            eb = previousNote.getEndBeat();
        }
        gap = sb - eb;
        double restbeat = (sb - gap) - this.measure.getStartBeat() + 1d;
        x = getXofBeatN(restbeat);
        logger.debug("sb {} eb {} gap {} x {} restbeat {}", sb, eb, gap, x, restbeat);
        if (gap > 0) {
            int pitch = note.getPitch().getMidiNumber();
            x = addRests(x, gap, pitch);
            x += model.getFontSize() / 2d;
            logger.debug("x {} after adding rest", x);
        } else {
            x += model.getFontSize() / 2d;
        }

        // now worry about the note
        x = getXofBeatN(measure.getBeatInMeasure(note));
        // x = createSymbol(note, x);
        x = createStaffSymbol(note, x);

        logger.debug("x {} after adding symbol", x);
        if (gap >= 0) {
            logger.debug("adding padding");
            // some padding between the symbols
            x += model.getFontSize() / 2d;
            logger.debug("x {} after adding gap 0 spacingl", x);
        }

        gap = 0;
        previousNote = note;
    }

    logger.debug("final durSet {}", durSet);
    if (!durSet.isEmpty()) {
        // then there are rests
        for (Range<Double> restRange : durSet.asRanges()) {
            logger.debug("restRange {}", restRange);
        }
    }

    // push all the x locations to be the previous x + width
    // make sure all the rects are large enough, adjust widths and x
    // locations.
    enlargeBeatRectangles();
    // resize the staves to the new rectangles
    createStaves();
}

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 ww  .  ja  va  2s.  c om*/
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:org.noroomattheinn.visibletesla.DataStore.java

private Range<Date> getDateRange(int dateField) {
    Calendar cal = Calendar.getInstance();
    cal.set(dateField, 1);/* www . j a  v a 2  s.co  m*/
    Date start = cal.getTime();
    cal.set(dateField, cal.getActualMaximum(dateField));
    Date end = cal.getTime();
    return Range.closed(start, end);
}

From source file:net.sf.mzmine.modules.visualization.spectra.SpectraVisualizerWindow.java

public void loadIsotopes(IsotopePattern newPattern) {

    // We need to find a normalization factor for the new isotope
    // pattern, to show meaningful intensity range
    double mz = newPattern.getHighestDataPoint().getMZ();
    Range<Double> searchMZRange = Range.closed(mz - 0.5, mz + 0.5);
    ScanDataSet scanDataSet = spectrumPlot.getMainScanDataSet();
    double normalizationFactor = scanDataSet.getHighestIntensity(searchMZRange);

    // If normalization factor is 0, it means there were no data points
    // in given m/z range. In such case we use the max intensity of
    // whole scan as normalization factor.
    if (normalizationFactor == 0) {
        searchMZRange = Range.atLeast(0.0);
        normalizationFactor = scanDataSet.getHighestIntensity(searchMZRange);
    }/*  ww  w .j a  v a  2 s .  c om*/

    IsotopePattern normalizedPattern = IsotopePatternCalculator.normalizeIsotopePattern(newPattern,
            normalizationFactor);
    Color newColor;
    if (newPattern.getStatus() == IsotopePatternStatus.DETECTED)
        newColor = detectedIsotopesColor;
    else
        newColor = predictedIsotopesColor;
    IsotopesDataSet newDataSet = new IsotopesDataSet(normalizedPattern);
    spectrumPlot.addDataSet(newDataSet, newColor, true);

}

From source file:applicationdriverlayer.pageobjects.squash.booking.CourtAndTimeSlotChooserPage.java

public boolean isCourtNumberValid(Integer court) {
    return Range.closed(1, 5).contains(court);
}

From source file:org.waveprotocol.box.server.persistence.blocks.impl.BlockIndexImpl.java

private RangeMap<RangeValue, String> getRanges(SegmentId segmentId) {
    RangeMap<RangeValue, String> ranges = rangeMap.getIfPresent(segmentId);
    if (ranges == null) {
        try {/*  w  ww .j a  v  a2s  .c o m*/
            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;
}