Example usage for com.google.common.collect ContiguousSet create

List of usage examples for com.google.common.collect ContiguousSet create

Introduction

In this page you can find the example usage for com.google.common.collect ContiguousSet create.

Prototype

public static <C extends Comparable> ContiguousSet<C> create(Range<C> range, DiscreteDomain<C> domain) 

Source Link

Document

Returns a ContiguousSet containing the same values in the given domain Range#contains contained by the range.

Usage

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/*from www.jav  a  2  s.c  om*/
            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:edu.mit.streamjit.impl.compiler2.Actor.java

public ImmutableSortedSet<Integer> translateOutputIndices(final int input, Range<Integer> logicalIndices) {
    return translateOutputIndices(input, ContiguousSet.create(logicalIndices, DiscreteDomain.integers()));
}

From source file:com.addthis.hydra.query.MeshQueryMaster.java

/** Returns the specified requested tasks as is if not empty, or expands to all known tasks if it is empty. */
private Set<Integer> expandRequestedTasks(Set<Integer> tasks, int canonicalTaskCount) {
    if (tasks.isEmpty()) {
        return ContiguousSet.create(Range.closedOpen(0, canonicalTaskCount), DiscreteDomain.integers());
    } else {//  w  w  w. ja  v a 2 s .c o  m
        return tasks;
    }
}

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];//  ww w .j  ava 2 s.  co m
    }

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

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

/**
 * Compute this storage's steady-state throughput and capacity.
 * @param externalSchedule the external schedule
 *//*from   ww  w . ja  v a 2s .c  o m*/
public void computeSteadyStateRequirements(Map<ActorGroup, Integer> externalSchedule) {
    Range<Integer> readIndices = readIndexSpan(externalSchedule);
    Range<Integer> writeIndices = writeIndexSpan(externalSchedule);
    assert readIndices.isEmpty() == writeIndices.isEmpty() : readIndices + " " + writeIndices;
    //We need to know the count of indices, so we can't just use the span
    //here.  There may be a lot of indices so writeIndices will use a lot of
    //memory.  But we know (assume) there are no overwrites, so we'll count.
    this.throughput = 0;
    for (Actor a : upstream()) {
        int iterations = a.group().schedule().get(a) * externalSchedule.get(a.group());
        for (int output = 0; output < a.outputs().size(); ++output)
            if (a.outputs().get(output).equals(this))
                this.throughput += iterations * a.push(output).max();
    }
    this.steadyStateCapacity = ContiguousSet.create(readIndices.span(writeIndices), DiscreteDomain.integers())
            .size();
}

From source file:com.stackframe.sarariman.StackFrameEmployee.java

@Override
public Map<Week, Timesheet> getTimesheets() {
    ContiguousSet<Week> allWeeks = ContiguousSet.create(Range.<Week>all(), Week.discreteDomain);
    return Maps.asMap(allWeeks, (Week w) -> {
        return sarariman.getTimesheets().get(StackFrameEmployee.this, w);
    });// www .j a v a 2s.  c o  m
}

From source file:com.github.rinde.rinsim.central.arrays.ArraysSolverValidator.java

/**
 * Validates the {@link SolutionObject} that is produced by a
 * {@link SingleVehicleArraysSolver} . If the {@link SolutionObject} is
 * infeasible, an {@link IllegalArgumentException} is thrown.
 * @param sol The {@link SolutionObject} that is validated.
 * @param travelTime Parameter as specified by
 *          {@link SingleVehicleArraysSolver#solve(int[][], int[], int[], int[][], int[], SolutionObject)}
 *          .//w  ww.ja  va  2s. c  o  m
 * @param releaseDates Parameter as specified by
 *          {@link SingleVehicleArraysSolver#solve(int[][], int[], int[], int[][], int[], SolutionObject)}
 *          .
 * @param dueDates Parameter as specified by
 *          {@link SingleVehicleArraysSolver#solve(int[][], int[], int[], int[][], int[], SolutionObject)}
 *          .
 * @param servicePairs Parameter as specified by
 *          {@link SingleVehicleArraysSolver#solve(int[][], int[], int[], int[][], int[], SolutionObject)}
 *          .
 * @param serviceTimes Parameter as specified by
 *          {@link SingleVehicleArraysSolver#solve(int[][], int[], int[], int[][], int[], SolutionObject)}
 *          .
 * @param currentSolution Parameter as specified by
 *          {@link SingleVehicleArraysSolver#solve(int[][], int[], int[], int[][], int[], SolutionObject)}
 *          .
 * @return The solution as is supplied, used for method chaining.
 */
