Java Code Examples for java.util.Set

The following are top voted examples for showing how to use java.util.Set. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: lettuce   File: SortedSetCommandTest.java View source code 7 votes vote down vote up
protected void setup100KeyValues(Set<String> expect) {
    for (int i = 0; i < 100; i++) {
        redis.zadd(key + 1, i, value + i);
        redis.zadd(key, i, value + i);
        expect.add(value + i);
    }

}
 
Example 2
Project: raylew_algorithm   File: ????.java View source code 7 votes vote down vote up
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 3
Project: lettuce   File: RedisURI.java View source code 6 votes vote down vote up
private static Builder configureStandalone(URI uri) {
    Builder builder;
    Set<String> allowedSchemes = ImmutableSet.of(URI_SCHEME_REDIS, URI_SCHEME_REDIS_SECURE, URI_SCHEME_REDIS_SOCKET);

    if (!allowedSchemes.contains(uri.getScheme())) {
        throw new IllegalArgumentException("Scheme " + uri.getScheme() + " not supported");
    }

    if (URI_SCHEME_REDIS_SOCKET.equals(uri.getScheme())) {
        builder = Builder.socket(uri.getPath());
    } else {
        if (uri.getPort() > 0) {
            builder = Builder.redis(uri.getHost(), uri.getPort());
        } else {
            builder = Builder.redis(uri.getHost());
        }
    }

    if (URI_SCHEME_REDIS_SECURE.equals(uri.getScheme())) {
        builder.withSsl(true);
    }
    return builder;
}
 
Example 4
Project: lettuce   File: SetCommandTest.java View source code 6 votes vote down vote up
@Test
public void sscanMultiple() throws Exception {

    Set<String> expect = new HashSet<String>();
    Set<String> check = new HashSet<String>();
    setup100KeyValues(expect);

    ValueScanCursor<String> cursor = redis.sscan(key, ScanArgs.Builder.limit(5));

    assertThat(cursor.getCursor()).isNotNull();
    assertNotEquals("0", cursor.getCursor());
    assertThat(cursor.isFinished()).isFalse();

    check.addAll(cursor.getValues());

    while (!cursor.isFinished()) {
        cursor = redis.sscan(key, cursor);
        check.addAll(cursor.getValues());
    }

    assertThat(new TreeSet<String>(check)).isEqualTo(new TreeSet<String>(expect));
}
 
Example 5
Project: sphereMiners   File: DumbMiner.java View source code 6 votes vote down vote up
private void endGame() {
    for (Sphere ownSphere : ownSpheres) {
        Position ownPos = ownSphere.getPosition();
        Position nextEnemy = null;

        // check if a mine is possible
        Set<Sphere> enemySpheres = getSurroundingEnemies(ownSphere);
        if (enemySpheres.size() > 0) {
            double minDist = Double.MAX_VALUE;
            for (Sphere enemy : enemySpheres){
                if (ownSphere.canBeMergedWidth(enemy)) {
                    mining.put(ownSphere, enemy);
                    break;
                } else if (minDist > ownPos.dist(enemy.getPosition())
                           && ownSphere.getSize() > enemy.getSize() + 30){
                    nextEnemy = enemy.getPosition();
                    minDist = ownPos.dist(nextEnemy);
                }
            }
        }

        //change direction to get to next enemy (if there is one in sight)
        if (nextEnemy != null) {
            final Position moveTo = nextEnemy.sub(ownSphere.getPosition());
            newDirections.put(ownSphere, moveTo);

        // no enemy in sight so just fetch some dots
        } else {
            fetchDots(ownSphere);
        }
    }
}
 
Example 6
Project: strongback-java   File: PropertiesUtils.java View source code 6 votes vote down vote up
private static String resolve(String key, Properties props, Set<String> visted) throws InvalidPropertiesException {
    if(visted.contains(key)) throw new InvalidPropertiesException(key + " is defined cyclically.");
    visted.add(key);
    
    if(!props.containsKey(key)) {
        if(System.getProperty(key)!=null) return System.getProperty(key);
        throw new InvalidPropertiesException(key + " is undefined.");
    }
    
    String value = props.getProperty(key);
    
    //One or more of any character preceded by ${ and followed by } but not including them
    Matcher grabber = Pattern.compile("(?<=\\$\\{).+(?=\\})").matcher(value);
    
    Set<String> toResolve = new HashSet<>();
    while(grabber.find()) {
        toResolve.add(grabber.group());
    }
    // No further resolution is needed
    if(toResolve.isEmpty()) return value;
    
    for(String s : toResolve) {
        String resolution = resolve(s, props, visted);
        value = value.replace("${"+s+"}", resolution);
    }
    
    // Set the value so it doesn't need to be resolved again later
    props.setProperty(key, value);
    return value;
}
 
