Example usage for com.google.common.collect Sets intersection

List of usage examples for com.google.common.collect Sets intersection

Introduction

In this page you can find the example usage for com.google.common.collect Sets intersection.

Prototype

public static <E> SetView<E> intersection(final Set<E> set1, final Set<?> set2) 

Source Link

Document

Returns an unmodifiable view of the intersection of two sets.

Usage

From source file:com.facebook.buck.command.config.AbstractConfigIgnoredByDaemon.java

@Value.Lazy
public ImmutableMap<String, ImmutableMap<String, String>> getRawConfigForParser() {
    ImmutableMap<String, ImmutableSet<String>> ignoredFields = getIgnoreFieldsForDaemonRestart();
    ImmutableMap<String, ImmutableMap<String, String>> rawSections = getDelegate().getConfig()
            .getSectionToEntries();/*from   w  w w. java  2  s  . co m*/

    // If the raw config doesn't have sections which have ignored fields, then just return it as-is.
    ImmutableSet<String> sectionsWithIgnoredFields = ignoredFields.keySet();
    if (Sets.intersection(rawSections.keySet(), sectionsWithIgnoredFields).isEmpty()) {
        return rawSections;
    }

    // Otherwise, iterate through the config to do finer-grain filtering.
    ImmutableMap.Builder<String, ImmutableMap<String, String>> filtered = ImmutableMap.builder();
    for (Map.Entry<String, ImmutableMap<String, String>> sectionEnt : rawSections.entrySet()) {
        String sectionName = sectionEnt.getKey();

        // If this section doesn't have a corresponding ignored section, then just add it as-is.
        if (!sectionsWithIgnoredFields.contains(sectionName)) {
            filtered.put(sectionEnt);
            continue;
        }

        // If none of this section's entries are ignored, then add it as-is.
        ImmutableMap<String, String> fields = sectionEnt.getValue();
        ImmutableSet<String> ignoredFieldNames = ignoredFields.getOrDefault(sectionName, ImmutableSet.of());
        if (Sets.intersection(fields.keySet(), ignoredFieldNames).isEmpty()) {
            filtered.put(sectionEnt);
            continue;
        }

        // Otherwise, filter out the ignored fields.
        ImmutableMap<String, String> remainingKeys = ImmutableMap
                .copyOf(Maps.filterKeys(fields, Predicates.not(ignoredFieldNames::contains)));
        filtered.put(sectionName, remainingKeys);
    }

    return MoreMaps.filterValues(filtered.build(), Predicates.not(Map::isEmpty));
}

From source file:org.usergrid.persistence.query.ir.result.IntersectionIterator.java

private Set<UUID> merge(Set<UUID> current, ResultIterator child) {

    Set<UUID> results = new LinkedHashSet<UUID>(pageSize);

    while (results.size() < pageSize) {
        if (!child.hasNext()) {
            // we've iterated to the end, reset for next pass
            child.reset();// w w  w .  j  a va 2 s .c o  m
            return results;
        }

        results.addAll(Sets.intersection(current, child.next()));
    }

    return results;

}

From source file:org.dllearner.experiments.Examples.java

/**
 * calculates recall based on the test set
 * //from  w  ww.  j  av  a2 s . c  om
 * 
 * @param retrieved
 * @return
 */
public double recall(SortedSet<String> retrieved) {
    if (sizeTotalOfPositives() == 0) {
        return 0.0d;
    }
    int posAsPos = Sets.intersection(getPosTest(), retrieved).size();
    return ((double) posAsPos) / ((double) posTest.size());
}

From source file:org.elasticlib.console.display.TreePrinter.java

private void addCurrentParents() {
    Set<Hash> parents = current.getParents();
    Set<Hash> known = Sets.intersection(parents, new HashSet<>(nextBranches));
    Set<Hash> unknown = Sets.difference(parents, known);
    nextBranches.addAll(known);/*from   w  w w  . j a  va2s .c  o  m*/
    nextBranches.addAll(unknown);
}

From source file:dynamicrefactoring.interfaz.wizard.classificationscombo.ClassificationsCheckBoxTreeListener.java

/**
 * Oscurece el padre si alguno de sus hijos esta marcado. Es decir
 * oscurece la clasificacion si alguna de sus categorias esta marcada.
 * // w  w w.  java  2  s .c o  m
 * @param classification
 *            elemento padre
 * @param viewer visor
 */

