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.github.rinde.gpem17.evo.FitnessEvaluator.java

@Override
public void evaluatePopulation(EvolutionState state) {
    SetMultimap<GPNodeHolder, IndividualHolder> mapping = getGPFitnessMapping(state);
    int fromIndex;
    if (useDifferentScenariosEveryGen) {
        fromIndex = state.generation * numScenariosPerGen;
    } else {/*w  w w.j a v a 2 s.  com*/
        fromIndex = 0;
    }
    int toIndex;
    int compSize;
    if (state.generation == state.numGenerations - 1) {
        compSize = compositeSize * 5;
        toIndex = fromIndex + numScenariosInLastGen;
    } else {
        compSize = compositeSize;
        toIndex = fromIndex + numScenariosPerGen;
    }
    System.out.println(
            scenariosDir + " " + paths.subList(fromIndex, toIndex).toString().replace(scenariosDir + "/", ""));

    String[] args;
    if (distributed) {

        args = new String[] { "--jppf", "--repetitions", "1", "--composite-size", Integer.toString(compSize) };
    } else {
        args = new String[] { "--repetitions", "1" };
    }
    File generationDir = new File(((StatsLogger) state.statistics).experimentDirectory,
            "generation" + state.generation);

    List<GPProgram<GpGlobal>> programs = new ArrayList<>();
    List<GPNodeHolder> nodes = ImmutableList.copyOf(mapping.keySet());
    for (GPNodeHolder node : nodes) {
        final GPProgram<GpGlobal> prog = GPProgramParser
                .convertToGPProgram((GPBaseNode<GpGlobal>) node.trees[0].child);
        programs.add(prog);
    }

    ExperimentResults results = Evaluate.execute(programs, false,
            FileProvider.builder().add(paths.subList(fromIndex, toIndex)), generationDir, false,
            Converter.INSTANCE, false, reauctOpt, objectiveFunction, null, false, false, 0L, args);

    Map<MASConfiguration, GPNodeHolder> configMapping = new LinkedHashMap<>();
    ImmutableList<MASConfiguration> configs = results.getConfigurations().asList();

    verify(configs.size() == nodes.size());
    for (int i = 0; i < configs.size(); i++) {
        configMapping.put(configs.get(i), nodes.get(i));
    }

    List<GPComputationResult> convertedResults = new ArrayList<>();
    for (SimulationResult sr : results.getResults()) {
        StatisticsDTO stats = ((SimResult) sr.getResultObject()).getStats();
        double cost = objectiveFunction.computeCost(stats);
        float fitness = (float) cost;
        if (!objectiveFunction.isValidResult(stats)) {
            // if the simulation is terminated early, we give a huge penalty, which
            // we reduce based on how far the simulation actually got.
            fitness = Float.MAX_VALUE - stats.simulationTime;
        }
        String id = configMapping.get(sr.getSimArgs().getMasConfig()).string;
        convertedResults.add(SingleResult.create((float) fitness, id, sr));
    }
    processResults(state, mapping, convertedResults);
}

From source file:com.facebook.buck.rules.args.WorkerMacroArg.java

public WorkerMacroArg(MacroHandler macroHandler, BuildTarget target, CellPathResolver cellNames,
        BuildRuleResolver resolver, String unexpanded) throws MacroException {
    super(macroHandler, target, cellNames, resolver, unexpanded);
    for (MacroMatchResult matchResult : macroHandler.getMacroMatchResults(unexpanded)) {
        if (macroHandler.getExpander(matchResult.getMacroType()) instanceof WorkerMacroExpander
                && matchResult.getStartIndex() != 0) {
            throw new MacroException(
                    String.format("the worker macro in \"%s\" must be at the beginning", unexpanded));
        }/*from   w w  w  . java  2  s . co m*/
    }

    // extract the BuildTargets referenced in any macros
    ImmutableList<BuildTarget> targets = macroHandler.extractParseTimeDeps(target, cellNames, unexpanded);

    if (targets.size() < 1) {
        throw new MacroException(String.format(
                "Unable to extract any build targets for the macros " + "used in \"%s\" of target %s",
                unexpanded, target));
    }
    this.buildTarget = targets.get(0);
    BuildRule workerTool = resolver.getRule(buildTarget);
    if (!(workerTool instanceof WorkerTool)) {
        throw new MacroException(String.format(
                "%s used in worker macro, \"%s\", of target %s does " + "not correspond to a worker_tool",
                buildTarget, unexpanded, target));
    }
    this.workerTool = (WorkerTool) workerTool;
    SourcePathResolver pathResolver = new SourcePathResolver(new SourcePathRuleFinder(resolver));
    Tool exe = this.workerTool.getTool();
    startupCommand = exe.getCommandPrefix(pathResolver);
    startupEnvironment = exe.getEnvironment();
    jobArgs = macroHandler.expand(target, cellNames, resolver, unexpanded).trim();
}