Example 7
Project: aws-toolkit-eclipse   File: QueryEditor.java View source code 6 votes vote down vote up
private synchronized void initializeElements() {
    if ( this.elements == null && this.input != null ) {
        List<SimpleDBItem> items = new LinkedList<SimpleDBItem>();
        Set<String> columns = new LinkedHashSet<String>();

        for ( Item item : this.input.getItems() ) {
            SimpleDBItem e = new SimpleDBItem(item);
            columns.addAll(e.columns);
            items.add(e);
        }
        this.elements = items.toArray();
        this.columns = columns.toArray(new String[columns.size()]);
    }
}
 
Example 8
Project: aws-toolkit-eclipse   File: DynamoDBTableEditor.java View source code 6 votes vote down vote up
private synchronized void initializeElements() {
    if ( elementList.isEmpty() && input != null ) {

        Set<String> columns = new HashSet<String>();

        for ( Map<String, AttributeValue> item : input ) {
            columns.addAll(item.keySet());
        }
        // We add the hash and range keys back in at the beginning, so
        // remove them for now
        columns.remove(tableKey.getHashKeyAttributeName());
        if ( tableKey.hasRangeKey() ) {
            columns.remove(tableKey.getRangeKeyAttributeName());
        }

        List<String> sortedColumns = new ArrayList<String>();
        sortedColumns.addAll(columns);
        Collections.sort(sortedColumns);

        sortedColumns.add(0, tableKey.getHashKeyAttributeName());
        if ( tableKey.hasRangeKey() ) {
            sortedColumns.add(1, tableKey.getRangeKeyAttributeName());
        }

        synchronized (knownAttributes) {
            knownAttributes.addAll(sortedColumns);
        }

        elementList.addAll(input);
        // empty row at the end for adding new rows
        elementList.add(new HashMap<String, AttributeValue>());

        this.columns.addAll(sortedColumns);
    }
}
 