public static SolutionObject validateOutputs(SolutionObject sol, int[][] travelTime, int[] releaseDates,
        int[] dueDates, int[][] servicePairs, int[] serviceTimes, @Nullable SolutionObject currentSolution) {
    // convert single vehicle version to multi vehicle version for checking
    // of inputs
    final int n = travelTime.length;
    final int[][] vehicleTravelTimes = new int[1][n];
    // copy first row
    for (int i = 0; i < n; i++) {
        vehicleTravelTimes[0][i] = travelTime[0][i];
    }
    final Set<Integer> locationSet = newHashSet(
            ContiguousSet.create(Range.closedOpen(1, n - 1), DiscreteDomain.integers()));
    for (int i = 0; i < servicePairs.length; i++) {
        locationSet.remove(servicePairs[i][0]);
        locationSet.remove(servicePairs[i][1]);
    }

    final int[][] inventories = new int[locationSet.size()][2];
    final Iterator<Integer> locationSetIterator = locationSet.iterator();
    for (int i = 0; i < locationSet.size(); i++) {
        inventories[i][0] = 0;
        inventories[i][1] = locationSetIterator.next();
    }

    final int[] remainingServiceTimes = new int[] { 0 };
    final int[] currentDestinations = new int[] { 0 };

    @Nullable
    final SolutionObject[] currentSolutions = currentSolution == null ? null
            : new SolutionObject[] { currentSolution };

    // check inputs again since we just modified them
    validateInputs(travelTime, releaseDates, dueDates, servicePairs, serviceTimes, vehicleTravelTimes,
            inventories, remainingServiceTimes, currentDestinations, currentSolutions);

    final SolutionObject[] sols = new SolutionObject[] { sol };
    validateOutputs(sols, travelTime, releaseDates, dueDates, servicePairs, serviceTimes, vehicleTravelTimes,
            inventories, remainingServiceTimes, currentDestinations);
    return sol;
}

From source file:zipkin.storage.cassandra3.CassandraSpanStore.java

ListenableFuture<Map<TraceIdUDT, Long>> getTraceIdsByServiceNames(QueryRequest request) {
    long oldestData = indexTtl == 0 ? 0 : (System.currentTimeMillis() - indexTtl * 1000);
    long startTsMillis = Math.max((request.endTs - request.lookback), oldestData);
    long endTsMillis = Math.max(request.endTs, oldestData);

    try {// w  w  w  .j a  v a  2 s.  co  m
        Set<String> serviceNames;
        if (null != request.serviceName) {
            serviceNames = Collections.singleton(request.serviceName);
        } else {
            serviceNames = new LinkedHashSet<>(getServiceNames().get());
            if (serviceNames.isEmpty()) {
                return immediateFuture(Collections.<TraceIdUDT, Long>emptyMap());
            }
        }

        int startBucket = CassandraUtil.durationIndexBucket(startTsMillis * 1000);
        int endBucket = CassandraUtil.durationIndexBucket(endTsMillis * 1000);
        if (startBucket > endBucket) {
            throw new IllegalArgumentException(
                    "Start bucket (" + startBucket + ") > end bucket (" + endBucket + ")");
        }
        Set<Integer> buckets = ContiguousSet.create(Range.closed(startBucket, endBucket), integers());
        boolean withDuration = null != request.minDuration || null != request.maxDuration;
        List<ListenableFuture<Map<TraceIdUDT, Long>>> futures = new ArrayList<>();

        if (200 < serviceNames.size() * buckets.size()) {
            LOG.warn("read against " + TABLE_TRACE_BY_SERVICE_SPAN + " fanning out to "
                    + serviceNames.size() * buckets.size() + " requests");
            //@xxx the fan-out of requests here can be improved
        }

        for (String serviceName : serviceNames) {
            for (Integer bucket : buckets) {
                BoundStatement bound = CassandraUtil
                        .bindWithName(withDuration ? selectTraceIdsByServiceSpanNameAndDuration
                                : selectTraceIdsByServiceSpanName, "select-trace-ids-by-service-name")
                        .setString("service_name", serviceName)
                        .setString("span_name", null != request.spanName ? request.spanName : "")
                        .setInt("bucket", bucket).setUUID("start_ts", UUIDs.startOf(startTsMillis))
                        .setUUID("end_ts", UUIDs.endOf(endTsMillis)).setInt("limit_", request.limit);

                if (withDuration) {
                    bound = bound
                            .setLong("start_duration", null != request.minDuration ? request.minDuration : 0)
                            .setLong("end_duration",
                                    null != request.maxDuration ? request.maxDuration : Long.MAX_VALUE);
                }
                bound.setFetchSize(Integer.MAX_VALUE);
                futures.add(transform(session.executeAsync(bound), traceIdToTimestamp));
            }
        }

        return transform(allAsList(futures), collapseTraceIdMaps);
    } catch (RuntimeException | InterruptedException | ExecutionException ex) {
        return immediateFailedFuture(ex);
    }
}

