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:org.onosproject.driver.optical.power.OplinkRoadmPowerConfig.java

private Range<Long> getInputPortPowerRange(PortNumber port) {
    Range<Long> range = null;
    long portNum = port.toLong();
    if (portNum == LINE_IN) {
        // TODO implement support for IR and ER range
        // only supports LR right now
        range = Range.closed(-2600L, 540L);
    } else if (portNum == AUX_IN_1 || portNum == AUX_IN_2) {
        range = Range.closed(-1250L, 1590L);
    } else if (portNum >= EXPRESS_IN_1 && portNum <= EXPRESS_IN_7) {
        range = Range.closed(-1420L, 1420L);
    }//from   ww  w  .j a  va 2  s.c o m
    return range;
}

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

/**
 * Returns a range spanning the indices written in this storage during an
 * execution of the given schedule. (Note that, as a span, not every
 * contained index will be written.) The returned range will be
 * {@link Range#canonical(com.google.common.collect.DiscreteDomain) canonical}.
 * The range is not cached so as to be responsive to changes in output index
 * functions.//from   ww  w .  j  av  a  2s.c om
 * @param externalSchedule the schedule
 * @return a range spanning the indices written during the given schedule
 * under the current index functions
 * @see #writeIndices(java.util.Map)
 */
public Range<Integer> writeIndexSpan(Map<ActorGroup, Integer> externalSchedule) {
    Range<Integer> range = null;
    for (Actor a : upstream()) {
        //just the first and last iteration
        int maxIteration = a.group().schedule().get(a) * externalSchedule.get(a.group()) - 1;
        if (maxIteration >= 0)
            for (int iteration : new int[] { 0, maxIteration }) {
                ImmutableSortedSet<Integer> writes = a.writes(this, iteration);
                Range<Integer> writeRange = writes.isEmpty() ? range
                        : Range.closed(writes.first(), writes.last());
                range = range == null ? writeRange : range.span(writeRange);
            }
    }
    range = (range != null ? range : Range.closedOpen(0, 0));
    return range.canonical(DiscreteDomain.integers());
}

From source file:org.onosproject.driver.optical.power.OplinkPowerConfigUtil.java

/**
 * Returns the acceptable attenuation range for a connection (represented as
 * a flow with attenuation instruction). Port can be either the input or
 * output port of the connection. Returns null if the connection does not
 * support attenuation.//  www.  j  a va2 s  .c o  m
 *
 * @param portNum the port number
 * @return attenuation range
 */
private Range<Long> getChannelAttenuationRange(PortNumber portNum) {
    OpenFlowSwitch ofs = getOpenFlowDevice();
    if (ofs == null) {
        return null;
    }
    if (ofs.deviceType() != Type.ROADM) {
        return null;
    }
    PortDescType portType = getPortDescType((OpenFlowOpticalSwitch) ofs, portNum);
    // Short time hard code.
    // The port type and attenuation range will be obtained from physical device in the future.
    if (portType == PortDescType.PA_LINE_OUT || portType == PortDescType.EXP_IN
            || portType == PortDescType.AUX_IN) {
        return Range.closed(ROADM_MIN_ATTENUATION, ROADM_MAX_ATTENUATION);
    }
    // Unexpected port. Do not need warning here for port polling.
    return null;
}

From source file:com.pinterest.pinlater.PinLaterBackendBase.java

public Future<Integer> getJobCount(final PinLaterGetJobCountRequest request) {
    // If no priority is specified, search for jobs of all priorities.
    Range<Integer> priorityRange = request.isSetPriority()
            ? Range.closed((int) request.getPriority(), (int) request.getPriority())
            : Range.closed(1, numPriorityLevels);
    final ContiguousSet<Integer> priorities = ContiguousSet.create(priorityRange, DiscreteDomain.integers());

    // Execute count query on each shard in parallel.
    List<Future<Integer>> futures = Lists.newArrayListWithCapacity(getShards().size());
    for (final String shardName : getShards()) {
        futures.add(futurePool.apply(new ExceptionalFunction0<Integer>() {
            @Override//  ww  w .  jav  a 2 s  .c  o  m
            public Integer applyE() throws Throwable {
                return getJobCountFromShard(request.getQueueName(), shardName, priorities,
                        request.getJobState(), request.isCountFutureJobs(), request.getBodyRegexToMatch());
            }
        }));
    }

    return Future.collect(futures).map(new Function<List<Integer>, Integer>() {
        @Override
        public Integer apply(List<Integer> shardCounts) {
            int totalCount = 0;
            for (Integer shardCount : shardCounts) {
                totalCount += shardCount;
            }
            return totalCount;
        }
    });
}

