Java Examples for java.util.Set

The following java examples will help you to understand the usage of java.util.Set. These source code samples are taken from different open source projects.

Example 1
Project: liferay-ide-master  File: TargetSDKPossibleValuesService.java View source code
@Override
protected void compute(Set<String> values) {
    try {
        for (String version : AdtUtils.getKnownVersions()) {
            values.add(version);
        }
    } catch (Throwable th) {
        values.add("API 17: Android 4.2 (Jelly Bean)");
    }
}
Example 2
Project: turmeric-eclipse-master  File: TestCollectionUtil.java View source code
/**
	 * Test method for [email protected] [email protected]til#intersection(java.util.Set, java.util.Set)}.
	 */
@Test
public void testIntersection() {
    Set<String> collection = new HashSet<String>();
    collection.add("3dfx");
    collection.add("Nvidia");
    collection.add("ATI");
    Set<String> collection2 = new HashSet<String>();
    collection2.add("3dfx");
    collection2.add("ATI");
    collection2.add("Trident");
    Set<String> expected = new HashSet<String>();
    expected.add("3dfx");
    expected.add("ATI");
    Set<String> data = CollectionUtil.intersection(collection, collection2);
    TestSetUtil.assertSetEquals(expected, data);
}
Example 3
Project: google-web-toolkit-svnmirror-master  File: TreeSetTest.java View source code
/**
   * Test method for 'java.util.Set.add(Object)'.
   * 
   * @see java.util.Set#add(Object)
   */
public void testAdd_entries3() {
    // verify that the method is not supported.
    if (isAddSupported) {
        // populate the set
        Set<E> set = createSet();
        set.add(getKeys()[0]);
        set.add(getKeys()[1]);
        set.add(getKeys()[2]);
        // test contents
        assertFalse(set.isEmpty());
        assertEquals(3, set.size());
        Collection<E> keys = set;
        // test contains all keys
        assertTrue(keys.contains(getKeys()[0]));
        assertTrue(keys.contains(getKeys()[1]));
        assertTrue(keys.contains(getKeys()[2]));
    }
}
Example 4
Project: expenditures-master  File: PersonAutoComplete.java View source code
@Override
public Collection getSearchResults(Map argsMap, String value, int maxCount) {
    Set<Person> people = new HashSet<Person>();
    String[] values = StringNormalizer.normalize(value).toLowerCase().split(" ");
    for (Person person : Bennu.getInstance().getPersonsSet()) {
        if (person.getUser() != null && person.getUser().getProfile() != null) {
            if (person.getUser().getProfile().getFullName() != null) {
                final String normalizedName = StringNormalizer.normalize(person.getUser().getProfile().getFullName()).toLowerCase();
                if (hasMatch(values, normalizedName)) {
                    people.add(person);
                }
            }
            if (person.getUser() != null && person.getUser().getUsername().indexOf(value) >= 0) {
                people.add(person);
            }
        }
    }
    return people;
}
Example 5
Project: molgenis-master  File: GenericDependencyResolver.java View source code
public <A> List<A> resolve(Collection<A> items, Function<A, Set<A>> getDependencies) {
    List<A> result = newArrayList();
    Set<A> alreadyResolved = newHashSet();
    Set<A> stillToResolve = newHashSet(items);
    while (!stillToResolve.isEmpty()) {
        List<A> newlyResolved = stillToResolve.stream().filter( item -> alreadyResolved.containsAll(getDependencies.apply(item))).collect(Collectors.toList());
        if (newlyResolved.isEmpty()) {
            throw new MolgenisDataException("Could not resolve dependencies of items " + stillToResolve + ". Are there circular dependencies?");
        }
        alreadyResolved.addAll(newlyResolved);
        stillToResolve.removeAll(newlyResolved);
        result.addAll(newlyResolved);
    }
    return result;
}
Example 6
Project: sonar-java-master  File: URLHashCodeAndEqualsCheck.java View source code
public void foo(URL url) throws Exception {
    // Noncompliant [[sc=5;ec=22]] {{Use the URI class instead.}}
    Map<URL, Integer> sites = new HashMap<>();
    // Noncompliant {{Use the URI class instead.}}
    Set<URL> otherSites = new HashSet<>();
    // Compliant
    URL homepage = new URL("http://sonarsource.com");
    // Noncompliant [[sc=5;ec=25]] {{Use the URI class instead.}}
    homepage.equals(url);
    // Noncompliant {{Use the URI class instead.}}
    homepage.hashCode();
    // Compliant
    homepage.getPath();
    // Compliant
    Map<URI, URL> uriToUrl = new HashMap<>();
    // Compliant
    Map uriToUrl2 = new Hashmap();
    // Compliant
    Map<> uriToUrl3 = new Hashmap<>();
}
Example 7
Project: tapestry-model-master  File: DefaultExclusionsBMModifierTest.java View source code
@Test
void exclude() {
    BeanModel model = mockBeanModel();
    DescriptorService descriptorService = newMock(DescriptorService.class);
    TynamoClassDescriptorImpl classDescriptor = new TynamoClassDescriptorImpl(Foo.class);
    IdentifierDescriptor idProp = new IdentifierDescriptorImpl(Foo.class, "id", String.class);
    TynamoPropertyDescriptor multiWordProp = new TynamoPropertyDescriptorImpl(Foo.class, "multiWordProperty", String.class);
    CollectionDescriptor bazzesDescriptor = new CollectionDescriptor(Foo.class, "bazzes", Set.class);
    bazzesDescriptor.setElementType(Baz.class);
    Collections.addAll(classDescriptor.getPropertyDescriptors(), idProp, multiWordProp, bazzesDescriptor);
    expect(model.exclude("id", "bazzes")).andReturn(model);
    expect(model.getBeanType()).andReturn(Foo.class);
    expect(descriptorService.getClassDescriptor(Foo.class)).andReturn(classDescriptor);
    replay();
    DefaultExclusionsBMModifier modifier = new DefaultExclusionsBMModifier(descriptorService);
    modifier.modify(model, PageType.LIST.getContextKey());
    verify();
}
Example 8
Project: bennu-master  File: SchedulerTaskAnnotationProcessor.java View source code
@Override
public void onStartup(Set<Class<?>> classes, ServletContext ctx) throws ServletException {
    if (classes != null) {
        for (Class<?> type : classes) {
            final Task annon = type.getAnnotation(Task.class);
            if (annon != null) {
                SchedulerSystem.addTask(type.getName(), annon);
            }
        }
    }
}
Example 9
Project: sitebricks-master  File: AbstractMagicTemplateCompiler.java View source code
public Renderable compile(final Class<?> page, final Template sitebricksTemplate) {
    return new Renderable() {

        @Override
        public void render(Object bound, Respond respond) {
            assert page.isInstance(bound);
            //
            // 1. Transform text to XHTML        
            // 2. Process the XHTML however the client wishes
            // 3. Blow the processed XHTML out of pipe
            //
            respond.write(process(page, bound, transform(sitebricksTemplate)));
        }

        @Override
        public <T extends Renderable> Set<T> collect(Class<T> clazz) {
            return ImmutableSet.of();
        }
    };
}
Example 10
Project: sisu-guice-master  File: SuiteUtils.java View source code
public static TestSuite removeSuppressedTests(TestSuite suite, Set<String> suppressedTestNames) {
    TestSuite result = new TestSuite(suite.getName());
    for (Enumeration e = suite.tests(); e.hasMoreElements(); ) {
        Test test = (Test) e.nextElement();
        if (suppressedTestNames.contains(test.toString())) {
            continue;
        }
        if (test instanceof TestSuite) {
            result.addTest(removeSuppressedTests((TestSuite) test, suppressedTestNames));
        } else {
            result.addTest(test);
        }
    }
    return result;
}
Example 11
Project: org.openntf.domino-master  File: ASTAssignment.java View source code
/*
	 * (non-Javadoc)
	 * @see org.openntf.formula.ast.SimpleNode#analyzeThis(java.util.Set, java.util.Set, java.util.Set, java.util.Set)
	 */
