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

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

Introduction

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

Prototype

int count(@Nullable Object element);

Source Link

Document

Returns the number of occurrences of an element in this multiset (the count of the element).

Usage

From source file:de.tum.bgu.msm.data.JobDataManager.java

public void calculateJobDensityByZone() {
    Multiset<Integer> counter = ConcurrentHashMultiset.create();
    jobs.values().parallelStream().forEach(j -> counter.add(j.getZoneId()));
    geoData.getZones()/*from   w  w  w . java 2 s  .co m*/
            .forEach((id, zone) -> zonalJobDensity.put(id, (double) (counter.count(id) / zone.getArea_sqmi())));
}

From source file:org.sonar.server.organization.ws.SearchMembersAction.java

private SearchMembersWsResponse buildResponse(List<UserDto> users, Common.Paging wsPaging,
        @Nullable Multiset<String> groupCountByLogin) {
    SearchMembersWsResponse.Builder response = SearchMembersWsResponse.newBuilder();

    User.Builder wsUser = User.newBuilder();
    users.stream().map(userDto -> {/*from   w ww  .  jav a2 s. com*/
        String login = userDto.getLogin();
        wsUser.clear().setLogin(login).setName(userDto.getName());
        setNullable(userDto.getEmail(), text -> wsUser.setAvatar(avatarResolver.create(userDto)));
        setNullable(groupCountByLogin, count -> wsUser.setGroupCount(groupCountByLogin.count(login)));
        return wsUser;
    }).forEach(response::addUsers);
    response.setPaging(wsPaging);

    return response.build();
}

From source file:org.splevo.jamopp.vpm.analyzer.programdependency.JaMoPPProgramDependencyVPMAnalyzer.java

private void printStatistics(Multiset<DependencyType> statistics) {
    StringBuilder builder = new StringBuilder();
    builder.append("Statistics:");
    for (DependencyType type : statistics.elementSet()) {
        builder.append("\n");
        builder.append(type + "\t" + statistics.count(type));
    }/*from w w  w  .ja v  a2  s.c  o  m*/
    logger.debug(builder.toString());
}

From source file:edu.cmu.cs.lti.ark.fn.identification.training.AlphabetCreationThreaded.java

private void conjoinAndWriteAlphabet(final Multiset<String> unconjoinedFeatures, final int minimumCount,
        File alphabetFile) throws IOException {
    final BufferedWriter output = Files.newWriter(alphabetFile, Charsets.UTF_8);
    final int unconjoinedSize = unconjoinedFeatures.elementSet().size();
    try {/* w  ww .j  ava  2  s .  c  o  m*/
        logger.info("Writing alphabet.");
        int numUnconjoined = 0;
        int numConjoined = 0;
        for (String unconjoinedFeature : unconjoinedFeatures.elementSet()) {
            if (unconjoinedFeatures.count(unconjoinedFeature) >= minimumCount) {
                final Set<String> conjoinedFeatureNames = featureExtractor.getConjoinedFeatureNames(allFrames,
                        unconjoinedFeature);
                numConjoined += conjoinedFeatureNames.size();
                for (String feature : conjoinedFeatureNames) {
                    output.write(String.format("%s\n", feature));
                }
            }
            numUnconjoined++;
            if (numUnconjoined % 50 == 0) {
                logger.info("Unconjoined: " + numUnconjoined + " of " + unconjoinedSize);
                logger.info("Conjoined: " + numConjoined);
            }
        }
        logger.info("Done writing alphabet.");
    } finally {
        closeQuietly(output);
    }
}

From source file:bots.mctsbot.ai.bots.bot.gametree.rollout.BucketRollOut.java

private WinDistribution[] calcWinDistributions(int botRank, Multiset<Integer> ranks,
        Multiset<Integer> deadRanks) {
    Iterator<Integer> iter = ranks.iterator();
    WinDistribution[] winProbs = new WinDistribution[10];
    for (int bucket = 0; bucket < nbBuckets; bucket++) {
        double winWeight = 0;
        double drawWeight = 0;
        double loseWeight = 0;
        for (int j = 0; j < nbSamplesPerBucket; j++) {
            int rank = iter.next();
            double weight = 1 - deadRanks.count(rank) / ranks.count(rank);
            if (rank < botRank) {
                winWeight += weight;/* w  w w  .  java2  s. c  o  m*/
            } else if (rank > botRank) {
                loseWeight += weight;
            } else {
                drawWeight += weight;
            }
        }
        double nbSamples = winWeight + drawWeight + loseWeight;
        if (nbSamples == 0)
            nbSamples = 1;
        winProbs[bucket] = new WinDistribution(winWeight / nbSamples, drawWeight / nbSamples,
                loseWeight / nbSamples);
    }
    return winProbs;
}

From source file:net.shipilev.elections.cikrf.Parser.java

private void printSummaries(PrintWriter pw, String label, SummaryData data, List<String> key) {
    pw.printf("**** Summary for %s (aggregate over %s):\n", label, key.toString());
    Multiset<Metric> set = data.get(key);
    if (set == null || set.isEmpty()) {
        pw.println("No data.");
    } else {/*from   w ww  . j  a v  a 2  s. com*/
        for (Metric s : set.elementSet()) {
            pw.printf("%15d : %s\n", set.count(s), s.getLabel());
        }
    }
    pw.printf("\n");
    pw.flush();
}

From source file:org.glowroot.ui.SyntheticResultJsonService.java

