Example usage for com.google.common.collect ImmutableList get

List of usage examples for com.google.common.collect ImmutableList get

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableList get.

Prototype

E get(int index);

Source Link

Document

Returns the element at the specified position in this list.

Usage

From source file:com.facebook.buck.versions.AbstractFlavorSearchTargetNodeFinder.java

public Optional<TargetNode<?>> get(BuildTarget target) {

    // If this node is in the graph under the given name, return it.
    TargetNode<?> node = getBuildTargetIndex().get(target);
    if (node != null) {
        return Optional.of(node);
    }/*from ww  w .j  a  v  a 2s  .c  om*/

    ImmutableSet<ImmutableSet<Flavor>> flavorList = getBaseTargetFlavorMap()
            .get(target.getUnflavoredBuildTarget());
    if (flavorList == null) {
        return Optional.empty();
    }

    // Otherwise, see if this node exists in the graph with a "less" flavored name.  We initially
    // select all targets which contain a subset of the original flavors, which should be sorted by
    // from largest flavor set to smallest.  We then use the first match, and verify the subsequent
    // matches are subsets.
    ImmutableList<ImmutableSet<Flavor>> matches = RichStream.from(flavorList)
            .filter(target.getFlavors()::containsAll).toImmutableList();
    if (!matches.isEmpty()) {
        ImmutableSet<Flavor> firstMatch = matches.get(0);
        for (ImmutableSet<Flavor> subsequentMatch : matches.subList(1, matches.size())) {
            Preconditions
                    .checkState(firstMatch.size() > subsequentMatch.size(),
                            "Expected to find larger flavor lists earlier in the flavor map "
                                    + "index (sizeof(%s) <= sizeof(%s))",
                            firstMatch.size(), subsequentMatch.size());
            Preconditions.checkState(firstMatch.containsAll(subsequentMatch),
                    "Found multiple disjoint flavor matches for %s: %s and %s (from %s)", target, firstMatch,
                    subsequentMatch, matches);
        }
        return Optional.of(Preconditions.checkNotNull(getBaseTargetIndex().get(target.withFlavors(firstMatch)),
                "%s missing in index", target.withFlavors(firstMatch)));
    }

    // Otherwise, return `null` to indicate this node isn't in the target graph.
    return Optional.empty();
}

From source file:com.github.rinde.rinsim.central.Solvers.java