@Override
protected void analyzeThis(final Set<String> readFields, final Set<String> modifiedFields, final Set<String> variables, final Set<String> functions) {
    switch(type) {
        case FIELD:
            modifiedFields.add(varName.toLowerCase());
            break;
        case VAR:
        case DEFAULT:
            variables.add(varName.toLowerCase());
            break;
        case ENV:
            break;
    }
}
Example 12
Project: LambdaDojo-master  File: S404StreamInsteadOfFor.java View source code
private void splitSentences() {
    List<String> sentences = Arrays.asList("Peter Piper picked", "a peck of pickled peppers.", "A peck of pickled peppers", "Peter Piper picked. ", "If Peter Piper picked", "a peck of pickled peppers,", "Where's the peck of pickled peppers", "Peter Piper picked? ");
    Set<String> words = new HashSet<>();
    for (String sentence : sentences) {
        String[] splitedSentence = sentence.split("[\\.,\\? ]");
        for (String word : splitedSentence) {
            words.add(word.toLowerCase());
        }
    }
    System.out.println(words);
}
Example 13
Project: dataverse-master  File: GroupUtil.java View source code
/**
     * @param authenticatedUser An non-null AuthenticatedUser.
     * @param groups The groups associated with an AuthenticatedUser.
     * @return A list of identifiers for the user including groups, single
     * quoted, and separated by commas. Null if a null AuthenticatedUser is
     * passed.
     */
