Example usage for com.google.common.collect ImmutableSet.Builder addAll

List of usage examples for com.google.common.collect ImmutableSet.Builder addAll

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableSet.Builder addAll.

Prototype

boolean addAll(Collection<? extends E> c);

Source Link

Document

Adds all of the elements in the specified collection to this set if they're not already present (optional operation).

Usage

From source file:com.jgaap.classifiers.MahalanobisDistance.java

public void train(List<Document> knowns) {
    ImmutableSet.Builder<Event> eventsBuilder = ImmutableSet.builder();
    ImmutableMap.Builder<Document, EventMap> knownHistogramsBuilder = ImmutableMap.builder();
    List<EventMap> histograms = new ArrayList<EventMap>(knowns.size());
    for (Document known : knowns) {
        EventMap histogram = new EventMap(known);
        eventsBuilder.addAll(histogram.uniqueEvents());
        histograms.add(histogram);//w w w.j av  a 2s  .c o  m
        knownHistogramsBuilder.put(known, histogram);
    }
    events = eventsBuilder.build();
    knownHistograms = knownHistogramsBuilder.build();
    EventMap mu = EventMap.centroid(histograms);
    double[][] s = new double[events.size()][events.size()];
    int i = 0;
    for (Event x : events) {
        int j = 0;
        for (Event y : events) {
            double tmp = 0;
            for (EventMap histogram : histograms) {
                tmp += (histogram.relativeFrequency(x) - mu.relativeFrequency(x))
                        * (histogram.relativeFrequency(y) - mu.relativeFrequency(y));
            }
            s[i][j] = tmp / (events.size() - 1);
            if (i == j) {
                s[i][j] += 0.00001;
            }
            j++;
        }
        i++;
    }
    inverseCovarianceMatrix = Float64Matrix.valueOf(s).pseudoInverse();
}

From source file:com.facebook.buck.apple.AppleBundleDescription.java

@Override
public Optional<ImmutableSet<FlavorDomain<?>>> flavorDomains() {
    ImmutableSet.Builder<FlavorDomain<?>> builder = ImmutableSet.builder();

    ImmutableSet<FlavorDomain<?>> localDomains = ImmutableSet.of(AppleDebugFormat.FLAVOR_DOMAIN,
            AppleDescriptions.INCLUDE_FRAMEWORKS);

    builder.addAll(localDomains);
    appleLibraryDescription.flavorDomains().ifPresent(domains -> builder.addAll(domains));
    appleBinaryDescription.flavorDomains().ifPresent(domains -> builder.addAll(domains));

    return Optional.of(builder.build());
}

From source file:com.facebook.buck.features.haskell.HaskellBinaryDescription.java

