Example usage for java.util Set retainAll

List of usage examples for java.util Set retainAll

Introduction

In this page you can find the example usage for java.util Set retainAll.

Prototype

boolean retainAll(Collection<?> c);

Source Link

Document

Retains only the elements in this set that are contained in the specified collection (optional operation).

Usage

From source file:grails.plugin.searchable.internal.util.GrailsDomainClassUtils.java

/**
 * Get the subclasses for the given GrailsDomainClass, filtering out any not in the given collection
 * @param grailsDomainClass the GrailsDomainClass to find subclasses for
 * @param grailsDomainClasses the collection of valid sub-classes
 * @return the collection of subclasses, if any
 *///ww  w.  ja va2 s  . c  o m
public static Collection getSubClasses(GrailsDomainClass grailsDomainClass, Collection grailsDomainClasses) {
    Set subClasses = new HashSet(grailsDomainClass.getSubClasses());
    subClasses.retainAll(grailsDomainClasses);
    return subClasses;
}

From source file:com.adaptris.core.marshaller.xstream.XStreamUtils.java

/**
 * Determine if the given Set <code>toCheck</code> contains any of the elements within <code>possibles</code>
 * /*from  w  w  w.  j  a va2  s  .  c om*/
 * @param toCheck - Set of Strings to check
 * @param possibles - Collection of
 * @return true if the set contains the possibles.
 */
public static boolean setContainsAnyOf(Set<String> toCheck, Collection<String> possibles) {
    Set<String> copy = new HashSet<String>(toCheck);
    copy.retainAll(possibles);
    return copy.size() > 0;
}

From source file:ubic.pubmedgate.interactions.evaluation.CreateSpreadSheetForRecall.java

public static void sentencesWithNoPredictions() throws Exception {

    String baseFolder = Config.config.getString("whitetext.iteractions.ppiBaseFolder")
            + "Saved Results/SL/CC/NegFixFullOnUnseen/";
    String corpusFilename = Config.config.getString("whitetext.iteractions.ppiBaseFolder")
            + "Corpora/Original-Modified/WhiteTextUnseen.orig.xml";
    String trainingSet = "WhiteTextNegFixFull";
    String testSet = "WhiteTextUnseen";
    String annotationSet = "Mallet";

    SLOutputReader SLReader = new SLOutputReader(trainingSet, testSet, baseFolder);
    log.info("Score size:" + SLReader.getScores().size());

    GateInterface p2g = new GateInterface();
    p2g.setUnSeenCorpNull();/* w w w.  ja  va 2s . c  o  m*/
    p2g.setNamedCorpNull("PubMedUnseenJNChem");
    // p2g.setNamedCorpNull("PubMedUnseenJCN");
    p2g.setNamedCorpNull("PubMedUnseenMScan1");
    p2g.setNamedCorpNull("PubMedUnseenMScan2");
    AirolaXMLReader XMLReader = new AirolaXMLReader(corpusFilename, p2g, annotationSet);

    Set<String> sentences = XMLReader.getAllSentences();
    log.info("All sentences:" + sentences.size());
    List<String> posPredictedPairs = SLReader.getPositivePredictions();
    StringToStringSetMap sentenceIDToPairs = XMLReader.getSentenceIDToPairs();
    int sentencesWithPosPrecitions = 0;
    int sentencesWithOnlyNegPrecitions = 0;
    int pairsFromSenPosPrecitions = 0;
    int pairsFromSenOnlyNegPrecitions = 0;
    Set<String> pairsToUse = new HashSet<String>();
    log.info("All pairs:" + SLReader.getAll().size());

    for (String sentence : sentences) {
        Set<String> pairs = new HashSet<String>(sentenceIDToPairs.get(sentence));
        int pairCount = pairs.size();
        pairs.retainAll(posPredictedPairs);
        if (pairs.size() > 0) {
            sentencesWithPosPrecitions++;
            pairsFromSenPosPrecitions += pairCount;
        } else {
            sentencesWithOnlyNegPrecitions++;
            pairsFromSenOnlyNegPrecitions += pairCount;
            double d = Math.random();
            // this number is based on the ratio of sentencesWithPosPrecitions/sentencesWithOnlyNegPrecitions
            if (d < (0.195d / 2)) {
                pairsToUse.addAll(sentenceIDToPairs.get(sentence));
            }
        }

    }
    log.info("sentencesWithOnlyNegPrecitions:" + sentencesWithOnlyNegPrecitions);
    log.info("pairsFromSenOnlyNegPrecitions:" + pairsFromSenOnlyNegPrecitions);
    log.info("");
    log.info("sentencesWithPosPrecitions:" + sentencesWithPosPrecitions);
    log.info("pairsFromSenPosPrecitions:" + pairsFromSenPosPrecitions);
    log.info("pairsToUse:" + pairsToUse.size());

    //        System.exit(1);

    String filename = Config.config.getString("whitetext.iteractions.results.folder")
            + "EvalForRecall.negatives.xls";
    CreateInteractionSpreadsheet test = new CreateInteractionSpreadsheet(filename, SLReader, XMLReader);
    test.populate(new LinkedList<String>(pairsToUse));
    test.save();

}

