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:compile.type.TypeVar.java

/**
 * build a param map for this singleton type var.
 *
 * Note: per the "types don't come from nowhere" rule, there should
 * be no legitimate cases where a param map is built for a lone type variable.
 *//*from w w  w  .  j a v a2 s .  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;

        // broken
        //            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;

    /*
    if (vars.contains(this))
    {
    Session.error(loc, "building param map for lone type var {0}", dump());
            
    final TypeParam param = hasSourceParam() ?
        getSourceParam() : new TypeParam(loc, name, kind, constraint);
            
    final SubstMap subst = SubstMap.bindVar(loc, this, param, env);
            
    if (subst == null)
    {
        Session.error(loc, "internal error: failed to bind var {0} to param {1}",
            dump(), param.dump());
            
        return SubstMap.EMPTY;
    }
            
    return subst;
    }
            
    // normal case
    return SubstMap.EMPTY;
    */
}

From source file:grakn.core.graql.reasoner.query.CompositeQuery.java

private Set<Variable> bindingVariables() {
    return Sets.intersection(getConjunctiveQuery().getVarNames(),
            getComplementQueries().stream().flatMap(q -> q.getVarNames().stream()).collect(Collectors.toSet()));
}

From source file:org.apache.cassandra.cql.CreateColumnFamilyStatement.java

/** Perform validation of parsed params */
private void validate() throws InvalidRequestException {
    // Column family name
    if (!name.matches("\\w+"))
        throw new InvalidRequestException(String.format("\"%s\" is not a valid column family name", name));

    // Catch the case where someone passed a kwarg that is not recognized.
    for (String bogus : Sets.difference(properties.keySet(), Sets.union(keywords, obsoleteKeywords)))
        throw new InvalidRequestException(bogus + " is not a valid keyword argument for CREATE COLUMNFAMILY");
    for (String obsolete : Sets.intersection(properties.keySet(), obsoleteKeywords))
        logger.warn("Ignoring obsolete property {}", obsolete);

    // Validate min/max compaction thresholds
    Integer minCompaction = getPropertyInt(KW_MINCOMPACTIONTHRESHOLD, null);
    Integer maxCompaction = getPropertyInt(KW_MAXCOMPACTIONTHRESHOLD, null);

    if ((minCompaction != null) && (maxCompaction != null)) // Both min and max are set
    {//from ww  w  .j a v a 2  s . co  m
        if ((minCompaction > maxCompaction) && (maxCompaction != 0))
            throw new InvalidRequestException(String.format("%s cannot be larger than %s",
                    KW_MINCOMPACTIONTHRESHOLD, KW_MAXCOMPACTIONTHRESHOLD));
    } else if (minCompaction != null) // Only the min threshold is set
    {
        if (minCompaction > CFMetaData.DEFAULT_MAX_COMPACTION_THRESHOLD)
            throw new InvalidRequestException(
                    String.format("%s cannot be larger than %s, (default %s)", KW_MINCOMPACTIONTHRESHOLD,
                            KW_MAXCOMPACTIONTHRESHOLD, CFMetaData.DEFAULT_MAX_COMPACTION_THRESHOLD));
    } else if (maxCompaction != null) // Only the max threshold is set
    {
        if ((maxCompaction < CFMetaData.DEFAULT_MIN_COMPACTION_THRESHOLD) && (maxCompaction != 0))
            throw new InvalidRequestException(
                    String.format("%s cannot be smaller than %s, (default %s)", KW_MAXCOMPACTIONTHRESHOLD,
                            KW_MINCOMPACTIONTHRESHOLD, CFMetaData.DEFAULT_MIN_COMPACTION_THRESHOLD));
    }

    // Ensure that exactly one key has been specified.
    if (keyValidator.size() < 1)
        throw new InvalidRequestException("You must specify a PRIMARY KEY");
    else if (keyValidator.size() > 1)
        throw new InvalidRequestException("You may only specify one PRIMARY KEY");

    AbstractType<?> comparator;

    try {
        comparator = getComparator();
    } catch (ConfigurationException e) {
        throw new InvalidRequestException(e.toString());
    }

    for (Map.Entry<Term, String> column : columns.entrySet()) {
        ByteBuffer name = column.getKey().getByteBuffer(comparator);

        if (keyAlias != null && keyAlias.equals(name))
            throw new InvalidRequestException("Invalid column name: " + column.getKey().getText()
                    + ", because it equals to the key_alias.");

    }
}

From source file:com.opengamma.strata.engine.config.pricing.PricingRule.java