@Override
public BuildRule createBuildRule(BuildRuleCreationContextWithTargetGraph context, BuildTarget buildTarget,
        BuildRuleParams params, HaskellBinaryDescriptionArg args) {

    ProjectFilesystem projectFilesystem = context.getProjectFilesystem();
    CellPathResolver cellRoots = context.getCellPathResolver();
    HaskellPlatform platform = getPlatform(buildTarget, args);

    ActionGraphBuilder graphBuilder = context.getActionGraphBuilder();
    Optional<Type> type = BINARY_TYPE.getValue(buildTarget);
    // Handle #ghci flavor
    if (type.isPresent() && type.get() == Type.GHCI) {
        return HaskellDescriptionUtils.requireGhciRule(buildTarget, projectFilesystem, params, cellRoots,
                graphBuilder, platform, cxxBuckConfig, args.getDeps(), args.getPlatformDeps(), args.getSrcs(),
                args.getGhciPreloadDeps(), args.getGhciPlatformPreloadDeps(), args.getCompilerFlags(),
                Optional.empty(), Optional.empty(), ImmutableList.of(), args.isEnableProfiling());
    }/*  w  w w .ja v a 2s. c om*/

    SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(graphBuilder);
    SourcePathResolver pathResolver = DefaultSourcePathResolver.from(ruleFinder);
    Linker.LinkableDepType depType = getLinkStyle(args, type);

    // The target to use for the link rule.
    BuildTarget binaryTarget = buildTarget.withFlavors(InternalFlavor.of("binary"));

    // Maintain backwards compatibility to ease upgrade flows.
    if (platform.shouldUsedOldBinaryOutputLocation().orElse(true)) {
        binaryTarget = binaryTarget.withAppendedFlavors(platform.getFlavor());
    }

    ImmutableSet.Builder<BuildRule> depsBuilder = ImmutableSet.builder();

    depsBuilder.addAll(CxxDeps.builder().addDeps(args.getDeps()).addPlatformDeps(args.getPlatformDeps()).build()
            .get(graphBuilder, platform.getCxxPlatform()));

    ImmutableList<BuildRule> depQueryDeps = args.getDepsQuery()
            .map(query -> Objects.requireNonNull(query.getResolvedQuery()).stream().map(graphBuilder::getRule)
                    .filter(NativeLinkable.class::isInstance))
            .orElse(Stream.of()).collect(ImmutableList.toImmutableList());
    depsBuilder.addAll(depQueryDeps);
    ImmutableSet<BuildRule> deps = depsBuilder.build();

    // Inputs we'll be linking (archives, objects, etc.)
    ImmutableList.Builder<Arg> linkInputsBuilder = ImmutableList.builder();
    // Additional linker flags passed to the Haskell linker
    ImmutableList.Builder<Arg> linkFlagsBuilder = ImmutableList.builder();

    CommandTool.Builder executableBuilder = new CommandTool.Builder();

    // Add the binary as the first argument.
    executableBuilder.addArg(SourcePathArg.of(DefaultBuildTargetSourcePath.of(binaryTarget)));

    Path outputDir = BuildTargetPaths.getGenPath(projectFilesystem, binaryTarget, "%s").getParent();
    Path outputPath = outputDir.resolve(binaryTarget.getShortName());

    Path absBinaryDir = buildTarget.getCellPath().resolve(outputDir);

    // Special handling for dynamically linked binaries.
    if (depType == Linker.LinkableDepType.SHARED) {

        // Create a symlink tree with for all shared libraries needed by this binary.
        SymlinkTree sharedLibraries = graphBuilder.addToIndex(
                CxxDescriptionEnhancer.createSharedLibrarySymlinkTree(buildTarget, projectFilesystem,
                        graphBuilder, ruleFinder, platform.getCxxPlatform(), deps, r -> Optional.empty()));

        // Embed a origin-relative library path into the binary so it can find the shared libraries.
        // The shared libraries root is absolute. Also need an absolute path to the linkOutput
        linkFlagsBuilder.addAll(StringArg.from(MoreIterables.zipAndConcat(Iterables.cycle("-optl"),
                Linkers.iXlinker("-rpath",
                        String.format("%s/%s", platform.getCxxPlatform().getLd().resolve(graphBuilder).origin(),
                                absBinaryDir.relativize(sharedLibraries.getRoot()).toString())))));

        // Add all the shared libraries and the symlink tree as inputs to the tool that represents
        // this binary, so that users can attach the proper deps.
        executableBuilder.addNonHashableInput(sharedLibraries.getRootSourcePath());
        executableBuilder.addInputs(sharedLibraries.getLinks().values());
    }

    // Add in linker flags.
    linkFlagsBuilder.addAll(ImmutableList.copyOf(Iterables.transform(args.getLinkerFlags(),
            f -> CxxDescriptionEnhancer.toStringWithMacrosArgs(buildTarget, cellRoots, graphBuilder,
                    platform.getCxxPlatform(), f))));

    // Generate the compile rule and add its objects to the link.
    HaskellCompileRule compileRule = graphBuilder.addToIndex(HaskellDescriptionUtils.requireCompileRule(
            buildTarget, projectFilesystem, params, graphBuilder, ruleFinder,
            RichStream.from(deps)
                    .filter(dep -> dep instanceof HaskellCompileDep || dep instanceof CxxPreprocessorDep)
                    .toImmutableSet(),
            platform, depType, args.isEnableProfiling(), args.getMain(), Optional.empty(),
            args.getCompilerFlags(), HaskellSources.from(buildTarget, graphBuilder, pathResolver, ruleFinder,
                    platform, "srcs", args.getSrcs())));
    linkInputsBuilder.addAll(SourcePathArg.from(compileRule.getObjects()));

    ImmutableList<Arg> linkInputs = linkInputsBuilder.build();
    ImmutableList<Arg> linkFlags = linkFlagsBuilder.build();

    CommandTool executable = executableBuilder.build();
    HaskellLinkRule linkRule = HaskellDescriptionUtils.createLinkRule(binaryTarget, projectFilesystem, params,
            graphBuilder, ruleFinder, platform, Linker.LinkType.EXECUTABLE, linkFlags, linkInputs,
            RichStream.from(deps).filter(NativeLinkable.class).toImmutableList(),
            args.getLinkDepsQueryWhole()
                    ? RichStream.from(depQueryDeps).map(BuildRule::getBuildTarget).toImmutableSet()
                    : ImmutableSet.of(),
            depType, outputPath, Optional.empty(), args.isEnableProfiling());

    return new HaskellBinary(buildTarget, projectFilesystem, params.copyAppendingExtraDeps(linkRule), deps,
            executable, linkRule.getSourcePathToOutput());
}

From source file:com.facebook.buck.android.exopackage.NativeExoHelper.java

private ImmutableMap<String, ImmutableMultimap<String, Path>> getFilesByHashForAbis() throws IOException {
    List<String> deviceAbis = abiSupplier.get();
    ImmutableMap.Builder<String, ImmutableMultimap<String, Path>> filesByHashForAbisBuilder = ImmutableMap
            .builder();// www  .  j  a  va  2s . c om
    ImmutableMultimap<String, Path> allLibraries = getAllLibraries();
    ImmutableSet.Builder<String> providedLibraries = ImmutableSet.builder();
    for (String abi : deviceAbis) {
        ImmutableMultimap<String, Path> filesByHash = getRequiredLibrariesForAbi(allLibraries, abi,
                providedLibraries.build());
        if (filesByHash.isEmpty()) {
            continue;
        }
        providedLibraries.addAll(filesByHash.keySet());
        filesByHashForAbisBuilder.put(abi, filesByHash);
    }
    return filesByHashForAbisBuilder.build();
}