From source file:com.github.fge.jsonschema2avro.predicates.AvroPredicates.java

public static Predicate<AvroPayload> simpleUnion() {
    return new Predicate<AvroPayload>() {
        @Override/*from  w w w.j  a  v a 2  s .  co  m*/
        public boolean apply(final AvroPayload input) {
            // NOTE: enums within enums are forbidden. This is tested in
            // writers, not here.
            final JsonNode node = schemaNode(input);
            final Set<String> members = Sets.newHashSet(node.fieldNames());
            members.retainAll(KNOWN_KEYWORDS);
            return members.equals(ImmutableSet.of("anyOf")) || members.equals(ImmutableSet.of("oneOf"));
        }
    };
}

From source file:net.recommenders.rival.evaluation.statistics.EffectSize.java

/**
 *
 * Estimation of effect size based on the distribution of score differences
 * (from paired samples)./*from   w w w .j  av a  2s .  c o  m*/
 *
 * @param <V> type of the keys of each map.
 * @param baselineMetricPerDimension map for the baseline method, one value
 * for each user (dimension)
 * @param testMetricPerDimension map for the test method, one value for each
 * user (dimension)
 * @return the effect size.
 */
public static <V> double getEffectSizePairedT(final Map<V, Double> baselineMetricPerDimension,
        final Map<V, Double> testMetricPerDimension) {
    Set<V> overlap = new HashSet<V>(baselineMetricPerDimension.keySet());
    overlap.retainAll(testMetricPerDimension.keySet());

    SummaryStatistics differences = new SummaryStatistics();
    for (V key : overlap) {
        double diff = testMetricPerDimension.get(key) - baselineMetricPerDimension.get(key);
        differences.addValue(diff);
    }

    return getEffectSizePairedT(differences.getMean(), Math.sqrt(differences.getVariance()));
}

From source file:com.github.fge.jsonschema2avro.predicates.AvroPredicates.java

public static Predicate<AvroPayload> isEnum() {
    return new Predicate<AvroPayload>() {
        @Override/*from  w  ww .j  a v a  2  s  .  c  o m*/
        public boolean apply(final AvroPayload input) {
            final JsonNode node = schemaNode(input);
            final Set<String> set = Sets.newHashSet(node.fieldNames());
            set.retainAll(KNOWN_KEYWORDS);
            if (!set.equals(ImmutableSet.of("enum")))
                return false;

            // Test individual entries: they must be strings, and must be
            // the same "shape" as any Avro name
            for (final JsonNode element : node.get("enum")) {
                if (!element.isTextual())
                    return false;
                if (!isValidAvroName(element.textValue()))
                    return false;
            }

            return true;
        }
    };
}

