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:com.google.googlejavaformat.java.Formatter.java
/** * Format an input string (a Java compilation unit) into an output string. * * <p>Leaves import statements untouched. * * @param input the input string//from w w w.ja v a 2 s.c om * @return the output string * @throws FormatterException if the input string cannot be parsed */ public String formatSource(String input) throws FormatterException { return formatSource(input, ImmutableList.of(Range.closedOpen(0, input.length()))); }
From source file:org.openmhealth.dsu.controller.DataPointController.java
@PreAuthorize("#oauth2.clientHasRole('" + CLIENT_ROLE + "') and #oauth2.hasScope('" + DATA_POINT_READ_SCOPE + "')")//from w ww . j a v a 2s . c o m // TODO look into any meaningful @PostAuthorize filtering @RequestMapping(value = "/dataPoints/caregiver", method = { HEAD, GET }, produces = APPLICATION_JSON_VALUE) public @ResponseBody ResponseEntity<Iterable<DataPoint>> readDataPointsCareGiver( @RequestParam(value = SCHEMA_NAMESPACE_PARAMETER) final String schemaNamespace, @RequestParam(value = SCHEMA_NAME_PARAMETER) final String schemaName, // TODO make this optional and update all associated code @RequestParam(value = SCHEMA_VERSION_PARAMETER) final String schemaVersion, @RequestParam(value = USER_ID) final String endUserId, @RequestParam(value = CAREGIVER_KEY) final String careGiverKey, // TODO replace with Optional<> in Spring MVC 4.1 @RequestParam(value = CREATED_ON_OR_AFTER_PARAMETER, required = false) final OffsetDateTime createdOnOrAfter, @RequestParam(value = CREATED_BEFORE_PARAMETER, required = false) final OffsetDateTime createdBefore, @RequestParam(value = RESULT_OFFSET_PARAMETER, defaultValue = "0") final Integer offset, @RequestParam(value = RESULT_LIMIT_PARAMETER, defaultValue = DEFAULT_RESULT_LIMIT) final Integer limit, Authentication authentication) { if (!careGiverKey.equals("someKey")) { return new ResponseEntity<>(NOT_ACCEPTABLE); } DataPointSearchCriteria searchCriteria = new DataPointSearchCriteria(endUserId, schemaNamespace, schemaName, schemaVersion); if (createdOnOrAfter != null && createdBefore != null) { searchCriteria.setCreationTimestampRange(Range.closedOpen(createdOnOrAfter, createdBefore)); } else if (createdOnOrAfter != null) { searchCriteria.setCreationTimestampRange(Range.atLeast(createdOnOrAfter)); } else if (createdBefore != null) { searchCriteria.setCreationTimestampRange(Range.lessThan(createdBefore)); } Iterable<DataPoint> dataPoints = dataPointService.findBySearchCriteria(searchCriteria, offset, limit); HttpHeaders headers = new HttpHeaders(); // FIXME add pagination headers // headers.set("Next"); // headers.set("Previous"); return new ResponseEntity<>(dataPoints, headers, OK); }
From source file:com.github.rinde.opt.localsearch.Swaps.java
static <C, T> Iterator<Swap<T>> oneItemSwapIterator(Schedule<C, T> schedule, IntList startIndices, T item, int fromRow) { final IntList indices = indices(schedule.routes.get(fromRow), item); final ImmutableList.Builder<Iterator<Swap<T>>> iteratorBuilder = ImmutableList.builder(); Range<Integer> range;/* w ww .ja v a 2s .c om*/ if (indices.size() == 1) { range = Range.closedOpen(fromRow, fromRow + 1); } else { range = Range.closedOpen(0, schedule.routes.size()); } for (int i = range.lowerEndpoint(); i < range.upperEndpoint(); i++) { int rowSize = schedule.routes.get(i).size(); if (fromRow == i) { rowSize -= indices.size(); } Iterator<IntList> it = new InsertionIndexGenerator(indices.size(), rowSize, startIndices.getInt(i)); // filter out swaps that have existing result if (fromRow == i) { it = Iterators.filter(it, Predicates.not(Predicates.equalTo(indices))); } iteratorBuilder.add(Iterators.transform(it, new IndexToSwapTransform<T>(item, fromRow, i))); } return Iterators.concat(iteratorBuilder.build().iterator()); }
From source file:org.apache.drill.exec.store.schedule.BlockMapBuilder.java
/** * For a given FileWork, calculate how many bytes are available on each on drillbit endpoint * * @param work the FileWork to calculate endpoint bytes for * @throws IOException//www . ja v a2 s . c o m */ public EndpointByteMap getEndpointByteMap(FileWork work) throws IOException { Stopwatch watch = new Stopwatch(); watch.start(); Path fileName = new Path(work.getPath()); ImmutableRangeMap<Long, BlockLocation> blockMap = getBlockMap(fileName); EndpointByteMapImpl endpointByteMap = new EndpointByteMapImpl(); long start = work.getStart(); long end = start + work.getLength(); Range<Long> rowGroupRange = Range.closedOpen(start, end); // Find submap of ranges that intersect with the rowGroup ImmutableRangeMap<Long, BlockLocation> subRangeMap = blockMap.subRangeMap(rowGroupRange); // Iterate through each block in this submap and get the host for the block location for (Map.Entry<Range<Long>, BlockLocation> block : subRangeMap.asMapOfRanges().entrySet()) { String[] hosts; Range<Long> blockRange = block.getKey(); try { hosts = block.getValue().getHosts(); } catch (IOException ioe) { throw new RuntimeException("Failed to get hosts for block location", ioe); } Range<Long> intersection = rowGroupRange.intersection(blockRange); long bytes = intersection.upperEndpoint() - intersection.lowerEndpoint(); // For each host in the current block location, add the intersecting bytes to the corresponding endpoint for (String host : hosts) { DrillbitEndpoint endpoint = getDrillBitEndpoint(host); if (endpoint != null) { endpointByteMap.add(endpoint, bytes); } else { logger.info("Failure finding Drillbit running on host {}. Skipping affinity to that host.", host); } } } logger.debug("FileWork group ({},{}) max bytes {}", work.getPath(), work.getStart(), endpointByteMap.getMaxBytes()); logger.debug("Took {} ms to set endpoint bytes", watch.stop().elapsed(TimeUnit.MILLISECONDS)); return endpointByteMap; }
From source file:org.dishevelled.bio.align.Alignments.java
/** * Return the alignment matches in the specified alignment pair as 0-based [closed, open) ranges. * * @param alignmentPair alignment pair, must not be null * @return the alignment matches in the alignment pair as 0-based [closed, open) ranges *///from www. j ava 2 s . co m public static List<Range<Long>> matches(final AlignmentPair alignmentPair) { checkNotNull(alignmentPair); List<Range<Long>> matches = new ArrayList<Range<Long>>(); int matchStart = -1; for (int i = 1, length = alignmentPair.length() + 1; i < length; i++) { if (isMatchSymbol(alignmentPair.symbolAt(i))) { if (matchStart < 0) { matchStart = i; } } else { if (matchStart > 0) { // biojava coordinates are 1-based matches.add(Range.closedOpen(Long.valueOf(matchStart - 1L), Long.valueOf(i - 1L))); matchStart = -1; } } } if (matchStart > 0) { matches.add(Range.closedOpen(Long.valueOf(matchStart - 1L), Long.valueOf(alignmentPair.length()))); } return matches; }
From source file:edu.mit.streamjit.impl.compiler2.ActorGroup.java
/** * Returns the physical indices written to the given storage during the * given group iteration./* w w w . j ava2 s .co m*/ * @param s the storage being written to * @param iterations the group iterations * @return the physical indices written */ public ImmutableSortedSet<Integer> writes(Storage s, Range<Integer> iterations) { ImmutableSortedSet.Builder<Integer> builder = ImmutableSortedSet.naturalOrder(); for (Actor a : actors()) builder.addAll(a.writes(s, Range.closedOpen(iterations.lowerEndpoint() * schedule.get(a), iterations.upperEndpoint() * schedule.get(a)))); return builder.build(); }
From source file:org.apache.drill.exec.record.RecordIterator.java
/** * Move iterator to next record.// www .j a va 2s.c o m * @return * Status of current record batch read. */ public IterOutcome next() { if (finished()) { return lastOutcome; } long nextOuterPosition = outerPosition + 1; final int nextInnerPosition = innerPosition + 1; if (!initialized || nextOuterPosition >= totalRecordCount) { nextBatch(); switch (lastOutcome) { case NONE: case STOP: // No more data, disallow reads unless reset is called. outerPosition = nextOuterPosition; lastBatchRead = true; if (!enableMarkAndReset) { container.clear(); } break; case OK_NEW_SCHEMA: case OK: // If Schema changes in the middle of the execution clear out data. if (initialized && lastOutcome == IterOutcome.OK_NEW_SCHEMA) { clear(); resetIndices(); initialized = false; nextOuterPosition = 0; } // Transfer vectors from incoming record batch. final RecordBatchData rbd = new RecordBatchData(incoming, oContext.getAllocator()); innerRecordCount = incoming.getRecordCount(); if (!initialized) { for (VectorWrapper<?> w : rbd.getContainer()) { container.addOrGet(w.getField()); } container.buildSchema(rbd.getContainer().getSchema().getSelectionVectorMode()); initialized = true; } if (innerRecordCount > 0) { if (enableMarkAndReset) { // Transfer vectors back to old batch. if (startBatchPosition != -1 && batches.get(startBatchPosition) != null) { container.transferOut(batches.get(outerPosition).getContainer()); } container.transferIn(rbd.getContainer()); batches.put(Range.closedOpen(nextOuterPosition, nextOuterPosition + innerRecordCount), rbd); } else { container.zeroVectors(); container.transferIn(rbd.getContainer()); } innerPosition = 0; startBatchPosition = nextOuterPosition; outerPosition = nextOuterPosition; totalRecordCount += innerRecordCount; } else { // Release schema/empty batches. rbd.clear(); } break; case OUT_OF_MEMORY: return lastOutcome; case NOT_YET: default: throw new UnsupportedOperationException("Unsupported outcome received " + lastOutcome); } } else { if (nextInnerPosition >= innerRecordCount) { assert enableMarkAndReset; // move to next batch final RecordBatchData rbdNew = batches.get(nextOuterPosition); final RecordBatchData rbdOld = batches.get(outerPosition); assert rbdNew != null; assert rbdOld != null; assert rbdOld != rbdNew; container.transferOut(rbdOld.getContainer()); container.transferIn(rbdNew.getContainer()); innerPosition = 0; outerPosition = nextOuterPosition; startBatchPosition = batches.getEntry(outerPosition).getKey().lowerEndpoint(); innerRecordCount = (int) (batches.getEntry(outerPosition).getKey().upperEndpoint() - startBatchPosition); } else { outerPosition = nextOuterPosition; innerPosition = nextInnerPosition; } } return lastOutcome; }
From source file:edu.mit.streamjit.impl.compiler2.Actor.java
/** * Returns the logical indices popped on the given input during the given * iteration./*from ww w .j a v a2 s .c o m*/ * @param input the input index * @param iterations the iteration numbers * @return the logical indices popped on the given input during the given * iterations */ public ContiguousSet<Integer> pops(int input, ContiguousSet<Integer> iterations) { if (iterations.isEmpty()) return ContiguousSet.create(Range.closedOpen(0, 0), DiscreteDomain.integers()); return ContiguousSet.create( Range.closedOpen(iterations.first() * pop(input).max(), (iterations.last() + 1) * pop(input).max()), DiscreteDomain.integers()); }
From source file:it.units.malelab.ege.benchmark.mapper.MapperUtils.java
private static List<BitsGenotype> split(BitsGenotype g, int n, int maxN) { if (n <= 0) { return Collections.singletonList(g); }/*from w w w .ja va2 s . c o m*/ if (n > maxN) { n = maxN; } if (g.size() == 0) { return Collections.nCopies(n, new BitsGenotype(0)); } n = Math.max(1, n); n = Math.min(n, g.size()); List<Range<Integer>> ranges = Utils.slices(Range.closedOpen(0, g.size()), n); return g.slices(ranges); }
From source file:edu.mit.streamjit.impl.compiler2.Storage.java
/** * Returns the indices read from this storage during an execution of the * given schedule. The returned set is not cached so as to be responsive * to changes in input index functions.// ww w . j a v a2s . c o m * @param externalSchedule the schedule * @return the indices read during the given schedule under the current * index functions * @see #readIndexSpan(java.util.Map) */ public ImmutableSortedSet<Integer> readIndices(Map<ActorGroup, Integer> externalSchedule) { ImmutableSortedSet.Builder<Integer> builder = ImmutableSortedSet.naturalOrder(); for (Actor a : downstream()) builder.addAll(a.reads(this, Range.closedOpen(0, a.group().schedule().get(a) * externalSchedule.get(a.group())))); return builder.build(); }