protected static void grayParentIfNeeded(Classification classification, CheckboxTreeViewer viewer) {
    // Si alguno de los hijos de la clasificacion tiene algun hijo marcado
    if (!Sets.intersection(classification.getCategories(),
            Sets.newHashSet(Arrays.asList(viewer.getCheckedElements()))).isEmpty()) {
        // El padre se oscurecera
        viewer.setGrayChecked(classification, true);
    } else {
        viewer.setGrayChecked(classification, false);
    }
}

From source file:compile.type.ScopeType.java

/**
 * Note: nameGenOffset is part of our scheme for avoiding (the appearance of)
 * name capture in dumps and error messages. We quantify inner-to-outer,
 * so the type checker passes in the number of ambient vars as a starting
 * offset to the name generator. That way outermost names are A, B, C, ...
 * Spacing is not perfect, there are gaps. It would give a prettier result to
 * do a consolidation pass at the end, but the important thing for round-
 * tripping (not that we do it currently) is that there is no overlap.
 *
 * NOTE: the relationship between a var's constraint and that of its
 * corresponding param is tricky--see comment in code body, and also
 * {@link TypeVarSubstitutor#visit(TypeVar)}.
 *//*w  ww  .  j  a  v a2s.  c o  m*/
public SubstMap buildParamMap(final Set<TypeVar> vars, final int nameGenOffset, final TypeEnv env) {
    final Set<TypeVar> qvars = Sets.intersection(vars, getVars());

    if (qvars.isEmpty())
        return SubstMap.EMPTY;

    // when generating param names, avoid names of used params.
    final Set<String> usedNames = new HashSet<String>();

    for (final TypeParam param : TypeParamCollector.collect(this))
        usedNames.add(param.getName());

    // begin generating names from this offset into the generated name space.
    int genIndex = nameGenOffset;

    final SubstMap substMap = new SubstMap();

    for (final TypeVar v : qvars) {
        final String name;

        final TypeParam param = v.getBackingParam(usedNames, this);
        if (param != null) {
            name = param.getName();
        } else {
            String tmp;
            do {
                tmp = nameGen(genIndex++);
            } while (usedNames.contains(tmp));

            name = tmp;
        }

        usedNames.add(name);

        // NOTE: v's constraint is ignored here, because it needs to be
        // not just transferred to the corresponding param, but also run
        // through this same substitution map at quantification time.
        // Users of this map are responsible for doing this.
        //
        substMap.put(v, new TypeParam(v.getLoc(), name, v.getKind(), null));
    }

    return substMap;
}

From source file:com.yahoo.bard.webservice.table.availability.MetricUnionAvailability.java

/**
 * Constructor./*from   w w  w .  j  a  v  a 2 s .c o m*/
 *
 * @param physicalTables  A set of <tt>PhysicalTable</tt>s whose dimension schemas are (typically) the same and
 *  Metric columns are unique(i.e. no overlap) on every table
 * @param columns  The set of all configured columns, including dimension columns, that metric union availability
 * will respond with
 */
public MetricUnionAvailability(@NotNull Set<PhysicalTable> physicalTables, @NotNull Set<Column> columns) {
    super(physicalTables.stream().map(PhysicalTable::getAvailability));

    metricNames = Utils.getSubsetByType(columns, MetricColumn.class).stream().map(MetricColumn::getName)
            .collect(Collectors.toSet());

    // Construct a map of availability to its assigned metric
    // by intersecting its underlying datasource metrics with table configured metrics
    availabilitiesToMetricNames = physicalTables.stream().map(PhysicalTable::getAvailability)
            .collect(Collectors.toMap(Function.identity(), availability -> Sets
                    .intersection(availability.getAllAvailableIntervals().keySet(), metricNames)));

    // validate metric uniqueness such that
    // each table's underlying datasource schema don't have repeated metric column
    if (!isMetricUnique(availabilitiesToMetricNames)) {
        String message = String.format(
                "Metric columns must be unique across the metric union data sources, but duplicate was found "
                        + "across the following data sources: %s",
                getDataSourceNames().stream().map(TableName::asName).collect(Collectors.joining(", ")));
        LOG.error(message);
        throw new RuntimeException(message);
    }
}

From source file:org.apache.cassandra.db.compaction.DateTieredCompactionStrategy.java

/**
 *
 * @param gcBefore//  www. j  av a2  s . co  m
 * @return
 */