private ImmutableList<SyntheticMonitor> getAllSyntheticMonitors(String agentRollupId, long from, long to)
        throws Exception {
    Map<String, String> syntheticMonitorIds = syntheticResultRepository.getSyntheticMonitorIds(agentRollupId,
            from, to);/*from  w w  w  .ja  va2s . co m*/
    Multiset<String> multiset = HashMultiset.create();
    multiset.addAll(syntheticMonitorIds.values());
    List<SyntheticMonitor> syntheticMonitors = Lists.newArrayList();
    for (Map.Entry<String, String> entry : syntheticMonitorIds.entrySet()) {
        String id = entry.getKey();
        String display = entry.getValue();
        if (multiset.count(entry.getValue()) > 1) {
            display += " (" + id + ")";
        }
        syntheticMonitors.add(ImmutableSyntheticMonitor.of(id, display));
    }
    if (to > clock.currentTimeMillis()) {
        // so that new synthetic monitors will show up right away
        List<SyntheticMonitorConfig> configs = configRepository.getSyntheticMonitorConfigs(agentRollupId);
        for (SyntheticMonitorConfig config : configs) {
            if (!syntheticMonitorIds.containsKey(config.getId())) {
                syntheticMonitors.add(ImmutableSyntheticMonitor.of(config.getId(),
                        MoreConfigDefaults.getDisplayOrDefault(config)));
            }
        }
    }
    return new SyntheticMonitorOrdering().immutableSortedCopy(syntheticMonitors);
}

From source file:com.clarkparsia.sbol.order.PartialOrder.java

/**
 * Returns the elements in an ascending topological order.
 * // ww  w  .j  a  v a 2 s  . com
 * @throws IllegalStateException if there are cycles between the elements
 */
@Override
public Iterator<T> iterator() throws IllegalStateException {
    Multiset<T> degrees = HashMultiset.create();
    Queue<T> nodesPending = new ArrayDeque<T>();
    List<T> nodesSorted = Lists.newArrayList();

    for (Entry<T, Set<T>> entry : precededBy.entrySet()) {
        T node = entry.getKey();
        Set<T> precededByList = entry.getValue();
        int degree = precededByList.size();
        degrees.setCount(node, degree);
        if (degree == 0) {
            nodesPending.add(node);
        }
    }

    while (!nodesPending.isEmpty()) {
        T node = nodesPending.remove();

        int deg = degrees.count(node);
        if (deg != 0)
            throw new IllegalStateException("Cycle detected " + node + " " + deg + " " + nodesSorted.size());

        nodesSorted.add(node);

        for (Entry<T, Set<T>> entry : precededBy.entrySet()) {
            T n = entry.getKey();
            Set<T> precededByList = entry.getValue();
            if (precededByList.contains(node)) {
                int degree = degrees.count(n);
                if (degree == 1) {
                    nodesPending.add(n);
                    degrees.setCount(n, 0);
                } else {
                    degrees.remove(n);
                }
            }
        }
    }

    if (nodesSorted.size() != precededBy.size()) {
        throw new IllegalStateException("Failed to sort elements");
    }

    return nodesSorted.iterator();
}

From source file:org.sonar.server.component.ws.ComponentAppAction.java

private void appendIssuesAggregation(JsonWriter json, RulesAggregation rulesAggregation,
        Multiset<String> severitiesAggregation) {
    json.name("severities").beginArray();
    for (String severity : severitiesAggregation.elementSet()) {
        json.beginArray().value(severity)
                .value(i18n.message(UserSession.get().locale(), "severity." + severity, null))
                .value(severitiesAggregation.count(severity)).endArray();
    }//from   w w w .  j a v a 2s  .  c  om
    json.endArray();

    json.name("rules").beginArray();
    for (RulesAggregation.Rule rule : rulesAggregation.rules()) {
        json.beginArray().value(rule.ruleKey().toString()).value(rule.name())
                .value(rulesAggregation.countRule(rule)).endArray();
    }
    json.endArray();
}

From source file:bio.gcat.operation.analysis.TupleUsage.java

@Override
public Result analyse(Collection<Tuple> tuples, Object... values) {
    Logger logger = getLogger();/*from   w w  w . ja  v a 2s  . c o m*/

    if (values[0] == null) {
        logger.log("Choose an existing file to count tuple usage in.");
        return null;
    }

    Acid acid;
    if ((acid = Tuple.tuplesAcid(tuples)) == null) {
        logger.log("Tuples with variable acids, can't analyse tuple usage.");
        return null; //tuples not all in same acid
    }

    Multiset<Tuple> tupleCount = HashMultiset.create();
    try (BufferedReader reader = new BufferedReader(new InputStreamReader((InputStream) values[0]))) {
        String line;
        while ((line = reader.readLine()) != null)
            tupleCount.addAll(normalizeTuples(splitTuples(tupleString(line).trim()), acid));
    } catch (IOException e) {
        logger.log("Error while reading file.", e);
        return null;
    }

    StringBuilder builder = new StringBuilder();
    for (Tuple tuple : (!tuples.isEmpty() && !containsOnly(tuples, EMPTY_TUPLE) ? normalizeTuples(tuples, acid)
            : tupleCount.elementSet()))
        builder.append(DELIMITER).append(tupleCount.count(tuple)).append(TIMES).append(tuple);
    return new SimpleResult(this,
            builder.length() != 0 ? builder.substring(DELIMITER.length()).toString() : "no tuples");
}