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

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

Introduction

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

Prototype

public C upperEndpoint() 

Source Link

Document

Returns the upper endpoint of this range.

Usage

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

@Override
public void append(String text, Range<Integer> range) {
    if (!range.isEmpty()) {
        boolean sawNewlines = false;
        // Skip over input line we've passed.
        int iN = javaInput.getLineCount();
        while (iLine < iN && (javaInput.getRanges(iLine).isEmpty()
                || javaInput.getRanges(iLine).upperEndpoint() <= range.lowerEndpoint())) {
            if (javaInput.getRanges(iLine).isEmpty()) {
                // Skipped over a blank line.
                sawNewlines = true;/*from  ww  w  . j a  v  a  2  s  .  co  m*/
            }
            ++iLine;
        }
        /*
         * Output blank line if we've called {@link OpsBuilder#blankLine}{@code (true)} here, or if
         * there's a blank line here and it's a comment.
         */
        BlankLineWanted wanted = blankLines.getOrDefault(lastK, BlankLineWanted.NO);
        if (isComment(text) ? sawNewlines : wanted.wanted().orElse(sawNewlines)) {
            ++newlinesPending;
        }
    }
    if (Newlines.isNewline(text)) {
        /*
         * Don't update range information, and swallow extra newlines. The case below for '\n' is for
         * block comments.
         */
        if (newlinesPending == 0) {
            ++newlinesPending;
        }
        spacesPending = 0;
    } else {
        boolean rangesSet = false;
        int textN = text.length();
        for (int i = 0; i < textN; i++) {
            char c = text.charAt(i);
            switch (c) {
            case ' ':
                ++spacesPending;
                break;
            case '\r':
                if (i + 1 < text.length() && text.charAt(i + 1) == '\n') {
                    i++;
                }
                // falls through
            case '\n':
                spacesPending = 0;
                ++newlinesPending;
                break;
            default:
                while (newlinesPending > 0) {
                    // drop leading blank lines
                    if (!mutableLines.isEmpty() || lineBuilder.length() > 0) {
                        mutableLines.add(lineBuilder.toString());
                    }
                    lineBuilder = new StringBuilder();
                    rangesSet = false;
                    --newlinesPending;
                }
                while (spacesPending > 0) {
                    lineBuilder.append(' ');
                    --spacesPending;
                }
                lineBuilder.append(c);
                if (!range.isEmpty()) {
                    if (!rangesSet) {
                        while (ranges.size() <= mutableLines.size()) {
                            ranges.add(Formatter.EMPTY_RANGE);
                        }
                        ranges.set(mutableLines.size(), union(ranges.get(mutableLines.size()), range));
                        rangesSet = true;
                    }
                }
            }
        }
    }
    if (!range.isEmpty()) {
        lastK = range.upperEndpoint();
    }
}

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  . j a v  a 2  s .co  m
        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:com.google.cloud.genomics.cba.GGAnnotateVariants.java