From source file:com.google.errorprone.bugpatterns.formatstring.StrictFormatStringValidation.java

/** Helps {@code validate()} validate a format string that is declared as a method parameter. */
private static ValidationResult validateFormatStringParamter(ExpressionTree formatStringTree,
        Symbol formatStringSymbol, List<? extends ExpressionTree> args, VisitorState state) {
    if (!isFormatStringParameter(formatStringSymbol, state)) {
        return ValidationResult.create(null, String.format(
                "Format strings must be compile time constant or parameters annotated " + "@FormatString: %s",
                formatStringTree));//from  w  w  w.ja va 2  s. c  o m
    }

    List<VarSymbol> ownerParams = ((MethodSymbol) formatStringSymbol.owner).getParameters();
    int ownerFormatStringIndex = ownerParams.indexOf(formatStringSymbol);

    ImmutableList.Builder<Type> ownerFormatArgTypesBuilder = ImmutableList.builder();
    for (VarSymbol paramSymbol : ownerParams.subList(ownerFormatStringIndex + 1, ownerParams.size())) {
        ownerFormatArgTypesBuilder.add(paramSymbol.type);
    }
    ImmutableList<Type> ownerFormatArgTypes = ownerFormatArgTypesBuilder.build();

    Types types = state.getTypes();
    ImmutableList.Builder<Type> calleeFormatArgTypesBuilder = ImmutableList.builder();
    for (ExpressionTree formatArgExpression : args) {
        calleeFormatArgTypesBuilder.add(types.erasure(((JCExpression) formatArgExpression).type));
    }
    ImmutableList<Type> calleeFormatArgTypes = calleeFormatArgTypesBuilder.build();

    if (ownerFormatArgTypes.size() != calleeFormatArgTypes.size()) {
        return ValidationResult.create(null,
                String.format(
                        "The number of format arguments passed "
                                + "with an @FormatString must match the number of format arguments in the "
                                + "@FormatMethod header where the format string was declared.\n\t"
                                + "Format args passed: %d\n\tFormat args expected: %d",
                        calleeFormatArgTypes.size(), ownerFormatArgTypes.size()));
    } else {
        for (int i = 0; i < calleeFormatArgTypes.size(); i++) {
            if (!ASTHelpers.isSameType(ownerFormatArgTypes.get(i), calleeFormatArgTypes.get(i), state)) {
                return ValidationResult.create(null,
                        String.format("The format argument types passed "
                                + "with an @FormatString must match the types of the format arguments in "
                                + "the @FormatMethod header where the format string was declared.\n\t"
                                + "Format arg types passed: %s\n\tFormat arg types expected: %s",
                                calleeFormatArgTypes.toArray(), ownerFormatArgTypes.toArray()));
            }
        }
    }

    // Format string usage was valid.
    return null;
}

From source file:org.glowroot.storage.repo.helper.RollupLevelService.java

public int getRollupLevelForView(long captureTimeFrom, long captureTimeTo) throws Exception {
    long millis = captureTimeTo - captureTimeFrom;
    long timeAgoMillis = clock.currentTimeMillis() - captureTimeFrom;
    ImmutableList<Integer> rollupExpirationHours = configRepository.getStorageConfig().rollupExpirationHours();
    List<RollupConfig> rollupConfigs = configRepository.getRollupConfigs();
    for (int i = 0; i < rollupConfigs.size() - 1; i++) {
        RollupConfig nextRollupConfig = rollupConfigs.get(i + 1);
        if (millis < nextRollupConfig.viewThresholdMillis()
                && HOURS.toMillis(rollupExpirationHours.get(i)) > timeAgoMillis) {
            return i;
        }//  w w  w .j  a v  a2  s .  c  o  m
    }
    return rollupConfigs.size() - 1;
}