private List<SSTableReader> getNextBackgroundSSTables(final int gcBefore) {
    if (cfs.getSSTables().isEmpty())
        return Collections.emptyList();

    Set<SSTableReader> uncompacting = Sets.intersection(sstables, cfs.getUncompactingSSTables());

    Set<SSTableReader> expired = Collections.emptySet();
    // we only check for expired sstables every 10 minutes (by default) due to it being an expensive operation
    if (System.currentTimeMillis() - lastExpiredCheck > options.expiredSSTableCheckFrequency) {
        // Find fully expired SSTables. Those will be included no matter what.
        expired = CompactionController.getFullyExpiredSSTables(cfs, uncompacting,
                cfs.getOverlappingSSTables(uncompacting), gcBefore);
        lastExpiredCheck = System.currentTimeMillis();
    }
    Set<SSTableReader> candidates = Sets.newHashSet(filterSuspectSSTables(uncompacting));

    List<SSTableReader> compactionCandidates = new ArrayList<>(
            getNextNonExpiredSSTables(Sets.difference(candidates, expired), gcBefore));
    if (!expired.isEmpty()) {
        logger.trace("Including expired sstables: {}", expired);
        compactionCandidates.addAll(expired);
    }
    return compactionCandidates;
}

From source file:org.apache.james.transport.mailets.jsieve.VacationAction.java

private boolean isValidForReply(final Mail mail, ActionVacation actionVacation, final ActionContext context) {
    Set<MailAddress> currentMailAddresses = ImmutableSet.copyOf(mail.getRecipients());
    Set<MailAddress> allowedMailAddresses = ImmutableSet.<MailAddress>builder()
            .addAll(Lists.transform(actionVacation.getAddresses(), new Function<String, MailAddress>() {
                public MailAddress apply(String s) {
                    return retrieveAddressFromString(s, context);
                }//from   ww w  .  j  a  v  a  2  s.c  o m
            })).add(context.getRecipient()).build();
    return !Sets.intersection(currentMailAddresses, allowedMailAddresses).isEmpty();
}

From source file:org.caleydo.view.histogram.v2.PieDistributionElement.java

@Override
protected void render(GLGraphics g, float w, float h) {
    final float r = Math.min(w, h) * 0.5f - HistogramRenderStyle.SIDE_SPACING_DETAIL_LOW;
    g.save();/*from  w  w  w . j av a 2s  .  com*/
    g.gl.glTranslatef(w * 0.5f, h * 0.5f, g.z());

    GLU glu = g.glu();
    GLUquadric quad = glu.gluNewQuadric();
    float s = 0;
    boolean idBased = data.hasIds();
    List<DistributionEntry> entries = data.getEntries();
    if (idBased)
        s = data.size();
    else {
        for (DistributionEntry entry : entries)
            s += entry.getValue();
    }
    double factor = 360. / s;
    double acc = 180.f;
    final int bins = entries.size();
    for (int i = 0; i < bins; ++i) {
        DistributionEntry bucket = entries.get(i);
        double sweep = factor * (idBased ? bucket.getIDs().size() : bucket.getValue());
        g.color(toHighlight(bucket.getColor(), i));
        g.pushName(bucketPickingIds.get(i));
        if (sweep > 0)
            glu.gluPartialDisk(quad, 0, r, toSlices(sweep), 2, acc, -sweep);
        g.popName();
        acc -= sweep;
    }

    if (!g.isPickingPass()) {
        glu.gluQuadricDrawStyle(quad, GLU.GLU_SILHOUETTE);
        if (RenderStyle.COLOR_BORDER != null) {
            g.color(RenderStyle.COLOR_BORDER);
            acc = 180;
            for (int i = 0; i < bins; ++i) {
                DistributionEntry bucket = entries.get(i);
                double sweep = factor * (idBased ? bucket.getIDs().size() : bucket.getValue());
                if (sweep > 0)
                    glu.gluPartialDisk(quad, 0, r, toSlices(sweep), 2, acc, -sweep);
                acc -= sweep;
            }
        }
        glu.gluQuadricDrawStyle(quad, GLU.GLU_FILL);
        for (SelectionType selectionType : SELECTIONTYPES) {
            Set<Integer> elements = data.getElements(selectionType);
            if (elements.isEmpty())
                continue;
            g.color(toHighlightColor(selectionType));
            acc = 180;
            for (int i = 0; i < bins; ++i) {
                DistributionEntry bucket = entries.get(i);
                final Set<Integer> ids = bucket.getIDs();
                float p = ids.isEmpty() ? 0 : Sets.intersection(elements, ids).size() / ids.size();
                double sweep = factor * p * (idBased ? ids.size() : bucket.getValue());
                if (sweep > 0)
                    glu.gluPartialDisk(quad, 0, r, toSlices(sweep), 2, acc, -sweep);
                sweep = factor * (idBased ? ids.size() : bucket.getValue());
                acc -= sweep;
            }
        }
    }
    glu.gluDeleteQuadric(quad);

    g.restore();
}