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:com.noodlewiz.xjavab.core.Connection.java

private void initXids() {
    final long base = mSetup.resourceIdBase;
    final long mask = mSetup.resourceIdMask;
    final long shifts = BigInteger.valueOf(mask).getLowestSetBit();

    final Iterable<Long> r = ContiguousSet.create(Range.closed(0L, mask >> shifts), DiscreteDomain.longs());
    final Iterable<Long> ids = Iterables.transform(r, new Function<Long, Long>() {

        @Override/*www  . jav a  2 s .  co  m*/
        public Long apply(final Long input) {
            return (input << shifts) | base;
        }

    });

    mXids = ids.iterator();
}

From source file:com.github.fge.grappa.matchers.join.JoinMatcherBuilder.java

private static Range<Integer> toClosedRange(Range<Integer> range) {
    /*// www.jav a2  s .c o m
     * The canonical form will always be the same: closed on the lower bound
     * (if any; but here we are guaranteed that), open on the upper bound
     * (if any).
     *
     * All we have to do is therefore to pick the canonical representation,
     * pick the lower bound, and if it has an upper bound, pick it and
     * substract 1.
     */
    Range<Integer> canonical = range.canonical(DiscreteDomain.integers());
    int lowerBound = canonical.lowerEndpoint();
    return canonical.hasUpperBound() ? Range.closed(lowerBound, canonical.upperEndpoint() - 1)
            : Range.atLeast(lowerBound);
}

From source file:org.arbeitspferde.groningen.experimentdb.jvmflags.JvmFlag.java

/**
 * Construct a new integer flag.// ww  w . j  a  v  a 2  s  .  c  o m
 *
 * @param name The name of the flag.
 * @param hotSpotFlagType The type of the flag.
 * @param minimum The minimum value.
 * @param maximum The maximum value.
 * @param stepSize The increment between values.
 */
JvmFlag(final String name, final HotSpotFlagType hotSpotFlagType, final Long minimum, final Long maximum,
        final Long stepSize, final DataSize dataSize, final ValueSeparator valueSeparator) {
    this.name = Preconditions.checkNotNull(name, "name may not be null.");
    this.hotSpotFlagType = Preconditions.checkNotNull(hotSpotFlagType, "hotSpotFlagType may not be null.");
    floorValue = Preconditions.checkNotNull(minimum, "minimum may not be null.");
    ceilingValue = Preconditions.checkNotNull(maximum, "maximum may not be null.");
    this.stepSize = Preconditions.checkNotNull(stepSize, "stepSize may not be null.");
    this.dataSize = Preconditions.checkNotNull(dataSize, "dataSize may not be null.");
    this.valueSeparator = Preconditions.checkNotNull(valueSeparator, "valueSeparator may not be null.");

    formatter = Formatters.INTEGER_FORMATTER;
    acceptableValueRange = Range.closed(minimum, maximum);
}

From source file:edu.cmu.sphinx.alignment.LongTextAligner.java

/**
 * Aligns query sequence with the previously built database.
 *
 * @return indices of alignment/*  w  ww. j  av a  2 s.  c om*/
 */
public int[] align(List<String> query) {
    return align(query, Range.closed(0, refWords.size() - 1));
}

From source file:org.opendaylight.lispflowmapping.type.lisp.LocatorRecord.java

public LocatorRecord setMulticastPriority(short value) {
    if (value != 0) {
        boolean isValidRange = false;
        List<Range<Short>> rangeConstraints = new ArrayList<>();
        rangeConstraints.add(Range.closed(new Short("0"), new Short("255")));
        for (Range<Short> r : rangeConstraints) {
            if (r.contains(value)) {
                isValidRange = true;//from   ww  w  .  j av a 2 s. co m
            }
        }
        if (!isValidRange) {
            throw new IllegalArgumentException(
                    String.format("Invalid range: %s, expected: %s.", value, rangeConstraints));
        }
    }
    this.multicastPriority = value;
    return this;
}

From source file:org.onosproject.powermanagement.PowerConfigWebResource.java