public static String getAllIdentifiersForUser(AuthenticatedUser authenticatedUser, Set<Group> groups) {
    if (authenticatedUser == null) {
        return null;
    }
    StringBuilder sb = new StringBuilder();
    sb.append("'").append(authenticatedUser.getIdentifier()).append("'");
    if (groups != null) {
        groups.stream().forEach(( group) -> {
            sb.append(", ").append("'").append(group.getIdentifier()).append("'");
        });
    }
    return sb.toString();
}
Example 14
Project: cloudtm-data-platform-master  File: CheckGaps.java View source code
public static void main(String[] args) {
    SortedSet<Integer> set = new TreeSet<Integer>();
    for (int i = 0; i < args.length; i++) {
        set.add(Integer.parseInt(args[i]));
    }
    int low = set.first(), high = set.last();
    System.out.println("input has " + set.size() + " numbers, low=" + low + ", high=" + high);
    Set<Integer> correct_set = new HashSet<Integer>();
    for (int i = low; i < high; i++) {
        correct_set.add(i);
    }
    correct_set.removeAll(set);
    System.out.println("missing seqnos: " + correct_set);
}
Example 15
Project: alien4cloud-master  File: ToscaDefinitionVersionParser.java View source code
@Override
public String parse(Node node, ParsingContextExecution context) {
    ArchiveRoot archiveRoot = (ArchiveRoot) context.getParent();
    String toscaDefinitionVersion = ParserUtils.getScalar(node, context);
    if (toscaDefinitionVersion != null) {
        CSARDependency dependency = ToscaNormativeImports.IMPORTS.get(toscaDefinitionVersion);
        if (dependency != null) {
            Set<CSARDependency> dependencies = archiveRoot.getArchive().getDependencies();
            if (dependencies == null) {
                dependencies = new HashSet<>();
                archiveRoot.getArchive().setDependencies(dependencies);
            }
            // Normative imports are automatically injected and supposed to be accessible, no specific validation is performed here.
            ToscaContext.get().addDependency(dependency);
            dependencies.add(dependency);
        }
    }
    return toscaDefinitionVersion;
}
Example 16
Project: geotools-old-master  File: StyleAttributeExtractorTest.java View source code
public void testGeometryTransformation() {
    PointSymbolizer ps = sb.createPointSymbolizer();
    ps.setGeometry(ff.function("offset", ff.property("the_geom"), ff.property("offx"), ff.property("offy")));
    Rule r = sb.createRule(ps);
    StyleAttributeExtractor extractor = new StyleAttributeExtractor();
    r.accept(extractor);
    Set<String> atts = extractor.getAttributeNameSet();
    assertEquals(3, atts.size());
    assertTrue(atts.contains("the_geom"));
    assertTrue(atts.contains("offx"));
    assertTrue(atts.contains("offy"));
    assertFalse(extractor.getDefaultGeometryUsed());
}
Example 17
Project: extFM-Tooling-master  File: MtextExpectedEnumerationTerminal.java View source code
public java.util.Set<String> getTokenNames() {
    // EnumerationTerminals are associated with multiple tokens, one for each literal
    // that was mapped to a string
    java.util.Set<String> tokenNames = new java.util.LinkedHashSet<String>();
    java.util.Map<String, String> mapping = enumerationTerminal.getLiteralMapping();
    for (String literalName : mapping.keySet()) {
        String text = mapping.get(literalName);
        if (text != null && !"".equals(text)) {
            tokenNames.add("'" + text + "'");
        }
    }
    return tokenNames;
}
Example 18
Project: ARTPart-master  File: Main.java View source code
public static void main(String[] args) throws Exception {
    // These charsets must be provided; anything else is optional.
    List<String> standardCharsets = Arrays.asList("US-ASCII", "ISO-8859-1", "UTF-8", "UTF-16BE", "UTF-16LE", "UTF-16");
    SortedMap<String, Charset> all = Charset.availableCharsets();
    Set<String> needed = new HashSet<String>(standardCharsets);
    for (Map.Entry<String, Charset> e : all.entrySet()) {
        String canonicalName = e.getKey();
        needed.remove(canonicalName);
    }
    System.out.println("Missing: " + needed);
}
Example 19
Project: parkandrideAPI-master  File: ElementLengthSetValidator.java View source code
@Override
public boolean isValid(Set<? extends CharSequence> set, ConstraintValidatorContext context) {
    context.disableDefaultConstraintViolation();
    boolean ok = true;
    if (set != null) {
        int i = 0;
        for (CharSequence val : set) {
            if (val != null && (val.length() < min || val.length() > max)) {
                context.buildConstraintViolationWithTemplate(message).addBeanNode().inIterable().atIndex(i).addConstraintViolation();
                ok = false;
            }
            i++;
        }
    }
    return ok;
}
Example 20
Project: many-ql-master  File: Refresher.java View source code
private Set<Refreshable> evaluate(Set<Refreshable> items) {
    Set<Refreshable> unresolved = new HashSet<>();
    for (Refreshable r : items) {
        Value val = r.evaluate(this.valueTable);
        if (val.isUndefined()) {
            unresolved.add(r);
        }
    }
    return unresolved;
}
Example 21
Project: mjprof-master  File: JPSUtil.java View source code
public static int lookupProcessId(String lookForMainClass) throws MonitorException, URISyntaxException {
    HostIdentifier hostId = new HostIdentifier("local://localhost");
    MonitoredHost monitoredHost = MonitoredHost.getMonitoredHost(hostId);
    // get the set active JVMs on the specified host.
    Set jvms = monitoredHost.activeVms();
    for (Object jvm : jvms) {
        int lvmid = (Integer) jvm;
        MonitoredVm vm = null;
        String vmidString = "//" + lvmid + "?mode=r";
        VmIdentifier id = new VmIdentifier(vmidString);
        vm = monitoredHost.getMonitoredVm(id, 0);
        String mainClass = MonitoredVmUtil.mainClass(vm, false);
        if (mainClass.equals(lookForMainClass))
            return lvmid;
    }
    return -1;
}
Example 22
Project: cms-ce-master  File: ContentIndexDataTestBase.java View source code
void verifyElementExistsAndNumberOfValues(Set<ContentIndexDataElement> contentDataElements, String name, int expectedValueElements) {
    for (ContentIndexDataElement contentDataElement : contentDataElements) {
        final Set<ContentIndexDataFieldAndValue> contentIndexDataFieldAndValues = ContentIndexDataFieldValueSetFactory.create(contentDataElement);
        final Set<ContentIndexDataFieldAndValue> allFieldAndValuesForElement = contentIndexDataFieldAndValues;
        for (ContentIndexDataFieldAndValue contentIndexDataFieldAndValue : allFieldAndValuesForElement) {
            if (name.equals(contentIndexDataFieldAndValue.getFieldName())) {
                final Object value = contentIndexDataFieldAndValue.getValue();
                if (expectedValueElements > 1) {
                    assertTrue(value instanceof Collection);
                    Collection collection = (Collection) value;
                    assertEquals(expectedValueElements, collection.size());
                } else {
                    if (value instanceof Collection) {
                        assertEquals(1, ((Collection) value).size());
                    }
                }
                return;
            }
        }
    }
    fail("Did not find Element with name: " + name);
}
Example 23
Project: quickml-master  File: AttributeCombiningEnricherTest.java View source code
@Test
public void simpleTest() {
    Set<List<String>> attributesToCombine = Sets.newHashSet();
    attributesToCombine.add(Lists.newArrayList("k1", "k2"));
    AttributeCombiningEnricher attributeCombiningEnricher = new AttributeCombiningEnricher(attributesToCombine);
    AttributesMap attributes = AttributesMap.newHashMap();
    attributes.put("k1", "a");
    attributes.put("k2", "b");
    final AttributesMap enhancedAttributes = attributeCombiningEnricher.apply(attributes);
    Assert.assertEquals(enhancedAttributes.size(), 3);
    Assert.assertEquals(enhancedAttributes.get("k1-k2"), "ab");
}
Example 24
Project: ManagedRuntimeInitiative-master  File: JavaCompiler.java View source code
/** Main method: compile a list of files, return all compiled classes
     *  @param filenames     The names of all files to be compiled.
     */