From source file:org.caleydo.view.table.TableView.java

private void showJustSelection() {
    rowHidder.showAllRows(); // show all by default

    // find out, which rows should be visible
    Collection<Integer> toKeep = new ArrayList<>();
    for (Integer id : selection.getRecordSelectionManager().getElements(SelectionType.SELECTION)) {
        int index = data.indexOfRowObject(id);
        if (index < 0)
            continue;
        int position = rowHidder.getRowPositionByIndex(index);
        if (position < 0)
            continue;
        toKeep.add(position);/*from w  w  w  .  j  a v a  2s.c  o  m*/
    }
    if (!toKeep.isEmpty()) { // at least one visible otherwise show all
        // all - visible = those to hide

        Set<Integer> all = new HashSet<>(ContiguousSet.create(Range.closed(rowHidder.getRowPositionByIndex(0),
                rowHidder.getRowPositionByIndex(data.getRowCount() - 1)), DiscreteDomain.integers()));
        all.removeAll(toKeep);
        rowHidder.hideRowPositions(all);
    }

    columnHidder.showAllColumns();
    toKeep.clear();
    for (Integer id : selection.getDimensionSelectionManager().getElements(SelectionType.SELECTION)) {
        int index = data.indexOfColumnObject(id);
        if (index < 0)
            continue;
        int position = columnHidder.getColumnPositionByIndex(index);
        if (position < 0)
            continue;
        toKeep.add(position);
    }
    if (!toKeep.isEmpty()) {
        Set<Integer> all = new HashSet<>(ContiguousSet.create(
                Range.closed(columnHidder.getColumnPositionByIndex(0),
                        columnHidder.getColumnPositionByIndex(data.getColumnCount() - 1)),
                DiscreteDomain.integers()));
        all.removeAll(toKeep);
        columnHidder.hideColumnPositions(all);
    }
}

From source file:org.sosy_lab.cpachecker.cfa.ast.c.CInitializers.java

/**
 * Handle the case when the current subobject that will be initialized next
 * is an array.//from  w w  w .  j  a va  2  s  .c  om
 * This method only prepares the two stacks by pushing one object on both
 * of them (for the next element to be initialized, and the iterator for the
 * remainder of the elements).
 * @param currentSubobject The struct/union to be initialized
 * @param startIndex The index of the first element to be initialized
 * @param arrayType The type of currentSubobject
 * @param currentSubobjects as in {@link #handleInitializerList(CExpression, CInitializerList, FileLocation, CFAEdge)}
 * @param nextSubobjects as in {@link #handleInitializerList(CExpression, CInitializerList, FileLocation, CFAEdge)}
 */
private static boolean handleInitializerForArray(final CExpression currentSubobject, final long startIndex,
        final CArrayType arrayType, final Deque<CExpression> currentSubobjects,
        final Deque<Iterator<CExpression>> nextSubobjects, final FileLocation loc, final CFAEdge edge,
        final CDesignator designator) throws UnrecognizedCCodeException {

    Range<Long> arrayIndices;
    if (arrayType.getLength() instanceof CIntegerLiteralExpression) {
        // fixed-size array
        BigInteger size = ((CIntegerLiteralExpression) arrayType.getLength()).getValue();
        if (!BigInteger.valueOf(size.longValue()).equals(size)) {
            throw new UnrecognizedCCodeException(
                    "Size of type " + arrayType + " is too large to initialize explicitly", edge, designator);
        }
        // TODO use DiscreteDomain.bigintegers() when it's available.

        arrayIndices = Range.closedOpen(startIndex, size.longValue());

    } else if (arrayType.getLength() == null) {
        // variable-length array, this array goes until there are no more initializer values

        arrayIndices = Range.atLeast(startIndex);

    } else {
        throw new UnrecognizedCCodeException(
                "Cannot initialize arrays with variable modified type like " + arrayType, edge, designator);
    }

    if (arrayIndices.isEmpty()) {
        return false;
    }

    final CType elementType = arrayType.getType();

    Set<Long> indexSet = ContiguousSet.create(arrayIndices, DiscreteDomain.longs());
    Iterator<CExpression> elements = from(indexSet).transform(new Function<Long, CExpression>() {
        @Override
        public CExpression apply(Long pInput) {
            CExpression index = new CIntegerLiteralExpression(loc, CNumericTypes.INT,
                    BigInteger.valueOf(pInput.longValue()));

            return new CArraySubscriptExpression(loc, elementType, currentSubobject, index);
        }
    }).iterator();

    CExpression firstElement = elements.next();

    currentSubobjects.push(firstElement);
    nextSubobjects.push(elements);

    return true;
}