Example usage for com.google.common.collect Multiset contains

List of usage examples for com.google.common.collect Multiset contains

Introduction

In this page you can find the example usage for com.google.common.collect Multiset contains.

Prototype

@Override
boolean contains(@Nullable Object element);

Source Link

Document

Determines whether this multiset contains the specified element.

Usage

From source file:ai.grakn.test.engine.tasks.BackgroundTaskTestUtils.java

public static Set<TaskId> failingTasks(List<TaskState> tasks) {
    Multiset<TaskId> completableTasks = completableTasks(tasks);
    return tasks.stream().map(TaskState::getId).filter(task -> !completableTasks.contains(task))
            .collect(toSet());//  ww w  .ja v a2 s. c  o  m
}

From source file:com.facebook.buck.rules.SymlinkTree.java

/**
 * Because of cross-cell, multiple {@link SourcePath}s can resolve to the same relative path,
 * despite having distinct absolute paths. This presents a challenge for rules that require
 * gathering all of the inputs in one directory.
 *
 * @param sourcePaths set of SourcePaths to process
 * @param resolver resolver//  w w  w  .  j  a v a 2  s.c  om
 * @return a map that assigns a unique relative path to each of the SourcePaths.
 */
public static ImmutableBiMap<SourcePath, Path> resolveDuplicateRelativePaths(
        ImmutableSortedSet<SourcePath> sourcePaths, SourcePathResolver resolver) {
    // This serves a dual purpose - it keeps track of whether a particular relative path had been
    // assigned to a SourcePath and how many times a particular relative path had been seen.
    Multiset<Path> assignedPaths = HashMultiset.create();
    ImmutableBiMap.Builder<SourcePath, Path> builder = ImmutableBiMap.builder();
    List<SourcePath> conflicts = new ArrayList<>();

    for (SourcePath sourcePath : sourcePaths) {
        Path relativePath = resolver.getRelativePath(sourcePath);
        if (!assignedPaths.contains(relativePath)) {
            builder.put(sourcePath, relativePath);
            assignedPaths.add(relativePath);
        } else {
            conflicts.add(sourcePath);
        }
    }

    for (SourcePath conflict : conflicts) {
        Path relativePath = resolver.getRelativePath(conflict);
        Path parent = MorePaths.getParentOrEmpty(relativePath);
        String extension = MorePaths.getFileExtension(relativePath);
        String name = MorePaths.getNameWithoutExtension(relativePath);

        while (true) {
            StringBuilder candidateName = new StringBuilder(name);
            candidateName.append('-');
            int suffix = assignedPaths.count(relativePath);
            candidateName.append(suffix);
            if (!extension.isEmpty()) {
                candidateName.append('.');
                candidateName.append(extension);
            }
            Path candidate = parent.resolve(candidateName.toString());

            if (!assignedPaths.contains(candidate)) {
                assignedPaths.add(candidate);
                builder.put(conflict, candidate);
                break;
            } else {
                assignedPaths.add(relativePath);
            }
        }
    }

    return builder.build();
}

From source file:org.apache.aurora.scheduler.async.preemptor.PendingTaskProcessor.java

/**
 * Creates execution sequence for pending task groups by interleaving their unique occurrences.
 * For example: {G1, G1, G1, G2, G2} will be converted into {G1, G2, G1, G2, G1}.
 *
 * @param groups Multiset of task groups.
 * @return A task group execution sequence.
 *//*www .j av  a2  s  . c o m*/
private static List<TaskGroupKey> getPreemptionSequence(Multiset<TaskGroupKey> groups) {
    Multiset<TaskGroupKey> mutableGroups = HashMultiset.create(groups);
    List<TaskGroupKey> instructions = Lists.newLinkedList();
    Set<TaskGroupKey> keys = ImmutableSet.copyOf(groups.elementSet());
    while (!mutableGroups.isEmpty()) {
        for (TaskGroupKey key : keys) {
            if (mutableGroups.contains(key)) {
                instructions.add(key);
                mutableGroups.remove(key);
            }
        }
    }

    return instructions;
}

From source file:org.apache.aurora.scheduler.preemptor.PendingTaskProcessor.java

/**
 * Creates execution sequence for pending task groups by interleaving batches of requested size of
 * their occurrences. For example: {G1, G1, G1, G2, G2} with batch size of 2 task per group will
 * be converted into {G1, G1, G2, G2, G1}.
 *
 * @param groups Multiset of task groups.
 * @param batchSize The batch size of tasks from each group to sequence together.
 * @return A task group execution sequence.
 *//*from   www  . j ava 2  s. com*/