From source file:org.sosy_lab.cpachecker.pcc.strategy.partitioning.ExplorationOrderBalancedGraphPartitioner.java

@Override
public List<Set<Integer>> computePartitioning(int pNumPartitions, PartialReachedSetDirectedGraph pGraph)
        throws InterruptedException {
    Deque<Integer> waitlist = new ArrayDeque<>();
    BitSet inPartition = new BitSet(pGraph.getNumNodes());
    int partitionSize = pGraph.getNumNodes() / pNumPartitions + 1;

    List<Set<Integer>> result = new ArrayList<>(pNumPartitions);
    for (int i = 0; i < pNumPartitions; i++) {
        result.add(Sets.<Integer>newHashSetWithExpectedSize(partitionSize));
    }/*from   w w w .  j a v a2 s  .com*/

    waitlist.add(0);
    inPartition.set(0);

    Integer next;
    int partition = 0;
    ImmutableList<ImmutableList<Integer>> adjacencyList = pGraph.getAdjacencyList();
    while (!waitlist.isEmpty()) {
        shutdownNotifier.shutdownIfNecessary();

        next = waitlist.poll();
        if (result.get(partition).size() > partitionSize) {
            partition++;
        }
        result.get(partition).add(next);

        for (Integer successor : adjacencyList.get(next)) {
            if (!inPartition.get(successor)) {
                inPartition.set(successor);
                if (useDFS) {
                    waitlist.push(successor);
                } else {
                    waitlist.offer(successor);
                }
            }
        }
    }

    return result;
}

From source file:com.google.template.soy.jbcsrc.restricted.BytecodeUtils.java

private static Expression asArray(final Type arrayType, final ImmutableList<? extends Expression> elements) {
    final Type elementType = arrayType.getElementType();
    return new Expression(arrayType, Feature.NON_NULLABLE) {
        @Override/*  w w  w  .j  a v a  2  s.c om*/
        protected void doGen(CodeBuilder adapter) {
            adapter.pushInt(elements.size());
            adapter.newArray(elementType);
            for (int i = 0; i < elements.size(); i++) {
                adapter.dup(); // dup the array
                adapter.pushInt(i); // the index to store into
                elements.get(i).gen(adapter); // the element to store
                adapter.arrayStore(elementType);
            }
        }
    };
}

From source file:com.amazonaws.services.kinesis.stormspout.KinesisSpout.java

@Override
public void nextTuple() {
    synchronized (stateManager) {
        // Task has no assignments.
        if (!stateManager.hasGetters()) {
            // Sleep here for a bit, so we don't consume too much cpu.
            try {
                Thread.sleep(emptyRecordListSleepTimeMillis);
            } catch (InterruptedException e) {
                LOG.debug(this + " sleep was interrupted.");
            }// w  ww  .  ja  v a 2  s  .  c  o m
            return;
        }

        final IShardGetter getter = stateManager.getNextGetter();
        String currentShardId = getter.getAssociatedShard();
        Record rec = null;
        boolean isRetry = false;

        if (stateManager.shouldRetry(currentShardId)) {
            safeMetricIncrement(retryCount);
            rec = stateManager.recordToRetry(currentShardId);
            if (LOG.isDebugEnabled()) {
                LOG.debug("ShardId " + currentShardId + ": Re-emitting record with partition key "
                        + rec.getPartitionKey() + ", sequence number " + rec.getSequenceNumber());
            }
            isRetry = true;
        } else {
            final Records records = getter.getNext(1);

            if (records.getMillisBehindLatest() >= 0) {
                safeMetricAssign(millisBehindLastMetric, records.getMillisBehindLatest());
            }

            final ImmutableList<Record> recordList = records.getRecords();

            if ((recordList != null) && (!recordList.isEmpty())) {
                rec = recordList.get(0);
            }
            if (records.isReshard()) {
                LOG.info(this + " detected reshard event for shard " + currentShardId);
                stateManager.handleReshard();
            }
        }

        if (rec != null) {
            // Copy record (ByteBuffer.duplicate()) so bolts in the same JVM don't affect the object (e.g. retries)
            Record recordToEmit = copyRecord(rec);
            List<Object> tuple = config.getScheme().deserialize(recordToEmit);
            LOG.info(this + " emitting record with seqnum " + recordToEmit.getSequenceNumber() + " from shard "
                    + currentShardId + " with data: " + tuple);
            collector.emit(tuple,
                    MessageIdUtil.constructMessageId(currentShardId, recordToEmit.getSequenceNumber()));
            stateManager.emit(currentShardId, recordToEmit, isRetry);
        } else {
            // Sleep here for a bit if there were no records to emit.
            try {
                Thread.sleep(emptyRecordListSleepTimeMillis);
            } catch (InterruptedException e) {
                LOG.debug(this + " sleep was interrupted.");
            }
        }

        // Do periodic ZK commit of shard states.
        if (System.currentTimeMillis() - lastCommitTime >= config.getCheckpointIntervalMillis()) {
            LOG.debug(this + " committing local shard states to ZooKeeper.");

            stateManager.commitShardStates();
            lastCommitTime = System.currentTimeMillis();
        } else {
            LOG.debug(this + " Not committing to ZooKeeper.");
        }
    }
}