/**
 * Computes a {@link StatisticsDTO} instance for the given
 * {@link GlobalStateObject} and routes. For each vehicle in the state the
 * specified route is used and its arrival times, tardiness and travel times
 * are computed. The resulting {@link StatisticsDTO} has the same properties
 * as performing a simulation with the same state. However, since the current
 * state may be half-way a simulation, it is possible that the returned
 * statistics describe only a partial simulation. As a result
 * {@link StatisticsDTO#totalDeliveries} does not necessarily equal
 * {@link StatisticsDTO#totalPickups}./*from   w  w w  . j  ava 2 s .c  om*/
 * @param state The state which represents a simulation.
 * @param routes Specifies the route the vehicles are currently following,
 *          must be of same size as the number of vehicles (one route per
 *          vehicle). If this is <code>null</code> the
 *          {@link VehicleStateObject#getRoute()} field must be set instead
 *          for <b>each</b> vehicle.
 * @return The statistics that will be generated when executing this
 *         simulation.
 */
public static ExtendedStats computeStats(GlobalStateObject state,
        @Nullable ImmutableList<ImmutableList<Parcel>> routes) {
    final Optional<ImmutableList<ImmutableList<Parcel>>> r = Optional.fromNullable(routes);

    if (r.isPresent()) {
        checkArgument(state.getVehicles().size() == r.get().size(),
                "Exactly one route should be supplied for every vehicle in state. %s "
                        + "vehicle(s) in state, received %s route(s).",
                state.getVehicles().size(), r.get().size());
    }

    double totalDistance = 0;
    int totalDeliveries = 0;
    int totalPickups = 0;
    long pickupTardiness = 0;
    long deliveryTardiness = 0;
    long overTime = 0;
    final long startTime = state.getTime();
    long maxTime = 0;
    int movedVehicles = 0;
    final Set<Parcel> parcels = newHashSet();

    final ImmutableList.Builder<ImmutableList<Long>> arrivalTimesBuilder = ImmutableList.builder();

    for (int i = 0; i < state.getVehicles().size(); i++) {
        final VehicleStateObject vso = state.getVehicles().get(i);
        checkArgument(r.isPresent() || vso.getRoute().isPresent(),
                "Vehicle routes must either be specified as an argument or must be part"
                        + " of the state object.");

        final ImmutableList.Builder<Long> truckArrivalTimesBuilder = ImmutableList.builder();
        truckArrivalTimesBuilder.add(state.getTime());

        ImmutableList<Parcel> route;
        if (r.isPresent()) {
            route = r.get().get(i);
        } else {
            route = vso.getRoute().get();
        }
        parcels.addAll(route);

        long time = state.getTime();
        Point vehicleLocation = vso.getLocation();
        final Measure<Double, Velocity> speed = Measure.valueOf(vso.getDto().getSpeed(), state.getSpeedUnit());
        final Set<Parcel> seen = newHashSet();
        for (int j = 0; j < route.size(); j++) {
            final Parcel cur = route.get(j);
            final boolean inCargo = vso.getContents().contains(cur) || seen.contains(cur);
            seen.add(cur);
            if (vso.getDestination().isPresent() && j == 0) {
                checkArgument(vso.getDestination().asSet().contains(cur),
                        "If a vehicle has a destination, the first position in the route "
                                + "must equal this. Expected %s, is %s.",
                        vso.getDestination().get(), cur);
            }

            boolean firstAndServicing = false;
            if (j == 0 && vso.getRemainingServiceTime() > 0) {
                // we are already at the service location
                firstAndServicing = true;
                truckArrivalTimesBuilder.add(time);
                time += vso.getRemainingServiceTime();
            } else {
                // vehicle is not there yet, go there first, then service
                final Point nextLoc = inCargo ? cur.getDeliveryLocation() : cur.getPickupLocation();
                final Measure<Double, Length> distance = Measure
                        .valueOf(Point.distance(vehicleLocation, nextLoc), state.getDistUnit());
                totalDistance += distance.getValue();
                vehicleLocation = nextLoc;
                final long tt = DoubleMath.roundToLong(
                        RoadModels.computeTravelTime(speed, distance, state.getTimeUnit()),
                        RoundingMode.CEILING);
                time += tt;
            }
            if (inCargo) {
                // check if we are early
                if (cur.getDeliveryTimeWindow().isBeforeStart(time)) {
                    time = cur.getDeliveryTimeWindow().begin();
                }

                if (!firstAndServicing) {
                    truckArrivalTimesBuilder.add(time);
                    time += cur.getDeliveryDuration();
                }
                // delivering
                if (cur.getDeliveryTimeWindow().isAfterEnd(time)) {
                    final long tardiness = time - cur.getDeliveryTimeWindow().end();
                    deliveryTardiness += tardiness;
                }
                totalDeliveries++;
            } else {
                // check if we are early
                if (cur.getPickupTimeWindow().isBeforeStart(time)) {
                    time = cur.getPickupTimeWindow().begin();
                }
                if (!firstAndServicing) {
                    truckArrivalTimesBuilder.add(time);
                    time += cur.getPickupDuration();
                }
                // picking up
                if (cur.getPickupTimeWindow().isAfterEnd(time)) {
                    final long tardiness = time - cur.getPickupTimeWindow().end();
                    pickupTardiness += tardiness;
                }
                totalPickups++;
            }
        }

        // go to depot
        final Measure<Double, Length> distance = Measure
                .valueOf(Point.distance(vehicleLocation, vso.getDto().getStartPosition()), state.getDistUnit());
        totalDistance += distance.getValue();
        final long tt = DoubleMath.roundToLong(
                RoadModels.computeTravelTime(speed, distance, state.getTimeUnit()), RoundingMode.CEILING);
        time += tt;
        // check overtime
        if (vso.getDto().getAvailabilityTimeWindow().isAfterEnd(time)) {
            overTime += time - vso.getDto().getAvailabilityTimeWindow().end();
        }
        maxTime = Math.max(maxTime, time);

        truckArrivalTimesBuilder.add(time);
        arrivalTimesBuilder.add(truckArrivalTimesBuilder.build());

        if (time > startTime) {
            // time has progressed -> the vehicle has moved
            movedVehicles++;
        }
    }
    final int totalParcels = parcels.size();
    final int totalVehicles = state.getVehicles().size();
    final long simulationTime = maxTime - startTime;

    return new ExtendedStats(totalDistance, totalPickups, totalDeliveries, totalParcels, totalParcels,
            pickupTardiness, deliveryTardiness, 0, simulationTime, true, totalVehicles, overTime, totalVehicles,
            movedVehicles, state.getTimeUnit(), state.getDistUnit(), state.getSpeedUnit(),
            arrivalTimesBuilder.build());
}

From source file:dagger.internal.codegen.DependencyCycleValidator.java

/**
 * Reports a dependency cycle at the dependency into the cycle that is closest to an entry point.
 *
 * <p>Looks for the shortest path from the component that contains the cycle (all bindings in a
 * cycle must be in the same component; see below) to some binding in the cycle. Then looks for
 * the last dependency in that path that is not in the cycle; that is the dependency that will be
 * reported, so that the dependency trace will end just before the cycle.
 *
 * <p>Proof (by counterexample) that all bindings in a cycle must be in the same component: Assume
 * one binding in the cycle is in a parent component. Bindings cannot depend on bindings in child
 * components, so that binding cannot depend on the next binding in the cycle.
 */// w  w  w  .j a va 2s  .  com
private void reportCycle(Cycle<Node> cycle, BindingGraph bindingGraph, DiagnosticReporter diagnosticReporter) {
    ImmutableList<Node> path = shortestPathToCycleFromAnEntryPoint(cycle, bindingGraph);
    Node cycleStartNode = path.get(path.size() - 1);
    Node previousNode = path.get(path.size() - 2);
    DependencyEdge dependencyToReport = chooseDependencyEdgeConnecting(previousNode, cycleStartNode,
            bindingGraph);
    diagnosticReporter.reportDependency(ERROR, dependencyToReport,
            errorMessage(cycle.shift(cycleStartNode), bindingGraph));
}

From source file:org.apache.beam.sdk.extensions.sql.impl.rel.BeamValuesRel.java

@Override
public PCollection<BeamRecord> buildBeamPipeline(PCollectionTuple inputPCollections, BeamSqlEnv sqlEnv)
        throws Exception {
    List<BeamRecord> rows = new ArrayList<>(tuples.size());
    String stageName = BeamSqlRelUtils.getStageName(this);
    if (tuples.isEmpty()) {
        throw new IllegalStateException("Values with empty tuples!");
    }/*from ww w.  ja va  2 s  .  com*/

    BeamRecordSqlType beamSQLRowType = CalciteUtils.toBeamRowType(this.getRowType());
    for (ImmutableList<RexLiteral> tuple : tuples) {
        List<Object> fieldsValue = new ArrayList<>(beamSQLRowType.getFieldCount());
        for (int i = 0; i < tuple.size(); i++) {
            fieldsValue.add(BeamTableUtils.autoCastField(beamSQLRowType.getFieldTypeByIndex(i),
                    tuple.get(i).getValue()));
        }
        rows.add(new BeamRecord(beamSQLRowType, fieldsValue));
    }

    return inputPCollections.getPipeline().apply(stageName, Create.of(rows))
            .setCoder(beamSQLRowType.getRecordCoder());
}

From source file:net.hydromatic.optiq.prepare.OptiqCatalogReader.java

private List<SqlOperator> toOps(final String name, final ImmutableList<TableFunction> tableFunctions) {
    return new AbstractList<SqlOperator>() {
        public SqlOperator get(int index) {
            return toOp(name, tableFunctions.get(index));
        }//from w  w  w .j  a va2s.c  om

        public int size() {
            return tableFunctions.size();
        }
    };
}

From source file:org.geogit.osm.map.internal.OSMMapOp.java

private Iterator<Feature> getFeatures(String ref) {
    Optional<ObjectId> id = command(RevParse.class).setRefSpec(ref).call();
    if (!id.isPresent()) {
        return Iterators.emptyIterator();
    }/*from  ww  w  .ja  v  a 2 s. c om*/
    LsTreeOp op = command(LsTreeOp.class).setStrategy(Strategy.DEPTHFIRST_ONLY_FEATURES).setReference(ref);

    Iterator<NodeRef> iterator = op.call();

    Function<NodeRef, Feature> function = new Function<NodeRef, Feature>() {

        @Override
        @Nullable
        public Feature apply(@Nullable NodeRef ref) {
            RevFeature revFeature = command(RevObjectParse.class).setObjectId(ref.objectId())
                    .call(RevFeature.class).get();
            SimpleFeatureType featureType;
            if (ref.path().startsWith(OSMUtils.NODE_TYPE_NAME)) {
                featureType = OSMUtils.nodeType();
            } else {
                featureType = OSMUtils.wayType();
            }
            SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(featureType);
            RevFeatureType revFeatureType = RevFeatureType.build(featureType);
            List<PropertyDescriptor> descriptors = revFeatureType.sortedDescriptors();
            ImmutableList<Optional<Object>> values = revFeature.getValues();
            for (int i = 0; i < descriptors.size(); i++) {
                PropertyDescriptor descriptor = descriptors.get(i);
                Optional<Object> value = values.get(i);
                featureBuilder.set(descriptor.getName(), value.orNull());
            }
            SimpleFeature feature = featureBuilder.buildFeature(ref.name());
            return feature;
        }

    };
    return Iterators.transform(iterator, function);
}

From source file:de.metas.ui.web.window.datatypes.LookupValuesList.java

/**
 * @param id/*from ww w . j  a v a2 s .co  m*/
 * @return first lookup value found for <code>id</code> or null
 */
public LookupValue getById(final Object id) {
    final ImmutableList<LookupValue> values = valuesById.get(id);
    return values.isEmpty() ? null : values.get(0);
}

From source file:org.cspoker.ai.bots.bot.gametree.mcts.nodes.InnerNode.java

public INode getRandomChild() {
    double randomNumber = random.nextDouble();
    ImmutableList<INode> children = getChildren();
    for (int i = 0; i < cumulativeProbability.length - 1; i++) {
        if (randomNumber < cumulativeProbability[i]) {
            return children.get(i);
        }//w  w  w. j  a v  a 2 s  . com
    }
    return children.get(cumulativeProbability.length - 1);
}

From source file:no.ssb.vtl.script.operations.join.InnerJoinMerger.java

private ImmutableListMultimap<Integer, Integer> buildIndices(ImmutableList<Component> leftList,
        ImmutableList<Component> rightList) {
    ImmutableListMultimap.Builder<Integer, Integer> indexMapBuilder = ImmutableListMultimap.builder();
    // Save the indices of the right data points that need to be moved to the left.
    for (int i = 0; i < rightList.size(); i++) {
        Component rightComponent = rightList.get(i);
        for (int j = 0; j < leftList.size(); j++) {
            Component leftComponent = leftList.get(j);
            if (rightComponent.equals(leftComponent)) {
                indexMapBuilder.put(i, j);
            }/*from   ww  w  .j a  v  a  2s .c om*/
        }
    }
    return indexMapBuilder.build();
}

From source file:li.klass.fhem.service.room.xmllist.XmlListParser.java

public Map<String, ImmutableList<XmlListDevice>> parse(String xmlList) throws Exception {
    Map<String, ImmutableList<XmlListDevice>> result = Maps.newHashMap();

    // replace device tag extensions
    xmlList = xmlList.replaceAll("_[0-9]+_LIST", "_LIST");
    xmlList = xmlList.replaceAll("(<[/]?[A-Z0-9]+)_[0-9]+([ >])", "$1$2");
    xmlList = xmlList.replaceAll("</>", "");
    xmlList = xmlList.replaceAll("< [^>]*>", "");
    xmlList = xmlList.replaceAll("< name=[a-zA-Z\"=0-9 ]+>", "");

    Document document = documentFromXmlList(xmlList);
    Node baseNode = findFHZINFONode(document);

    NodeList childNodes = baseNode.getChildNodes();
    for (int i = 0; i < childNodes.getLength(); i++) {
        Node node = childNodes.item(i);
        if (node.getNodeName().endsWith("_LIST")) {
            ImmutableList<XmlListDevice> devices = handleListNode(node);
            if (devices.isEmpty()) {
                continue;
            }/*  ww w .ja v  a 2 s . com*/
            String deviceType = devices.get(0).getType().toLowerCase(Locale.getDefault());
            if (result.containsKey(deviceType)) {
                // In case we have two LISTs for the same device type, we need to merge
                // existing lists. FHEM will not send out those lists, but we replace
                // i.e. SWAP_123_LIST by SWAP_LIST, resulting in two same list names.
                Iterable<XmlListDevice> existing = result.get(deviceType);
                result.put(deviceType, ImmutableList.copyOf(Iterables.concat(existing, devices)));
            } else {
                result.put(deviceType, devices);
            }
        }
    }

    return ImmutableMap.copyOf(result);
}