private ObjectNode encode(PowerConfig<Object> powerConfig, String direction, String channel) {
    checkNotNull(powerConfig, "PowerConfig cannot be null");
    ObjectNode powerConfigPorts = mapper.createObjectNode();
    Multimap<PortNumber, Object> portsMap = HashMultimap.create();

    if (direction != null) {
        for (PortNumber port : powerConfig.getPorts(direction)) {
            portsMap.put(port, Direction.valueOf(direction.toUpperCase()));
        }/*  w  ww  .j a  v a 2  s  .c  o  m*/
    }

    if (channel != null) {
        for (PortNumber port : powerConfig.getPorts(channel)) {
            // TODO: channel to be handled
            portsMap.put(port, channel);
        }
    }

    for (Map.Entry<PortNumber, Object> entry : portsMap.entries()) {
        PortNumber port = entry.getKey();
        ObjectNode powerConfigComponents = mapper.createObjectNode();
        for (Object component : portsMap.get(port)) {
            // TODO: channel to be handled
            String componentName = "unknown";
            if (component instanceof Direction) {
                componentName = component.toString();
            }
            ObjectNode powerConfigNode = mapper.createObjectNode()
                    .put(CURRENT_POWER, powerConfig.currentPower(port, component).orElse(0L))
                    .put(TARGET_POWER, powerConfig.getTargetPower(port, component).orElse(0L))
                    .put(INPUT_POWER_RANGE,
                            powerConfig.getInputPowerRange(port, component).orElse(Range.closed(0L, 0L))
                                    .toString())
                    .put(TARGET_POWER_RANGE, powerConfig.getTargetPowerRange(port, component)
                            .orElse(Range.closed(0L, 0L)).toString());
            powerConfigComponents.set(componentName, powerConfigNode);
        }
        powerConfigPorts.set(port.toString(), powerConfigComponents);
    }

    ObjectNode result = mapper.createObjectNode();
    result.set("powerConfigPorts", powerConfigPorts);
    return result;
}

From source file:com.giaybac.traprange.extractor.PDFTableExtractor.java

/**
 *
 * @param rowIdx/* www.j a v  a2  s .  com*/
 * @param rowContent
 * @param columnTrapRanges
 * @return
 */
private TableRow buildRow(int rowIdx, List<TextPosition> rowContent, List<Range<Integer>> columnTrapRanges) {
    TableRow retVal = new TableRow(rowIdx);
    //Sort rowContent
    Collections.sort(rowContent, new Comparator<TextPosition>() {
        @Override
        public int compare(TextPosition o1, TextPosition o2) {
            int retVal = 0;
            if (o1.getX() < o2.getX()) {
                retVal = -1;
            } else if (o1.getX() > o2.getX()) {
                retVal = 1;
            }
            return retVal;
        }
    });
    int idx = 0;
    int columnIdx = 0;
    List<TextPosition> cellContent = new ArrayList<>();
    while (idx < rowContent.size()) {
        TextPosition textPosition = rowContent.get(idx);
        Range<Integer> columnTrapRange = columnTrapRanges.get(columnIdx);
        Range<Integer> textRange = Range.closed((int) textPosition.getX(),
                (int) (textPosition.getX() + textPosition.getWidth()));
        if (columnTrapRange.encloses(textRange)) {
            cellContent.add(textPosition);
            idx++;
        } else {
            TableCell cell = buildCell(columnIdx, cellContent);
            retVal.getCells().add(cell);
            //next column: clear cell content
            cellContent.clear();
            columnIdx++;
        }
    }
    if (!cellContent.isEmpty() && columnIdx < columnTrapRanges.size()) {
        TableCell cell = buildCell(columnIdx, cellContent);
        retVal.getCells().add(cell);
    }
    //return
    return retVal;
}

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

/**
 * Emit a list of {@link Replacement}s to convert from input to output.
 *
 * @return a list of {@link Replacement}s, sorted by start index, without overlaps
 *//* www  .ja  v a  2s.c o m*/
