Java Code Examples for java.util.Set#size()

The following examples show how to use java.util.Set#size() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: QuantityTypeArithmeticGroupFunction.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public State calculate(Set<Item> items) {
    if (items == null || items.size() <= 0) {
        return UnDefType.UNDEF;
    }

    QuantityType<?> sum = null;
    for (Item item : items) {
        if (isSameDimension(item)) {
            QuantityType itemState = item.getStateAs(QuantityType.class);
            if (itemState != null) {
                if (sum == null) {
                    sum = itemState; // initialise the sum from the first item
                } else if (sum.getUnit().isCompatible(itemState.getUnit())) {
                    sum = sum.add(itemState);
                }
            }
        }
    }

    return sum != null ? sum : UnDefType.UNDEF;
}
 
Example 2
Source File: GoogleAPISearcher.java    From SEAL with Apache License 2.0 6 votes vote down vote up
public static void main(String args[]) {
  int numResults = 64;
  GoogleAPISearcher gs = new GoogleAPISearcher();
  gs.setLangID("en");
  gs.setCacheDir(new File("/www.cache/"));
  gs.setNumResults(numResults);
  gs.setTimeOutInMS(10*1000);
  gs.setMaxDocSizeInKB(512);
  gs.addQuery("(\"Richard C. Wang\" OR \"David C. Wang\")", false);
  gs.run();
  Set<Snippet> snippets = gs.getSnippets();
  for (Snippet snippet : snippets)
    log.info(snippet);
  if (numResults == snippets.size())
    log.info("Test succeeded!");
  else log.error("Test failed! Expecting: " + numResults + " Actual: " + snippets.size());
}
 
Example 3
Source File: ActiveObjectMap.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public  boolean hasMultipleIDs(AOMEntry value)
{
    Set set = (Set)entryToKeys.get( value ) ;
    if (set == null)
        return false ;
    return set.size() > 1 ;
}
 
Example 4
Source File: FactoryBuilder.java    From butterfly-di-container with Apache License 2.0 5 votes vote down vote up
private Constructor findMatchingConstructor(Class theClass, Class[] factoryReturnTypes, Class[] forcedArgumentTypes) {
    if(factoryReturnTypes.length != forcedArgumentTypes.length){
        throw new IllegalArgumentException("The factoryReturnTypes and the forcedArgumentTypes arrays must be of equal length.");
    }
    Constructor[]    allConstructors = theClass.getConstructors();
    Set<Constructor> bestMatches     = new HashSet<Constructor>();
    int              bestMatchLevel  = NO_MATCH;

    for(Constructor constructor : allConstructors){
        Class[] candidateArgTypes = constructor.getParameterTypes();
        if(candidateArgTypes.length != factoryReturnTypes.length) continue;

        int candidateMatchLevel = argumentMatch(candidateArgTypes, factoryReturnTypes, forcedArgumentTypes);

        if(candidateMatchLevel == NO_MATCH){
            //do nothing, ignore constructor
        } else if(candidateMatchLevel > bestMatchLevel){
            bestMatches.clear();
            bestMatches.add(constructor);
            bestMatchLevel = candidateMatchLevel;
        } else if(candidateMatchLevel == bestMatchLevel){
            bestMatches.add(constructor);
        }
    }

    if(bestMatches.size() == 0){
        throw new ParserException(
                "FactoryBuilder", "CONSTRUCTOR_FACTORY_ERROR",
                "No constructors in " + theClass + " matched the return types of the argument factories: " +
                        toClassNames(factoryReturnTypes));
    } else if(bestMatches.size() > 1){
        throw new ParserException(
                "FactoryBuilder", "CONSTRUCTOR_FACTORY_ERROR",
                "More than one constructor in " + theClass +" matched the return types of the argument factories:" +
                        toClassNames(factoryReturnTypes));
    }

    return bestMatches.iterator().next();
}
 
Example 5
Source File: QuickDayTest.java    From htm.java with GNU Affero General Public License v3.0 5 votes vote down vote up
public int[] getSDR(Set<Cell> cells) {
    int[] retVal = new int[cells.size()];
    int i = 0;
    for(Iterator<Cell> it = cells.iterator();i < retVal.length;i++) {
        retVal[i] = it.next().getIndex();
        retVal[i] /= cellsPerColumn; // Get the column index
    }
    Arrays.sort(retVal);
    retVal = ArrayUtils.unique(retVal);

    return retVal;
}
 
