List of usage examples for com.google.common.collect ImmutableList size
int size();
From source file:com.github.jsdossier.Main.java
@VisibleForTesting static void run(String[] args, FileSystem fileSystem) { Flags flags = Flags.parse(args, fileSystem); Config config = null;//from ww w .j a v a2 s. c o m try (InputStream stream = newInputStream(flags.config)) { config = Config.load(stream, fileSystem); } catch (IOException e) { e.printStackTrace(System.err); System.exit(-1); } if (flags.printConfig) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); String header = " Configuration "; int len = header.length(); String pad = Strings.repeat("=", len / 2); System.err.println(pad + header + pad); System.err.println(gson.toJson(config.toJson())); System.err.println(Strings.repeat("=", 79)); System.exit(1); } Iterable<String> standardFlags = STANDARD_FLAGS; if (config.isStrict()) { standardFlags = transform(standardFlags, new Function<String, String>() { @Override public String apply(String input) { return input.replace("--jscomp_warning", "--jscomp_error"); } }); } ImmutableList<String> compilerFlags = ImmutableList.<String>builder() .addAll(transform(config.getSources(), toFlag("--js="))) .addAll(transform(config.getModules(), toFlag("--js="))) .addAll(transform(config.getExterns(), toFlag("--externs="))) .add("--language_in=" + config.getLanguage().getName()).addAll(standardFlags).build(); PrintStream nullStream = new PrintStream(ByteStreams.nullOutputStream()); args = compilerFlags.toArray(new String[compilerFlags.size()]); Logger log = Logger.getLogger(Main.class.getPackage().getName()); log.setLevel(Level.WARNING); log.addHandler(new Handler() { @Override public void publish(LogRecord record) { System.err.printf("[%s][%s] %s\n", record.getLevel(), record.getLoggerName(), record.getMessage()); } @Override public void flush() { } @Override public void close() { } }); Main main = new Main(args, nullStream, System.err, config); main.runCompiler(); }
From source file:com.github.rinde.opt.localsearch.Swaps.java
/** * Moves the occurrences of <code>item</code> to their new positions. This * does not change the relative ordering of any other items in the list. * @param originalList The original list that will be swapped. * @param insertionIndices The indices where item should be inserted relative * to the positions of the <code>originalList</code> <b>without</b> * <code>item</code>. The number of indices must equal the number of * occurrences of item in the original list. * @param item The item to swap.//ww w.j a v a 2 s.c o m * @return The swapped list. * @throws IllegalArgumentException if an attempt is made to move the item to * the previous location(s), this would have no effect and is * therefore considered a bug. */ static <T> ImmutableList<T> inListSwap(ImmutableList<T> originalList, IntList insertionIndices, T item) { checkArgument(!originalList.isEmpty(), "The list may not be empty."); final List<T> newList = newArrayList(originalList); final IntList indices = removeAll(newList, item); checkArgument(newList.size() == originalList.size() - insertionIndices.size(), "The number of occurrences (%s) of item should equal the number of " + "insertionIndices (%s), original list: %s, item %s, " + "insertionIndices %s.", indices.size(), insertionIndices.size(), originalList, item, insertionIndices); checkArgument(!indices.equals(insertionIndices), "Attempt to move the item to exactly the same locations as the input. " + "Indices in original list %s, insertion indices %s.", indices, insertionIndices); return Insertions.insert(newList, insertionIndices, item); }
From source file:org.locationtech.geogig.storage.datastream.FormatCommonV2.java
public static void writeFeatureType(RevFeatureType object, DataOutput data) throws IOException { writeName(object.getName(), data);/* w w w. j a va2s .c o m*/ ImmutableList<PropertyDescriptor> descriptors = object.sortedDescriptors(); writeUnsignedVarInt(descriptors.size(), data); for (PropertyDescriptor desc : object.type().getDescriptors()) { writeProperty(desc, data); } }
From source file:com.facebook.buck.features.rust.RustCompileUtils.java
/** * Given a list of sources, return the one which is the root based on the defaults and user * parameters./* ww w.j a v a 2 s .c o m*/ * * @param resolver SourcePathResolver for rule * @param crate Name of crate * @param defaults Default names for this rule (library, binary, etc) * @param sources List of sources * @return The matching source */ public static Optional<SourcePath> getCrateRoot(SourcePathResolver resolver, String crate, ImmutableSet<String> defaults, Stream<SourcePath> sources) { String crateName = String.format("%s.rs", crate); ImmutableList<SourcePath> res = sources.filter(src -> { String name = resolver.getRelativePath(src).getFileName().toString(); return defaults.contains(name) || name.equals(crateName); }).collect(ImmutableList.toImmutableList()); if (res.size() == 1) { return Optional.of(res.get(0)); } else { return Optional.empty(); } }
From source file:com.github.rinde.opt.localsearch.Swaps.java
static <C, T> ImmutableList<ImmutableList<T>> opt2(ImmutableList<ImmutableList<T>> schedule, IntList startIndices, C context, RouteEvaluator<C, T> evaluator, boolean depthFirst, Optional<RandomGenerator> rng, Optional<? extends ProgressListener<T>> listener) throws InterruptedException { checkArgument(schedule.size() == startIndices.size()); final Schedule<C, T> baseSchedule = Schedule.create(context, schedule, startIndices, evaluator); final Object2DoubleLinkedOpenHashMap<ImmutableList<T>> routeCostCache = new Object2DoubleLinkedOpenHashMap<>( CACHE_SIZE);/*from w w w . ja v a 2s . c o m*/ for (int i = 0; i < baseSchedule.routes.size(); i++) { routeCostCache.put(baseSchedule.routes.get(i), baseSchedule.objectiveValues.getDouble(i)); } Schedule<C, T> bestSchedule = baseSchedule; boolean isImproving = true; while (isImproving) { isImproving = false; final Schedule<C, T> curBest = bestSchedule; Iterator<Swap<T>> it = swapIterator(curBest); if (depthFirst) { // randomize ordering of swaps final List<Swap<T>> swaps = newArrayList(it); Collections.shuffle(swaps, new RandomAdaptor(rng.get())); it = swaps.iterator(); } while (it.hasNext()) { if (Thread.interrupted()) { throw new InterruptedException(); } final Swap<T> swapOperation = it.next(); final Optional<Schedule<C, T>> newSchedule = swap(curBest, swapOperation, bestSchedule.objectiveValue - curBest.objectiveValue, routeCostCache); if (newSchedule.isPresent()) { isImproving = true; bestSchedule = newSchedule.get(); if (listener.isPresent()) { listener.get().notify(bestSchedule.routes, bestSchedule.objectiveValue); } if (depthFirst) { // first improving swap is chosen as new starting point (depth // first). break; } } } } return bestSchedule.routes; }
From source file:org.spongepowered.api.item.inventory.ItemStackBuilderPopulators.java
/** * Creates a new {@link BiConsumer} that provides a random * {@link ItemType} from the provided collection of item types. * * @param itemTypes The item types to use * @return The new biconsumer to apply to an itemstack builder *//*w w w . jav a2 s.co m*/ public static BiConsumer<ItemStack.Builder, Random> items(final Collection<ItemType> itemTypes) { final ImmutableList<ItemType> copiedItemTypes = ImmutableList.copyOf(itemTypes); return (builder, random) -> builder.itemType(copiedItemTypes.get(random.nextInt(copiedItemTypes.size()))); }
From source file:com.facebook.buck.apple.project_generator.WorkspaceAndProjectGenerator.java
private static Function<BuildTarget, PBXTarget> getTargetNodeToPBXTargetTransformFunction( final Multimap<BuildTarget, PBXTarget> buildTargetToTarget, final boolean buildWithBuck) { return input -> { ImmutableList<PBXTarget> targets = ImmutableList.copyOf(buildTargetToTarget.get(input)); if (targets.size() == 1) { return targets.get(0); }//from www . ja va 2s.c o m // The only reason why a build target would map to more than one project target is if // there are two project targets: one is the usual one, the other is a target that just // shells out to Buck. Preconditions.checkState(targets.size() == 2); PBXTarget first = targets.get(0); PBXTarget second = targets.get(1); Preconditions.checkState(first.getName().endsWith(ProjectGenerator.BUILD_WITH_BUCK_POSTFIX) ^ second.getName().endsWith(ProjectGenerator.BUILD_WITH_BUCK_POSTFIX)); PBXTarget buildWithBuckTarget; PBXTarget buildWithXcodeTarget; if (first.getName().endsWith(ProjectGenerator.BUILD_WITH_BUCK_POSTFIX)) { buildWithBuckTarget = first; buildWithXcodeTarget = second; } else { buildWithXcodeTarget = first; buildWithBuckTarget = second; } return buildWithBuck ? buildWithBuckTarget : buildWithXcodeTarget; }; }
From source file:com.google.template.soy.jbcsrc.BytecodeUtils.java
private static Expression doShortCircuitingLogicalOperator( final ImmutableList<? extends Expression> expressions, final boolean isOrOperator) { checkArgument(!expressions.isEmpty()); for (Expression expr : expressions) { expr.checkAssignableTo(Type.BOOLEAN_TYPE); }/* ww w .j a va 2s. c o m*/ if (expressions.size() == 1) { return expressions.get(0); } return new Expression(Type.BOOLEAN_TYPE, Expression.areAllCheap(expressions) ? Features.of(Feature.CHEAP) : Features.of()) { @Override void doGen(CodeBuilder adapter) { Label end = new Label(); Label shortCircuit = new Label(); for (int i = 0; i < expressions.size(); i++) { Expression expr = expressions.get(i); expr.gen(adapter); if (i == expressions.size() - 1) { // if we are the last one, just goto end. Whatever the result of the last expression is // determines the result of the whole expression (when all prior tests fail). adapter.goTo(end); } else { adapter.ifZCmp(isOrOperator ? Opcodes.IFNE : Opcodes.IFEQ, shortCircuit); } } adapter.mark(shortCircuit); adapter.pushBoolean(isOrOperator); // default for || is true && is false adapter.mark(end); } }; }
From source file:brooklyn.entity.rebind.Dumpers.java
public static void logUnserializableChains(Object root, final ObjectReplacer replacer) throws IllegalArgumentException, IllegalAccessException { final Map<List<Object>, Class<?>> unserializablePaths = Maps.newLinkedHashMap(); Visitor visitor = new Visitor() { @Override//from w ww.j a v a 2 s .c om public boolean visit(Object o, Iterable<Object> refChain) { try { Serializers.reconstitute(o, replacer); return true; } catch (Throwable e) { Exceptions.propagateIfFatal(e); // not serializable in some way: report ImmutableList<Object> refChainList = ImmutableList.copyOf(refChain); // for debugging it can be useful to turn this on // LOG.warn("Unreconstitutable object detected ("+o+"): "+e); // First strip out any less specific paths for (Iterator<List<Object>> iter = unserializablePaths.keySet().iterator(); iter.hasNext();) { List<Object> existing = iter.next(); if (refChainList.size() >= existing.size() && refChainList.subList(0, existing.size()).equals(existing)) { iter.remove(); } } // Then add this list unserializablePaths.put(ImmutableList.copyOf(refChainList), o.getClass()); return false; } } }; deepVisitInternal(root, SERIALIZED_FIELD_PREDICATE, Lists.newArrayList(), new LinkedList<Object>(), visitor); LOG.warn("Not serializable (" + root + "):"); for (Map.Entry<List<Object>, Class<?>> entry : unserializablePaths.entrySet()) { StringBuilder msg = new StringBuilder("\t" + "type=" + entry.getValue() + "; chain=" + "\n"); for (Object chainElement : entry.getKey()) { // try-catch motivated by NPE in org.jclouds.domain.LoginCredentials.toString String chainElementStr; try { chainElementStr = chainElement.toString(); } catch (Exception e) { Exceptions.propagateIfFatal(e); LOG.error("Error calling toString on instance of " + chainElement.getClass(), e); chainElementStr = "<error " + e.getClass().getSimpleName() + " in toString>"; } msg.append("\t\t" + "type=").append(chainElement.getClass()).append("; val=") .append(chainElementStr).append("\n"); } LOG.warn(msg.toString()); } }
From source file:com.github.rinde.rinsim.central.arrays.ArraysSolvers.java
static int[][] toInventoriesArray(GlobalStateObject state, ArraysObject sva) { final UnmodifiableIterator<VehicleStateObject> iterator = state.getVehicles().iterator(); final ImmutableList.Builder<ImmutableList<Integer>> invPairBuilder = ImmutableList.builder(); for (int i = 0; i < state.getVehicles().size(); i++) { final VehicleStateObject cur = iterator.next(); for (final Parcel dp : cur.getContents()) { invPairBuilder.add(ImmutableList.of(i, sva.parcel2index.get(dp).deliveryIndex)); }//from www.j a v a 2s . c o m } final ImmutableList<ImmutableList<Integer>> inventoryPairs = invPairBuilder.build(); final int[][] inventories = new int[inventoryPairs.size()][2]; for (int i = 0; i < inventoryPairs.size(); i++) { inventories[i][0] = inventoryPairs.get(i).get(0); inventories[i][1] = inventoryPairs.get(i).get(1); } return inventories; }