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:uk.ac.ebi.intact.editor.services.admin.report.AssignmentReportService.java

@Transactional(value = "jamiTransactionManager", propagation = Propagation.REQUIRED, readOnly = true)
public List<AssignmentInfo> calculateComplexReviewerAssignments(Date fromDate, Date toDate) {
    List<AssignmentInfo> assignmentInfos = new ArrayList<AssignmentInfo>();

    Query query = getIntactDao().getEntityManager()
            .createQuery("select distinct c from IntactComplex c join c.lifecycleEvents as e where "
                    + "e.cvEvent.shortName = :cvEvent and e.when >= :dateFrom and e.when <= :dateTo and e.note is null");
    query.setParameter("cvEvent", LifeCycleEventType.READY_FOR_CHECKING.shortLabel());
    query.setParameter("dateFrom", fromDate);
    query.setParameter("dateTo", new DateTime(toDate).plusDays(1).minusSeconds(1).toDate());

    List<IntactComplex> complexes = query.getResultList();

    Multiset<String> multiset = HashMultiset.create();

    for (IntactComplex pub : complexes) {
        for (LifeCycleEvent event : pub.getLifecycleEvents()) {
            multiset.add(pub.getCurrentReviewer().getLogin());
        }//from   www . j av a  2 s  .c  o  m
    }

    int total = multiset.size();

    for (String reviewer : multiset.elementSet()) {
        int count = multiset.count(reviewer);
        int percentage = count * 100 / total;
        assignmentInfos.add(new AssignmentInfo(reviewer, count, percentage));
    }

    return assignmentInfos;
}

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.j  a  v a 2 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:org.mule.runtime.extension.internal.loader.validator.ConnectionProviderNameModelValidator.java

@Override
public void validate(ExtensionModel model, ProblemsReporter problemsReporter)
        throws IllegalModelDefinitionException {
    Multiset<String> names = HashMultiset.create();
    Set<ConnectionProviderModel> models = new HashSet<>();
    new IdempotentExtensionWalker() {

        @Override//w  w w  .j a v a 2  s.  c  om
        public void onConnectionProvider(ConnectionProviderModel model) {
            models.add(model);
            names.add(model.getName());
        }
    }.walk(model);

    Set<ConnectionProviderModel> repeatedNameModels = models.stream()
            .filter(cp -> names.count(cp.getName()) > 1).collect(toSet());

    if (!repeatedNameModels.isEmpty()) {
        problemsReporter.addError(new Problem(model,
                format("There are %d connection providers with repeated names. Offending names are: [%s]",
                        repeatedNameModels.size(),
                        repeatedNameModels.stream().map(NamedObject::getName).collect(joining(",")))));
    }
}

From source file:org.apache.mahout.knn.generate.Multinomial.java

public Multinomial(Multiset<T> counts, int width) {
    Preconditions.checkArgument(counts.size() > 0, "Need some data to build sampler");
    rand = RandomUtils.getRandom();//from w ww  . j  a  va 2s . c  o  m
    List<WeightedThing<T>> things = Lists.newArrayList();
    double n = counts.size();
    for (T t : counts.elementSet()) {
        things.add(new WeightedThing<T>(t, counts.count(t) / n));
    }
    init(width, things);
}

From source file:org.sonar.server.computation.task.projectanalysis.issue.IssueCounter.java

private void addMeasuresByPeriod(Component component) {
    if (!periodHolder.hasPeriod()) {
        return;//from  www. ja va 2 s  . c  o  m
    }
    Double unresolvedVariations = (double) currentCounters.counterForPeriod().unresolved;
    measureRepository.add(component, metricRepository.getByKey(NEW_VIOLATIONS_KEY),
            Measure.newMeasureBuilder().setVariation(unresolvedVariations).createNoValue());

    for (Map.Entry<String, String> entry : SEVERITY_TO_NEW_METRIC_KEY.entrySet()) {
        String severity = entry.getKey();
        String metricKey = entry.getValue();
        Multiset<String> bag = currentCounters.counterForPeriod().severityBag;
        Metric metric = metricRepository.getByKey(metricKey);
        measureRepository.add(component, metric,
                Measure.newMeasureBuilder().setVariation((double) bag.count(severity)).createNoValue());
    }

    // waiting for Java 8 lambda in order to factor this loop with the previous one
    // (see call currentCounters.counterForPeriod(period.getIndex()).xxx with xxx as severityBag or typeBag)
    for (Map.Entry<RuleType, String> entry : TYPE_TO_NEW_METRIC_KEY.entrySet()) {
        RuleType type = entry.getKey();
        String metricKey = entry.getValue();
        Multiset<RuleType> bag = currentCounters.counterForPeriod().typeBag;
        Metric metric = metricRepository.getByKey(metricKey);
        measureRepository.add(component, metric,
                Measure.newMeasureBuilder().setVariation((double) bag.count(type)).createNoValue());
    }
}

From source file:master.conditions.LeafCountPostSimCondition.java

/**
 * Returns true iff the given inheritance trajectory
 * meet the post-simulation acceptance condition.
 * //from  www . j  ava  2  s.com
 * @param itraj inheritance trajectory
 * @return true if the end condition is met.
 */
@Override
public boolean accept(InheritanceTrajectory itraj) {

    // Assemble leaf counts:
    Multiset<Population> leafCounts = HashMultiset.create();
    for (Node leaf : itraj.getEndNodes())
        leafCounts.add(leaf.getPopulation());

    // Check whether condition is met:
    int size;
    if (populationInput.get().isEmpty())
        size = leafCounts.size();
    else {
        size = 0;
        for (Population pop : populationInput.get())
            size += leafCounts.count(pop);
    }

    if (exact)
        return size == nTerminalNodes;

    if (exceed)
        return size >= nTerminalNodes;
    else
        return size <= nTerminalNodes;
}