From source file:juicebox.mapcolorui.HeatmapRenderer.java

private void updatePreDefColors() {
    int arrSize = MainViewPanel.preDefMapColorGradient.size();

    ImmutableSortedSet<Integer> set = ContiguousSet.create(Range.closed(0, arrSize), DiscreteDomain.integers());
    Integer[] arrTmp = set.toArray(new Integer[arrSize]);
    final int[] arrScores = new int[arrSize];

    for (int idx = 0; idx < arrSize; idx++) {
        arrScores[idx] = arrTmp[idx];//from  ww  w.jav a  2  s . com
    }

    preDefColorScale.updateColors(MainViewPanel.preDefMapColorGradient.toArray(new Color[arrSize]), arrScores);
}

From source file:org.gbif.occurrence.download.service.HiveQueryVisitor.java

/**
 * Converts a Date query into conjunction predicate.
 * If the value has the forms 'yyyy'/'yyyy-MM' it's translated to:
 *  field >= firstDateOfYear/Month(value) and field <= lastDateOfYear/Month(value).
 * If the value is a range it is translated to: field >= range.lower AND field <= range.upper.
 *//*w  w w  .jav a  2  s .  c o m*/
private CompoundPredicate toDatePredicateQuery(OccurrenceSearchParameter key, String value,
        IsoDateFormat dateFormat) {
    final Date lowerDate = IsoDateParsingUtils.parseDate(value);
    return toDateRangePredicate(Range.closed(lowerDate, IsoDateParsingUtils.toLastDayOf(lowerDate, dateFormat)),
            key);
}

From source file:net.sf.mzmine.util.components.PeakSummaryComponent.java