@VisibleForTesting
static List<TaskGroupKey> getPreemptionSequence(Multiset<TaskGroupKey> groups, int batchSize) {

    Preconditions.checkArgument(batchSize > 0, "batchSize should be positive.");

    Multiset<TaskGroupKey> mutableGroups = HashMultiset.create(groups);
    List<TaskGroupKey> instructions = Lists.newLinkedList();
    Set<TaskGroupKey> keys = ImmutableSet.copyOf(groups.elementSet());
    while (!mutableGroups.isEmpty()) {
        for (TaskGroupKey key : keys) {
            if (mutableGroups.contains(key)) {
                int elementCount = mutableGroups.remove(key, batchSize);
                int removedCount = Math.min(elementCount, batchSize);
                instructions.addAll(Collections.nCopies(removedCount, key));
            }
        }
    }

    return instructions;
}

From source file:org.apache.jackrabbit.oak.segment.SegmentGraph.java

/**
 * Write the segment graph of a file store to a stream.
 * <p>/*  w  ww.ja  va2 s  .  c o m*/
 * The graph is written in
 * <a href="https://gephi.github.io/users/supported-graph-formats/gdf-format/">the Guess GDF format</a>,
 * which is easily imported into <a href="https://gephi.github.io/">Gephi</a>.
 * As GDF only supports integers but the segment time stamps are encoded as long
 * the {@code epoch} argument is used as a negative offset translating all timestamps
 * into a valid int range.
 *
 * @param fileStore     file store to graph
 * @param out           stream to write the graph to
 * @param epoch         epoch (in milliseconds)
 * @param pattern       regular expression specifying inclusion of nodes or {@code null}
 *                      for all nodes.
 * @throws Exception
 */
public static void writeSegmentGraph(@Nonnull ReadOnlyStore fileStore, @Nonnull OutputStream out,
        @Nonnull Date epoch, @CheckForNull String pattern) throws Exception {
    checkNotNull(epoch);
    PrintWriter writer = new PrintWriter(checkNotNull(out));
    try {
        SegmentNodeState root = checkNotNull(fileStore).getHead();
        Predicate<UUID> filter = pattern == null ? Predicates.<UUID>alwaysTrue()
                : createRegExpFilter(pattern, fileStore);
        Graph<UUID> segmentGraph = parseSegmentGraph(fileStore, filter);
        Graph<UUID> headGraph = parseHeadGraph(fileStore.getReader(), root.getRecordId());

        writer.write(
                "nodedef>name VARCHAR, label VARCHAR, type VARCHAR, wid VARCHAR, gc INT, t INT, size INT, head BOOLEAN\n");
        for (UUID segment : segmentGraph.vertices()) {
            writeNode(segment, writer, headGraph.containsVertex(segment), epoch, fileStore);
        }

        writer.write("edgedef>node1 VARCHAR, node2 VARCHAR, head BOOLEAN\n");
        for (Entry<UUID, Multiset<UUID>> edge : segmentGraph.edges()) {
            UUID from = edge.getKey();
            for (UUID to : edge.getValue()) {
                if (!from.equals(to)) {
                    Multiset<UUID> he = headGraph.getEdge(from);
                    boolean inHead = he != null && he.contains(to);
                    writer.write(from + "," + to + "," + inHead + "\n");
                }
            }
        }
    } finally {
        writer.close();
    }
}

From source file:org.apache.jackrabbit.oak.plugins.segment.SegmentGraph.java

/**
 * Write the segment graph of a file store to a stream.
 * <p>//from w w w . j a v  a  2 s.co m
 * The graph is written in
 * <a href="https://gephi.github.io/users/supported-graph-formats/gdf-format/">the Guess GDF format</a>,
 * which is easily imported into <a href="https://gephi.github.io/">Gephi</a>.
 * As GDF only supports integers but the segment time stamps are encoded as long
 * the {@code epoch} argument is used as a negative offset translating all timestamps
 * into a valid int range.
 *
 * @param fileStore     file store to graph
 * @param out           stream to write the graph to
 * @param epoch         epoch (in milliseconds)
 * @param pattern       regular expression specifying inclusion of nodes or {@code null}
 *                      for all nodes.
 * @throws Exception
 */