Example 6
Source File: OpExecutorImplJUnitTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public Connection exchangeConnection(Connection conn, Set excludedServers,
    long aquireTimeout) {
  if(excludedServers.size() >= numServers) {
    throw new NoAvailableServersException();
  }
  exchanges++;
  return new DummyConnection(new ServerLocation("localhost", currentServer++ % numServers));
}
 
Example 7
Source File: SimpleRegistryService.java    From dubbox-hystrix with Apache License 2.0 5 votes vote down vote up
public void unregister(URL url) {
    String client = RpcContext.getContext().getRemoteAddressString();
    Set<URL> urls = remoteRegistered.get(client);
    if (urls != null && urls.size() > 0) {
        urls.remove(url);
    }
    super.unregister(url);
    unregistered(url);
}
 
Example 8
Source File: ParallelListResourceBundle.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
@Override
public int size() {
    if (parent == null) {
        return set.size();
    }
    Set<String> allset = new HashSet<>(set);
    allset.addAll(parent.keySet());
    return allset.size();
}
 
Example 9
Source File: LoadBalanceSelector.java    From twister2 with Apache License 2.0 5 votes vote down vote up
@Override
public void prepare(Communicator comm, Set<Integer> sources, Set<Integer> destinations) {
  for (int s : sources) {
    ArrayList<Integer> destList = new ArrayList<>(destinations);
    destination.put(s, destList);
    destinationIndexes.put(s, 0);
    HashMap<Integer, Integer> value = new HashMap<>();
    invertedIndexes.put(s, value);
    for (int i = 0; i < destinations.size(); i++) {
      value.put(destList.get(i), i);
    }
  }
}
 
Example 10
Source File: SnapshotScannerHDFSAclController.java    From hbase with Apache License 2.0 5 votes vote down vote up
@Override
public void postCompletedDeleteTableAction(ObserverContext<MasterCoprocessorEnvironment> ctx,
    TableName tableName) throws IOException {
  if (!tableName.isSystemTable() && checkInitialized("deleteTable " + tableName)) {
    /*
     * Remove table user access HDFS acl from namespace directory if the user has no permissions
     * of global, ns of the table or other tables of the ns, eg: Bob has 'ns1:t1' read permission,
     * when delete 'ns1:t1', if Bob has global read permission, '@ns1' read permission or
     * 'ns1:other_tables' read permission, then skip remove Bob access acl in ns1Dirs, otherwise,
     * remove Bob access acl.
     */
    try (Table aclTable =
        ctx.getEnvironment().getConnection().getTable(PermissionStorage.ACL_TABLE_NAME)) {
      Set<String> users = SnapshotScannerHDFSAclStorage.getTableUsers(aclTable, tableName);
      if (users.size() > 0) {
        // 1. Remove table archive directory default ACLs
        hdfsAclHelper.removeTableDefaultAcl(tableName, users);
        // 2. Delete table owner permission is synced to HDFS in acl table
        SnapshotScannerHDFSAclStorage.deleteTableHdfsAcl(aclTable, tableName);
        // 3. Remove namespace access acls
        Set<String> removeUsers = filterUsersToRemoveNsAccessAcl(aclTable, tableName, users);
        if (removeUsers.size() > 0) {
          hdfsAclHelper.removeNamespaceAccessAcl(tableName, removeUsers, "delete");
        }
      }
    }
  }
}
 
Example 11
Source File: ValidationKeysAuditorTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
private void prepareConfluenceSummary(final Set<String> untestedKeys, final StringBuilder output, final String newLine) {
    final int total = allKeys.size();
    final int untested = untestedKeys.size();
    final int tested = total - untested;
    final double coverage = (((tested + 0.0) / (total + 0.0)) * 100);
    output.append("{warning:title=Warning}This page is auto-generated. Any manual changes would be over-written the next time this page is regenerated{warning}").append(
        newLine);
    output.append("{info:title=Audit Result}h2.Out of a total of ").append(total).append(" keys, ").append(tested).append(" have been tested. Test coverage for keys is ").append(coverage).append(" %.{info}")
        .append(newLine);
}
 
Example 12
Source File: ImportServiceImpl.java    From studio with GNU General Public License v3.0 5 votes vote down vote up
/**
 * publish items
 *
 * @param site
 * @param publishChannelGroup
 * @param targetRoot
 * @param fullPaths
 * @param chunkSize
 */