public void actionPerformed(ActionEvent e) {

    String command = e.getActionCommand();

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

        String visualizerType = (String) comboShow.getSelectedItem();
        int[] indexesRow = peaksInfoList.getSelectedRows();
        Feature[] selectedPeaks = new Feature[indexesRow.length];
        RawDataFile[] dataFiles = new RawDataFile[indexesRow.length];
        Range<Double> rtRange = null, mzRange = null;
        for (int i = 0; i < indexesRow.length; i++) {
            selectedPeaks[i] = listElementModel.getElementAt(indexesRow[i]);
            dataFiles[i] = selectedPeaks[i].getDataFile();

            if ((rtRange == null) || (mzRange == null)) {
                rtRange = dataFiles[i].getDataRTRange(1);
                mzRange = selectedPeaks[i].getRawDataPointsMZRange();
            } else {
                rtRange = rtRange.span(dataFiles[i].getDataRTRange(1));
                mzRange = mzRange.span(selectedPeaks[i].getRawDataPointsMZRange());
            }/*from w w  w.jav  a2 s .  c  o  m*/
        }

        if (dataFiles.length == 0) {
            return;
        }

        if (visualizerType.equals("Chromatogram")) {

            // Label best peak with preferred identity.
            final Feature bestPeak = row.getBestPeak();
            final PeakIdentity peakIdentity = row.getPreferredPeakIdentity();
            final Map<Feature, String> labelMap = new HashMap<Feature, String>(1);
            if (bestPeak != null && peakIdentity != null) {

                labelMap.put(bestPeak, peakIdentity.getName());
            }

            ScanSelection scanSelection = new ScanSelection(rtRange, 1);

            TICVisualizerModule.showNewTICVisualizerWindow(dataFiles, selectedPeaks, labelMap, scanSelection,
                    TICPlotType.BASEPEAK, mzRange);
            return;

        } else if (visualizerType.equals("Mass spectrum")) {
            for (int i = 0; i < selectedPeaks.length; i++) {
                SpectraVisualizerModule.showNewSpectrumWindow(dataFiles[i],
                        selectedPeaks[i].getRepresentativeScanNumber());
            }
        } else if (visualizerType.equals("Peak in 2D")) {
            for (int i = 0; i < selectedPeaks.length; i++) {
                Range<Double> peakRTRange = selectedPeaks[i].getRawDataPointsRTRange();
                Range<Double> peakMZRange = selectedPeaks[i].getRawDataPointsMZRange();
                final double rtLen = peakRTRange.upperEndpoint() - peakRTRange.lowerEndpoint();
                Range<Double> localRTRange = Range.closed(Math.max(0, peakRTRange.lowerEndpoint() - rtLen),
                        peakRTRange.upperEndpoint() + rtLen);

                final double mzLen = peakMZRange.upperEndpoint() - peakMZRange.lowerEndpoint();
                Range<Double> localMZRange = Range.closed(Math.max(0, peakMZRange.lowerEndpoint() - mzLen),
                        peakMZRange.upperEndpoint() + mzLen);
                TwoDVisualizerModule.show2DVisualizerSetupDialog(dataFiles[i], localMZRange, localRTRange);
            }
        } else if (visualizerType.equals("Peak in 3D")) {
            for (int i = 0; i < selectedPeaks.length; i++) {
                Range<Double> peakRTRange = selectedPeaks[i].getRawDataPointsRTRange();
                Range<Double> peakMZRange = selectedPeaks[i].getRawDataPointsMZRange();
                final double rtLen = peakRTRange.upperEndpoint() - peakRTRange.lowerEndpoint();
                Range<Double> localRTRange = Range.closed(Math.max(0, peakRTRange.lowerEndpoint() - rtLen),
                        peakRTRange.upperEndpoint() + rtLen);
                final double mzLen = peakMZRange.upperEndpoint() - peakMZRange.lowerEndpoint();
                Range<Double> localMZRange = Range.closed(Math.max(0, peakMZRange.lowerEndpoint() - mzLen),
                        peakMZRange.upperEndpoint() + mzLen);
                ThreeDVisualizerModule.setupNew3DVisualizer(dataFiles[i], localMZRange, localRTRange);
            }
        } else if (visualizerType.equals("MS/MS")) {
            for (int i = 0; i < selectedPeaks.length; i++) {
                int scanNumber = selectedPeaks[i].getMostIntenseFragmentScanNumber();
                if (scanNumber > 0) {
                    SpectraVisualizerModule.showNewSpectrumWindow(dataFiles[i], scanNumber);
                } else {
                    JFrame frame = (JFrame) SwingUtilities.getAncestorOfClass(JFrame.class, this);
                    MZmineCore.getDesktop().displayMessage(frame, "There is no fragment for the mass "
                            + MZmineCore.getConfiguration().getMZFormat().format(selectedPeaks[i].getMZ())
                            + "m/z in the current raw data.");
                    return;
                }
            }

        } else if (visualizerType.equals("Isotope pattern")) {
            for (int i = 0; i < selectedPeaks.length; i++) {
                IsotopePattern ip = selectedPeaks[i].getIsotopePattern();
                if (ip == null) {
                    return;
                }
                SpectraVisualizerModule.showNewSpectrumWindow(dataFiles[i],
                        selectedPeaks[i].getMostIntenseFragmentScanNumber(), ip);

            }
        }
        return;
    }

    if (command.equals("CHANGE")) {
        int indexRow = peaksInfoList.getSelectedRow();
        if (indexRow == -1) {
            return;
        }
        Feature selectedPeak = listElementModel.getElementAt(indexRow);
        ManualPeakPickerModule.runManualDetection(selectedPeak.getDataFile(), row, null, null);

        return;
    }

}

From source file:org.corpus_tools.salt.common.tokenizer.Tokenizer.java