public List<ClassSymbol> compile(List<String> filenames, Map<String, String> origOptions, ClassLoader aptCL, AnnotationProcessorFactory providedFactory, java.util.Set<Class<? extends AnnotationProcessorFactory>> productiveFactories, java.util.Set<java.io.File> aggregateGenFiles) throws Throwable {
    // it has been used before.
    assert !hasBeenUsed : "attempt to reuse JavaCompiler";
    hasBeenUsed = true;
    this.aggregateGenFiles = aggregateGenFiles;
    long msec = System.currentTimeMillis();
    ListBuffer<ClassSymbol> classes = new ListBuffer<ClassSymbol>();
    try {
        //parse all files
        ListBuffer<JCCompilationUnit> trees = new ListBuffer<JCCompilationUnit>();
        for (List<String> l = filenames; l.nonEmpty(); l = l.tail) {
            if (classesAsDecls) {
                if (!l.head.endsWith(".java")) {
                    // process as class file
                    ClassSymbol cs = reader.enterClass(names.fromString(l.head));
                    try {
                        cs.complete();
                    } catch (Symbol.CompletionFailure cf) {
                        bark.aptError("CantFindClass", l);
                        continue;
                    }
                    // add to list of classes
                    classes.append(cs);
                    continue;
                }
            }
            trees.append(parse(l.head));
        }
        //enter symbols for all files
        List<JCCompilationUnit> roots = trees.toList();
        if (errorCount() == 0) {
            boolean prev = bark.setDiagnosticsIgnored(true);
            try {
                enter.main(roots);
            } finally {
                bark.setDiagnosticsIgnored(prev);
            }
        }
        if (errorCount() == 0) {
            apt.main(roots, classes, origOptions, aptCL, providedFactory, productiveFactories);
            genSourceFileNames.addAll(apt.getSourceFileNames());
            genClassFileNames.addAll(apt.getClassFileNames());
        }
    } catch (Abort ex) {
    }
    if (verbose)
        printVerbose("total", Long.toString(System.currentTimeMillis() - msec));
    chk.reportDeferredDiagnostics();
    printCount("error", errorCount());
    printCount("warn", warningCount());
    return classes.toList();
}
Example 25
Project: EclipseTrader-master  File: BaseWireFeedGenerator.java View source code
/**
     * Purging unused declarations is less optimal, performance-wise, than never adding them in the first place.  So, we
     * should still ask the ROME guys to fix their code (not adding dozens of unnecessary module declarations). Having
     * said that: purging them here, before XML generation, is more efficient than parsing and re-molding the XML after
     * ROME generates it.
     * <p/>
     * Note that the calling app could still add declarations/modules to the Feed tree after this.  Which is fine.  But
     * those modules are then responsible for crawling to the root of the tree, at generate() time, to make sure their
     * namespace declarations are present.
     */