public ImmutableList<Replacement> getFormatReplacements(RangeSet<Integer> iRangeSet0) {
    ImmutableList.Builder<Replacement> result = ImmutableList.builder();
    Map<Integer, Range<Integer>> kToJ = JavaOutput.makeKToIJ(this);

    // Expand the token ranges to align with re-formattable boundaries.
    RangeSet<Integer> breakableRanges = TreeRangeSet.create();
    RangeSet<Integer> iRangeSet = iRangeSet0.subRangeSet(Range.closed(0, javaInput.getkN()));
    for (Range<Integer> iRange : iRangeSet.asRanges()) {
        Range<Integer> range = expandToBreakableRegions(iRange.canonical(DiscreteDomain.integers()));
        if (range.equals(EMPTY_RANGE)) {
            // the range contains only whitespace
            continue;
        }
        breakableRanges.add(range);
    }

    // Construct replacements for each reformatted region.
    for (Range<Integer> range : breakableRanges.asRanges()) {

        Input.Tok startTok = startTok(javaInput.getToken(range.lowerEndpoint()));
        Input.Tok endTok = endTok(javaInput.getToken(range.upperEndpoint() - 1));

        // Add all output lines in the given token range to the replacement.
        StringBuilder replacement = new StringBuilder();

        int replaceFrom = startTok.getPosition();
        // Replace leading whitespace in the input with the whitespace from the formatted file
        while (replaceFrom > 0) {
            char previous = javaInput.getText().charAt(replaceFrom - 1);
            if (!CharMatcher.whitespace().matches(previous)) {
                break;
            }
            replaceFrom--;
        }

        int i = kToJ.get(startTok.getIndex()).lowerEndpoint();
        // Include leading blank lines from the formatted output, unless the formatted range
        // starts at the beginning of the file.
        while (i > 0 && getLine(i - 1).isEmpty()) {
            i--;
        }
        // Write out the formatted range.
        for (; i < kToJ.get(endTok.getIndex()).upperEndpoint(); i++) {
            // It's possible to run out of output lines (e.g. if the input ended with
            // multiple trailing newlines).
            if (i < getLineCount()) {
                if (i > 0) {
                    replacement.append(lineSeparator);
                }
                replacement.append(getLine(i));
            }
        }

        int replaceTo = Math.min(endTok.getPosition() + endTok.length(), javaInput.getText().length());
        // If the formatted ranged ended in the trailing trivia of the last token before EOF,
        // format all the way up to EOF to deal with trailing whitespace correctly.
        if (endTok.getIndex() == javaInput.getkN() - 1) {
            replaceTo = javaInput.getText().length();
        }
        // Replace trailing whitespace in the input with the whitespace from the formatted file.
        // If the trailing whitespace in the input includes one or more line breaks, preserve the
        // whitespace after the last newline to avoid re-indenting the line following the formatted
        // line.
        int newline = -1;
        while (replaceTo < javaInput.getText().length()) {
            char next = javaInput.getText().charAt(replaceTo);
            if (!CharMatcher.whitespace().matches(next)) {
                break;
            }
            int newlineLength = Newlines.hasNewlineAt(javaInput.getText(), replaceTo);
            if (newlineLength != -1) {
                newline = replaceTo;
                // Skip over the entire newline; don't count the second character of \r\n as a newline.
                replaceTo += newlineLength;
            } else {
                replaceTo++;
            }
        }
        if (newline != -1) {
            replaceTo = newline;
        }

        if (newline == -1) {
            // There wasn't an existing trailing newline; add one.
            replacement.append(lineSeparator);
        }
        for (; i < getLineCount(); i++) {
            String after = getLine(i);
            int idx = CharMatcher.whitespace().negate().indexIn(after);
            if (idx == -1) {
                // Write out trailing empty lines from the formatted output.
                replacement.append(lineSeparator);
            } else {
                if (newline == -1) {
                    // If there wasn't a trailing newline in the input, indent the next line.
                    replacement.append(after.substring(0, idx));
                }
                break;
            }
        }

        result.add(Replacement.create(replaceFrom, replaceTo, replacement.toString()));
    }
    return result.build();
}

From source file:net.sf.mzmine.modules.visualization.scatterplot.ScatterPlotBottomPanel.java