/**
 * The general task of this class is to tokenize a given text in the same
 * order as the tool TreeTagger will do. A list of tokenized text is
 * returned with the text anchor (start and end position) in original text.
 * If the {@link SDocumentGraph} already contains tokens, the tokens will be
 * preserved, if they overlap the same textual range as the new one.
 * Otherwise a {@link SSpan} is created covering corresponding to the
 * existing token. The span than overlaps all new tokens and contains all
 * annotations the old token did. In case, the span would overlaps the same
 * textual range as the old token did, no span is created.
 * /*from w  w  w  .j  ava 2  s  .c  o m*/
 * @param strInput
 *            original text
 * @return tokenized text fragments and their position in the original text
 */
public List<SToken> tokenizeToToken(STextualDS sTextualDS, LanguageCode language, Integer startPos,
        Integer endPos) {
    List<SToken> retVal = null;
    List<String> strTokens = null;
    String strInput = sTextualDS.getText().substring(startPos, endPos);

    strTokens = tokenizeToString(strInput, language);
    if (strTokens.size() > 0) {
        char[] chrText = strInput.toCharArray();
        int tokenCntr = 0;

        // check if tokens exist for passed span
        List<SToken> tokens = null;
        if ((startPos != 0) || (endPos != sTextualDS.getText().length())
                || (getDocumentGraph().getTextualDSs().size() > 1)) {
            DataSourceSequence sequence = new DataSourceSequence();
            sequence.setDataSource(sTextualDS);
            sequence.setStart(startPos);
            sequence.setEnd(endPos);
            tokens = getDocumentGraph().getTokensBySequence(sequence);
        } else {
            tokens = getDocumentGraph().getTokens();
        }

        RangeMap<Integer, SToken> oldTokens = null;
        // create an organization structure for a tokens interval which
        // corresponds to a token
        if ((tokens != null) && (tokens.size() != 0)) {
            if ((getDocumentGraph().getTextualRelations() != null)
                    && (getDocumentGraph().getTextualRelations().size() > 0)) {
                oldTokens = TreeRangeMap.create();
                for (STextualRelation rel : getDocumentGraph().getTextualRelations()) {
                    oldTokens.put(Range.closed(rel.getStart(), rel.getEnd()), rel.getSource());
                }
            }
        }
        // a map mapping new created tokens, to old already existing tokens.
        // The old tokens should be removed later on and spans should be
        // created instead
        Multimap<SToken, SToken> old2newToken = ArrayListMultimap.create();

        for (int i = 0; i < chrText.length; i++) {
            if ((strTokens.get(tokenCntr).length() < 1)
                    || (strTokens.get(tokenCntr).substring(0, 1).equals(String.valueOf(chrText[i])))) {
                // first letter matches
                StringBuffer pattern = new StringBuffer();
                for (int y = 0; y < strTokens.get(tokenCntr).length(); y++) {
                    // compute pattern in text
                    pattern.append(chrText[i + y]);
                } // compute pattern in text
                if (strTokens.get(tokenCntr).hashCode() == pattern.toString().hashCode()) {
                    // pattern found
                    int start = i + startPos;
                    int end = i + startPos + strTokens.get(tokenCntr).length();

                    if (this.getDocumentGraph() == null) {
                        throw new SaltTokenizerException(
                                "Cannot add tokens to an empty SDocumentGraph object.");
                    }

                    SToken sTok = this.getDocumentGraph().createToken(sTextualDS, start, end);
                    if (retVal == null) {
                        retVal = new ArrayList<SToken>();
                    }
                    retVal.add(sTok);
                    i = i + strTokens.get(tokenCntr).length() - 1;
                    tokenCntr++;
                    if (tokenCntr >= strTokens.size()) {
                        break;
                    }

                    /**
                     * check, if there is an old token, overlapping the same
                     * or a bigger span as the currently created one. If
                     * yes, remove the old one and create a span overlapping
                     * the new one.
                     **/
                    if (oldTokens != null) {
                        SToken oldToken = oldTokens.get(start);
                        if (oldToken != null) {
                            old2newToken.put(oldToken, sTok);
                        }
                    }

                } // pattern found
            } // first letter matches
        }

        if (old2newToken != null) {
            for (SToken oldToken : old2newToken.keySet()) {
                // create span for oldToken
                List<SToken> overlappedTokens = new ArrayList<SToken>(old2newToken.get(oldToken));
                if (overlappedTokens.size() == 1) {
                    getDocumentGraph().removeNode(overlappedTokens.get(0));
                } else {

                    SSpan span = getDocumentGraph().createSpan(overlappedTokens);

                    // move all annotations from old token to span
                    for (SAnnotation sAnno : oldToken.getAnnotations()) {
                        span.addAnnotation(sAnno);
                    }

                    // redirect all relations to span
                    List<SRelation<SNode, SNode>> inRels = new ArrayList<>();
                    for (SRelation rel : getDocumentGraph().getInRelations(oldToken.getId())) {
                        inRels.add(rel);
                    }
                    for (SRelation inRel : inRels) {
                        if (inRel instanceof SSpanningRelation) {
                            // in case of edge is a SSpanningRelation remove
                            // it and create new ones for each token under
                            // the span
                            if (inRel.getSource() instanceof SSpan) {
                                SSpan parentSpan = (SSpan) inRel.getSource();
                                getDocumentGraph().removeRelation(inRel);
                                for (SToken overlappedToken : overlappedTokens) {
                                    SSpanningRelation rel = SaltFactory.createSSpanningRelation();
                                    rel.setSource(parentSpan);
                                    rel.setTarget(overlappedToken);
                                    getDocumentGraph().addRelation(rel);
                                }
                            }
                        } else {
                            inRel.setTarget(span);
                        }
                    }
                    List<SRelation<SNode, SNode>> outRels = new ArrayList<>();
                    for (SRelation outRel : getDocumentGraph().getOutRelations(oldToken.getId())) {
                        if (!(outRel instanceof STextualRelation)) {
                            outRels.add(outRel);
                        }
                    }
                    for (SRelation outRel : outRels) {
                        outRel.setSource(span);
                    }
                    getDocumentGraph().removeNode(oldToken);
                }
            }
        }
    }
    return (retVal);
}