From source file:org.spongepowered.common.mixin.core.world.MixinWorld_Data.java

@Override
public Set<Key<?>> getKeys(int x, int y, int z) {
    final ImmutableSet.Builder<Key<?>> builder = ImmutableSet.builder();
    final BlockState blockState = getBlock(x, y, z).withExtendedProperties(new Location<>(this, x, y, z));
    builder.addAll(blockState.getKeys());
    final Optional<TileEntity> tileEntity = getTileEntity(x, y, z);
    if (tileEntity.isPresent()) {
        builder.addAll(tileEntity.get().getKeys());
    }/*w  ww . j  av  a 2s  .  co m*/
    return builder.build();
}

From source file:org.onosproject.pathpainter.PathPainterTopovMessageHandler.java

private ImmutableSet.Builder<Link> buildDisjointPaths(ImmutableSet.Builder<Link> pathBuilder) {
    paths.forEach(path -> {//from   w w  w.ja  v a 2  s  .co  m
        DisjointPath dp = (DisjointPath) path;
        pathBuilder.addAll(dp.primary().links());
        pathBuilder.addAll(dp.backup().links());
    });
    return pathBuilder;
}

From source file:org.geogit.remote.BinaryPackedObjects.java

/**
 * Find commits which should be previsited to avoid resending objects that are already on the
 * receiving end. A commit should be previsited if:
 * <ul>/* w w  w .  jav  a 2 s .  com*/
 * <li>It is not going to be visited, and
 * <li>It is the immediate ancestor of a commit which is going to be previsited.
 * </ul>
 * 
 */
private ImmutableList<ObjectId> scanForPrevisitList(List<ObjectId> want, List<ObjectId> have,
        Deduplicator deduplicator) {
    /*
     * @note Implementation note: To find the previsit list, we just iterate over all the
     * commits that will be visited according to our want and have lists. Any parents of commits
     * in this traversal which are part of the 'have' list will be in the previsit list.
     */
    Iterator<RevCommit> willBeVisited = Iterators.filter( //
            PostOrderIterator.rangeOfCommits(want, have, database, deduplicator), //
            RevCommit.class);
    ImmutableSet.Builder<ObjectId> builder = ImmutableSet.builder();

    while (willBeVisited.hasNext()) {
        RevCommit next = willBeVisited.next();
        List<ObjectId> parents = new ArrayList<ObjectId>(next.getParentIds());
        parents.retainAll(have);
        builder.addAll(parents);
    }

    return ImmutableList.copyOf(builder.build());
}

From source file:grakn.core.graql.gremlin.fragment.Fragment.java

/**
 * Get all variables in the fragment including the start and end (if present)
 *//*from   www  .  j av a 2s.  co  m*/
public final Set<Variable> vars() {
    if (vars == null) {
        ImmutableSet.Builder<Variable> builder = ImmutableSet.<Variable>builder().add(start());
        Variable end = end();
        if (end != null)
            builder.add(end);
        builder.addAll(otherVars());
        vars = builder.build();
    }

    return vars;
}

From source file:org.spongepowered.common.mixin.core.world.MixinWorld_Data.java

@Override
public Set<ImmutableValue<?>> getValues(int x, int y, int z) {
    final ImmutableSet.Builder<ImmutableValue<?>> builder = ImmutableSet.builder();
    final BlockState blockState = getBlock(x, y, z).withExtendedProperties(new Location<>(this, x, y, z));
    builder.addAll(blockState.getValues());
    final Optional<TileEntity> tileEntity = getTileEntity(x, y, z);
    if (tileEntity.isPresent()) {
        builder.addAll(tileEntity.get().getValues());
    }/*from   w w  w.j  av  a  2  s  . c o m*/
    return builder.build();
}

From source file:com.brighttag.agathon.security.SecurityGroupUpdaterService.java

/**
 * Retrieve ingress rules tied to the configured security group and {@code dataCenter}.
 *
 * @return set of ip ranges in CIDR notation associated with the security group
 *///from   w ww.  j  a v a 2  s.  c o  m
@VisibleForTesting
Set<Netmask> listGroupRules(String securityGroupName, String dataCenter, int port) {
    ImmutableSet.Builder<Netmask> rules = ImmutableSet.builder();
    Set<SecurityGroupPermission> permissions = securityGroupService.getPermissions(securityGroupName,
            dataCenter);
    for (SecurityGroupPermission permission : permissions) {
        if (permission.getPortRange().contains(port)) {
            rules.addAll(permission.getNetmasks());
        }
    }
    return rules.build();
}