List of usage examples for com.google.common.collect Sets intersection
public static <E> SetView<E> intersection(final Set<E> set1, final Set<?> set2)
From source file:edu.cmu.lti.oaqa.baseqa.answer.yesno.scorers.NegationYesNoScorer.java
@Override public Map<String, Double> score(JCas jcas) throws AnalysisEngineProcessException { List<JCas> views = ViewType.listViews(jcas, viewNamePrefix); List<Integer> negationCuesCounts = new ArrayList<>(); Map<String, Double> features = new HashMap<>(); for (JCas view : views) { Set<String> tokens = TypeUtil.getOrderedTokens(view).stream() .flatMap(token -> Stream.of(token.getLemmaForm(), token.getCoveredText().toLowerCase())) .collect(toSet());/*www. ja v a2s. c o m*/ Set<String> containedNegationCues = Sets.intersection(tokens, negationCues); negationCuesCounts.add(containedNegationCues.isEmpty() ? 0 : 1); containedNegationCues.forEach(cue -> features.put("negation-cue@" + cue, 1.0)); } features.putAll(YesNoScorer.aggregateFeatures(negationCuesCounts, "negation-cues")); return features; }
From source file:org.caleydo.view.relationshipexplorer.ui.util.EntityMappingUtil.java
public static List<MappingOverlap> getMappingOverlap(IEntityCollection pathwayCollection, IEntityCollection clusterCollection, IEntityCollection compoundCollection) { Map<Object, Set<Object>> pathwaysToCompounds = new HashMap<>(); for (Object pathway : pathwayCollection.getAllElementIDs()) { pathwaysToCompounds.put(pathway, getAllMappedElementIDs(pathway, pathwayCollection, compoundCollection)); }/*from ww w. jav a 2 s . c om*/ Map<Object, Set<Object>> clustersToCompounds = new HashMap<>(); for (Object cluster : clusterCollection.getAllElementIDs()) { clustersToCompounds.put(cluster, getAllMappedElementIDs(cluster, clusterCollection, compoundCollection)); } List<MappingOverlap> overlaps = new ArrayList<>(pathwaysToCompounds.size() * clustersToCompounds.size()); for (Entry<Object, Set<Object>> pathwayEntry : pathwaysToCompounds.entrySet()) { for (Entry<Object, Set<Object>> clusterEntry : clustersToCompounds.entrySet()) { float overlap = Sets.intersection(pathwayEntry.getValue(), clusterEntry.getValue()).size(); float notInOverlap = clusterEntry.getValue().size() - overlap; float score = (overlap / (overlap + notInOverlap)) / ((pathwayEntry.getValue().size()) / compoundCollection.getAllElementIDs().size()); overlaps.add(new MappingOverlap(pathwayEntry.getKey(), clusterEntry.getKey(), score)); } } return overlaps; }
From source file:com.facebook.buck.jvm.java.AbstractAnnotationProcessingParams.java
@Value.Lazy protected ImmutableList<JavacPluginProperties> getLegacyProcessors() { JavacPluginProperties.Builder legacySafeProcessorsBuilder = JavacPluginProperties.builder() .setCanReuseClassLoader(true).setDoesNotAffectAbi(false).setSupportsAbiGenerationFromSource(false) .setProcessorNames(Sets.intersection(getLegacyAnnotationProcessorNames(), getLegacySafeAnnotationProcessors())); JavacPluginProperties.Builder legacyUnsafeProcessorsBuilder = JavacPluginProperties.builder() .setCanReuseClassLoader(false).setDoesNotAffectAbi(false).setSupportsAbiGenerationFromSource(false) .setProcessorNames(// w ww . ja va2s . c o m Sets.difference(getLegacyAnnotationProcessorNames(), getLegacySafeAnnotationProcessors())); for (BuildRule dep : getLegacyAnnotationProcessorDeps()) { legacySafeProcessorsBuilder.addDep(dep); legacyUnsafeProcessorsBuilder.addDep(dep); } JavacPluginProperties legacySafeProcessors = legacySafeProcessorsBuilder.build(); JavacPluginProperties legacyUnsafeProcessors = legacyUnsafeProcessorsBuilder.build(); ImmutableList.Builder<JavacPluginProperties> resultBuilder = ImmutableList.builder(); if (!legacySafeProcessors.isEmpty()) { resultBuilder.add(legacySafeProcessors); } if (!legacyUnsafeProcessors.isEmpty()) { resultBuilder.add(legacyUnsafeProcessors); } return resultBuilder.build(); }
From source file:co.mitro.core.servlets.GetPublicKeyForIdentity.java
@Override protected MitroRPC processCommand(MitroRequestContext context) throws SQLException, MitroServletException { RPC.GetPublicKeysForIdentityRequest in = gson.fromJson(context.jsonRequest, RPC.GetPublicKeysForIdentityRequest.class); RPC.GetPublicKeyForIdentityResponse out = new RPC.GetPublicKeyForIdentityResponse(); out.userIdToPublicKey = Maps.newTreeMap(); out.missingUsers = Lists.newLinkedList(); Set<String> userIdSet = Sets.newHashSet(in.userIds); for (DBIdentity i : DBIdentity.getUsersFromNames(context.manager, in.userIds)) { Set<String> aliases = DBUserName.getAliasesForIdentity(context.manager, i); Set<String> matchingAliasesForThisUser = Sets.intersection(userIdSet, aliases).immutableCopy(); if (matchingAliasesForThisUser.size() > 1) { throw new UserVisibleException("The following emails are aliases and cannot" + " be included simultaneously: " + Joiner.on(",").join(matchingAliasesForThisUser)); }//from w w w .j av a 2s . c o m for (String email : matchingAliasesForThisUser) { out.userIdToPublicKey.put(email, i.getPublicKeyString()); userIdSet.remove(email); } } if (!userIdSet.isEmpty()) { assert in.addMissingUsers : "addMissingUsers must be true."; if (!context.isGroupSyncRequest() && !isPermittedToGetMissingUsers(context.requestor.getName(), userIdSet.size())) { throw new TooManyAccountsException(Integer.toString(in.userIds.size())); } try { for (String newUser : userIdSet) { DBIdentity identity = InviteNewUser.inviteNewUser(keyFactory, context.manager, context.requestor, newUser); out.userIdToPublicKey.put(newUser, identity.getPublicKeyString()); } } catch (CryptoError | CyclicGroupError e) { throw new MitroServletException(e); } } @SuppressWarnings("deprecation") AuthenticatedDB udb = AuthenticatedDB.deprecatedNew(context.manager, context.requestor); if (null != in.groupIds && !in.groupIds.isEmpty()) { for (Integer gid : in.groupIds) { DBGroup group = udb.getGroupForAddSecret(gid); assert (group != null) : "Invalid permissions"; out.groupIdToPublicKey.put(group.getId(), group.getPublicKeyString()); } } return out; }
From source file:org.icgc.dcc.portal.model.UnionUnit.java
@JsonIgnore public boolean isValid() { /*/* w w w . j a v a2s . c om*/ * simple sanity check - the intersection should NOT have any element in the exclusion set. */ return (exclusions.isEmpty()) ? true : Sets.intersection(intersection, exclusions).isEmpty(); }
From source file:org.janusgraph.graphdb.types.StandardRelationTypeMaker.java
private void checkGeneralArguments() { checkSortKey(sortKey);// w w w. ja va 2 s . c o m Preconditions.checkArgument(sortOrder == Order.ASC || hasSortKey(), "Must define a sort key to use ordering"); checkSignature(signature); Preconditions.checkArgument( Sets.intersection(Sets.newHashSet(sortKey), Sets.newHashSet(signature)).isEmpty(), "Signature and sort key must be disjoined"); Preconditions.checkArgument(!hasSortKey() || !multiplicity.isConstrained(), "Cannot define a sort-key on constrained edge labels"); }
From source file:org.gradle.api.internal.resolve.VariantsMatcher.java
public Collection<? extends BinarySpec> filterBinaries(VariantsMetaData variantsMetaData, Collection<BinarySpec> binaries) { if (binaries.isEmpty()) { return binaries; }/*from ww w . j a v a 2s . c o m*/ Set<String> resolveDimensions = variantsMetaData.getNonNullVariantAxes(); TreeMultimap<String, VariantValue> selectedVariants = TreeMultimap.create(String.CASE_INSENSITIVE_ORDER, SPEC_COMPARATOR); Set<BinarySpec> removedSpecs = Sets.newHashSet(); for (BinarySpec binarySpec : binaries) { if (binarySpecType.isAssignableFrom(binarySpec.getClass())) { VariantsMetaData binaryVariants = DefaultVariantsMetaData.extractFrom(binarySpec, schemaStore); Set<String> commonsDimensions = Sets.intersection(resolveDimensions, binaryVariants.getNonNullVariantAxes()); Set<String> incompatibleDimensionTypes = VariantsMetaDataHelper .determineAxesWithIncompatibleTypes(variantsMetaData, binaryVariants, commonsDimensions); if (incompatibleDimensionTypes.isEmpty()) { for (String dimension : commonsDimensions) { Class<?> dimensionType = variantsMetaData.getVariantAxisType(dimension).getConcreteClass(); boolean isStringType = String.class == dimensionType; Object requestedValue = isStringType ? variantsMetaData.getValueAsString(dimension) : variantsMetaData.getValueAsType( Cast.<Class<? extends Named>>uncheckedCast(dimensionType), dimension); Object binaryValue = isStringType ? binaryVariants.getValueAsString(dimension) : binaryVariants.getValueAsType( Cast.<Class<? extends Named>>uncheckedCast(dimensionType), dimension); VariantAxisCompatibility<Object> selector = createSelector(requestedValue); if (selector.isCompatibleWithRequirement(requestedValue, binaryValue)) { VariantValue value = new VariantValue(binaryValue, binarySpec); SortedSet<VariantValue> variantValues = selectedVariants.get(dimension); for (VariantValue variantValue : variantValues) { // all the values are equal, but we store all the binaries that match that value // and incrementally build a list of binaries which are excluded because of a better match if (selector.betterFit(requestedValue, variantValue.value, binaryValue)) { // the new value is a better fit than the old one removedSpecs.add(variantValue.spec); } else if (selector.betterFit(requestedValue, binaryValue, variantValue.value)) { // the old value is a better fit than the new one, let's ignore the new one altogether removedSpecs.add(value.spec); } } selectedVariants.put(dimension, value); } else { removedSpecs.add(binarySpec); } } } } } Set<BinarySpec> union = null; for (String dimension : selectedVariants.keySet()) { Set<BinarySpec> variantValues = ImmutableSet .copyOf(Iterables.transform(selectedVariants.get(dimension), VariantValue.SPEC_FUNCTION)); union = union == null ? variantValues : Sets.union(union, variantValues); } return union == null ? Collections.<BinarySpec>emptySet() : Sets.difference(union, removedSpecs); }
From source file:org.dishevelled.venn.model.BinaryVennModelImpl.java
/** * Create a new binary venn model with the specified sets. * * @param first first set, must not be null * @param second second set, must not be null *//*from w w w . j a va 2 s . co m*/ public BinaryVennModelImpl(final Set<? extends E> first, final Set<? extends E> second) { if (first == null) { throw new IllegalArgumentException("first must not be null"); } if (second == null) { throw new IllegalArgumentException("second must not be null"); } // todo defensive copy? this.first = new ObservableSetImpl(first); this.second = new ObservableSetImpl(second); firstOnly = Sets.difference(this.first, this.second); secondOnly = Sets.difference(this.second, this.first); intersection = Sets.intersection(this.first, this.second); union = Sets.union(this.first, this.second); selection = new SelectionView<E>(union, this.first, this.second); exclusives = new HashMap<ImmutableBitSet, Set<E>>(3); exclusives.put(toImmutableBitSet(0), firstOnly); exclusives.put(toImmutableBitSet(1), secondOnly); exclusives.put(toImmutableBitSet(0, 1), intersection); // copy to immutable map? }
From source file:org.obm.push.backend.CollectionChangeListener.java
@Override public boolean monitorOneOf(ChangedCollections changedCollections) { SortedSet<String> collectionPathSet = convertSetToComparePath(changedCollections); return !Sets.intersection(Sets.newHashSet( Iterables.transform(getMonitoredCollections(), new Function<AnalysedSyncCollection, String>() { @Override//from ww w. j a va 2 s . c o m public String apply(AnalysedSyncCollection input) { return input.getCollectionPath(); } })), collectionPathSet).isEmpty(); }
From source file:edu.cmu.lti.oaqa.bioasq.eval.calculator.AnswerEvalCalculator.java
@Override public Map<Measure, Double> calculate(JCas jcas, Collection<T> resultEvaluatees, Collection<T> gsEvaluatees, Comparator<T> comparator, Function<T, String> uniqueIdMapper) { Set<String> gsVariants = gsEvaluatees.stream().map(TypeUtil::getCandidateAnswerVariantNames) .flatMap(Collection::stream).map(String::toLowerCase).collect(toSet()); List<Answer> resultAnswers = resultEvaluatees.stream().sorted(comparator).collect(toList()); String questionType = TypeUtil.getQuestion(jcas).getQuestionType(); ImmutableMap.Builder<Measure, Double> builder = ImmutableMap.builder(); switch (questionType) { case "FACTOID": Set<String> strictResultVariants = resultAnswers.stream().limit(1) .map(TypeUtil::getCandidateAnswerVariantNames).flatMap(Collection::stream) .map(String::toLowerCase).collect(toSet()); Set<String> lenientResultVariants = resultAnswers.stream().limit(5) .map(TypeUtil::getCandidateAnswerVariantNames).flatMap(Collection::stream) .map(String::toLowerCase).collect(toSet()); int strictRetrieved = Sets.intersection(gsVariants, strictResultVariants).isEmpty() ? 0 : 1; builder.put(FACTOID_STRICT_RETRIEVED, (double) strictRetrieved); int lenientRetrieved = Sets.intersection(gsVariants, lenientResultVariants).isEmpty() ? 0 : 1; builder.put(FACTOID_LENIENT_RETRIEVED, (double) lenientRetrieved); double reciprocalRank = IntStream.range(0, resultAnswers.size()) .filter(i -> TypeUtil.getCandidateAnswerVariantNames(resultAnswers.get(i)).stream() .map(String::toLowerCase).anyMatch(gsVariants::contains)) .mapToDouble(i -> 1.0 / (i + 1.0)).findFirst().orElse(0.0); builder.put(FACTOID_RECIPROCAL_RANK, reciprocalRank); builder.put(FACTOID_COUNT, 1.0); break;/* w w w . j a va2 s . c om*/ case "LIST": int relevantRetrieved = (int) resultAnswers.stream().map(TypeUtil::getCandidateAnswerVariantNames) .filter(names -> names.stream().map(String::toLowerCase).anyMatch(gsVariants::contains)) .count(); double precision = EvalCalculatorUtil.calculatePrecision(resultAnswers.size(), relevantRetrieved); builder.put(LIST_PRECISION, precision); double recall = EvalCalculatorUtil.calculateRecall(gsVariants.size(), relevantRetrieved); builder.put(LIST_RECALL, recall); builder.put(LIST_F1, EvalCalculatorUtil.calculateF1(precision, recall)); builder.put(LIST_COUNT, 1.0); break; case "YES_NO": String gs = Iterables.getOnlyElement(gsVariants); String result = resultAnswers.stream().map(Answer::getText).findAny().orElse(""); int correctRetrieved = gs.equals(result) ? 1 : 0; builder.put(YESNO_CORRECT, (double) correctRetrieved); if (gs.equals("yes")) { int truePositive = result.equals("yes") ? 1 : 0; builder.put(YESNO_TRUE_POS, (double) truePositive); } else { int trueNegative = result.equals("no") ? 1 : 0; builder.put(YESNO_TRUE_NEG, (double) trueNegative); } break; } return builder.build(); }