From source file:org.sleuthkit.autopsy.timeline.ui.detailview.DetailsChartLane.java

/**
 * Given information about the current layout pass so far and about a
 * particular node, compute the y position of that node.
 *
 *
 * @param yMin    the smallest (towards the top of the screen) y position to
 *                consider//  w  ww  .j  a  va 2 s  .c  o  m
 * @param h       the height of the node we are trying to position
 * @param maxXatY a map from y ranges to the max x within that range. NOTE:
 *                This map will be updated to include the node in question.
 * @param xLeft   the left x-cord of the node to position
 * @param xRight  the left x-cord of the node to position
 *
 * @return the y position for the node in question.
 *
 *
 */
double computeYTop(double yMin, double h, TreeRangeMap<Double, Double> maxXatY, double xLeft, double xRight) {
    double yTop = yMin;
    double yBottom = yTop + h;
    //until the node is not overlapping any others try moving it down.
    boolean overlapping = true;
    while (overlapping) {
        overlapping = false;
        //check each pixel from bottom to top.
        for (double y = yBottom; y >= yTop; y -= MINIMUM_ROW_HEIGHT) {
            final Double maxX = maxXatY.get(y);
            if (maxX != null && maxX >= xLeft - MINIMUM_EVENT_NODE_GAP) {
                //if that pixel is already used
                //jump top to this y value and repeat until free slot is found.
                overlapping = true;
                yTop = y + MINIMUM_EVENT_NODE_GAP;
                yBottom = yTop + h;
                break;
            }
        }
    }
    maxXatY.put(Range.closed(yTop, yBottom), xRight);
    return yTop;
}

From source file:ddf.catalog.filter.impl.SimpleFilterDelegate.java

public T propertyIsBetween(String propertyName, Date lowerBoundary, Date upperBoundary) {
    return comparisonOperation(propertyName, Range.closed(lowerBoundary, upperBoundary), Range.class,
            ComparisonPropertyOperation.IS_BETWEEN);
}