public void actionPerformed(ActionEvent event) {

    String command = event.getActionCommand();

    if (command.equals("DATA_CHANGE")) {

        ScatterPlotAxisSelection optionX = (ScatterPlotAxisSelection) comboX.getSelectedItem();
        ScatterPlotAxisSelection optionY = (ScatterPlotAxisSelection) comboY.getSelectedItem();

        if ((optionX == null) || (optionY == null))
            return;

        String foldText = foldXvalues[comboFold.getSelectedIndex()];
        int foldValue = Integer.parseInt(foldText);
        if (foldValue <= 0)
            foldValue = 2;// w  ww.  j ava  2 s  . co m

        chart.setDisplayedAxes(optionX, optionY, foldValue);
        return;
    }

    if (command.equals("LABEL_ITEMS")) {
        chart.setItemLabels(labeledItems.isSelected());
    }

    if (command.equals("SEARCH")) {

        SearchDefinitionType searchType = (SearchDefinitionType) comboSearchDataType.getSelectedItem();
        String searchRegex = txtSearchField.getText();
        Number minValue = ((Number) minSearchField.getValue());
        if (minValue == null)
            minValue = 0;
        Number maxValue = ((Number) maxSearchField.getValue());
        if (maxValue == null)
            maxValue = 0;
        Range<Double> searchRange = Range.closed(minValue.doubleValue(), maxValue.doubleValue());
        try {
            SearchDefinition newSearch = new SearchDefinition(searchType, searchRegex, searchRange);
            chart.updateSearchDefinition(newSearch);
        } catch (PatternSyntaxException pe) {
            MZmineCore.getDesktop().displayErrorMessage(window,
                    "The regular expression's syntax is invalid: " + pe);
        }
        return;
    }

    if (command.equals("SEARCH_DATA_TYPE")) {

        SearchDefinitionType searchType = (SearchDefinitionType) comboSearchDataType.getSelectedItem();

        switch (searchType) {

        case MASS:
            minSearchField.setVisible(true);
            maxSearchField.setVisible(true);
            labelRange.setVisible(true);
            txtSearchField.setVisible(false);
            NumberFormat mzFormatter = MZmineCore.getConfiguration().getMZFormat();
            Range<Double> mzRange = peakList.getRowsMZRange();
            DefaultFormatterFactory mzFormatFac = new DefaultFormatterFactory(new NumberFormatter(mzFormatter));
            minSearchField.setFormatterFactory(mzFormatFac);
            minSearchField.setValue(mzRange.lowerEndpoint());
            maxSearchField.setFormatterFactory(mzFormatFac);
            maxSearchField.setValue(mzRange.upperEndpoint());
            break;

        case RT:
            minSearchField.setVisible(true);
            maxSearchField.setVisible(true);
            labelRange.setVisible(true);
            txtSearchField.setVisible(false);
            NumberFormat rtFormatter = MZmineCore.getConfiguration().getRTFormat();
            Range<Double> rtRange = peakList.getRowsRTRange();
            DefaultFormatterFactory rtFormatFac = new DefaultFormatterFactory(new NumberFormatter(rtFormatter));
            minSearchField.setFormatterFactory(rtFormatFac);
            minSearchField.setValue(rtRange.lowerEndpoint());
            maxSearchField.setFormatterFactory(rtFormatFac);
            maxSearchField.setValue(rtRange.upperEndpoint());
            break;

        case NAME:
            minSearchField.setVisible(false);
            maxSearchField.setVisible(false);
            labelRange.setVisible(false);
            txtSearchField.setVisible(true);
            break;
        }

        return;
    }

}

From source file:io.github.msdk.io.mzml.MzMLFileImportMethod.java