public static void writeSegmentGraph(@Nonnull ReadOnlyStore fileStore, @Nonnull OutputStream out,
        @Nonnull Date epoch, @CheckForNull String pattern) throws Exception {
    checkNotNull(epoch);
    PrintWriter writer = new PrintWriter(checkNotNull(out));
    try {
        SegmentNodeState root = checkNotNull(fileStore).getHead();

        Predicate<UUID> filter = pattern == null ? Predicates.<UUID>alwaysTrue()
                : createRegExpFilter(pattern, fileStore.getTracker());
        Graph<UUID> segmentGraph = parseSegmentGraph(fileStore, filter);
        Graph<UUID> headGraph = parseHeadGraph(root.getRecordId());

        writer.write(
                "nodedef>name VARCHAR, label VARCHAR, type VARCHAR, wid VARCHAR, gc INT, t INT, size INT, head BOOLEAN\n");
        for (UUID segment : segmentGraph.vertices()) {
            writeNode(segment, writer, headGraph.containsVertex(segment), epoch, fileStore.getTracker());
        }

        writer.write("edgedef>node1 VARCHAR, node2 VARCHAR, head BOOLEAN\n");
        for (Entry<UUID, Multiset<UUID>> edge : segmentGraph.edges()) {
            UUID from = edge.getKey();
            for (UUID to : edge.getValue()) {
                if (!from.equals(to)) {
                    Multiset<UUID> he = headGraph.getEdge(from);
                    boolean inHead = he != null && he.contains(to);
                    writer.write(from + "," + to + "," + inHead + "\n");
                }
            }
        }
    } finally {
        writer.close();
    }
}

From source file:com.github.rinde.rinsim.scenario.measure.Metrics.java

/**
 * Computes the number of occurrences of each event type in the specified
 * {@link Scenario}./*from www  .  ja v  a  2s  .  com*/
 * @param s The scenario to check.
 * @return A {@link ImmutableMultiset} of event types.
 */
public static ImmutableMultiset<Class<?>> getEventTypeCounts(Scenario s) {
    final Multiset<Class<?>> set = LinkedHashMultiset.create();
    for (final TimedEvent te : s.getEvents()) {
        set.add(te.getClass());
    }
    final List<Class<?>> toMove = new ArrayList<>();
    for (final Class<?> c : set.elementSet()) {
        if (!Modifier.isPublic(c.getModifiers()) && TimedEvent.class.isAssignableFrom(c.getSuperclass())
                && !set.contains(c.getSuperclass())) {
            toMove.add(c);
        }
    }
    for (final Class<?> c : toMove) {
        set.add(c.getSuperclass(), set.count(c));
        set.remove(c, set.count(c));
    }
    return ImmutableMultiset.copyOf(set);
}

From source file:com.sonarsource.lits.IssuesChecker.java

@Override
public boolean accept(FilterableIssue issue, IssueFilterChain chain) {
    if (disabled) {
        return true;
    }/* w ww.ja  va 2  s .c  om*/

    IssueKey issueKey = new IssueKey(issue.componentKey(), issue.ruleKey().toString(), issue.line());
    dump.add(issueKey);
    Multiset<IssueKey> componentIssues = getByComponentKey(issueKey.componentKey);
    if (componentIssues.contains(issueKey)) {
        // old issue => no need to persist
        componentIssues.remove(issueKey);
        Preconditions.checkState(Severity.INFO.equals(issue.severity()));
        return false;
    } else {
        // new issue => persist
        different = true;
        differences++;
        return true;
    }
}

From source file:com.continuuity.loom.layout.change.AddServicesChange.java

@Override
public Set<Node> applyChange(Cluster cluster, Set<Node> clusterNodes, Map<String, Service> serviceMap) {
    Set<Node> changedNodes = Sets.newHashSet();
    Multiset<NodeLayout> countsToAdd = HashMultiset.create(countsPerNodeLayout);
    for (Node node : clusterNodes) {
        NodeLayout nodeLayout = NodeLayout.fromNode(node);
        if (countsToAdd.contains(nodeLayout)) {
            for (String service : services) {
                node.addService(serviceMap.get(service));
            }/*from  www .ja  va2  s.c o m*/
            countsToAdd.setCount(nodeLayout, countsToAdd.count(nodeLayout) - 1);
            changedNodes.add(node);
        }
    }
    cluster.setServices(Sets.union(cluster.getServices(), services));
    return changedNodes;
}

From source file:cuchaz.enigma.convert.ClassIdentity.java

private int getNumMatches(Multiset<String> a, Multiset<String> b) {
    int numMatches = 0;
    for (String val : a) {
        if (b.contains(val)) {
            numMatches++;//  w w  w . ja  v  a2 s  .c  o  m
        }
    }
    return numMatches;
}