/**
 * Returns the set of measures configured for a calculation target.
 * //from  www  .j  a  v a 2  s.  c  o m
 * @param target  a target
 * @return the set of measures configured by this rule
 */
public ImmutableSet<Measure> configuredMeasures(CalculationTarget target) {
    if (!targetType.isInstance(target)) {
        return ImmutableSet.of();
    }
    Set<Measure> measuresConfigured = functionGroup.configuredMeasures(target);
    if (!measures.isEmpty()) {
        measuresConfigured = Sets.intersection(measures, functionGroup.configuredMeasures(target));
    }
    return ImmutableSet.copyOf(measuresConfigured);
}

From source file:com.android.tools.lint.checks.OverrideDetector.java

@Override
public void afterCheckProject(@NonNull Context context) {
    // Process the check in two passes:
    ///*from   ww  w  .  j  a v  a 2  s .  c  om*/
    // In the first pass, gather the full set of package private methods for
    // each class.
    // When all classes have been processed at the end of the first pass,
    // find out whether any of the methods are potentially overriding those
    // in its super classes.
    //
    // If so, request a second pass. In the second pass, we gather full locations
    // for both the base and overridden method calls, and store these.
    // If the location is found to be in a suppressed context, remove that error
    // entry.
    //
    // At the end of the second pass, we generate the errors, combining locations
    // from both the overridden and overriding methods.
    if (context.getPhase() == 1) {
        Set<String> classes = mPackagePrivateMethods.keySet();
        LintDriver driver = context.getDriver();
        for (String owner : classes) {
            Set<String> methods = mPackagePrivateMethods.get(owner);
            String superClass = driver.getSuperClass(owner);
            int packageIndex = owner.lastIndexOf('/');
            while (superClass != null) {
                int superPackageIndex = superClass.lastIndexOf('/');

                // Only compare methods that differ in packages
                if (packageIndex == -1 || superPackageIndex != packageIndex
                        || !owner.regionMatches(0, superClass, 0, packageIndex)) {
                    Set<String> superMethods = mPackagePrivateMethods.get(superClass);
                    if (superMethods != null) {
                        SetView<String> intersection = Sets.intersection(methods, superMethods);
                        if (!intersection.isEmpty()) {
                            if (mLocations == null) {
                                mLocations = Maps.newHashMap();
                            }
                            // We need a separate data structure to keep track of which
                            // signatures are in error,
                            if (mErrors == null) {
                                mErrors = Maps.newHashMap();
                            }

                            for (String signature : intersection) {
                                Map<String, Location> locations = mLocations.get(owner);
                                if (locations == null) {
                                    locations = Maps.newHashMap();
                                    mLocations.put(owner, locations);
                                }
                                locations.put(signature, null);

                                locations = mLocations.get(superClass);
                                if (locations == null) {
                                    locations = Maps.newHashMap();
                                    mLocations.put(superClass, locations);
                                }
                                locations.put(signature, null);

                                Map<String, String> errors = mErrors.get(owner);
                                if (errors == null) {
                                    errors = Maps.newHashMap();
                                    mErrors.put(owner, errors);
                                }
                                errors.put(signature, superClass);
                            }
                        }
                    }
                }
                superClass = driver.getSuperClass(superClass);
            }
        }

        if (mErrors != null) {
            context.requestRepeat(this, ISSUE.getImplementation().getScope());
        }
    } else {
        assert context.getPhase() == 2;

        for (Entry<String, Map<String, String>> ownerEntry : mErrors.entrySet()) {
            String owner = ownerEntry.getKey();
            Map<String, String> methodToSuper = ownerEntry.getValue();
            for (Entry<String, String> entry : methodToSuper.entrySet()) {
                String signature = entry.getKey();
                String superClass = entry.getValue();

                Map<String, Location> ownerLocations = mLocations.get(owner);
                if (ownerLocations != null) {
                    Location location = ownerLocations.get(signature);
                    if (location != null) {
                        Map<String, Location> superLocations = mLocations.get(superClass);
                        if (superLocations != null) {
                            Location superLocation = superLocations.get(signature);
                            if (superLocation != null) {
                                location.setSecondary(superLocation);
                                superLocation.setMessage("This method is treated as overridden");
                            }
                        }
                        String methodName = signature;
                        int index = methodName.indexOf('(');
                        if (index != -1) {
                            methodName = methodName.substring(0, index);
                        }
                        String message = String.format(
                                "This package private method may be unintentionally "
                                        + "overriding `%1$s` in `%2$s`",
                                methodName, ClassContext.getFqcn(superClass));
                        context.report(ISSUE, location, message);
                    }
                }
            }
        }
    }
}