From source file:TwitterClustering.java

public static float jaccardDistance(Set<String> a, Set<String> b) {

    if (a.size() == 0 || b.size() == 0) {
        return 0;
    }//from   w ww . j  ava 2 s  .  c om

    Set<String> unionXY = new HashSet<String>(a);
    unionXY.addAll(b);

    Set<String> intersectionXY = new HashSet<String>(a);
    intersectionXY.retainAll(b);
    float retValue = (float) intersectionXY.size() / (float) unionXY.size();
    return retValue;

}

From source file:main.Draft_text_categorization.java

/**
 * //  w  w  w  .j a  va2  s  . c om
 * http://stackoverflow.com/questions/3622112/vector-space-model-algorithm-in-java-to-get-the-similarity-score-between-two-peo
 * 
 * @param v1
 * @param v2
 * @return
 */
static double cosine_similarity(Map<String, Integer> v1, Map<String, Integer> v2) {
    Set<String> both = new HashSet<String>(v1.keySet());
    both.retainAll(v2.keySet());
    double sclar = 0, norm1 = 0, norm2 = 0;

    for (String k : both)
        sclar += v1.get(k) * v2.get(k);
    for (String k : v1.keySet())
        norm1 += v1.get(k) * v1.get(k);
    for (String k : v2.keySet())
        norm2 += v2.get(k) * v2.get(k);
    return sclar / Math.sqrt(norm1 * norm2);
}

From source file:uniol.apt.tasks.ModuleParameterVerifyTask.java

/** Do the work */
private static boolean analyseClass(ModuleParameterVerifyClassVisitor cv,
        Map<String, ModuleParameterVerifyClassVisitor> classes) {
    String className = cv.getClassName();

    Map<String, Type> requestedInputs = new HashMap<>();
    Map<String, Type> optionalInputs = new HashMap<>();
    Map<String, Type> usedInputs = new HashMap<>();
    Map<String, Type> announcedOutputs = new HashMap<>();
    Map<String, Type> providedOutputs = new HashMap<>();

    getClassInformation(cv, classes, requestedInputs, optionalInputs, usedInputs, announcedOutputs,
            providedOutputs);/*from   w  w  w  .  j  ava2s.  c  o m*/

    boolean fail = false;

    Set<String> requiredOptionalInputs = new HashSet<>(requestedInputs.keySet());
    requiredOptionalInputs.retainAll(optionalInputs.keySet());

    for (String parameter : requiredOptionalInputs) {
        System.err.println(
                "error: " + className + ": Parameter specified as required and also as optional: " + parameter);
        fail = true;
    }

    for (Map.Entry<String, Type> entry : requestedInputs.entrySet()) {
        String parameter = entry.getKey();
        Type requestedClass = entry.getValue();
        Type usedClass = usedInputs.get(parameter);

        if (requestedClass == DIFFERENT_TYPES_DETECTED_TYPE) {
            System.err
                    .println("error: " + className + ": Parameter required with multiple types: " + parameter);
            fail = true;
        } else if (usedClass == null) {
            System.err.println("warning: " + className + ": Never used parameter: " + parameter);
        } else if (usedClass == DIFFERENT_TYPES_DETECTED_TYPE) {
            System.err.println("error: " + className + ": Parameter used with multiple types: " + parameter);
            fail = true;
        } else if (!usedClass.equals(requestedClass)) {
            System.err.println(
                    "error: " + className + ": Parameter used with other type as requested: " + parameter);
            fail = true;
        }
    }

    for (Map.Entry<String, Type> entry : optionalInputs.entrySet()) {
        String parameter = entry.getKey();
        Type usedClass = usedInputs.get(parameter);
        Type requestedClass = entry.getValue();

        if (requestedClass == DIFFERENT_TYPES_DETECTED_TYPE) {
            System.err
                    .println("error: " + className + ": Parameter required with multiple types: " + parameter);
            fail = true;
        } else if (usedClass == null) {
            System.err.println("warning: " + className + ": Never used parameter: " + parameter);
        } else if (usedClass == DIFFERENT_TYPES_DETECTED_TYPE) {
            System.err.println("error: " + className + ": Parameter used with multiple types: " + parameter);
            fail = true;
        } else if (!usedClass.equals(requestedClass)) {
            System.err.println(
                    "error: " + className + ": Parameter used with other type as requested: " + parameter);
            fail = true;
        }
    }

    Set<String> unknownInputs = new HashSet<>(usedInputs.keySet());
    unknownInputs.removeAll(requestedInputs.keySet());
    unknownInputs.removeAll(optionalInputs.keySet());
    for (String parameter : unknownInputs) {
        System.err.println("error: " + className + ": Used but not requested parameter: " + parameter);
        fail = true;
    }

    for (Map.Entry<String, Type> entry : announcedOutputs.entrySet()) {
        String parameter = entry.getKey();
        Type providedClass = providedOutputs.get(parameter);
        Type announcedClass = entry.getValue();

        if (announcedClass == DIFFERENT_TYPES_DETECTED_TYPE) {
            System.err.println(
                    "error: " + className + ": Return value announced with multiple types: " + parameter);
            fail = true;
        } else if (providedClass == null) {
            System.err.println("warning: " + className + ": Return value gets never set: " + parameter);
        } else if (providedClass == DIFFERENT_TYPES_DETECTED_TYPE) {
            System.err.println(
                    "error: " + className + ": Return value provided with multiple types: " + parameter);
            fail = true;
        } else if (!providedClass.equals(announcedClass)) {
            System.err.println("error: " + className + ": Return value gets set with other type as announced: "
                    + parameter);
            fail = true;
        }
    }

    Set<String> unknownOutputs = new HashSet<>(providedOutputs.keySet());
    unknownOutputs.removeAll(announcedOutputs.keySet());
    for (String parameter : unknownOutputs) {
        System.err.println("error: " + className + ": Unannounced return value: " + parameter);
        fail = true;
    }

    return fail;
}