protected void publish(String site, String publishChannelGroup, String targetRoot, List<String> fullPaths,
                       int chunkSize) {
    if (chunkSize < 1) {
        logger.info("[IMPORT] publising chunk size not defined. publishing all together.");
        submitToGoLive(site, publishChannelGroup, fullPaths);
    } else {
        int total = fullPaths.size();
        int count = 0;
        // group pages in a small chucks
        Set<String> goLiveItemPaths = new HashSet<String>(chunkSize);
        List<String> goLiveItemFullPaths = new ArrayList<String>(chunkSize);
        for (String importedFullPath : fullPaths) {
            logger.debug("		" + importedFullPath);
            if (goLiveItemFullPaths.size() < chunkSize) {
                goLiveItemFullPaths.add(importedFullPath);
                String goLiveItemPath = importedFullPath.replaceFirst(targetRoot, "");
                goLiveItemPaths.add(goLiveItemPath);
                count++;
            }
            if (goLiveItemPaths.size() == chunkSize) {
                logger.info("[IMPORT] submitting " + chunkSize + " imported files to " + publishChannelGroup
                        + " (" + count + "/" + total + ")");

                submitToGoLive(site, publishChannelGroup, goLiveItemFullPaths);
                goLiveItemPaths = new HashSet<String>(chunkSize);
                goLiveItemFullPaths = new ArrayList<String>(chunkSize);
            }
        }
        // submit the last set
        if (goLiveItemPaths.size() < chunkSize) {
            logger.info("[IMPORT] submitting " + chunkSize + " imported files to " + publishChannelGroup + " ("
                        + count + "/" + total + ")");
            submitToGoLive(site, publishChannelGroup, goLiveItemFullPaths);
            goLiveItemPaths = new HashSet<String>(chunkSize);
            goLiveItemFullPaths = new ArrayList<String>(chunkSize);
        }
    }
}
 
Example 13
Source File: Bluetooth.java    From Makeblock-App-For-Android with MIT License 5 votes vote down vote up
public List<String> getPairedList(){
       List<String> data = new ArrayList<String>();
       Set<BluetoothDevice> pairedDevices = mBTAdapter.getBondedDevices();
       prDevices.clear();
	if (pairedDevices.size() > 0) {
           for (BluetoothDevice device : pairedDevices) {
               prDevices.add(device);
           }
       }
       for(BluetoothDevice dev : prDevices){
       	String s = dev.getName();
       	s=s+" "+dev.getAddress();
       	if(connDev!=null && connDev.equals(dev)){
       		s="-> "+s;
       	}
       	data.add(s);
       }
       return data;
}
 
Example 14
Source File: LargeEnumIteratorRemoveResilience.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void checkSetAfterRemoval(final Set<LargeEnum> set,
        final int origSize, final LargeEnum removedElement)
        throws Exception {
    if (set.size() != (origSize - 1)) {
        throw new Exception("Test FAILED: Unexpected set size after removal; expected '" + (origSize - 1) + "' but found '" + set.size() + "'");
    }
    if (set.contains(removedElement)) {
        throw new Exception("Test FAILED: Element returned from iterator unexpectedly still in set after removal.");
    }
}
 
Example 15
Source File: AttributeValueImpl.java    From smithy with Apache License 2.0 5 votes vote down vote up
@Override
public AttributeValue getProperty(String property) {
    Set<Shape> shapes = vars.getOrDefault(property, Collections.emptySet());
    List<AttributeValue> values = new ArrayList<>(shapes.size());
    for (Shape shape : shapes) {
        values.add(AttributeValue.shape(shape, vars));
    }
    return AttributeValue.projection(values);
}
 
Example 16
Source File: ApkSigningBlockUtils.java    From Xpatch with Apache License 2.0 5 votes vote down vote up
public static Map<ContentDigestAlgorithm, byte[]> computeContentDigests(
            RunnablesExecutor executor,
            Set<ContentDigestAlgorithm> digestAlgorithms,
            DataSource beforeCentralDir,
            DataSource centralDir,
            DataSource eocd) throws IOException, NoSuchAlgorithmException, DigestException {
        Map<ContentDigestAlgorithm, byte[]> contentDigests = new HashMap<>();
        // 不使用stream,以兼容android6以及一下
//        Set<ContentDigestAlgorithm> oneMbChunkBasedAlgorithm = digestAlgorithms.stream()
//                .filter(a -> a == ContentDigestAlgorithm.CHUNKED_SHA256 ||
//                             a == ContentDigestAlgorithm.CHUNKED_SHA512)
//                .collect(Collectors.toSet());

        Set<ContentDigestAlgorithm> oneMbChunkBasedAlgorithm = new HashSet<>();
        if (digestAlgorithms != null && digestAlgorithms.size() > 0) {
            for (ContentDigestAlgorithm a : digestAlgorithms) {
                if (a == ContentDigestAlgorithm.CHUNKED_SHA256 ||
                        a == ContentDigestAlgorithm.CHUNKED_SHA512) {
                    oneMbChunkBasedAlgorithm.add(a);
                }
            }
        }

        computeOneMbChunkContentDigests(
                executor,
                oneMbChunkBasedAlgorithm,
                new DataSource[] { beforeCentralDir, centralDir, eocd },
                contentDigests);

        if (digestAlgorithms.contains(ContentDigestAlgorithm.VERITY_CHUNKED_SHA256)) {
            computeApkVerityDigest(beforeCentralDir, centralDir, eocd, contentDigests);
        }
        return contentDigests;
    }
 