@org.apache.beam.sdk.transforms.DoFn.ProcessElement
public void processElement(DoFn<StreamVariantsRequest, KV<String, String>>.ProcessContext c) throws Exception {

    Genomics genomics = GenomicsFactory.builder().build().fromOfflineAuth(auth);

    StreamVariantsRequest request = StreamVariantsRequest.newBuilder(c.element()).addAllCallSetIds(callSetIds)
            .build();//  w  w w.  j  a v a 2  s  .  co m

    if (canonicalizeRefName(request.getReferenceName()).equals("M") && supportChrM == false) {
        LOG.info("There is no information about Chr M in the provided AnnotationSet!");
        return;
    }

    Iterator<StreamVariantsResponse> streamVariantIter = VariantStreamIterator.enforceShardBoundary(auth,
            request, ShardBoundary.Requirement.STRICT, VARIANT_FIELDS);

    if (!streamVariantIter.hasNext()) {
        LOG.info("region has no variants, skipping");
        return;
    }

    Stopwatch stopwatch = Stopwatch.createStarted();
    int varCount = 0;

    ListMultimap<Range<Long>, Annotation> variantAnnotationSetList = null;
    if (this.variantAnnotationSetIds != null)
        variantAnnotationSetList = retrieveVariantAnnotations(genomics, request);

    IntervalTree<Annotation> transcripts = null;
    if (this.transcriptSetIds != null)
        transcripts = retrieveTranscripts(genomics, request);

    while (streamVariantIter.hasNext()) {
        Iterable<Variant> varIter;
        if (onlySNP)
            varIter = FluentIterable.from(streamVariantIter.next().getVariantsList())
                    .filter(VariantUtils.IS_SNP);
        else
            varIter = FluentIterable.from(streamVariantIter.next().getVariantsList());

        for (Variant variant : varIter) {
            Range<Long> pos = Range.closedOpen(variant.getStart(), variant.getEnd());

            // This variable helps to keep track of alignment
            String VCFOutput = "";

            // Keep track of Empty VCF records
            boolean EmptyVCF = false;

            // Variant Annotation Section
            if (variantAnnotationSetList != null) {

                // Sort the list of matched annotations
                SortedSet<String> VariantAnnotationKeys = new TreeSet<String>(VariantColInfo.keySet());

                // Retrieve a list of matched variant annotations
                List<Annotation> listMatchedAnnotations = variantAnnotationSetList.get(pos);

                // Visit overlapped annotations in order, and the matches in
                // order (First convert to VCF format, and then add it to
                // VCFOutput);
                int index = 0;
                for (String key : VariantAnnotationKeys) {
                    // The following variables help to put a semicolon
                    // between multiple matches from the same annotationSet
                    // e.g., allele_freq1;allele_freq2;...;allele_freqn;
                    boolean SemiColon = false;

                    for (Annotation match : listMatchedAnnotations) {
                        if (match.getAnnotationSetId().compareTo(key) == 0) {
                            // if (match.getVariant().getAlternateBases() !=
                            // null
                            // && variant.getAlternateBasesList() != null)
                            {
                                // check if Variant's alternate bases are
                                // the same as the matched annotation's
                                // alternate bases

                                if (compareAlternateBases(match.getVariant().getAlternateBases(),
                                        variant.getAlternateBasesList(), variant.getReferenceBases())) {

                                    EmptyVCF = true;

                                    if (DEBUG)
                                        LOG.info("MATCHED: variant: (" + variant.getStart() + ", Annotation: "
                                                + match.getStart() + ") ");

                                    if (!SemiColon) {
                                        VCFOutput += createVCFFormat(variant, match);
                                        SemiColon = true;
                                        // Activate it for the next matched
                                        // element

                                        // TESTING
                                        VCFOutput += "ALT:" + match.getVariant().getAlternateBases() + "\t";
                                    } else {
                                        VCFOutput += ";" + createVCFFormat(variant, match);

                                        // TESTING
                                        VCFOutput += "ALT:" + match.getVariant().getAlternateBases() + "\t";
                                    }
                                }
                            }
                        }
                    }
                    index++;
                    /*
                     * formatTabs function helps to keep track of alignment
                     * in the VCF format (e.g., if there is no match for
                     * Variant X in AnnotationSet Y then add spaces equals
                     * to the number of AnnotationSet Y's columns in the VCF
                     * file)
                     */
                    if (VCFOutput.isEmpty()
                            && (VariantAnnotationKeys.size() > index || TranscriptColInfo.size() > 0)) {
                        VCFOutput += formatTabs(VariantColInfo.get(key));
                    }
                } // end of keys
                if (!EmptyVCF)
                    VCFOutput = "";
            } // End of Variant Annotation

            // Transcript Annotation Section
            if (transcripts != null) {

                // Find all the overlapped matches and create an interval
                // tree
                Iterator<Node<Annotation>> transcriptIter = transcripts
                        .overlappers(pos.lowerEndpoint().intValue(), pos.upperEndpoint().intValue() - 1); // Inclusive.

                Iterator<Node<Annotation>> StartPoint = transcriptIter;
                if (transcriptIter != null) {
                    // Sort the list of matched annotations
                    SortedSet<String> transcriptKeys = new TreeSet<String>(TranscriptColInfo.keySet());
                    int index = 0;
                    // Check annotations in order, and in the case of match
                    // convert the matches to VCF format
                    for (String key : transcriptKeys) {
                        transcriptIter = StartPoint;
                        boolean SemiColon = false;
                        while (transcriptIter.hasNext()) {
                            Annotation transcript = transcriptIter.next().getValue();
                            if (transcript.getAnnotationSetId().compareTo(key) == 0) {
                                if (!SemiColon) {
                                    VCFOutput += createVCFFormat(variant, transcript);
                                    SemiColon = true;
                                } else
                                    VCFOutput += ";" + createVCFFormat(variant, transcript);
                            }
                        }
                        index++;

                        if (VCFOutput.isEmpty() && transcriptKeys.size() > index) {
                            VCFOutput += formatTabs(TranscriptColInfo.get(key));
                        }
                    }
                }
            } // End of Transcripts

            String varintALTs = "";
            for (int index = 0; index < variant.getAlternateBasesCount(); index++) {
                if (index > 0)
                    varintALTs += ",";
                varintALTs += variant.getAlternateBases(index);
            }

            // The following section helps to add genotypes
            /*
             * String VariantGenotype=""; List<VariantCall> Genotypes =
             * variant.getCallsList();
             * 
             * for(String CId: callSetIds){ for(VariantCall VC:Genotypes){
             * if(VC.getCallSetId().equals(CId)){
             * 
             * List<Integer> GentotypeList = VC.getGenotypeList(); for(int
             * index=0; index < GentotypeList.size(); index++){ int Genotype
             * = GentotypeList.get(index);
             * 
             * if(index>0) VariantGenotype += "/";
             * 
             * VariantGenotype += Genotype; } } } VariantGenotype += "\t"; }
             */
            // Map<String, ListValue> VariantInfoMap = variant.getInfo();
            /*
             * String VariantInfo=""; List<VariantCall> VariantCall =
             * variant.getCallsList(); for (Iterator<VariantCall> iter =
             * VariantCall.iterator(); iter.hasNext(); ) { VariantCall
             * element = iter.next(); Map<String, ListValue> VariantCallInfo
             * = element.getInfo(); for (Map.Entry<String, ListValue> entry
             * : VariantCallInfo.entrySet()) { VariantInfo +=entry.getKey()
             * + ":" +
             * entry.getValue().getValuesList().get(0).getStringValue() +
             * ";"; } }
             * 
             * 
             * 
             * /* for (Map.Entry<String, ListValue> entry :
             * VariantInfoMap.entrySet()) { //System.out.println("Key = " +
             * entry.getKey() + ", Value = " + entry.getValue());
             * VariantInfo += entry.getKey() + ":" + entry.getValue() + ";";
             * }
             */

            /*
             * Emit the information in the form of <Key, Value> Print out
             * the variant w/ or w/o any matched annotations Key: (ChromId,
             * Start, End) Value:(variant's <referenceName start end
             * referenceBases alternateBases quality>, + The content of
             * "VCFOutput" OR Annotation's fields
             */
            if (this.BigQuery) {
                if (!VCFOutput.isEmpty()) {
                    c.output(KV.of(
                            variant.getReferenceName() + ";" + Long.toString(variant.getStart()) + ";"
                                    + Long.toString(variant.getEnd()),
                            // Value
                            VCFOutput));
                }
            } else {
                if (!VCFOutput.isEmpty()) {
                    c.output(KV.of(
                            variant.getReferenceName() + ";" + Long.toString(variant.getStart()) + ";"
                                    + Long.toString(variant.getEnd()),
                            // Value
                            variant.getReferenceName()
                                    // <-- increment by 1 => convert to 1-based
                                    // -->
                                    + "\t" + (variant.getStart() + 1) + "\t" + variant.getEnd() + "\t"
                                    + variant.getReferenceBases() + "\t" + varintALTs
                                    // + "\t" + VariantInfo
                                    // + "\t" + variant.getQuality()
                                    // + "\t" + VariantGenotype
                                    + "\t" + VCFOutput));
                }
            }

            varCount++;
            if (varCount % 1e3 == 0) {
                LOG.info(String.format("read %d variants (%.2f / s)", varCount,
                        (double) varCount / stopwatch.elapsed(TimeUnit.SECONDS)));
            }
        }

    }

    LOG.info("finished reading " + varCount + " variants in " + stopwatch);
}