protected static void purgeUnusedNamespaceDeclarations(Element root) {
    java.util.Set usedPrefixes = new java.util.HashSet();
    collectUsedPrefixes(root, usedPrefixes);
    List list = root.getAdditionalNamespaces();
    List additionalNamespaces = new java.util.ArrayList();
    // the duplication will prevent a ConcurrentModificationException below
    additionalNamespaces.addAll(list);
    for (int i = 0; i < additionalNamespaces.size(); i++) {
        Namespace ns = (Namespace) additionalNamespaces.get(i);
        String prefix = ns.getPrefix();
        if (prefix != null && prefix.length() > 0 && !usedPrefixes.contains(prefix)) {
            root.removeNamespaceDeclaration(ns);
        }
    }
}
Example 26
Project: Mint-Programming-Language-master  File: ViewStrings.java View source code
@Override
public Pointer apply(SmartList<Pointer> args) throws MintException {
    short i = 0;
    while (i < Short.MAX_VALUE) {
        try {
            HashMap<Integer, String> strs = Heap.strings;
            if (strs == null) {
                return EMPTY_LIST;
            }
            Table tbl = new Table();
            ArrayList<Integer> keys = new ArrayList<Integer>();
            Set<Integer> s = strs.keySet();
            for (int element : s) {
                keys.add(element);
            }
            s = null;
            for (int key : keys) {
                SmartList<Pointer> pair = new SmartList<Pointer>();
                pair.add(new Pointer(Constants.INT_TYPE, key));
                pair.add(Heap.allocateString(strs.get(key)));
                tbl.addBinding(pair);
            }
            return Heap.allocateTable(tbl);
        } catch (Throwable t) {
        }
        ++i;
    }
    try {
        return Heap.allocateString(Heap.strings.toString());
    } catch (Throwable t) {
        return ChangeString.ERROR;
    }
}
Example 27
Project: openjdk-master  File: T6362067.java View source code
public boolean process(Set<? extends TypeElement> annos, RoundEnvironment roundEnv) {
    for (Element e : roundEnv.getRootElements()) {
        messager.printMessage(NOTE, "note:elem", e);
        for (AnnotationMirror a : e.getAnnotationMirrors()) {
            messager.printMessage(NOTE, "note:anno", e, a);
            for (AnnotationValue v : a.getElementValues().values()) {
                messager.printMessage(NOTE, "note:value", e, a, v);
            }
        }
    }
    if (roundEnv.processingOver())
        messager.printMessage(NOTE, "note:nopos");
    return true;
}
Example 28
Project: erlide-master  File: MapUtils.java View source code
public static <K, V> Map<V, Set<K>> inverseSet(final Map<K, Set<V>> map) {
    final Map<V, Set<K>> result = new LinkedHashMap<>();
    for (final Map.Entry<K, Set<V>> entry : map.entrySet()) {
        for (final V v : entry.getValue()) {
            if (!result.containsKey(v)) {
                result.put(v, new HashSet<K>());
            }
            result.get(v).add(entry.getKey());
        }
    }
    return result;
}
Example 29
Project: dtangler-master  File: GroupRuleMemberTest.java View source code
@Test
public void testAppliesTo() {
    String excludedPackages = "org.public.*";
    String excludedSubpackage = "org.public.stats";
    String containedPackages = "org.*";
    String containedSubpackage = "org.db";
    String otherPackage = "test.util";
    Set<String> included = new HashSet();
    included.add(containedPackages);
    Set<String> excluded = new HashSet();
    excluded.add(excludedPackages);
    Group a = new Group("A", included, excluded);
    RuleMember member = new GroupRuleMember(a);
    assertTrue(member.appliesTo(new TestDependable(containedSubpackage)));
    assertFalse(member.appliesTo(new TestDependable(otherPackage)));
    assertFalse(member.appliesTo(new TestDependable(excludedSubpackage)));
    assertFalse(member.appliesTo((new TestDependable(excludedPackages))));
}
Example 30
Project: cdo-master  File: CrossReferencesPackageClosure.java View source code
protected void collectCrossReferences(EObject content, Set<EPackage> visited) {
    EList<EObject> crossReferences = content.eCrossReferences();
    for (EObject crossReference : crossReferences) {
        EPackage crossReferencePackage = crossReference.eClass().getEPackage();
        if (!visited.contains(crossReferencePackage)) {
            handleEPackage(crossReferencePackage, visited);
        }
    }
}
Example 31
Project: geoserver-enterprise-master  File: FeatureGSExclusion.java View source code
@Override
public ProcessFactory filterFactory(ProcessFactory pf) {
    if (pf instanceof VectorProcessFactory || (pf instanceof DelegatingProcessFactory && ((DelegatingProcessFactory) pf).getInnermostDelegate() instanceof VectorProcessFactory)) {
        return null;
    }
    if (pf instanceof DeprecatedProcessFactory) {
        //strip out all the "gs" processes
        Set<Name> disabled = new HashSet();
        for (Name n : pf.getNames()) {
            if ("gs".equals(n.getNamespaceURI())) {
                disabled.add(n);
            }
        }
        return new SelectingProcessFactory(pf, new DisabledProcessesSelector(disabled));
    }
    return pf;
}
Example 32
Project: ISAcreator-master  File: AnnotatorSearchClientTest.java View source code
@Test
public void testAnnotatorClient() {
    System.out.println("_____Testing NCBO Annotator search client____");
    AnnotatorSearchClient sc = new AnnotatorSearchClient();
    Set<String> testTerms = new HashSet<String>();
    testTerms.add("CY3");
    testTerms.add("DOSE");
    testTerms.add("ASSAY");
    testTerms.add("Ethanol");
    testTerms.add("drug vehicle (90% ethanol/10% tween-20)");
    Map<String, Map<String, AnnotatorResult>> result = sc.searchForTerms(testTerms);
    for (String key : result.keySet()) {
        System.out.println(key + " matched:");
        for (String ontologyId : result.get(key).keySet()) {
            System.out.println("\t" + ontologyId + " -> " + result.get(key).get(ontologyId).getOntologyTerm().getOntologyTermName() + " (" + result.get(key).get(ontologyId).getOntologySource().getOntologyDisplayLabel() + ")");
        }
    }
    assertTrue("No matches found", result.size() > 0);
}
Example 33
Project: geotoolkit-master  File: GPXDemo.java View source code
public static void main(String[] args) throws DataStoreException, URISyntaxException {
    Demos.init();
    final Map<String, Serializable> parameters = new HashMap<String, Serializable>();
    parameters.put("path", GPXDemo.class.getResource("/data/sampleGPX.gpx").toURI());
    final FeatureStore store = (FeatureStore) DataStores.open(parameters);
    System.out.println("=================== Feature types ====================");
    final Set<GenericName> names = store.getNames();
    for (GenericName name : names) {
        System.out.println(store.getFeatureType(name.toString()));
    }
}
Example 34
Project: FTL-Hyperion-master  File: InstallAugmentationAction.java View source code
@Override
public void preform(String action, Object... params) {
    //TODO: Check for augmentation in inventory
    Ship ship = game.getShip((String) params[0]);
    if (ship == null)
        return;
    String augName = (String) params[1];
    AbstractAugmentation aug = AugmentationRegistry.getAugmentation(augName);
    if (aug == null)
        return;
    Properties prop = ship.getProperties();
    Properties augmentations = prop.getProperty("augmentations");
    if (augmentations == null) {
        augmentations = new Properties();
        prop.setProperty("augmentations", augmentations);
    }
    Set<String> augs = augmentations.getKeys();
    int numAugs = 0;
    for (String i : augs) {
        numAugs += augmentations.getInteger(i);
    }
    if (numAugs < 3) {
        int numThisAug = augmentations.getInteger(augName);
        augmentations.setInteger(augName, numThisAug + 1);
        aug.install(ship.getName());
    }
}
Example 35
Project: dcache-master  File: GplazmaMultiMapPlugin.java View source code
@Override
public void map(Set<Principal> principals) throws AuthenticationException {
    mapFile.ensureUpToDate();
    Set<Principal> mappedPrincipals = principals.stream().flatMap( p -> mapFile.getMappedPrincipals(p).stream()).collect(Collectors.toSet());
    checkAuthentication(!mappedPrincipals.isEmpty(), "no mappable principals");
    principals.addAll(mappedPrincipals);
}
Example 36
Project: eclipselink.runtime-master  File: IndirectSet.java View source code
/**
     * INTERNAL:
     * Return the freshly-built delegate.
     */