From source file:fr.inria.maestro.lga.clustering.analysis.impl.PrecisionQuantity.java

public Pair<Double, Double> getPrecisionRecallWithIntersection(
        final ClusteringPreprocessor analysisClustering) {
    final Set<String> expertClusterNames = Sets.newHashSet();
    final Set<String> expertClusterEntries = Sets.newHashSet();

    for (final ICluster cluster : expertFormingClustering.getClustering().getClusters()) {
        expertClusterNames.add(cluster.getName());

        for (final String clusterEntryName : cluster.getEntriesNames()) {
            if (!analysisClustering.getClustersByEntryName(clusterEntryName).isEmpty()) {
                expertClusterEntries.add(clusterEntryName);
            }/*from  w w  w  .j av a2  s  . c om*/
        }

        final ICluster judgementCluster = analysisClustering.getClusterByName(cluster.getName());
        if (judgementCluster == null) {
            throw new IllegalArgumentException("can't find analog for cluster: " + cluster.getName());
        }
    }

    int tp = 0;
    int fp = 0;
    int fn = 0;

    for (final ICluster cluster : expertFormingClustering.getClustering().getClusters()) {
        final Set<String> expertDocuments = Sets.intersection(cluster.getEntriesNames(), expertClusterEntries);

        final ICluster analysisCluster = CollectionUtils
                .forceNotNull(analysisClustering.getClusterByName(cluster.getName()));
        final Set<String> analysisDocuments = Sets.intersection(analysisCluster.getEntriesNames(),
                expertClusterEntries);

        tp += Sets.intersection(analysisDocuments, expertDocuments).size();
        fp += Sets.difference(analysisDocuments, expertDocuments).size();
        fn += Sets.difference(expertDocuments, analysisDocuments).size();
    }

    return Pair.create(tp / (1. * (tp + fp)), tp / (1. * (tp + fn)));
}

From source file:grakn.core.graql.reasoner.atom.Atom.java

/**
 * @return true if this atom is disconnected (doesn't have neighbours)
 *///from w w  w.  java 2  s.co m
public boolean isDisconnected() {
    return isSelectable()
            && getParentQuery().getAtoms(Atom.class).filter(Atomic::isSelectable).filter(at -> !at.equals(this))
                    .allMatch(at -> Sets.intersection(at.getVarNames(), this.getVarNames()).isEmpty());
}

From source file:grakn.core.graql.reasoner.rule.InferenceRule.java

/**
 * @return true if head satisfies the pattern specified in the body of the rule
 *//*from w  ww.  j a va  2 s .co  m*/
boolean headSatisfiesBody() {
    Set<Atomic> atoms = new HashSet<>(getHead().getAtoms());
    Set<Variable> headVars = getHead().getVarNames();
    getBody().getAtoms(TypeAtom.class).filter(t -> !t.isRelation())
            .filter(t -> !Sets.intersection(t.getVarNames(), headVars).isEmpty()).forEach(atoms::add);
    return getBody().isEquivalent(ReasonerQueries.create(atoms, tx));
}

From source file:ai.grakn.graql.internal.hal.HALUtils.java

private static boolean bothRolePlayersAreSelected(Atom atom, MatchQuery matchQuery) {
    Relation reasonerRel = ((Relation) atom);
    Set<Var> rolePlayersInAtom = reasonerRel.getRolePlayers().stream().collect(Collectors.toSet());
    Set<Var> selectedVars = matchQuery.admin().getSelectedNames();
    //If all the role players contained in the current relation are also selected in the user query
    return Sets.intersection(rolePlayersInAtom, selectedVars).equals(rolePlayersInAtom);
}

From source file:ubic.gemma.core.expression.experiment.service.ExpressionExperimentSearchServiceImpl.java

@Override
public Collection<ExpressionExperimentValueObject> searchExpressionExperiments(List<String> query) {

    Set<ExpressionExperimentValueObject> all = new HashSet<>();
    Set<ExpressionExperimentValueObject> prev = null;
    Set<ExpressionExperimentValueObject> current;
    for (String s : query) {
        s = StringUtils.strip(s);/*ww w  .ja  va 2 s.c o m*/
        if (prev == null) {
            prev = new HashSet<>(this.searchExpressionExperiments(s));
            all = new HashSet<>(prev);
            continue;
        }
        current = new HashSet<>(this.searchExpressionExperiments(s));

        all = Sets.intersection(all, current);
    }
    return all;
}