From source file:dagger.internal.codegen.writer.EnumWriter.java

@Override
public Appendable write(Appendable appendable, Context context) throws IOException {
    context = context.createSubcontext(//from  ww  w.  j  a v a 2 s.  c o m
            FluentIterable.from(nestedTypeWriters).transform(new Function<TypeWriter, ClassName>() {
                @Override
                public ClassName apply(TypeWriter input) {
                    return input.name;
                }
            }).toSet());
    writeAnnotations(appendable, context);
    writeModifiers(appendable).append("enum ").append(name.simpleName());
    Iterator<TypeName> implementedTypesIterator = implementedTypes.iterator();
    if (implementedTypesIterator.hasNext()) {
        appendable.append(" implements ");
        implementedTypesIterator.next().write(appendable, context);
        while (implementedTypesIterator.hasNext()) {
            appendable.append(", ");
            implementedTypesIterator.next().write(appendable, context);
        }
    }
    appendable.append(" {");

    checkState(!constantWriters.isEmpty(), "Cannot write an enum with no constants.");
    appendable.append('\n');
    ImmutableList<ConstantWriter> constantWriterList = ImmutableList.copyOf(constantWriters.values());
    for (ConstantWriter constantWriter : constantWriterList.subList(0, constantWriterList.size() - 1)) {
        constantWriter.write(appendable, context);
        appendable.append(",\n");
    }
    constantWriterList.get(constantWriterList.size() - 1).write(appendable, context);
    appendable.append(";\n");

    if (!fieldWriters.isEmpty()) {
        appendable.append('\n');
    }
    for (VariableWriter fieldWriter : fieldWriters.values()) {
        fieldWriter.write(new IndentingAppendable(appendable), context).append("\n");
    }
    for (ConstructorWriter constructorWriter : constructorWriters) {
        appendable.append('\n');
        if (!isDefaultConstructor(constructorWriter)) {
            constructorWriter.write(new IndentingAppendable(appendable), context);
        }
    }
    for (MethodWriter methodWriter : methodWriters) {
        appendable.append('\n');
        methodWriter.write(new IndentingAppendable(appendable), context);
    }
    for (TypeWriter nestedTypeWriter : nestedTypeWriters) {
        appendable.append('\n');
        nestedTypeWriter.write(new IndentingAppendable(appendable), context);
    }
    appendable.append("}\n");
    return appendable;
}

From source file:com.facebook.litho.testing.viewtree.ViewTreeAssert.java

private String getTextProof(@Nullable final ImmutableList<View> path) {
    if (path == null) {
        return "";
    }/*  www .j a v  a2s.com*/

    final View last = path.get(path.size() - 1);
    return ((TextView) last).getText().toString();
}

From source file:com.google.cloud.bigtable.grpc.io.ChannelPool.java

/**
 * Performs a simple round robin on the list of {@link InstrumentedChannel}s in the {@code channels}
 * list. This method should not be synchronized, if possible, to reduce bottlenecks.
 *
 * @return A {@link InstrumentedChannel} that can be used for a single RPC call.
 *///ww  w .j a v a2 s. c  om
private InstrumentedChannel getNextChannel() {
    int currentRequestNum = requestCount.getAndIncrement();
    ImmutableList<InstrumentedChannel> channelsList = channels.get();
    int index = Math.abs(currentRequestNum % channelsList.size());
    return channelsList.get(index);
}