List of usage examples for com.google.common.collect Range closedOpen
public static <C extends Comparable<?>> Range<C> closedOpen(C lower, C upper)
From source file:org.nmdp.ngs.fca.CrossTable.java
public Row getRow(int index) { checkArgument(Range.closedOpen(0, (int) nrow).contains(index)); return table.get(index); }
From source file:edu.cmu.lti.oaqa.framework.eval.passage.PassageMAPEvalAggregator.java
private float getAvgPsg2MAP(List<Passage> docs, List<Passage> gs) { if (gs.size() == 0) { return 0; }/* w w w .j ava 2s . c o m*/ Map<String, RangeSet<Integer>> gsId2Spans = Maps.newHashMap(); Map<String, RangeSet<Integer>> trackGsId2Spans = Maps.newHashMap(); for (Passage g : gs) { String id = g.getUri(); if (!gsId2Spans.containsKey(id)) { gsId2Spans.put(id, TreeRangeSet.<Integer>create()); trackGsId2Spans.put(id, TreeRangeSet.<Integer>create()); } gsId2Spans.get(g.getUri()).add(Range.closedOpen(g.getBegin(), g.getEnd())); trackGsId2Spans.get(g.getUri()).add(Range.closedOpen(g.getBegin(), g.getEnd())); } int totalChars = 0; int overlapLength = 0; float sumPrecision = 0; for (Passage doc : docs) { Range<Integer> docRange = Range.closedOpen(doc.getBegin(), doc.getEnd()); String docId = doc.getUri(); if (!gsId2Spans.containsKey(docId) || gsId2Spans.get(docId).encloses(docRange)) { totalChars += docRange.upperEndpoint() - docRange.lowerEndpoint(); continue; } for (int offset = docRange.lowerEndpoint(); offset < docRange.upperEndpoint(); offset++) { if (gsId2Spans.containsKey(docId) && gsId2Spans.get(docId).contains(offset)) { if (trackGsId2Spans.get(docId).contains(offset)) { trackGsId2Spans.get(docId).remove(Range.singleton(offset)); // +1 totalChars++; overlapLength++; sumPrecision += (float) overlapLength / (float) totalChars; } } else { // -1 totalChars++; } } } int count = 0; for (RangeSet<Integer> spans : gsId2Spans.values()) { for (Range<Integer> span : spans.asRanges()) { count += span.upperEndpoint() - span.lowerEndpoint(); } } return (float) sumPrecision / (float) count; }
From source file:edu.cmu.lti.oaqa.baseqa.abstract_query.TokenConceptAbstractQueryGenerator.java
@Override public void process(JCas jcas) throws AnalysisEngineProcessException { Collection<Concept> concepts = TypeUtil.getConcepts(jcas); List<QueryConcept> qconcepts = ConceptAbstractQueryGenerator.createQueryConceptsFromConceptMentions(jcas, concepts, useType, useWeight); // filter tokens that are covered by concept mentions RangeSet<Integer> cmentionRanges = TreeRangeSet.create(); concepts.stream().map(TypeUtil::getConceptMentions).flatMap(Collection::stream) .map(cmention -> Range.closedOpen(cmention.getBegin(), cmention.getEnd())) .forEach(cmentionRanges::add); // create an aquery using all tokens with POS in posTags set List<Token> tokens = TypeUtil.getOrderedTokens(jcas).stream() .filter(token -> !cmentionRanges.encloses(Range.closedOpen(token.getBegin(), token.getEnd()))) .collect(toList());/*ww w .j a va 2s . c o m*/ List<QueryConcept> qconceptTokens = TokenSelectionAbstractQueryGenerator.createQueryConceptsFromTokens(jcas, tokens, posTags, stoplist); qconceptTokens.addAll(qconcepts); AbstractQuery aquery = TypeFactory.createAbstractQuery(jcas, qconceptTokens); aquery.addToIndexes(); // create a backup aquery using only nouns List<QueryConcept> qconceptNouns = TokenSelectionAbstractQueryGenerator.createQueryConceptsFromTokens(jcas, tokens, nounTags, stoplist); qconceptNouns.addAll(qconcepts); AbstractQuery aqueryNoun = TypeFactory.createAbstractQuery(jcas, qconceptNouns); aqueryNoun.addToIndexes(); }
From source file:guru.qas.martini.gherkin.DefaultMixology.java
protected RangeMap<Integer, ScenarioDefinition> getRangeMap(FeatureWrapper feature) { List<ScenarioDefinition> children = Lists.newArrayList(feature.getChildren()); ImmutableRangeMap.Builder<Integer, ScenarioDefinition> builder = ImmutableRangeMap.builder(); while (!children.isEmpty()) { ScenarioDefinition child = children.remove(0); Location location = child.getLocation(); Integer childStart = location.getLine(); ScenarioDefinition sibling = children.isEmpty() ? null : children.get(0); Location siblingLocation = null == sibling ? null : sibling.getLocation(); Integer siblingStart = null == siblingLocation ? null : siblingLocation.getLine(); Range<Integer> range = null == siblingStart ? Range.atLeast(childStart) : Range.closedOpen(childStart, siblingStart); builder.put(range, child);//from www .j a v a 2s.c om } return builder.build(); }
From source file:com.google.errorprone.bugpatterns.BooleanParameter.java
private void checkParameter(VarSymbol paramSym, ExpressionTree a, int start, Deque<ErrorProneToken> tokens, VisitorState state) {/*from ww w . j ava 2 s . co m*/ if (!isBooleanLiteral(a)) { return; } if (state.getTypes().unboxedTypeOrType(paramSym.type).getTag() != TypeTag.BOOLEAN) { // don't suggest on non-boolean (e.g., generic) parameters) return; } String name = paramSym.getSimpleName().toString(); if (name.length() < 2) { // single-character parameter names aren't helpful return; } if (EXCLUDED_NAMES.contains(name)) { return; } while (!tokens.isEmpty() && ((start + tokens.peekFirst().pos()) < ((JCTree) a).getStartPosition())) { tokens.removeFirst(); } if (tokens.isEmpty()) { return; } Range<Integer> argRange = Range.closedOpen(((JCTree) a).getStartPosition(), state.getEndPosition(a)); if (!argRange.contains(start + tokens.peekFirst().pos())) { return; } if (hasParameterComment(tokens.removeFirst())) { return; } state.reportMatch( describeMatch(a, SuggestedFix.prefixWith(a, String.format("/* %s= */", paramSym.getSimpleName())))); }
From source file:it.units.malelab.ege.ge.mapper.HierarchicalMapper.java
@Override public Node<T> map(BitsGenotype genotype, Map<String, Object> report) throws MappingException { int[] bitUsages = new int[genotype.size()]; Node<T> tree;/*from w w w . j a va 2 s . co m*/ if (recursive) { tree = mapRecursively(grammar.getStartingSymbol(), Range.closedOpen(0, genotype.size()), genotype, bitUsages); } else { tree = mapIteratively(genotype, bitUsages); } report.put(BIT_USAGES_INDEX_NAME, bitUsages); //convert return tree; }
From source file:com.google.devtools.javatools.transform.scrubber.StrippingRangeRecorder.java
private void removeElement(JCTree tree) { int startPos = tree.getStartPosition(); /*//from w w w.j av a 2 s. c om * The end position of this element, exclusive. Move to the beginning * of the next line if possible. */ int endPos = tree.getEndPosition(compilationUnit.endPositions); final int endPosLineNumber = (int) lineMap.getLineNumber(endPos); if (endPosLineNumber < lastLine) { endPos = (int) lineMap.getStartPosition(endPosLineNumber + 1); } /* * If this element has javadoc, backtrack and skip it. The javadoc is * identified by a regex derived from the content. */ if (compilationUnit.docComments.containsKey(tree)) { startPos = backtrackForJavadoc(tree, startPos); } /* * Strip the leading blank lines as well. */ startPos = backtraceForLeadingWhitespace(startPos); /* * Move the startingPos to the beginning of line to avoid trailing whitespace * of the previous remaining program elements. */ startPos = (int) lineMap.getStartPosition(lineMap.getLineNumber(startPos)); rangesToRemove.add(Range.closedOpen(startPos, endPos)); }
From source file:com.google.errorprone.bugpatterns.javadoc.UnescapedEntity.java
private Description handle(@Nullable DocTreePath path, VisitorState state) { if (path == null) { return NO_MATCH; }//from ww w. ja v a2 s . com RangesFinder rangesFinder = new RangesFinder(state); rangesFinder.scan(path, null); Comment comment = ((DCDocComment) path.getDocComment()).comment; Matcher matcher = GENERIC_PATTERN.matcher(comment.getText()); RangeSet<Integer> generics = TreeRangeSet.create(); while (matcher.find()) { generics.add( Range.closedOpen(comment.getSourcePos(matcher.start()), comment.getSourcePos(matcher.end()))); } RangeSet<Integer> emittedFixes = fixGenerics(generics, rangesFinder.preTags, rangesFinder.dontEmitCodeFix, state); new EntityChecker(state, generics, rangesFinder.preTags, emittedFixes).scan(path, null); return NO_MATCH; }
From source file:com.google.googlejavaformat.java.StringWrapper.java
/** * Reflows string literals in the given Java source code that extend past the given column limit. */// ww w. ja v a 2 s. c o m static String wrap(final int columnLimit, final String input) throws FormatterException { if (!longLines(columnLimit, input)) { // fast path return input; } JCTree.JCCompilationUnit unit = parse(input, /* allowStringFolding= */ false); String separator = Newlines.guessLineSeparator(input); // Paths to string literals that extend past the column limit. List<TreePath> toFix = new ArrayList<>(); final Position.LineMap lineMap = unit.getLineMap(); new TreePathScanner<Void, Void>() { @Override public Void visitLiteral(LiteralTree literalTree, Void aVoid) { if (literalTree.getKind() != Kind.STRING_LITERAL) { return null; } Tree parent = getCurrentPath().getParentPath().getLeaf(); if (parent instanceof MemberSelectTree && ((MemberSelectTree) parent).getExpression().equals(literalTree)) { return null; } int endPosition = getEndPosition(unit, literalTree); int lineEnd = endPosition; while (Newlines.hasNewlineAt(input, lineEnd) == -1) { lineEnd++; } if (lineMap.getColumnNumber(lineEnd) - 1 <= columnLimit) { return null; } toFix.add(getCurrentPath()); return null; } }.scan(new TreePath(unit), null); TreeRangeMap<Integer, String> replacements = TreeRangeMap.create(); for (TreePath path : toFix) { // Find the outermost contiguous enclosing concatenation expression TreePath enclosing = path; while (enclosing.getParentPath().getLeaf().getKind() == Tree.Kind.PLUS) { enclosing = enclosing.getParentPath(); } // Is the literal being wrapped the first in a chain of concatenation expressions? // i.e. `ONE + TWO + THREE` // We need this information to handle continuation indents. AtomicBoolean first = new AtomicBoolean(false); // Finds the set of string literals in the concat expression that includes the one that needs // to be wrapped. List<Tree> flat = flatten(input, unit, path, enclosing, first); // Zero-indexed start column int startColumn = lineMap.getColumnNumber(getStartPosition(flat.get(0))) - 1; // Handling leaving trailing non-string tokens at the end of the literal, // e.g. the trailing `);` in `foo("...");`. int end = getEndPosition(unit, getLast(flat)); int lineEnd = end; while (Newlines.hasNewlineAt(input, lineEnd) == -1) { lineEnd++; } int trailing = lineEnd - end; // Get the original source text of the string literals, excluding `"` and `+`. ImmutableList<String> components = stringComponents(input, unit, flat); replacements.put(Range.closedOpen(getStartPosition(flat.get(0)), getEndPosition(unit, getLast(flat))), reflow(separator, columnLimit, startColumn, trailing, components, first.get())); } String result = applyReplacements(input, replacements); { // We really don't want bugs in this pass to change the behaviour of programs we're // formatting, so check that the pretty-printed AST is the same before and after reformatting. String expected = parse(input, /* allowStringFolding= */ true).toString(); String actual = parse(result, /* allowStringFolding= */ true).toString(); if (!expected.equals(actual)) { throw new FormatterException(String.format("Something has gone terribly wrong. Please file a bug: " + "https://github.com/google/google-java-format/issues/new" + "\n\n=== Actual: ===\n%s\n=== Expected: ===\n%s\n", actual, expected)); } } return result; }
From source file:com.yahoo.bard.webservice.metadata.DataSourceMetadata.java
/** * Build the range set of intervals for the entries. * * @param entries Entries to build the intervals for * @param interval Interval to add to each of the entries * @param container Map into which to build the interval sets *//* w w w .j a va2 s. c o m*/ private static void buildRangeSet(List<String> entries, Interval interval, Map<String, RangeSet<DateTime>> container) { entries.stream().map(entry -> container.computeIfAbsent(entry, ignored -> TreeRangeSet.create())) .forEach(set -> set.add(Range.closedOpen(interval.getStart(), interval.getEnd()))); }