List of usage examples for com.google.common.collect Range upperEndpoint
public C upperEndpoint()
From source file:org.apache.kylin.common.util.RangeUtil.java
/** * remove from self the elements that exist in other * @return/*www . j av a 2 s .c om*/ */ public static <C extends Comparable<?>> List<Range<C>> remove(Range<C> self, Range<C> other) { // mimic the following logic in guava 18: // RangeSet<C> rangeSet = TreeRangeSet.create(); // rangeSet.add(self); // rangeSet.remove(other); // return Lists.newArrayList(rangeSet.asRanges()); if (other == null || !self.isConnected(other)) { return Collections.singletonList(self); } Range<C> share = self.intersection(other); if (share.isEmpty()) { return Collections.singletonList(self); } List<Range<C>> ret = Lists.newArrayList(); //see left part if (!self.hasLowerBound()) { if (share.hasLowerBound()) { if (share.lowerBoundType() == BoundType.CLOSED) { ret.add(Range.lessThan(share.lowerEndpoint())); } else { ret.add(Range.atMost(share.lowerEndpoint())); } } } else { if (self.lowerEndpoint() != share.lowerEndpoint()) { if (self.lowerBoundType() == BoundType.CLOSED) { if (share.lowerBoundType() == BoundType.CLOSED) { ret.add(Range.closedOpen(self.lowerEndpoint(), share.lowerEndpoint())); } else { ret.add(Range.closed(self.lowerEndpoint(), share.lowerEndpoint())); } } else { if (share.lowerBoundType() == BoundType.CLOSED) { ret.add(Range.open(self.lowerEndpoint(), share.lowerEndpoint())); } else { ret.add(Range.openClosed(self.lowerEndpoint(), share.lowerEndpoint())); } } } else { if (self.lowerBoundType() == BoundType.CLOSED && share.lowerBoundType() == BoundType.OPEN) { ret.add(Range.closed(self.lowerEndpoint(), share.lowerEndpoint())); } } } //see right part if (!self.hasUpperBound()) { if (share.hasUpperBound()) { if (share.upperBoundType() == BoundType.CLOSED) { ret.add(Range.greaterThan(share.upperEndpoint())); } else { ret.add(Range.atLeast(share.upperEndpoint())); } } } else { if (self.upperEndpoint() != share.upperEndpoint()) { if (self.upperBoundType() == BoundType.CLOSED) { if (share.upperBoundType() == BoundType.CLOSED) { ret.add(Range.openClosed(share.upperEndpoint(), self.upperEndpoint())); } else { ret.add(Range.closed(share.upperEndpoint(), self.upperEndpoint())); } } else { if (share.upperBoundType() == BoundType.CLOSED) { ret.add(Range.open(share.upperEndpoint(), self.upperEndpoint())); } else { ret.add(Range.closedOpen(share.upperEndpoint(), self.upperEndpoint())); } } } else { if (self.upperBoundType() == BoundType.CLOSED && share.upperBoundType() == BoundType.OPEN) { ret.add(Range.closed(self.upperEndpoint(), share.upperEndpoint())); } } } return ret; }
From source file:edu.mit.streamjit.impl.compiler2.CompositionAllocationStrategy.java
@Override public void allocateGroup(ActorGroup group, Range<Integer> iterations, List<Core> cores, Configuration config) { if (group.isStateful()) { int minStatefulId = Integer.MAX_VALUE; for (Actor a : group.actors()) if (a instanceof WorkerActor && ((WorkerActor) a).archetype().isStateful()) minStatefulId = Math.min(minStatefulId, a.id()); Configuration.SwitchParameter<Integer> param = config.getParameter("Group" + minStatefulId + "Core", Configuration.SwitchParameter.class, Integer.class); cores.get(param.getValue() % cores.size()).allocate(group, iterations); return;//from www . ja v a 2 s.co m } Configuration.CompositionParameter param = config.getParameter("Group" + group.id() + "Cores", Configuration.CompositionParameter.class); assert iterations.lowerBoundType() == BoundType.CLOSED && iterations.upperBoundType() == BoundType.OPEN; int totalAvailable = iterations.upperEndpoint() - iterations.lowerEndpoint(); int[] allocations = new int[cores.size()]; int totalAllocated = 0; for (int i = 0; i < param.getLength() && i < allocations.length; ++i) { int allocation = DoubleMath.roundToInt(param.getValue(i) * totalAvailable, RoundingMode.HALF_EVEN); allocations[i] = allocation; totalAllocated += allocation; } //If we allocated more than we have, remove from the cores with the least. //Need a loop here because we might not have enough on the least core. while (totalAllocated > totalAvailable) { int least = Ints.indexOf(allocations, Ints.max(allocations)); for (int i = 0; i < allocations.length; ++i) if (allocations[i] > 0 && allocations[i] < allocations[least]) least = i; int toRemove = Math.min(allocations[least], totalAllocated - totalAvailable); allocations[least] -= toRemove; totalAllocated -= toRemove; } //If we didn't allocate enough, allocate on the cores with the most. if (totalAllocated < totalAvailable) { int most = Ints.indexOf(allocations, Ints.min(allocations)); for (int i = 0; i < allocations.length; ++i) if (allocations[i] > allocations[most]) most = i; allocations[most] += totalAvailable - totalAllocated; totalAllocated += totalAvailable - totalAllocated; } assert totalAllocated == totalAvailable : totalAllocated + " " + totalAvailable; int lower = iterations.lowerEndpoint(); for (int i = 0; i < allocations.length; ++i) if (allocations[i] > 0) { cores.get(i).allocate(group, Range.closedOpen(lower, lower + allocations[i])); lower += allocations[i]; } }
From source file:org.eclipse.fx.ui.controls.styledtext.internal.LineNode.java
protected Range<Integer> toGlobal(Range<Integer> range) { int lineOffset = this.lineHelper.getOffset(index); return Range.range(lineOffset + range.lowerEndpoint(), range.lowerBoundType(), lineOffset + range.upperEndpoint(), range.upperBoundType()); }
From source file:jetbrains.jetpad.hybrid.BaseHybridSynchronizer.java
private CellTrait createTargetTrait() { return new CellTrait() { @Override/*from w w w . jav a2s.c o m*/ public Object get(Cell cell, CellTraitPropertySpec<?> spec) { if (spec == HYBRID_SYNCHRONIZER) { return BaseHybridSynchronizer.this; } if (spec == CellStateHandler.PROPERTY) { return getCellStateHandler(); } return super.get(cell, spec); } @Override public void onKeyPressed(Cell cell, KeyEvent event) { Cell focusedCell = cell.getContainer().focusedCell.get(); if (myTargetList.contains(focusedCell)) { Cell currentCell = cell.getContainer().focusedCell.get(); if (!hasSelection()) { if (event.is(KeyStrokeSpecs.SELECT_UP) && currentCell != null) { mySelectionSupport.select(currentCell, currentCell); event.consume(); } } else { Range<Integer> currentRange = selection(); if (event.is(KeyStrokeSpecs.SELECT_UP)) { ParseNode parseNode = myTokenListEditor.getParseNode(); if (parseNode != null) { if (!currentRange.equals(parseNode.getRange())) { ParseNode node = ParseNodes.findForRange(parseNode, currentRange); ParseNode parentNode = ParseNodes.nonSameRangeParent(node); if (parentNode != null) { select(parentNode.getRange()); event.consume(); } } } else { if (!currentRange.equals(Range.closed(0, tokens().size()))) { select(Range.closed(0, tokens().size())); event.consume(); } } } if (event.is(KeyStrokeSpecs.SELECT_DOWN)) { ParseNode parseNode = myTokenListEditor.getParseNode(); if (parseNode != null) { ParseNode node = ParseNodes.findForRange(parseNode, currentRange); ParseNode childNode = ParseNodes.nonSameRangeChild(node, myTargetList.indexOf(mySelectionSupport.currentCell())); if (childNode != null) { select(childNode.getRange()); event.consume(); return; } } if (!mySelectionSupport.isCurrentCompletelySelected()) { mySelectionSupport.clearSelection(); event.consume(); } } } } super.onKeyPressed(cell, event); } @Override public void onCopy(Cell cell, CopyCutEvent event) { if (canCopy()) { event.consume(copy()); return; } super.onCopy(cell, event); } @Override public void onCut(Cell cell, CopyCutEvent event) { if (canCut()) { ClipboardContent content = cut(); myTokensEditPostProcessor.afterTokensEdit(tokens(), property().get()); event.consume(content); return; } super.onCut(cell, event); } @Override public void onPaste(Cell cell, PasteEvent event) { if (canPaste(event.getContent())) { paste(event.getContent()); myTokensEditPostProcessor.afterTokensEdit(tokens(), property().get()); event.consume(); return; } super.onPaste(cell, event); } private boolean canPaste(ClipboardContent content) { return content.isSupported(TOKENS_CONTENT); } private void paste(ClipboardContent content) { List<Token> tokens = content.get(TOKENS_CONTENT); Cell currentCell = mySelectionSupport.currentCell(); int targetIndex; if (currentCell != null) { int currentCellIndex = myTargetList.indexOf(currentCell); boolean home = Positions.isHomePosition(currentCell); boolean end = Positions.isEndPosition(currentCell); if (home && end) { // One-char token which allows editing at only one side if (currentCell instanceof TextTokenCell && ((TextTokenCell) currentCell).noSpaceToLeft()) { targetIndex = currentCellIndex + 1; } else { targetIndex = currentCellIndex; } } else if (home) { targetIndex = currentCellIndex; } else { targetIndex = currentCellIndex + 1; } } else { targetIndex = 0; } myTokenListEditor.tokens.addAll(targetIndex, tokens); myTokenListEditor.updateToPrintedTokens(); tokenOperations().select(targetIndex + tokens.size() - 1, LAST).run(); } private boolean canCopy() { return hasSelection(); } private ClipboardContent copy() { final Range<Integer> selection = selection(); final List<Token> copiedTokens = new ArrayList<>( selection.upperEndpoint() - selection.lowerEndpoint()); for (Token token : tokens().subList(selection.lowerEndpoint(), selection.upperEndpoint())) { copiedTokens.add(token.copy()); } return new ClipboardContent() { @Override public boolean isSupported(ContentKind<?> kind) { return kind == TOKENS_CONTENT; } @Override public <T> T get(ContentKind<T> kind) { if (kind == TOKENS_CONTENT) { List<Token> result = new ArrayList<>(copiedTokens.size()); for (Token token : copiedTokens) { result.add(token.copy()); } return (T) Collections.unmodifiableList(result); } return null; } @Override public String toString() { try { return TokenUtil.getText(copiedTokens); } catch (UnsupportedOperationException e) { return super.toString(); } } }; } private boolean canCut() { return hasSelection(); } private ClipboardContent cut() { ClipboardContent result = copy(); clearSelection(); return result; } }; }
From source file:org.eclipse.fx.ui.controls.styledtext.internal.LineNode.java
protected Range<Integer> toLocal(Range<Integer> range) { int lineOffset = -this.lineHelper.getOffset(index); return Range.range(lineOffset + range.lowerEndpoint(), range.lowerBoundType(), lineOffset + range.upperEndpoint(), range.upperBoundType()); }
From source file:com.google.cloud.genomics.dataflow.pipelines.AnnotateVariants.java
@Override public void processElement(DoFn<StreamVariantsRequest, KV<String, VariantAnnotation>>.ProcessContext c) throws Exception { Genomics genomics = GenomicsFactory.builder().build().fromOfflineAuth(auth); StreamVariantsRequest request = StreamVariantsRequest.newBuilder(c.element()).addAllCallSetIds(callSetIds) .build();//from ww w . j a v a 2 s. c om LOG.info("processing contig " + request); Iterator<StreamVariantsResponse> iter = VariantStreamIterator.enforceShardBoundary(auth, request, ShardBoundary.Requirement.STRICT, VARIANT_FIELDS); if (!iter.hasNext()) { LOG.info("region has no variants, skipping"); return; } IntervalTree<Annotation> transcripts = retrieveTranscripts(genomics, request); ListMultimap<Range<Long>, Annotation> variantAnnotations = retrieveVariantAnnotations(genomics, request); Stopwatch stopwatch = Stopwatch.createStarted(); int varCount = 0; while (iter.hasNext()) { Iterable<Variant> varIter = FluentIterable.from(iter.next().getVariantsList()) .filter(VariantUtils.IS_SNP); for (Variant variant : varIter) { List<String> alleles = ImmutableList.<String>builder().addAll(variant.getAlternateBasesList()) .add(variant.getReferenceBases()).build(); Range<Long> pos = Range.openClosed(variant.getStart(), variant.getEnd()); for (String allele : alleles) { String outKey = Joiner.on(":").join(variant.getReferenceName(), variant.getStart(), allele, variant.getId()); for (Annotation match : variantAnnotations.get(pos)) { if (allele.equals(match.getVariant().getAlternateBases())) { // Exact match to a known variant annotation; straightforward join. c.output(KV.of(outKey, match.getVariant())); } } Iterator<Node<Annotation>> transcriptIter = transcripts .overlappers(pos.lowerEndpoint().intValue(), pos.upperEndpoint().intValue() - 1); // Inclusive. while (transcriptIter.hasNext()) { // Calculate an effect of this allele on the coding region of the given transcript. Annotation transcript = transcriptIter.next().getValue(); VariantEffect effect = AnnotationUtils.determineVariantTranscriptEffect(variant.getStart(), allele, transcript, getCachedTranscriptBases(genomics, transcript)); if (effect != null && !VariantEffect.SYNONYMOUS_SNP.equals(effect)) { c.output(KV.of(outKey, new VariantAnnotation().setAlternateBases(allele).setType("SNP") .setEffect(effect.toString()).setGeneId(transcript.getTranscript().getGeneId()) .setTranscriptIds(ImmutableList.of(transcript.getId())))); } } } 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); }
From source file:fr.openwide.core.export.excel.AbstractExcelTableExport.java
/** * Finalise la cration de la feuille de calcul, notamment en demandant le * redimensionnement automatique des colonnes. * //w w w . j a v a 2 s. c o m * @param sheet feuilles de calcul * @param columnInfos map contenant l'en-tte et les informations d'une colonne * @param landscapePrintSetup dfinit si la feuille est imprime en paysage ou non */ protected void finalizeSheet(Sheet sheet, RangeMap<Integer, ColumnInformation> columnInfos, boolean landscapePrintSetup) { for (Map.Entry<Range<Integer>, ColumnInformation> entry : columnInfos.asMapOfRanges().entrySet()) { ColumnInformation columnInformation = entry.getValue(); Range<Integer> range = entry.getKey(); int beginIndex = range.lowerEndpoint(); int endIndex = range.upperEndpoint(); // Dtermination de la taille maximum de cette colonne int maxColumnWidth; if (columnInformation.getColumnMaxWidth() != -1) { maxColumnWidth = columnInformation.getColumnMaxWidth(); } else { maxColumnWidth = ABSOLUTE_MAX_COLUMN_WIDTH; } // Dtermination de la taille souhaite pour la colonne if (columnInformation.getColumnWidth() != -1) { // On force la taille des colonnes en fonction de la columnInformation int columnWidth = columnInformation.getColumnWidth(); columnWidth = Math.min(columnWidth, maxColumnWidth); // On prend en compte le fait que la "colonne" peut s'tendre en fait sur plusieurs colonnes (fusion de cellules au niveau du header) int columnSpan = endIndex - beginIndex + 1; columnWidth = columnWidth / columnSpan; // On redimmensionne les colonnes for (int columnIndex = beginIndex; columnIndex <= endIndex; ++columnIndex) { sheet.setColumnWidth(columnIndex, columnWidth); } } else { // On redimmensionne les colonnes une une en prennant leur taille actuelle et en les augmentant un petit peu for (int columnIndex = beginIndex; columnIndex <= endIndex; ++columnIndex) { sheet.autoSizeColumn(columnIndex); int columnWidth = (int) (sheet.getColumnWidth(beginIndex) * COLUMN_RESIZE_RATIO); columnWidth = Math.min(columnWidth, maxColumnWidth); sheet.setColumnWidth(columnIndex, columnWidth); } } } finalizeSheet(sheet, landscapePrintSetup); }
From source file:google.registry.model.registry.Registry.java
/** * Returns the EAP fee for the registry at the given time. *//*w w w . j ava 2s . c o m*/ public Fee getEapFeeFor(DateTime now) { ImmutableSortedMap<DateTime, Money> valueMap = eapFeeSchedule.toValueMap(); DateTime periodStart = valueMap.floorKey(now); DateTime periodEnd = valueMap.ceilingKey(now); // NOTE: assuming END_OF_TIME would never be reached... Range<DateTime> validPeriod = Range.closedOpen(periodStart != null ? periodStart : START_OF_TIME, periodEnd != null ? periodEnd : END_OF_TIME); return Fee.create(eapFeeSchedule.getValueAtTime(now).getAmount(), FeeType.EAP, validPeriod, validPeriod.upperEndpoint()); }
From source file:edu.mit.streamjit.impl.compiler2.ActorGroup.java
/** * Make loop handles for each Actor that execute the iteration given as * an argument, then bind them together in an outer loop body that * executes all the iterations. Before the outer loop we must also * reinitialize the splitter/joiner index arrays to their initial * values./*from w w w. ja v a2 s . co m*/ */ private MethodHandle makeGroupLoop(Range<Integer> iterations, int unrollFactor, Map<Actor, MethodHandle> withRWHandlesBound) { if (iterations.isEmpty()) return Combinators.nop(); List<MethodHandle> loopHandles = new ArrayList<>(actors().size()); Map<int[], int[]> requiredCopies = new LinkedHashMap<>(); for (Actor a : actors()) loopHandles.add(makeWorkerLoop((WorkerActor) a, withRWHandlesBound.get(a), unrollFactor, iterations.lowerEndpoint(), requiredCopies)); MethodHandle groupLoop = MethodHandles.insertArguments(OVERALL_GROUP_LOOP, 0, Combinators.semicolon(loopHandles), iterations.lowerEndpoint(), iterations.upperEndpoint(), unrollFactor); if (!requiredCopies.isEmpty()) { int[][] copies = new int[requiredCopies.size() * 2][]; int i = 0; for (Map.Entry<int[], int[]> e : requiredCopies.entrySet()) { copies[i++] = e.getKey(); copies[i++] = e.getValue(); } groupLoop = Combinators .semicolon(MethodHandles.insertArguments(REINITIALIZE_ARRAYS, 0, (Object) copies), groupLoop); } return groupLoop; }
From source file:net.sf.mzmine.modules.peaklistmethods.peakpicking.deconvolution.centwave.CentWaveDetector.java
/** * Do peak picking using xcms::findPeaks.centWave. * /* ww w .j a va2s . c om*/ * @param scanTime * retention times (for each scan). * @param intensity * intensity values (for each scan). * @param mz * fixed m/z value for EIC. * @param snrThreshold * signal:noise ratio threshold. * @param peakWidth * peak width range. * @param integrationMethod * integration method. * @return a matrix with a row for each detected peak. * @throws RSessionWrapperException */ private static double[][] centWave(RSessionWrapper rSession, final double[] scanTime, final double[] intensity, final double mz, final double snrThreshold, final Range<Double> peakWidth, final PeakIntegrationMethod integrationMethod) throws RSessionWrapperException { LOG.finest("Detecting peaks."); final double[][] peaks; // Set vectors. rSession.assign("scantime", scanTime); rSession.assign("intensity", intensity); // Initialize. rSession.eval("mz <- " + mz); rSession.eval("numPoints <- length(intensity)"); // Construct xcmsRaw object rSession.eval("xRaw <- new(\"xcmsRaw\")"); rSession.eval("xRaw@tic <- intensity"); rSession.eval("xRaw@scantime <- scantime * " + SECONDS_PER_MINUTE); rSession.eval("xRaw@scanindex <- 1:numPoints"); rSession.eval("xRaw@env$mz <- rep(mz, numPoints)"); rSession.eval("xRaw@env$intensity <- intensity"); // Construct ROIs. rSession.eval("ROIs <- list()"); int roi = 1; for (int start = 0; start < intensity.length; start++) { // Found non-zero section. if (intensity[start] > 0.0) { // Look for end. int end = start + 1; while (end < intensity.length && intensity[end] > 0.0) { end++; } // Add ROI to list. rSession.eval("ROIs[[" + roi + "]] <- list('scmin'=" + (start + 1) + ", 'scmax'=" + end + ", 'mzmin'=mz, 'mzmax'=mz)"); // Next ROI. start = end; roi++; } } // Do peak picking. final Object centWave = roi <= 1 ? null : (double[][]) rSession.collect( "findPeaks.centWave(xRaw, ppm=0, mzdiff=0, verbose=TRUE" + ", peakwidth=c(" + peakWidth.lowerEndpoint() * SECONDS_PER_MINUTE + ", " + peakWidth.upperEndpoint() * SECONDS_PER_MINUTE + ')' + ", snthresh=" + snrThreshold + ", integrate=" + integrationMethod.getIndex() + ", ROI.list=ROIs)", false); peaks = (centWave == null) ? null : (double[][]) centWave; return peaks; }