Example 17
Source File: FlinkPulsarITest.java    From pulsar-flink with Apache License 2.0 5 votes vote down vote up
@Override
public void flatMap(Row value, Collector<Row> out) throws Exception {
    String topic = (String) value.getField(2);
    int v = Integer.parseInt(value.getField(0).toString());
    List<Integer> current = map.getOrDefault(topic, new ArrayList<>());
    current.add(v);
    map.put(topic, current);

    count++;

    if (count == total) {
        for (Map.Entry<String, List<Integer>> e : map.entrySet()) {
            Set<Integer> s = new HashSet<>(e.getValue());
            if (s.size() != e.getValue().size()) {
                throw new RuntimeException("duplicate elements in " + topic + " " + e.getValue().toString());
            }
            Set<Integer> expectedSet = expected.getOrDefault(e.getKey(), null);
            if (expectedSet == null) {
                throw new RuntimeException("Unknown topic seen " + e.getKey());
            } else {
                if (!expectedSet.equals(s)) {
                    throw new RuntimeException("" + expectedSet + "\n" + s);
                }
            }
        }
        throw new SuccessException();
    }
}
 
Example 18
Source File: ServicesPageHandler.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public Page handle(URL url) {
    Set<String> services = RegistryContainer.getInstance().getServices();
    List<List<String>> rows = new ArrayList<List<String>>();
    int providerCount = 0;
    int consumerCount = 0;
    if (services != null && services.size() > 0) {
        for (String service : services) {
            List<URL> providers = RegistryContainer.getInstance().getProvidersByService(service);
            int providerSize = providers == null ? 0 : providers.size();
            providerCount += providerSize;
            List<URL> consumers = RegistryContainer.getInstance().getConsumersByService(service);
            int consumerSize = consumers == null ? 0 : consumers.size();
            consumerCount += consumerSize;
            List<String> row = new ArrayList<String>();
            row.add(service);
            if (providerSize > 0 || consumerSize > 0) {
                if (providerSize > 0) {
                    URL provider = providers.iterator().next();
                    row.add(provider.getParameter(Constants.APPLICATION_KEY, ""));
                    row.add(provider.getParameter("owner", "") + (provider.hasParameter("organization") ?  " (" + provider.getParameter("organization") + ")" : ""));
                } else {
                    row.add("");
                    row.add("");
                }
                row.add(providerSize == 0 ? "<font color=\"red\">No provider</a>" : "<a href=\"providers.html?service=" + service + "\">Providers(" + providerSize + ")</a>");
                row.add(consumerSize == 0 ? "<font color=\"blue\">No consumer</a>" : "<a href=\"consumers.html?service=" + service + "\">Consumers(" + consumerSize + ")</a>");
                row.add("<a href=\"statistics.html?service=" + service + "\">Statistics</a>");
                row.add("<a href=\"charts.html?service=" + service + "\">Charts</a>");
                rows.add(row);
            }
        }
    }
    return new Page("Services", "Services (" + rows.size() + ")",
            new String[] { "Service Name:", "Application", "Owner", "Providers(" + providerCount + ")", "Consumers(" + consumerCount + ")", "Statistics", "Charts" }, rows);
}
 