Example 9
Project: iswc2012metadata   File: ToolJena.java View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
	public static Set listLinkedResources(Model m){
		Set<RDFNode> ret = m.listObjects().toSet();
		ret.addAll(m.listSubjects().toSet());
		ret.removeAll(m.listObjectsOfProperty(RDF.type).toSet());

		Iterator<RDFNode> iter = ret.iterator();
		while (iter.hasNext()){
			RDFNode node = iter.next();
			if (!node.isURIResource()){
				iter.remove();
				continue;
			}
			//to simplify the case, only include Resource with URI
			try {
				DataQname dq = DataQname.create(getNodeString(node), getNodePrefix(node));
				if (dq.hasLocalname()){
					iter.remove();
					continue;
				}
			} catch (Sw4jException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
/*			//as of now, skip obvious non-rdf data by file extension
			String uri = node.toString().toLowerCase();
			final String [] FILTER = new String []{
				".jpeg",	
				".jpg",	
				".png",	
				".gif",	
			};
			for (int i=0; i<FILTER.length; i++){
				if (uri.endsWith(FILTER[i]))
					iter.remove();
			}
*/		}
		
		return ret;
	}
 
Example 10
Project: virgo.kernel   File: DependencyCalculator.java View source code 6 votes vote down vote up
private Set<BundleDescription> getNewImmediateDependencies(BundleDescription bundle, Collection<BundleDescription> newBundles) {
    Set<BundleDescription> immediateDependencies = new HashSet<BundleDescription>();
    immediateDependencies.addAll(Arrays.asList(bundle.getFragments()));
    immediateDependencies.addAll(Arrays.asList(bundle.getResolvedRequires()));
    immediateDependencies.addAll(getPackageProviders(bundle));

    HostSpecification hostSpecification = bundle.getHost();
    if (hostSpecification != null) {
        for (BundleDescription host : hostSpecification.getHosts()) {
            immediateDependencies.add(host);
        }
    }
    immediateDependencies.retainAll(newBundles);
    return immediateDependencies;
}
 
Example 11
Project: virgo.kernel   File: DeadlockMonitor.java View source code 6 votes vote down vote up
/**
 * [email protected]}
 */
public void run() {
    synchronized (this.monitor) {
        Deadlock[] deadlocks = this.analyser.findDeadlocks();
        if (deadlocks != null && deadlocks.length > 0) {
            Set<Deadlock> asSet = Sets.asSet(deadlocks);
            if (!asSet.equals(this.lastSeenDeadlocks)) {
                this.eventLogger.log(ConcurrentLogEvents.DEADLOCK_DETECTED);
                this.dumpGenerator.generateDump("deadlock");
                this.lastSeenDeadlocks.clear();
                this.lastSeenDeadlocks.addAll(asSet);
            }
        } else {
            this.lastSeenDeadlocks.clear();
        }
    }
}
 
Example 12
Project: bixie   File: CdcChecker.java View source code 6 votes vote down vote up
private boolean isInLearnedConflicts(Set<BasicBlock> path) {
	for (Set<BasicBlock> conflict : learnedConflicts) {
		if (conflict.size() > 0 && path.size() > conflict.size()
				&& path.containsAll(conflict)) {
			return true;
		}
	}
	return false;
}
 
Example 13
Project: lizard   File: ClusterMonitor.java View source code 6 votes vote down vote up
@Override
public void process(WatchedEvent event) throws Exception {
    if ( ! watching )
        // and don't rearm.
        return ;
    log.debug("WATCH: type = " + event.getType()) ;
    log.debug("WATCH: path = " + event.getPath()) ;
    // reload if not closing
    List<String> x = Cluster.members() ;

    Set<String> current2 = new HashSet<>() ;
    current2.addAll(x) ;

    Set<String> leavers = SetUtils.difference(current, current2) ;
    Set<String> arrivals = SetUtils.difference(current2, current) ;

    leavers.forEach(s ->  log.info("Leave:   " +s));
    arrivals.forEach(s -> log.info("Arrival: " +s));
    current = current2 ;
    arm() ;
}
 
Example 14
Project: extFM-Tooling   File: Util.java View source code 6 votes vote down vote up
/**
 * creates a view from the [email protected] FeatureModel}
 * 
 * @param featureModel the original [email protected] FeatureModel}
 * @param features which are part of the view.
 * @return a view from a [email protected] FeatureModel}
 */
public static FeatureModel createFeatureModel(FeatureModel featureModel, Set<Feature> features, Flag canBeConsistent) {
   FeatureModelHelper helper = new FeatureModelHelper(featureModel);
   if (helper.getAllFeatures().size() == features.size()) {
      return featureModel;
   }
   URI uri = featureModel.eResource().getURI().trimFileExtension().trimFragment();
   ResourceSet resourceSet = featureModel.eResource().getResourceSet();
   String uriString = uri.toString() + System.currentTimeMillis() + features.hashCode();
   // log.debug("FeaturemodelURI: " + uriString);
   uri = URI.createURI(uriString);
   uri = uri.appendFileExtension("feature");
   Resource resource = resourceSet.createResource(uri);
   FeatureModel view = EcoreUtil.copy(featureModel);
   traverseFeatureModelAndRemoveFeatures(view.getRoot(), features);
   FeatureModelHelper viewHelper = new FeatureModelHelper(view);
   if (viewHelper.getAllFeatures().size() == features.size()) {
      removeUnusedConstraints(view, featureModel, canBeConsistent);
      resource.getContents().add(view);
   } else {
      view = null;
   }
   return view;
}
 
Example 15
Project: jbosgi   File: FrameworkBootstrapService.java View source code 6 votes vote down vote up
private void setupIntegrationProperties(StartContext context, Map<String, String> props) {

        // Setup the Framework's storage area.
        String storage = props.get(Constants.FRAMEWORK_STORAGE);
        if (storage == null) {
            ServerEnvironment environment = injectedServerEnvironment.getValue();
            File dataDir = environment.getServerDataDir();
            storage = dataDir.getAbsolutePath() + File.separator + "osgi-store";
            props.put(Constants.FRAMEWORK_STORAGE, storage);
        }

        // Provide the ModuleLogger
        ModuleLogger moduleLogger = Module.getModuleLogger();
        if (moduleLogger != null)
            props.put(ModuleLogger.class.getName(), moduleLogger.getClass().getName());

        // Setup default system modules
        String sysmodules = props.get(PROP_JBOSS_OSGI_SYSTEM_MODULES);
        if (sysmodules == null) {
            Set<String> sysModules = new LinkedHashSet<String>();
            sysModules.addAll(Arrays.asList(SystemPackagesIntegration.DEFAULT_SYSTEM_MODULES));
            sysmodules = sysModules.toString();
            sysmodules = sysmodules.substring(1, sysmodules.length() - 1);
            props.put(PROP_JBOSS_OSGI_SYSTEM_MODULES, sysmodules);
        }

        // Setup default system packages
        String syspackages = (String) getPropertyWithSystemFallback(props, Constants.FRAMEWORK_SYSTEMPACKAGES);
        if (syspackages == null) {
            Set<String> sysPackages = new LinkedHashSet<String>();
            sysPackages.addAll(Arrays.asList(SystemPackagesIntegration.JAVAX_API_PACKAGES));
            sysPackages.addAll(Arrays.asList(SystemPaths.DEFAULT_FRAMEWORK_PACKAGES));
            sysPackages.addAll(Arrays.asList(SystemPackagesIntegration.DEFAULT_INTEGRATION_PACKAGES));
            syspackages = sysPackages.toString();
            syspackages = syspackages.substring(1, syspackages.length() - 1);
            props.put(Constants.FRAMEWORK_SYSTEMPACKAGES, syspackages);
        }

        String extrapackages = (String) getPropertyWithSystemFallback(props, Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA);
        if (extrapackages != null) {
            props.put(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, extrapackages);
        }
    }
 
Example 16
Project: google-web-toolkit-svnmirror   File: IdentitySets.java View source code 6 votes vote down vote up
public static <T> Set<T> normalize(Set<T> set) {
  switch (set.size()) {
    case 0:
      return create();
    case 1: {
      if (set.getClass() == SINGLETON_SET_CLASS) {
        return set;
      }
      return create(set.iterator().next());
    }
    default:
      if (set.getClass() == MULTI_SET_CLASS) {
        return set;
      }
      IdentityHashSet<T> result = new IdentityHashSet<T>();
      result.addAll(set);
      return result;
  }
}
 
Example 17
Project: word2vec-query-expansion   File: Distance.java View source code 5 votes vote down vote up
public static List<ScoredTerm> measure(Vectors vectors, int wordsToReturn, String[] tokens)
        throws OutOfVocabularyException {
    double distance, length;
    float[] bestDistance = new float[wordsToReturn];
    String[] bestWords = new String[wordsToReturn];
    int d;
    int size = vectors.vectorSize();
    float[] vec = new float[size];
    float[][]allVec = vectors.getVectors();

    Set<Integer> wordIdx = new TreeSet<Integer>();

    int tokenCount = tokens.length;
    boolean outOfDict = false;
    String outOfDictWord = null;
    Arrays.fill(vec, 0.0f);
    wordIdx.clear();
    for (int i = 0; i < tokenCount; i++) {
        Integer idx = vectors.getIndexOrNull(tokens[i]);
        if (idx == null) {
            outOfDictWord = tokens[i];
            outOfDict = true;
            break;
        }
        wordIdx.add(idx);
        float[] vect1 = allVec[idx];
        for (int j = 0; j < size; j++)
            vec[j] += vect1[j];
    }
    if (outOfDict)
        throw new OutOfVocabularyException(outOfDictWord);

    length = 0;
    for (int i = 0; i < size; i++)
        length += vec[i] * vec[i];
    length = (float) Math.sqrt(length);
    for (int i = 0; i < size; i++)
        vec[i] /= length;

    for (int i = 0; i < wordsToReturn; i++) {
        bestDistance[i] = Float.MIN_VALUE;
        bestWords[i] = "";
    }

    for (int c = 0; c < vectors.wordCount(); c++) {
        if (wordIdx.contains(c))
            continue;
        distance = 0;
        for (int i = 0; i < size; i++)
            distance += vec[i] * allVec[c][i];
        for (int i = 0; i < wordsToReturn; i++) {
            if (distance > bestDistance[i]) {
                for (d = wordsToReturn - 1; d > i; d--) {
                    bestDistance[d] = bestDistance[d - 1];
                    bestWords[d] = bestWords[d - 1];
                }
                bestDistance[i] = (float) distance;
                bestWords[i] = vectors.getTerm(c);
                break;
            }
        }
    }
    List<ScoredTerm> result = new ArrayList<ScoredTerm>(wordsToReturn);
    for (int i = 0; i < wordsToReturn; i++)
        result.add(new ScoredTerm(bestWords[i], bestDistance[i]));
    return result;
}