/** {@inheritDoc} */
@Override//from  w  w  w .  j av a2 s  .  c o  m
public RawDataFile execute() throws MSDKException {

    logger.info("Started parsing file " + sourceFile);

    MzMLUnmarshaller parser;

    // MzMLUnmarshaller throws IllegalStateException when the mzML file
    // structure is invalid
    try {
        parser = new MzMLUnmarshaller(sourceFile);
    } catch (Exception e) {
        throw new MSDKException(e);
    }

    totalScans = parser.getObjectCountForXpath("/run/spectrumList/spectrum");
    totalChromatograms = parser.getObjectCountForXpath("/run/chromatogramList/chromatogram");

    // Prepare data structures
    List<MsFunction> msFunctionsList = new ArrayList<>();
    List<MsScan> scansList = new ArrayList<>();
    List<Chromatogram> chromatogramsList = new ArrayList<>();

    // Create the MzMLRawDataFile object
    final MzMLRawDataFile newRawFile = new MzMLRawDataFile(sourceFile, parser, msFunctionsList, scansList,
            chromatogramsList);
    this.newRawFile = newRawFile;

    // Create the converter from jmzml data model to our data model
    final MzMLConverter converter = new MzMLConverter();

    if (totalScans > 0) {
        MzMLObjectIterator<Spectrum> iterator = parser
                .unmarshalCollectionFromXpath("/run/spectrumList/spectrum", Spectrum.class);

        @Nonnull
        double mzValues[] = new double[1000];
        @Nonnull
        float intensityValues[] = new float[1000];

        while (iterator.hasNext()) {

            if (canceled)
                return null;

            Spectrum spectrum = iterator.next();

            // Get spectrum ID
            String spectrumId = spectrum.getId();

            // Get the scan number
            Integer scanNumber = converter.extractScanNumber(spectrum);

            // Ignore scans that are not MS, e.g. UV, or scans that have no
            // ID or number
            if ((!converter.isMsSpectrum(spectrum)) || (spectrumId == null) || (scanNumber == null)) {
                parsedScans++;
                continue;
            }

            // Get the scan definition
            String scanDefinition = converter.extractScanDefinition(spectrum);

            // Get the MS function
            MsFunction msFunction = converter.extractMsFunction(spectrum);
            msFunctionsList.add(msFunction);

            // Store the chromatography data
            ChromatographyInfo chromData = converter.extractChromatographyData(spectrum);

            // Extract the scan data points, so we can check the m/z range
            // and detect the spectrum type (profile/centroid)
            mzValues = MzMLConverter.extractMzValues(spectrum, mzValues);
            intensityValues = MzMLConverter.extractIntensityValues(spectrum, intensityValues);
            final Integer numOfDataPoints = spectrum.getDefaultArrayLength();

            // Get the m/z range
            Range<Double> mzRange = MsSpectrumUtil.getMzRange(mzValues, numOfDataPoints);

            // Get the instrument scanning range
            Range<Double> scanningRange = null;

            // Get the TIC
            Float tic = MsSpectrumUtil.getTIC(intensityValues, numOfDataPoints);

            // Auto-detect whether this scan is centroided
            MsSpectrumType spectrumType = SpectrumTypeDetectionAlgorithm.detectSpectrumType(mzValues,
                    intensityValues, numOfDataPoints);

            // Get the MS scan type
            MsScanType scanType = converter.extractScanType(spectrum);

            // Get the polarity
            PolarityType polarity = converter.extractPolarity(spectrum);

            // Get the in-source fragmentation
            ActivationInfo sourceFragmentation = converter.extractSourceFragmentation(spectrum);

            // Get the in-source fragmentation
            List<IsolationInfo> isolations = converter.extractIsolations(spectrum);

            // Create a new MsScan instance
            MzMLMsScan scan = new MzMLMsScan(newRawFile, spectrumId, spectrumType, msFunction, chromData,
                    scanType, mzRange, scanningRange, scanNumber, scanDefinition, tic, polarity,
                    sourceFragmentation, isolations, numOfDataPoints);

            // Add the scan to the final raw data file
            scansList.add(scan);

            parsedScans++;

        }
    }

    if (totalChromatograms > 0) {
        MzMLObjectIterator<uk.ac.ebi.jmzml.model.mzml.Chromatogram> iterator = parser
                .unmarshalCollectionFromXpath("/run/chromatogramList/chromatogram",
                        uk.ac.ebi.jmzml.model.mzml.Chromatogram.class);

        ChromatographyInfo rtValues[] = new ChromatographyInfo[1000];

        while (iterator.hasNext()) {

            if (canceled)
                return null;

            uk.ac.ebi.jmzml.model.mzml.Chromatogram chromatogram = iterator.next();

            // Get the chromatogram id
            String chromatogramId = chromatogram.getId();

            // Get the chromatogram number
            Integer chromatogramNumber = chromatogram.getIndex() + 1;

            // Get the separation type
            SeparationType separationType = converter.extractSeparationType(chromatogram);

            // Get the chromatogram type
            ChromatogramType chromatogramType = converter.extractChromatogramType(chromatogram);

            // Get the chromatogram m/z value
            Double mz = converter.extractMz(chromatogram);

            Integer numOfDataPoints = chromatogram.getDefaultArrayLength();

            rtValues = MzMLConverter.extractRtValues(chromatogram, rtValues);
            Range<ChromatographyInfo> rtRange = null;
            if (numOfDataPoints > 0)
                rtRange = Range.closed(rtValues[0], rtValues[numOfDataPoints - 1]);

            // Get the in-source fragmentation
            List<IsolationInfo> isolations = converter.extractIsolations(chromatogram);

            // Create a new Chromatogram instance
            MzMLChromatogram chrom = new MzMLChromatogram(newRawFile, chromatogramId, chromatogramNumber,
                    separationType, mz, chromatogramType, isolations, numOfDataPoints, rtRange);

            // Add the chromatogram to the final raw data file
            chromatogramsList.add(chrom);

            parsedChromatograms++;

        }
    }

    parsedChromatograms = totalChromatograms;
    logger.info("Finished importing " + sourceFile + ", parsed " + parsedScans + " scans and "
            + parsedChromatograms + " chromatograms");

    return newRawFile;

}