From source file:com.task.springsec.SecurityUtil.java

/**
 * Find the common authorities between the current authentication's {@link GrantedAuthority} and the ones
 * that have been specified in the tag's ifAny, ifNot or ifAllGranted attributes.<p>We need to manually
 * iterate over both collections, because the granted authorities might not implement {@link
 * Object#equals(Object)} and {@link Object#hashCode()} in the same way as {@link SimpleGrantedAuthority}, thereby
 * invalidating {@link Collection#retainAll(java.util.Collection)} results.</p>
 * <p>/*from w  w w  .  java  2  s  .  c  om*/
 * <strong>CAVEAT</strong>:  This method <strong>will not</strong> work if the granted authorities
 * returns a <code>null</code> string as the return value of {@link
 * org.springframework.security.GrantedAuthority#getAuthority()}.
 * </p>
 * <p>Reported by rawdave, on Fri Feb 04, 2005 2:11 pm in the Spring Security forum.</p>
 *
 * @param granted The authorities granted by the authentication. May be any implementation of {@link
 *        GrantedAuthority} that does <strong>not</strong> return <code>null</code> from {@link
 *        org.springframework.security.GrantedAuthority#getAuthority()}.
 * @param required A {@link Set} of {@link SimpleGrantedAuthority}s that have been built using ifAny, ifAll or
 *        ifNotGranted.
 *
 * @return A set containing only the common authorities between <var>granted</var> and <var>required</var>.
 */
private static Set retainAll(final Collection<? extends GrantedAuthority> granted,
        final Collection<? extends GrantedAuthority> required) {
    Set<String> grantedRoles = toRoles(granted);
    Set<String> requiredRoles = toRoles(required);
    grantedRoles.retainAll(requiredRoles);

    return toAuthorities(grantedRoles, granted);
}