protected Set<E> buildDelegate() {
    Set<E> newDelegate = (Set<E>) getValueHolder().getValue();
    if (newDelegate == null) {
        newDelegate = new HashSet<>(this.initialCapacity, this.loadFactor);
    }
    // Unwrap any redundant indirection layers, which can cause issues and impact performance.
    while (newDelegate instanceof IndirectSet) {
        newDelegate = ((IndirectSet) newDelegate).getDelegate();
    }
    // First add/remove any cached changes.
    if (hasAddedElements()) {
        for (Iterator<E> iterator = getAddedElements().iterator(); iterator.hasNext(); ) {
            newDelegate.add(iterator.next());
        }
        this.addedElements = null;
    }
    if (hasRemovedElements()) {
        for (Iterator<E> iterator = getRemovedElements().iterator(); iterator.hasNext(); ) {
            newDelegate.remove(iterator.next());
        }
        this.removedElements = null;
    }
    return newDelegate;
}
Example 37
Project: raylew_algorithm-master  File: 统计字符.java View source code
public static void main(String[] args) {
    String str = "zdsgzd";
    Map map = new HashMap();
    int maxvalue = 0;
    for (int i = 0; i < str.length(); i++) {
        char c = str.charAt(i);
        if (map.get(c) == null) {
            map.put(c, 1);
        } else {
            int total = (Integer) map.get(c);
            total++;
            map.put(c, total);
            if (maxvalue < total) {
                maxvalue = total;
            }
        }
    }
    System.out.println("maxvalue:" + maxvalue);
    System.out.println(map.toString());
    Set set = map.keySet();
    Iterator iterator = set.iterator();
    int max = 0;
    char maxkey = 0;
    char key = 0;
    while (iterator.hasNext()) {
        key = (Character) iterator.next();
        if (max <= (Integer) map.get(key)) {
            max = (Integer) map.get(key);
            maxkey = key;
        }
    }
    System.out.println(maxkey + ":" + max);
}
Example 38
Project: tmdm-studio-se-master  File: ProcessAllCallJobVariableCandidatesHolder.java View source code
@Override
public String[] getExternalInfo() {
    if (service == null) {
        return new String[0];
    }
    Set<String> inputVariables = new HashSet<String>();
    for (WSTransformerProcessStep step : service.getProcessSteps()) {
        for (WSTransformerVariablesMapping mapping : step.getInputMappings()) {
            inputVariables.add(mapping.getPipelineVariable() == null ? TransformerMainPage.DEFAULT_VAR : mapping.getPipelineVariable());
        }
    }
    String[] results = inputVariables.toArray(new String[0]);
    Arrays.sort(results);
    return results;
}
Example 39
Project: beowulf-master  File: BwExecutorService.java View source code
public void submitJobs(Set<TestJob> testJobs) {
    for (TestJob job : testJobs) try {
        submitJob(job);
    } catch (JMSException e) {
        logger.error("Failed to submit testjob with id: {} and webscanObjId: {}", job.getTestJobObjId(), job.getWebScanObjId());
        e.printStackTrace();
    }
}
Example 40
Project: Light-Controller-master  File: AppReciever.java View source code
@Override
public void onReceive(Context context, Intent intent) {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
    Set<String> enabled = prefs.getStringSet("enabled_api_apps", new HashSet<String>());
    if (intent.getAction().equals(Intent.ACTION_PACKAGE_REMOVED)) {
        String packageName = intent.getData().getEncodedSchemeSpecificPart();
        Log.d("package", "Package Removed:" + packageName);
        if (enabled.contains(packageName)) {
            enabled.remove(packageName);
            prefs.edit().putStringSet("enabled_api_apps", enabled).apply();
            Log.d("package", "API Permission removed");
        }
    }
}
Example 41
Project: metrics-master  File: ThreadDeadlockHealthCheckTest.java View source code
@Test
public void isUnhealthyIfThreadsAreDeadlocked() throws Exception {
    final Set<String> threads = new TreeSet<String>();
    threads.add("one");
    threads.add("two");
    final ThreadDeadlockDetector detector = mock(ThreadDeadlockDetector.class);
    final ThreadDeadlockHealthCheck healthCheck = new ThreadDeadlockHealthCheck(detector);
    when(detector.getDeadlockedThreads()).thenReturn(threads);
    final HealthCheck.Result result = healthCheck.execute();
    assertThat(result.isHealthy()).isFalse();
    assertThat(result.getMessage()).isEqualTo("[one, two]");
}
Example 42
Project: REST-OCD-Services-master  File: ExcelFileGenerator.java View source code
public void genFile(Map<String, Object[]> data) {
    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet sheet = workbook.createSheet("Data");
    Set<String> keyset = data.keySet();
    int rownum = 0;
    for (String key : keyset) {
        rownum = Integer.parseInt(key);
        Row row = sheet.createRow(rownum);
        Object[] objectArray = data.get(key);
        int cellnum = 0;
        for (Object o : objectArray) {
            Cell c = row.createCell(cellnum++);
            if (o instanceof String) {
                c.setCellValue((String) o);
            }
            if (o instanceof Double) {
                c.setCellValue((Double) o);
            }
            if (o instanceof Integer) {
                c.setCellValue((Integer) o);
            }
        }
    }
    try {
        FileOutputStream out = new FileOutputStream(new File("Evaluation.xlsx"));
        workbook.write(out);
        out.close();
        System.out.println("Excel file written");
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 43
Project: ldbc_snb_datagen-master  File: MinHash.java View source code
public ArrayList<Long> minHash(Set<Long> set) {
    ArrayList<Long> minHashes = new ArrayList<Long>();
    for (int i = 0; i < numHashes_; ++i) {
        long min = Long.MAX_VALUE;
        long minl = 0;
        for (Long l : set) {
            long hash = (a[i] * l + b[i]) % p[i];
            if (hash <= min) {
                min = hash;
                minl = l;
            }
        }
        minHashes.add(minl);
    }
    return minHashes;
}
Example 44
Project: Desktop-master  File: IncrementalSearcher.java View source code
protected boolean searchFields(Set<String> fields, BibtexEntry bibtexEntry, String searchString) {
    boolean found = false;
    if (fields != null) {
        for (String field : fields) {
            try {
                /*Globals.logger("Searching field '"+fields[i].toString()
				       +"' for '"
				       +pattern.toString()+"'.");*/
                if (bibtexEntry.getField(field.toString()) != null) {
                    if (prefs.getBoolean("caseSensitiveSearch")) {
                        if (bibtexEntry.getField(field.toString()).toString().indexOf(searchString) > -1)
                            found = true;
                    } else {
                        if (bibtexEntry.getField(field.toString()).toString().toLowerCase().indexOf(searchString.toLowerCase()) > -1)
                            found = true;
                    }
                    if (found) {
                        hitInField = field.toString();
                        return true;
                    }
                }
            } catch (Throwable t) {
                System.err.println("Searching error: " + t);
            }
        }
    }
    return false;
}
Example 45
Project: Katari-master  File: RoleSecurityUtils.java View source code
/**
   * Obtains the roles of the currently logged on user.
   *
   * @return a set the currently logged on user. It returns null only if the
   * user has not logged in yet.
   */
public static Set<Role> getCurrentUserRoles() {
    log.trace("Entering getCurrentUserRoles");
    Set<Role> roles = null;
    // Obtains the current user definition.
    Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    if (principal != null) {
        if (!(principal instanceof RoleDetails)) {
            throw new RuntimeException("The currently logged on user does not" + " implement RoleDetails.");
        }
        roles = ((RoleDetails) principal).getUserRoles();
    }
    log.trace("Leaving getCurrentUserRoles");
    return roles;
}
Example 46
Project: framework-master  File: NotselectablePaintSelections.java View source code
@Override
protected void setup() {
    // Multiselect
    Table t = new Table("Multiselect");
    addComponent(t);
    t.setSelectable(false);
    t.setMultiSelect(true);
    t.setPageLength(5);
    t.addContainerProperty("Name", String.class, null);
    Set<Object> selected = new HashSet<>();
    for (int i = 0; i < 30; i++) {
        Item item = t.addItem(i);
        item.getItemProperty("Name").setValue("Name " + i);
        if (i % 2 == 0) {
            selected.add(i);
        }
    }
    t.setValue(selected);
    // Singleselect
    t = new Table("Singleselect");
    addComponent(t);
    t.setSelectable(false);
    t.setMultiSelect(false);
    t.setPageLength(5);
    t.addContainerProperty("Name", String.class, null);
    for (int i = 0; i < 30; i++) {
        Item item = t.addItem(i);
        item.getItemProperty("Name").setValue("Name " + i);
    }
    t.setValue(3);
}
Example 47
Project: TextSecureSMP-master  File: CountryListLoader.java View source code
@Override
public ArrayList<Map<String, String>> loadInBackground() {
    Set<String> regions = PhoneNumberUtil.getInstance().getSupportedRegions();
    ArrayList<Map<String, String>> results = new ArrayList<Map<String, String>>(regions.size());
    for (String region : regions) {
        Map<String, String> data = new HashMap<String, String>(2);
        data.put("country_name", PhoneNumberFormatter.getRegionDisplayName(region));
        data.put("country_code", "+" + PhoneNumberUtil.getInstance().getCountryCodeForRegion(region));
        results.add(data);
    }
    Collections.sort(results, new RegionComparator());
    return results;
}
Example 48
Project: xmind-master  File: SpaceCollaborativeEngine.java View source code
public void refreshMinorSpace() {
    int maxCount = 0;
    ContentPane contentPane = null;
    Set<Object> keys = managedContentPanes.keySet();
    for (Object key : keys) {
        ContentPane cp = managedContentPanes.get(key);
        int size = cp.getChildren().size();
        if (size >= maxCount) {
            contentPane = cp;
            maxCount = size;
        }
    }
    List elements = contentPane.getChildren();
    if (contentPane == null || elements.isEmpty())
        return;
    Rectangle clientArea = contentPane.getClientArea();
    int totalSize = clientArea.width;
    int elementSize = ((IFigure) elements.get(0)).getPreferredSize(-1, -1).width;
    int calculatedCount = totalSize / elementSize;
    int calculatedTotalSpace = totalSize - calculatedCount * elementSize;
    int calculatedEachSpace = 0;
    if (calculatedCount > 1) {
        calculatedEachSpace = calculatedTotalSpace / (calculatedCount - 1);
    }
    Set<Object> managedKeys = managedContentPanes.keySet();
    for (Object key : managedKeys) {
        ContentPane cp = managedContentPanes.get(key);
        int oldSpace = cp.getMinorSpacing();
        if (oldSpace != calculatedEachSpace) {
            cp.setMinorSpacing(calculatedEachSpace);
        }
    }
}
Example 49
Project: dk-master  File: CacheService.java View source code
/**
	 * 将所有的redis指定key的缓存都清空
	 * 
	 * @param key
	 */
public void clear(Object key) {
    if (cacheService == null || cacheService.size() == 0) {
        return;
    }
    Set<Entry<String, SpringRedisCacheService>> entrySet = cacheService.entrySet();
    for (Entry<String, SpringRedisCacheService> entry : entrySet) {
        if (entry.getKey().equalsIgnoreCase(LOCAL)) {
            continue;
        }
        long result = entry.getValue().deleteObjectKey(key);
        if (// 重试一次
        result == // 重试一次
        FAIL) {
            entry.getValue().deleteObjectKey(key);
        }
    }
}
Example 50
Project: nuxeo-jsf-master  File: JSFAnnotationProvider.java View source code
@Override
public Map<Class<? extends Annotation>, Set<Class<?>>> getAnnotatedClasses(Set<URI> urls) {
    if (JSFContainerInitializer.self == null) {
        LogFactory.getLog(JSFAnnotationProvider.class).warn("container scanned classes unavailable, applying default scanning");
        return base.getAnnotatedClasses(urls);
    }
    return JSFContainerInitializer.self.index;
}
Example 51
Project: lettuce-master  File: NodeTopologyViewsTest.java View source code
@Test
public void shouldReuseKnownUris() throws Exception {
    RedisURI localhost = RedisURI.create("localhost", 6479);
    RedisURI otherhost = RedisURI.create("127.0.0.2", 7000);
    RedisURI host3 = RedisURI.create("127.0.0.3", 7000);
    String viewByLocalhost = "1 127.0.0.1:6479 master,myself - 0 1401258245007 2 connected 8000-11999\n" + "2 127.0.0.2:7000 master - 111 1401258245007 222 connected 7000 12000 12002-16383\n" + "3 127.0.0.3:7000 master - 111 1401258245007 222 connected 7000 12000 12002-16383\n";
    String viewByOtherhost = "1 127.0.0.1:6479 master - 0 1401258245007 2 connected 8000-11999\n" + "2 127.0.0.2:7000 master,myself - 111 1401258245007 222 connected 7000 12000 12002-16383\n" + "3 127.0.0.3:7000 master - 111 1401258245007 222 connected 7000 12000 12002-16383\n";
    NodeTopologyView localhostView = new NodeTopologyView(localhost, viewByLocalhost, "", 0);
    NodeTopologyView otherhostView = new NodeTopologyView(otherhost, viewByOtherhost, "", 0);
    NodeTopologyViews nodeTopologyViews = new NodeTopologyViews(Arrays.asList(localhostView, otherhostView));
    Set<RedisURI> clusterNodes = nodeTopologyViews.getClusterNodes();
    assertThat(clusterNodes).contains(localhost, otherhost, host3);
}