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:org.waveprotocol.box.server.waveserver.WaveletContainerImpl.java

protected void notifyOfDeltas(ImmutableList<WaveletDeltaRecord> deltas, ImmutableSet<String> domainsToNotify) {
    Preconditions.checkState(writeLock.isHeldByCurrentThread(), "must hold write lock");
    Preconditions.checkArgument(!deltas.isEmpty(), "empty deltas");
    HashedVersion endVersion = deltas.get(deltas.size() - 1).getResultingVersion();
    HashedVersion currentVersion = getCurrentVersion();
    Preconditions.checkArgument(endVersion.equals(currentVersion),
            "cannot notify of deltas ending in %s != current version %s", endVersion, currentVersion);
    notifiee.waveletUpdate(waveletState.getSnapshot(), deltas, domainsToNotify);
}

From source file:org.prebake.html.Table.java

Table(List<TextChunk> parts) {
    ImmutableList<TextChunk> rows;
    {//from   www  .j a v  a 2 s.c  o  m
        ImmutableList.Builder<TextChunk> rowsBuilder = ImmutableList.builder();
        findRows(parts, rowsBuilder);
        rows = rowsBuilder.build();
    }
    int nCols = 0;
    int nRows = 0;
    {
        ImmutableList.Builder<Cell> cellsBuilder = ImmutableList.builder();
        List<BitSet> rowUsage = Lists.newArrayList();
        for (int y = 0, n = rows.size(); y < n; ++y) {
            TextChunk row = rows.get(y);
            List<TextChunk> cells;
            if (row instanceof InlineText) {
                cells = ((InlineText) row).parts;
            } else {
                cells = ImmutableList.of(row);
            }
            while (rowUsage.size() <= y) {
                rowUsage.add(new BitSet());
            }
            BitSet freeCells = rowUsage.get(y);
            for (TextChunk cell : cells) {
                int colspan = 1, rowspan = 1;
                if (cell instanceof TableCell) {
                    colspan = ((TableCell) cell).colspan;
                    rowspan = ((TableCell) cell).rowspan;
                }
                int x = freeCells.nextClearBit(0);
                cellsBuilder.add(new Cell(x, y, colspan, rowspan, cell));
                int f = y + rowspan;
                while (rowUsage.size() < f) {
                    rowUsage.add(new BitSet());
                }
                for (int j = y; j < f; ++j) {
                    rowUsage.get(j).set(x, x + colspan);
                }
            }
            nCols = Math.max(freeCells.cardinality(), nCols);
        }
        this.cells = cellsBuilder.build();
        nRows = rowUsage.size();
    }
    // Sort cells by rightmost column.
    // As long as the cells are seen left to right, we can compute the width
    // by making sure htat the rightmost column a cell occupies can contain its
    // overflow.
    int[] colWidths = new int[nCols];
    int width;
    int height;
    {
        Cell[] cellArr = new Cell[cells.size()];
        cells.toArray(cellArr);
        Arrays.sort(cellArr, new Comparator<Cell>() {
            public int compare(Cell a, Cell b) {
                return (a.x + a.colspan) - (b.x + b.colspan);
            }
        });
        for (Cell c : cellArr) {
            int endCol = c.x + c.colspan - 1;
            int bodyWidth = c.body.width() - (c.colspan - 1); // 1 space between each pair of adjacent columns
            for (int i = c.x; i < endCol; ++i) {
                bodyWidth -= colWidths[i];
            }
            colWidths[endCol] = Math.max(colWidths[endCol], bodyWidth);
        }
        width = nCols - 1; // 1 space between each pair of adjacent columns
        for (int colWidth : colWidths) {
            width += colWidth;
        }

        int[] rowHeights = new int[nRows];
        Arrays.sort(cellArr, new Comparator<Cell>() {
            public int compare(Cell a, Cell b) {
                return (a.y + a.rowspan) - (b.y + b.rowspan);
            }
        });
        for (Cell c : cellArr) {
            int endRow = c.y + c.rowspan - 1;
            int bodyHeight = c.body.height();
            for (int j = c.y; j < endRow; ++j) {
                bodyHeight -= rowHeights[j];
            }
            rowHeights[endRow] = Math.max(rowHeights[endRow], bodyHeight);
        }
        height = 0;
        for (int rowHeight : rowHeights) {
            height += rowHeight;
        }
    }
    this.colWidths = colWidths;
    this.width = width;
    this.height = height;
}