From source file:org.mitre.openid.connect.service.impl.DefaultStatsService.java

private Map<Long, Integer> computeByClientId() {
    // get all approved sites
    Collection<ApprovedSite> allSites = approvedSiteService.getAll();

    Multiset<String> clientIds = HashMultiset.create();
    for (ApprovedSite approvedSite : allSites) {
        clientIds.add(approvedSite.getClientId());
    }//from w w w .  ja  v  a 2s  .c om

    Map<Long, Integer> counts = getEmptyClientCountMap();
    for (String clientId : clientIds) {
        ClientDetailsEntity client = clientService.loadClientByClientId(clientId);
        counts.put(client.getId(), clientIds.count(clientId));
    }

    return counts;
}

From source file:org.opennms.features.jmxconfiggenerator.webui.ui.validators.UniqueAttributeNameValidator.java

@Override
protected boolean isValidValue(String value) {
    if (value == null || !(value instanceof String))
        return false; //validation not possible
    String alias = (String) value;
    //count name occurance
    Multiset<String> nameMultiSet = HashMultiset.create();
    for (Entry<Object, String> entry : provider.getNames().entrySet()) {
        Object itemId = entry.getKey();
        String name = entry.getValue();
        //use name from textFieldItemMap if an entry for itemId exists, otherwise use name from provider
        nameMultiSet.add(//from ww  w.j av  a  2s.com
                textFieldItemMap.get(itemId) == null ? name : (String) textFieldItemMap.get(itemId).getValue());
    }
    return nameMultiSet.count(alias) <= 1; //is only valid if name exists 0 or 1 times 
}

From source file:nl.knaw.huygens.facetedsearch.AbstractSolrServer.java

private Map<String, Integer> getTermCountMap(Multiset<String> terms) {
    Map<String, Integer> termCountMap = Maps.newHashMap();
    for (String term : terms.elementSet()) {
        termCountMap.put(term, terms.count(term));
    }/*from  ww  w.j a v a 2  s. c  om*/
    return termCountMap;
}

From source file:it.units.malelab.ege.distributed.master.UIRunnable.java

private void printJobs(TextGraphics g, int x0, int y0, int w, int h) {
    //count jobs/*from   ww  w  . j  av a2s  . c om*/
    int nToDoJobs = 0;
    int nOngoingJobs = 0;
    int nDoneJobs = 0;
    synchronized (master.getJobs()) {
        for (JobInfo jobInfo : master.getJobs().values()) {
            if (jobInfo.getStatus().equals(JobInfo.Status.TO_DO)) {
                nToDoJobs = nToDoJobs + 1;
            } else if (jobInfo.getStatus().equals(JobInfo.Status.ONGOING)) {
                nOngoingJobs = nOngoingJobs + 1;
            } else if (jobInfo.getStatus().equals(JobInfo.Status.DONE)) {
                nDoneJobs = nDoneJobs + 1;
            }
        }
    }
    //print job info
    g.setForegroundColor(TextColor.ANSI.WHITE);
    putString(g, 0, 0, x0, y0, w, h, String.format("All/todo/running/done: %3d/%3d/%3d/%3d",
            master.getJobs().size(), nToDoJobs, nOngoingJobs, nDoneJobs));
    Map<String, Map<Object, Multiset<JobInfo.Status>>> allKeyCounts = new TreeMap<>();
    synchronized (master.getJobs()) {
        for (JobInfo jobInfo : master.getJobs().values()) {
            for (Map.Entry<String, Object> jobKeyEntry : ((Map<String, Object>) jobInfo.getJob().getKeys())
                    .entrySet()) {
                inc(jobKeyEntry.getKey(), jobKeyEntry.getValue(), jobInfo.getStatus(), allKeyCounts);
            }
        }
    }
    int y = 2;
    for (String keyName : allKeyCounts.keySet()) {
        g.setForegroundColor(TextColor.ANSI.WHITE);
        putString(g, 0, y, x0, y0, w, h, keyName + ":");
        y = y + 1;
        int x = 2;
        for (Object keyValue : allKeyCounts.get(keyName).keySet()) {
            Multiset<JobInfo.Status> statuses = allKeyCounts.get(keyName).get(keyValue);
            double completionRate = (double) statuses.count(JobInfo.Status.DONE) / (double) (statuses.size());
            if (x >= w - 1) {
                x = 2;
                y = y + 1;
            }
            if (completionRate == 1) {
                g.setForegroundColor(TextColor.ANSI.GREEN);
            } else if (statuses.count(JobInfo.Status.ONGOING) > 0) {
                g.setForegroundColor(TextColor.ANSI.YELLOW);
            } else {
                g.setForegroundColor(TextColor.ANSI.RED);
            }
            if (completionRate == 0) {
                putString(g, x, y, x0, y0, w, h, "-");
            } else if (completionRate < .25) {
                putString(g, x, y, x0, y0, w, h, "" + Symbols.BLOCK_SPARSE);
            } else if (completionRate < .50) {
                putString(g, x, y, x0, y0, w, h, "" + Symbols.BLOCK_MIDDLE);
            } else if (completionRate < .75) {
                putString(g, x, y, x0, y0, w, h, "" + Symbols.BLOCK_DENSE);
            } else {
                putString(g, x, y, x0, y0, w, h, "" + Symbols.BLOCK_SOLID);
            }
            x = x + 1;
        }
        y = y + 1;
    }
}