Example 19
Source File: HostXml_6.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
protected void parseStaticDiscoveryOption(final XMLExtendedStreamReader reader, final ModelNode address, final List<ModelNode> list, final Set<String> staticDiscoveryOptionNames) throws XMLStreamException {

        // OP_ADDR will be set after parsing the NAME attribute
        final ModelNode staticDiscoveryOptionAddress = address.clone();
        staticDiscoveryOptionAddress.add(CORE_SERVICE, DISCOVERY_OPTIONS);
        final ModelNode addOp = Util.getEmptyOperation(ADD, new ModelNode());
        list.add(addOp);

        // Handle attributes
        final Set<Attribute> required = EnumSet.of(Attribute.NAME, Attribute.HOST, Attribute.PORT);
        final int count = reader.getAttributeCount();
        for (int i = 0; i < count; i++) {
            requireNoNamespaceAttribute(reader, i);
            final String value = reader.getAttributeValue(i);
            final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
            required.remove(attribute);
            switch (attribute) {
                case NAME: {
                    if (!staticDiscoveryOptionNames.add(value)) {
                        throw ParseUtils.duplicateNamedElement(reader, value);
                    }
                    addOp.get(OP_ADDR).set(staticDiscoveryOptionAddress).add(STATIC_DISCOVERY, value);
                    break;
                }
                case HOST: {
                    StaticDiscoveryResourceDefinition.HOST.parseAndSetParameter(value, addOp, reader);
                    break;
                }
                case PROTOCOL: {
                    StaticDiscoveryResourceDefinition.PROTOCOL.parseAndSetParameter(value, addOp, reader);
                    break;
                }
                case PORT: {
                    StaticDiscoveryResourceDefinition.PORT.parseAndSetParameter(value, addOp, reader);
                    break;
                }
                default:
                    throw unexpectedAttribute(reader, i);
            }
        }

        if (required.size() > 0) {
            throw missingRequired(reader, required);
        }

        requireNoContent(reader);
    }
 
Example 20
Source File: FilterPipeline.java    From AILibs with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public DataSet applyFilter(final DataSet data, final boolean copy) throws InterruptedException {
	if (this.filters == null) {
		return data;
	}

	// Copy graph
	Graph<FilterDataEntry> dataGraph = this.copyGraphIntoDataGraph();

	// Create a new data copy for each leaf node
	List<FilterDataEntry> leafNodes = new ArrayList<>(dataGraph.getSinks());
	HashSet<FilterDataEntry> nextNodes = new HashSet<>();
	for (FilterDataEntry entry : leafNodes) {
		entry.dataset = entry.filter.applyFilter(data, true);
		nextNodes.addAll(dataGraph.getPredecessors(entry));
	}

	// Iterate through graph to generate data sets by applying filters
	while (!nextNodes.isEmpty()) {
		if (Thread.currentThread().isInterrupted()) {
			throw new InterruptedException("Execution of filter pipeline got interrupted.");
		}
		FilterDataEntry nextEntry = pollRandomElementFromSet(nextNodes);

		if (nextEntry == null) {
			throw new IllegalStateException("Could not poll first entry from tree set which is not empty.");
		}

		// Detect cycles
		if (nextEntry.dataset != null) {
			logger.warn("Detected cycle in the filter graph.");
		} else {
			boolean addPredecessors = true;

			// Check for union
			Set<FilterDataEntry> successors = dataGraph.getSuccessors(nextEntry);
			if (successors.isEmpty()) {
				throw new IllegalStateException("Entry propagated to the working set by a successor should have successors.");
			}
			if (successors.size() > 1) {
				// Union
				Iterator<FilterDataEntry> it = successors.iterator();
				FilterDataEntry succ1 = it.next();
				FilterDataEntry succ2 = it.next();

				if (succ1.dataset == null || succ2.dataset == null) {
					nextNodes.add(nextEntry);
					continue;
				}

				nextEntry.dataset = nextEntry.filter.applyFilter(UnionFilter.union(succ1.dataset, succ2.dataset), false);
				dataGraph = this.eraseSubTreeData(dataGraph, nextEntry);

			} else {
				FilterDataEntry successor = successors.iterator().next();
				if (successor.dataset != null) {
					nextEntry.dataset = nextEntry.filter.applyFilter(successor.dataset, false);
				} else {
					nextNodes.add(nextEntry);
					addPredecessors = false;
				}
			}
			if (addPredecessors) {
				// Add predecessors to working set
				nextNodes.addAll(dataGraph.getPredecessors(nextEntry));
			}
		}
	}

	DataSet resultDataSet = data;
	if (!dataGraph.getItems().isEmpty()) {
		resultDataSet = dataGraph.getRoot().dataset;
	}

	// Update intermediate instances into Weka instances
	logger.debug("Updating instances...");
	resultDataSet.updateInstances();
	logger.debug("Done.");
	return resultDataSet;
}