From source file:pl.asie.foamfix.client.Deduplicator.java

public Object deduplicateObject(Object o, int recursion) {
    if (o == null || recursion > maxRecursion)
        return o;

    Class c = o.getClass();/*from w  w  w  .  j a va  2s  . c om*/
    if (!shouldCheckClass(c))
        return o;

    if (!deduplicatedObjects.add(o))
        return o;

    // System.out.println("-" + Strings.repeat("-", recursion) + " " + c.getName());

    if (o instanceof IBakedModel) {
        if (o instanceof IPerspectiveAwareModel.MapWrapper) {
            try {
                Object to = IPAM_MW_TRANSFORMS_GETTER.invoke(o);
                Object toD = deduplicate0(to);
                if (toD != null && to != toD) {
                    IPAM_MW_TRANSFORMS_SETTER.invoke(o, toD);
                }
            } catch (Throwable t) {
                t.printStackTrace();
            }
        } else if ("net.minecraftforge.client.model.ItemLayerModel$BakedItemModel".equals(c.getName())) {
            try {
                Object to = BIM_TRANSFORMS_GETTER.invoke(o);
                Object toD = deduplicate0(to);
                if (toD != null && to != toD) {
                    BIM_TRANSFORMS_SETTER.invoke(o, toD);
                }
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }
    }

    if (c == UnpackedBakedQuad.class) {
        try {
            float[][][] array = (float[][][]) FIELD_UNPACKED_DATA_GETTER.invokeExact((UnpackedBakedQuad) o);
            // float[][][]s are not currently deduplicated
            deduplicate0(array);
        } catch (Throwable t) {
            t.printStackTrace();
        }
    } else if (o instanceof ResourceLocation || o instanceof TRSRTransformation) {
        return deduplicate0(o);
    } else if (c == ItemCameraTransforms.class) {
        Object d = deduplicate0(o);
        if (d != o)
            return d;
        // TODO: Add ItemTransformVec3f dedup, maybe
        return o;
    } else if (o instanceof Item || o instanceof Block || o instanceof World || o instanceof Entity
            || o instanceof Logger || o instanceof IRegistry) {
        BLACKLIST_CLASS.add(c);
    } else if (o != ItemOverrideList.NONE && c == ItemOverrideList.class
            && ((ItemOverrideList) o).getOverrides().isEmpty()) {
        successfuls++;
        return ItemOverrideList.NONE;
    } else if (o instanceof com.google.common.base.Optional) {
        Optional opt = (Optional) o;
        if (opt.isPresent()) {
            Object b = deduplicateObject(opt.get(), recursion + 1);
            if (b != null && b != opt.get()) {
                return Optional.of(b);
            }
        }
    } else if (o instanceof Multimap) {
        if (o instanceof ImmutableMultimap) {
            // TODO: Handle me?
        } else {
            for (Object key : ((Multimap) o).keySet()) {
                List l = Lists.newArrayList(((Multimap) o).values());
                for (int i = 0; i < l.size(); i++) {
                    l.set(i, deduplicateObject(l.get(i), recursion + 1));
                }

                ((Multimap) o).replaceValues(key, l);
            }
        }
    } else if (o instanceof Map) {
        if (o instanceof ImmutableMap) {
            ImmutableMap im = (ImmutableMap) o;
            Map newMap = new HashMap();
            boolean deduplicated = false;
            for (Object key : im.keySet()) {
                Object a = im.get(key);
                Object b = deduplicateObject(a, recursion + 1);
                newMap.put(key, b != null ? b : a);
                if (b != null && b != a)
                    deduplicated = true;
            }
            if (deduplicated) {
                return ImmutableMap.copyOf(newMap);
            }
        } else {
            for (Object key : ((Map) o).keySet()) {
                Object value = ((Map) o).get(key);
                Object valueD = deduplicateObject(value, recursion + 1);
                if (valueD != null && value != valueD)
                    ((Map) o).put(key, valueD);
            }
        }
    } else if (o instanceof List) {
        if (o instanceof ImmutableList) {
            ImmutableList il = (ImmutableList) o;
            List newList = new ArrayList();
            boolean deduplicated = false;
            for (int i = 0; i < il.size(); i++) {
                Object a = il.get(i);
                Object b = deduplicateObject(a, recursion + 1);
                newList.add(b != null ? b : a);
                if (b != null && b != a)
                    deduplicated = true;
            }
            if (deduplicated) {
                return ImmutableList.copyOf(newList);
            }
        } else {
            List l = (List) o;
            for (int i = 0; i < l.size(); i++) {
                l.set(i, deduplicateObject(l.get(i), recursion + 1));
            }
        }
    } else if (o instanceof Collection) {
        if (!COLLECTION_CONSTRUCTORS.containsKey(c)) {
            try {
                COLLECTION_CONSTRUCTORS.put(c,
                        MethodHandles.publicLookup().findConstructor(c, MethodType.methodType(void.class)));
            } catch (Exception e) {
                COLLECTION_CONSTRUCTORS.put(c, null);
            }
        }

        MethodHandle constructor = COLLECTION_CONSTRUCTORS.get(c);
        if (constructor != null) {
            try {
                Collection nc = (Collection) constructor.invoke();
                for (Object o1 : ((Collection) o)) {
                    nc.add(deduplicateObject(o1, recursion + 1));
                }
                return nc;
            } catch (Throwable t) {

            }
        }

        // fallback
        for (Object o1 : ((Collection) o)) {
            deduplicateObject(o1, recursion + 1);
        }
    } else if (c.isArray()) {
        for (int i = 0; i < Array.getLength(o); i++) {
            Object entry = Array.get(o, i);
            Object entryD = deduplicateObject(entry, recursion + 1);
            if (entryD != null && entry != entryD)
                Array.set(o, i, entryD);
        }
    } else {
        if (!CLASS_FIELDS.containsKey(c)) {
            ImmutableSet.Builder<MethodHandle[]> fsBuilder = ImmutableSet.builder();
            Class cc = c;
            do {
                for (Field f : cc.getDeclaredFields()) {
                    f.setAccessible(true);
                    if ((f.getModifiers() & Modifier.STATIC) != 0)
                        continue;

                    if (shouldCheckClass(f.getType())) {
                        try {
                            fsBuilder.add(new MethodHandle[] { MethodHandles.lookup().unreflectGetter(f),
                                    MethodHandles.lookup().unreflectSetter(f) });
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }
                    }
                }
            } while ((cc = cc.getSuperclass()) != Object.class);
            CLASS_FIELDS.put(c, fsBuilder.build());
        }

        for (MethodHandle[] mh : CLASS_FIELDS.get(c)) {
            try {
                // System.out.println("-" + Strings.repeat("-", recursion) + "* " + f.getName());
                Object value = mh[0].invoke(o);
                Object valueD = deduplicateObject(value, recursion + 1);

                if (TRIM_ARRAYS_CLASSES.contains(c)) {
                    if (valueD instanceof ArrayList) {
                        ((ArrayList) valueD).trimToSize();
                    }
                }

                if (valueD != null && value != valueD)
                    mh[1].invoke(o, valueD);
            } catch (IllegalAccessException e) {

            } catch (Throwable t) {
                t.printStackTrace();
            }
        }
    }

    return o;
}

From source file:com.opengamma.strata.market.sensitivity.PointSensitivities.java

/**
 * Checks if this sensitivity equals another within the specified tolerance.
 * <p>// w ww  .  ja v a  2 s.  c  o  m
 * This returns true if the two instances have the list of {@code PointSensitivity},
 * where the sensitivity {@code double} values are compared within the specified tolerance.
 * It is expected that this comparator will be used on the normalized version of the sensitivity.
 * 
 * @param other  the other sensitivity
 * @param tolerance  the tolerance
 * @return true if equal up to the tolerance
 */
public boolean equalWithTolerance(PointSensitivities other, double tolerance) {
    ImmutableList<PointSensitivity> list1 = this.getSensitivities();
    ImmutableList<PointSensitivity> list2 = other.getSensitivities();
    int nbList1 = list1.size();
    int nbList2 = list2.size();
    if (nbList1 != nbList2) {
        return false;
    }
    for (int i1 = 0; i1 < nbList1; i1++) {
        if (list1.get(i1).compareKey(list2.get(i1)) == 0) {
            if (Math.abs(list1.get(i1).getSensitivity() - list2.get(i1).getSensitivity()) > tolerance) {
                return false;
            }
        } else {
            return false;
        }
    }
    return true;
}

From source file:com.google.devtools.build.benchmark.BuildGroupRunner.java

BuildGroupResult run(BenchmarkOptions opt) throws IOException, CommandException {
    BuildCase buildCase = new BazelBuildCase();
    ImmutableList<BuildTargetConfig> buildTargetConfigs = buildCase.getBuildTargetConfigs();
    ImmutableList<BuildEnvConfig> buildEnvConfigs = buildCase.getBuildEnvConfigs();

    // Prepare builder (Bazel)
    prepareBuilder();//from  w ww .  jav  a  2  s  .c  o m
    System.out.println("Done preparing builder.");

    // Get code versions (commit hashtag for Bazel) and datetimes
    ImmutableList<String> codeVersions = buildCase.getCodeVersions(builder, opt);
    ImmutableList<String> datetimes = builder.getDatetimeForCodeVersions(codeVersions);
    System.out.println("Ready to run benchmark for the following versions:");
    for (String version : codeVersions) {
        System.out.println(version);
    }

    BuildGroupResult.Builder buildGroupResultBuilder = getBuildGroupResultBuilder(buildTargetConfigs,
            buildEnvConfigs, codeVersions, datetimes);

    for (int versionIndex = 0; versionIndex < codeVersions.size(); ++versionIndex) {
        String version = codeVersions.get(versionIndex);
        System.out.format("Benchmark for version %s started.\n", version);

        // Get builder binary (build Bazel binary)
        Path buildBinary = builder.getBuildBinary(version);

        // Repeat several times to calculate average result
        for (int t = 0; t < REPEAT_TIMES; ++t) {
            // Prepare generated code for build
            buildCase.prepareGeneratedCode(workspace.resolve(GENERATED_CODE_FOR_COPY_DIR),
                    workspace.resolve(GENERATED_CODE_DIR));

            // Target config
            for (int targetIndex = 0; targetIndex < buildTargetConfigs.size(); ++targetIndex) {
                System.out.println("Started target: " + buildTargetConfigs.get(targetIndex).getDescription());

                // Environment config
                for (int envIndex = 0; envIndex < buildEnvConfigs.size(); ++envIndex) {
                    System.out.println("Started config: " + buildEnvConfigs.get(envIndex).getDescription());

                    double elapsedTime = buildSingleTargetAndGetElapsedTime(buildTargetConfigs, buildEnvConfigs,
                            buildBinary, targetIndex, envIndex);

                    // Store result
                    buildGroupResultBuilder.getBuildTargetResultsBuilder(targetIndex)
                            .getBuildEnvResultsBuilder(envIndex).getResultsBuilder(versionIndex)
                            .addResults(elapsedTime);
                }
            }
        }
    }

    return buildGroupResultBuilder.build();
}

From source file:com.facebook.buck.parser.TargetSpecResolver.java

/**
 * @return a list of sets of build targets where each set contains all build targets that match a
 *     corresponding {@link TargetNodeSpec}.
 *///  w w  w  . j  ava 2 s . c o m
public <T extends HasBuildTarget> ImmutableList<ImmutableSet<BuildTarget>> resolveTargetSpecs(Cell rootCell,
        Iterable<? extends TargetNodeSpec> specs, TargetConfiguration targetConfiguration,
        FlavorEnhancer<T> flavorEnhancer, TargetNodeProviderForSpecResolver<T> targetNodeProvider,
        TargetNodeFilterForSpecResolver<T> targetNodeFilter)
        throws BuildFileParseException, InterruptedException {

    // Convert the input spec iterable into a list so we have a fixed ordering, which we'll rely on
    // when returning results.
    ImmutableList<TargetNodeSpec> orderedSpecs = ImmutableList.copyOf(specs);

    Multimap<Path, Integer> perBuildFileSpecs = groupSpecsByBuildFile(rootCell, orderedSpecs);

    // Kick off parse futures for each build file.
    ArrayList<ListenableFuture<Map.Entry<Integer, ImmutableSet<BuildTarget>>>> targetFutures = new ArrayList<>();
    for (Path buildFile : perBuildFileSpecs.keySet()) {
        Collection<Integer> buildFileSpecs = perBuildFileSpecs.get(buildFile);
        TargetNodeSpec firstSpec = orderedSpecs.get(Iterables.get(buildFileSpecs, 0));
        Cell cell = rootCell.getCell(firstSpec.getBuildFileSpec().getCellPath());

        // Format a proper error message for non-existent build files.
        if (!cell.getFilesystem().isFile(buildFile)) {
            throw new MissingBuildFileException(firstSpec.toString(),
                    cell.getFilesystem().getRootPath().relativize(buildFile));
        }

        for (int index : buildFileSpecs) {
            TargetNodeSpec spec = orderedSpecs.get(index);
            handleTargetNodeSpec(flavorEnhancer, targetNodeProvider, targetNodeFilter, targetFutures, cell,
                    buildFile, targetConfiguration, index, spec);
        }
    }

    return collectTargets(orderedSpecs.size(), targetFutures);
}

From source file:com.appunite.example.debugutilsexample.detector.ChangesDetector.java

public void newData(@Nonnull ChangesAdapter adapter, @Nonnull List<T> values, boolean force) {
    checkNotNull(adapter);/*from  ww  w.  ja v  a  2 s  .  co m*/
    checkNotNull(values);

    final ImmutableList<H> list = FluentIterable.from(values).transform(mDetector).toList();

    int firstListPosition = 0;
    int secondListPosition = 0;

    int counter = 0;
    int toRemove = 0;

    for (; firstListPosition < mItems.size(); ++firstListPosition) {
        final H first = mItems.get(firstListPosition);
        final int indexOf = indexOf(list, secondListPosition, first);
        if (indexOf >= 0) {
            int itemsInserted = indexOf - secondListPosition;
            counter = notify(adapter, counter, toRemove, itemsInserted);
            toRemove = 0;
            secondListPosition = indexOf + 1;

            final H second = list.get(indexOf);
            if (force || !mDetector.same(first, second)) {
                adapter.notifyItemRangeChanged(counter, 1);
            }
            counter += 1;
        } else {
            toRemove += 1;
        }
    }

    int itemsInserted = values.size() - secondListPosition;
    notify(adapter, counter, toRemove, itemsInserted);
    mItems = list;
}

From source file:org.locationtech.geogig.cli.porcelain.Show.java

private void printRaw(GeogigCLI cli) throws IOException {
    ConsoleReader console = cli.getConsole();
    GeoGIG geogig = cli.getGeogig();/*from  ww w .j  av a 2  s.  co  m*/
    for (String ref : refs) {
        Optional<RevObject> obj = geogig.command(RevObjectParse.class).setRefSpec(ref).call();
        if (!obj.isPresent()) {
            ref = getFullRef(ref);
            obj = geogig.command(RevObjectParse.class).setRefSpec(ref).call();
        }
        checkParameter(obj.isPresent(), "refspec did not resolve to any object.");
        RevObject revObject = obj.get();
        if (revObject instanceof RevFeature) {
            Optional<RevFeatureType> opt = geogig.command(ResolveFeatureType.class).setRefSpec(ref).call();
            if (opt.isPresent()) {
                RevFeatureType ft = opt.get();
                ImmutableList<PropertyDescriptor> attribs = ft.sortedDescriptors();
                RevFeature feature = (RevFeature) revObject;
                Ansi ansi = super.newAnsi(console.getTerminal());
                ansi.a(ref).newline();
                ansi.a(feature.getId().toString()).newline();
                ImmutableList<Optional<Object>> values = feature.getValues();
                int i = 0;
                for (Optional<Object> value : values) {
                    PropertyDescriptor attrib = attribs.get(i);
                    ansi.a(attrib.getName()).newline();
                    PropertyType attrType = attrib.getType();
                    String typeName = FieldType.forBinding(attrType.getBinding()).name();
                    if (attrType instanceof GeometryType) {
                        GeometryType gt = (GeometryType) attrType;
                        CoordinateReferenceSystem crs = gt.getCoordinateReferenceSystem();
                        String crsText = CrsTextSerializer.serialize(crs);
                        ansi.a(typeName).a(" ").a(crsText).newline();
                    } else {
                        ansi.a(typeName).newline();
                    }
                    ansi.a(value.or("[NULL]").toString()).newline();
                    i++;
                }
                console.println(ansi.toString());
            } else {
                CharSequence s = geogig.command(CatObject.class).setObject(Suppliers.ofInstance(revObject))
                        .call();
                console.println(s);
            }
        } else {
            CharSequence s = geogig.command(CatObject.class).setObject(Suppliers.ofInstance(revObject)).call();
            console.println(s);
        }
    }
}

From source file:org.geogit.geotools.plumbing.ExportOp.java

private Iterator<SimpleFeature> alter(Iterator<SimpleFeature> plainFeatures,
        final ObjectId targetFeatureTypeId) {

    final RevFeatureType targetType = database.getFeatureType(targetFeatureTypeId);

    Function<SimpleFeature, SimpleFeature> alterFunction = new Function<SimpleFeature, SimpleFeature>() {
        @Override//from  ww  w . j a  v  a 2 s. c  o  m
        public SimpleFeature apply(SimpleFeature input) {
            final RevFeatureType oldFeatureType;
            oldFeatureType = (RevFeatureType) input.getUserData().get(RevFeatureType.class);

            final ObjectId metadataId = oldFeatureType.getId();
            if (targetType.getId().equals(metadataId)) {
                return input;
            }

            final RevFeature oldFeature;
            oldFeature = (RevFeature) input.getUserData().get(RevFeature.class);

            ImmutableList<PropertyDescriptor> oldAttributes = oldFeatureType.sortedDescriptors();
            ImmutableList<PropertyDescriptor> newAttributes = targetType.sortedDescriptors();

            ImmutableList<Optional<Object>> oldValues = oldFeature.getValues();
            List<Optional<Object>> newValues = Lists.newArrayList();
            for (int i = 0; i < newAttributes.size(); i++) {
                int idx = oldAttributes.indexOf(newAttributes.get(i));
                if (idx != -1) {
                    Optional<Object> oldValue = oldValues.get(idx);
                    newValues.add(oldValue);
                } else {
                    newValues.add(Optional.absent());
                }
            }
            RevFeature newFeature = RevFeature.build(ImmutableList.copyOf(newValues));
            FeatureBuilder featureBuilder = new FeatureBuilder(targetType);
            SimpleFeature feature = (SimpleFeature) featureBuilder.build(input.getID(), newFeature);
            return feature;
        }
    };
    return Iterators.transform(plainFeatures, alterFunction);
}

From source file:com.opengamma.strata.pricer.impl.volatility.local.ImpliedTrinomialTreeLocalVolatilityCalculator.java

@Override
public InterpolatedNodalSurface localVolatilityFromImpliedVolatility(Surface impliedVolatilitySurface,
        double spot, Function<Double, Double> interestRate, Function<Double, Double> dividendRate) {

    Function<DoublesPair, Double> surface = new Function<DoublesPair, Double>() {
        @Override//from   ww  w.j av a2  s. c om
        public Double apply(DoublesPair tk) {
            return impliedVolatilitySurface.zValue(tk);
        }
    };
    ImmutableList<double[]> localVolData = calibrate(surface, spot, interestRate, dividendRate).getFirst();
    SurfaceMetadata metadata = DefaultSurfaceMetadata.builder().xValueType(ValueType.YEAR_FRACTION)
            .yValueType(ValueType.STRIKE).zValueType(ValueType.LOCAL_VOLATILITY)
            .surfaceName(SurfaceName.of("localVol_" + impliedVolatilitySurface.getName())).build();
    return InterpolatedNodalSurface.ofUnsorted(metadata, DoubleArray.ofUnsafe(localVolData.get(0)),
            DoubleArray.ofUnsafe(localVolData.get(1)), DoubleArray.ofUnsafe(localVolData.get(2)), interpolator);
}