size ( )源码实例Demo

java.util.LinkedHashSet#size ( )源码实例Demo

下面列出了java.util.LinkedHashSet#size ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: Concurnas   文件: LowestCommonAncestor.java
private LinkedHashSet<NamedType> getShortestList(ArrayList<LinkedHashSet<NamedType>> searchLists)
{
	LinkedHashSet<NamedType> shortSoFar = null;
	int shotest = -1;
	
	for(LinkedHashSet<NamedType> s : searchLists)
	{
		if(shotest == -1)
		{
			shortSoFar = s;
			shotest = s.size();
		}
		else
		{
			int ss = s.size();
			if(ss < shotest)
			{
				shortSoFar = s;
				shotest = ss;
			}
		}
		
	}
	
	return shortSoFar;
}
 
/** Returns one handler for as many reporters as exist. */
@Bean
SpanHandler zipkinSpanHandler(@Nullable List<Reporter<Span>> spanReporters,
		@Nullable Tag<Throwable> errorTag) {
	if (spanReporters == null) {
		return SpanHandler.NOOP;
	}

	LinkedHashSet<Reporter<Span>> reporters = new LinkedHashSet<>(spanReporters);
	reporters.remove(Reporter.NOOP);
	if (spanReporters.isEmpty()) {
		return SpanHandler.NOOP;
	}

	Reporter<Span> spanReporter = reporters.size() == 1 ? reporters.iterator().next()
			: new CompositeSpanReporter(reporters.toArray(new Reporter[0]));

	ZipkinSpanHandler.Builder builder = ZipkinSpanHandler.newBuilder(spanReporter);
	if (errorTag != null) {
		builder.errorTag(errorTag);
	}
	return builder.build();
}
 
源代码3 项目: pentaho-reporting   文件: PasswordPolicyManager.java
private LinkedHashSet<String> getFilesAsList()
  throws BackingStoreException {
  final LinkedHashSet<String> retval = new LinkedHashSet<String>();
  final String[] strings = properties.keys();
  final int maxFiles = Math.min( 10, strings.length );
  for ( int i = 0; i < maxFiles; i++ ) {
    final String key = strings[ i ];
    final String file = properties.get( key, null );

    if ( file == null ) {
      continue;
    }
    retval.add( file );
  }

  if ( retval.size() != strings.length ) {
    // store ..
    store( retval );
  }
  return retval;
}
 
源代码4 项目: gate-core   文件: Strings.java
/**
 * Get back a Map of String*String from its String representation.
 * Unescape backslashed separator characters.
 * @param string String to convert to a Map
 * @return a Map
 * @see #toString(java.util.Map)
 */
public static Map<String, String> toMap(String string) {
  Map<String, String> map = new HashMap<String, String>();
  if (string == null
   || string.length() < 3) {
    return map;
  }
  Set<String> firstList = toSet(string, ", ");
  for (String element : firstList) {
    LinkedHashSet<String> secondList = toSet("[" + element + "]", "=");
    if (secondList.size() == 2) {
      Iterator<String> iterator = secondList.iterator();
      map.put(iterator.next(), iterator.next());
    } else {
      Err.prln("Ignoring element: [" + element + "]");
      Err.prln("Expecting: [key=value]");
    }
  }
  return map;
}
 
源代码5 项目: clust4j   文件: LabelEncoder.java
public LabelEncoder(int[] labels) {
	VecUtils.checkDims(labels);
	
	final LinkedHashSet<Integer> unique = VecUtils.unique(labels);
	numClasses = unique.size();
	if(numClasses < 2 && !allowSingleClass()) {
		throw new IllegalArgumentException("y has "+numClasses+" unique class" 
			+ (numClasses!=1?"es":"") + " and requires at least two");
	}
	
	this.rawLabels = VecUtils.copy(labels);
	this.n = rawLabels.length;
	
	int idx = 0;
	this.classes = new int[numClasses];
	for(Integer u: unique) classes[idx++] = u.intValue();
	
	// Initialize mappings
	encodedMapping = new TreeMap<>();
	reverseMapping = new TreeMap<>();
	encodedLabels = new int[n];
}
 
源代码6 项目: proarc   文件: Authenticators.java
public List<Authenticator> getAuthenticators() {
    List<Object> authenticatorIds = conf.getList(PROPERTY_AUTHENTICATORS);
    LinkedHashSet<Object> ids = new LinkedHashSet<Object>(authenticatorIds);
    // ensure the ProArc authenticator used as a last resort
    ids.remove(TYPE_PROARC);
    ids.add(TYPE_PROARC);
    ArrayList<Authenticator> authenticators = new ArrayList<Authenticator>(ids.size());
    for (Object id : ids) {
        if (TYPE_PROARC.equals(id)) {
            authenticators.add(new ProArcAuthenticator());
        } else if (TYPE_DESA.equals(id)) {
            authenticators.add(new DESAAuthenticator());
        } else {
            LOG.warning("Unknown authenticator: " + id);
        }
    }
    return authenticators;
}
 
源代码7 项目: RoaringBitmap   文件: TestSerialization.java
private static int[] toArray(LinkedHashSet<Integer> integers) {
  int[] ints = new int[integers.size()];
  int i = 0;
  for (Integer n : integers) {
    ints[i++] = n;
  }
  return ints;
}
 
static LinkedHashSet<Cipher> defaultSort(final LinkedHashSet<Cipher> ciphers) {
    final LinkedHashSet<Cipher> result = new LinkedHashSet<>(ciphers.size());
    final LinkedHashSet<Cipher> ecdh = new LinkedHashSet<>(ciphers.size());

    /* Everything else being equal, prefer ephemeral ECDH over other key exchange mechanisms */
    ecdh.addAll(filterByKeyExchange(ciphers, Collections.singleton(KeyExchange.EECDH)));

    /* AES is our preferred symmetric cipher */
    Set<Encryption> aes = new HashSet<>(Arrays.asList(Encryption.AES128, Encryption.AES128CCM,
            Encryption.AES128CCM8, Encryption.AES128GCM, Encryption.AES256,
            Encryption.AES256CCM, Encryption.AES256CCM8, Encryption.AES256GCM));

    /* Now arrange all ciphers by preference: */
    result.addAll(filterByEncryption(ecdh, aes));
    result.addAll(filterByEncryption(ciphers, aes));

    /* Add everything else */
    result.addAll(ecdh);
    result.addAll(ciphers);

    /* Low priority for MD5 */
    moveToEnd(result, filterByMessageDigest(result, Collections.singleton(MessageDigest.MD5)));

    /* Move anonymous ciphers to the end.  Usually, these will remain disabled.
     * (For applications that allow them, they aren't too bad, but we prefer
     * authenticated ciphers.) */
    moveToEnd(result, filterByAuthentication(result, Collections.singleton(Authentication.aNULL)));

    /* Move ciphers without forward secrecy to the end */
    moveToEnd(result, filterByAuthentication(result, Collections.singleton(Authentication.ECDH)));
    moveToEnd(result, filterByKeyExchange(result, Collections.singleton(KeyExchange.RSA)));
    moveToEnd(result, filterByKeyExchange(result, Collections.singleton(KeyExchange.PSK)));

    /* RC4 is sort-of broken -- move the the end */
    moveToEnd(result, filterByEncryption(result, Collections.singleton(Encryption.RC4)));
    return strengthSort(result);
}
 
源代码9 项目: mollyim-android   文件: RecentEmojiPageModel.java
private String[] toReversePrimitiveArray(@NonNull LinkedHashSet<String> emojiSet) {
  String[] emojis = new String[emojiSet.size()];
  int i = emojiSet.size() - 1;
  for (String emoji : emojiSet) {
    emojis[i--] = emoji;
  }
  return emojis;
}
 
源代码10 项目: RoaringBitmap   文件: SerializationBenchmark.java
private int[] toArray(LinkedHashSet<Integer> integers) {
  int[] ints = new int[integers.size()];
  int i = 0;
  for (Integer n : integers) {
    ints[i++] = n;
  }
  return ints;
}
 
源代码11 项目: flink   文件: PojoSerializer.java
/**
 * Creates an array of serializers for provided list of registered subclasses.
 * Order of returned serializers will correspond to order of provided subclasses.
 */
private static TypeSerializer<?>[] createRegisteredSubclassSerializers(
		LinkedHashSet<Class<?>> registeredSubclasses,
		ExecutionConfig executionConfig) {

	final TypeSerializer<?>[] subclassSerializers = new TypeSerializer[registeredSubclasses.size()];

	int i = 0;
	for (Class<?> registeredClass : registeredSubclasses) {
		subclassSerializers[i] = TypeExtractor.createTypeInfo(registeredClass).createSerializer(executionConfig);
		i++;
	}

	return subclassSerializers;
}
 
源代码12 项目: RoaringBitmap   文件: IteratorsBenchmark32.java
private int[] toArray(LinkedHashSet<Integer> integers) {
  int[] ints = new int[integers.size()];
  int i = 0;
  for (Integer n : integers) {
    ints[i++] = n;
  }
  return ints;
}
 
源代码13 项目: requery   文件: Attributes.java
static <E> Attribute<E, ?>[] toArray(Collection<Attribute<E, ?>> attributes,
                                     Predicate<Attribute<E, ?>> filter) {
    LinkedHashSet<Attribute> filtered = new LinkedHashSet<>();
    for (Attribute<E, ?> attribute : attributes) {
        if (filter == null || filter.test(attribute)) {
            filtered.add(attribute);
        }
    }
    Attribute<E, ?>[] array = new Attribute[filtered.size()];
    return filtered.toArray(array);
}
 
源代码14 项目: oneops   文件: AbstractOrderExecutor.java
protected LinkedHashSet<String> createCookbookSearchPath(String cookbookRelativePath,
    Map<String, Map<String, CmsCISimple>> cloudServices,
    String cloudName) {
  String cookbookDir = config.getCircuitDir();
  if (!cookbookRelativePath.equals("")) {
    cookbookDir = config.getCircuitDir().replace("packer",
        cookbookRelativePath);
  }

  cookbookDir += "/components/cookbooks";
  String sharedDir = config.getCircuitDir().replace("packer", "shared/cookbooks");

  LinkedHashSet<String> cookbookPaths = new LinkedHashSet<>();
  if (cloudServices != null) {
    for (String serviceName : cloudServices.keySet()) { // for each service
      CmsCISimple serviceCi = cloudServices.get(serviceName).get(cloudName);
      if (serviceCi != null) {
        String serviceClassName = serviceCi.getCiClassName();
        String serviceCookbookCircuit = getCookbookPath(serviceClassName);
        if (!serviceCookbookCircuit.equals(cookbookRelativePath)) {
          cookbookPaths.add(config.getCircuitDir().replace("packer", serviceCookbookCircuit)
              + "/components/cookbooks");
        }
      }
    }
  }
  if (cookbookPaths.size() > 0) {
    //Remove the current component's circuit from the cookbook_path so that we can add it after other circuits
    //This is to make sure the current component's circuit is higher priority in search path
    cookbookPaths.remove(cookbookDir);
  }
  cookbookPaths.add(cookbookDir);
  cookbookPaths.add(sharedDir);
  return cookbookPaths;
}
 
源代码15 项目: Mixin   文件: InjectionPoint.java
@Override
public boolean find(String desc, InsnList insns, Collection<AbstractInsnNode> nodes) {
    LinkedHashSet<AbstractInsnNode> allNodes = new LinkedHashSet<AbstractInsnNode>();

    for (int i = 0; i < this.components.length; i++) {
        this.components[i].find(desc, insns, allNodes);
    }

    nodes.addAll(allNodes);

    return allNodes.size() > 0;
}
 
源代码16 项目: bazel   文件: ConfigExpander.java
/**
 * @param configAncestorSet is the chain of configs that have led to this one getting expanded.
 *     This should only contain the configs that expanded, recursively, to this one, and should
 *     not contain "siblings," as it is used to detect cycles. {@code build:foo --config=bar},
 *     {@code build:bar --config=foo}, is a cycle, detected because this list will be [foo, bar]
 *     when we find another 'foo' to expand. However, {@code build:foo --config=bar}, {@code
 *     build:foo --config=bar} is not a cycle just because bar is expanded twice, and the 1st bar
 *     should not be in the parents list of the second bar.
 * @param longestChain will be populated with the longest inheritance chain of configs.
 */
private static List<String> getExpansion(
    ListMultimap<String, RcChunkOfArgs> commandToRcArgs,
    List<String> commandsToParse,
    LinkedHashSet<String> configAncestorSet,
    String configToExpand,
    List<String> longestChain,
    Consumer<String> rcFileNotesConsumer)
    throws OptionsParsingException {
  List<String> expansion = new ArrayList<>();
  boolean foundDefinition = false;
  // The expansion order of rc files is first by command priority, and then in the order the
  // rc files were read, respecting import statement placement.
  for (String commandToParse : commandsToParse) {
    String configDef = commandToParse + ":" + configToExpand;
    for (RcChunkOfArgs rcArgs : commandToRcArgs.get(configDef)) {
      foundDefinition = true;
      rcFileNotesConsumer.accept(
          String.format(
              "Found applicable config definition %s in file %s: %s",
              configDef, rcArgs.getRcFile(), String.join(" ", rcArgs.getArgs())));

      // For each arg in the rcARgs chunk, we first check if it is a config, and if so, expand
      // it in place. We avoid cycles by tracking the parents of this config.
      for (String arg : rcArgs.getArgs()) {
        expansion.add(arg);
        if (arg.length() >= 8 && arg.substring(0, 8).equals("--config")) {
          // We have a config. For sanity, because we don't want to worry about formatting,
          // we will only accept --config=value, and will not accept value on a following line.
          int charOfConfigValue = arg.indexOf('=');
          if (charOfConfigValue < 0) {
            throw new OptionsParsingException(
                String.format(
                    "In file %s, the definition of config %s expands to another config "
                        + "that either has no value or is not in the form --config=value. For "
                        + "recursive config definitions, please do not provide the value in a "
                        + "separate token, such as in the form '--config value'.",
                    rcArgs.getRcFile(), configToExpand));
          }
          String newConfigValue = arg.substring(charOfConfigValue + 1);
          LinkedHashSet<String> extendedConfigAncestorSet =
              new LinkedHashSet<>(configAncestorSet);
          if (!extendedConfigAncestorSet.add(newConfigValue)) {
            throw new OptionsParsingException(
                String.format(
                    "Config expansion has a cycle: config value %s expands to itself, "
                        + "see inheritance chain %s",
                    newConfigValue, extendedConfigAncestorSet));
          }
          if (extendedConfigAncestorSet.size() > longestChain.size()) {
            longestChain.clear();
            longestChain.addAll(extendedConfigAncestorSet);
          }

          expansion.addAll(
              getExpansion(
                  commandToRcArgs,
                  commandsToParse,
                  extendedConfigAncestorSet,
                  newConfigValue,
                  longestChain,
                  rcFileNotesConsumer));
        }
      }
    }
  }

  if (!foundDefinition) {
    throw new OptionsParsingException(
        "Config value " + configToExpand + " is not defined in any .rc file");
  }
  return expansion;
}
 
源代码17 项目: netbeans   文件: GoToDecoratorAtCaretAction.java
@Override
protected void modelAcessAction( WebBeansModel model,
        final MetadataModel<WebBeansModel> metaModel, Object[] subject,
        final JTextComponent component, FileObject fileObject )
{
    Element element = ((ElementHandle<?>)subject[0]).resolve( 
            model.getCompilationController());
    if (element == null) {
        return;
    }
    Collection<TypeElement> decorators = model.getDecorators((TypeElement)element);
    if (decorators.size() == 0) {
        StatusDisplayer.getDefault().setStatusText(
                NbBundle.getMessage(GoToDecoratorAtCaretAction.class,
                        "LBL_DecoratorsNotFound"),              // NOI18N
                StatusDisplayer.IMPORTANCE_ERROR_HIGHLIGHT);
        return;
    }
    
    BeansModel beansModel = model.getModelImplementation().getBeansModel();
    final LinkedHashSet<TypeElement> enabledDecorators = WebBeansActionHelper.
            getEnabledDecorators(decorators, beansModel, null, 
                    model.getCompilationController());
    if (enabledDecorators.size() == 0) {
        StatusDisplayer.getDefault().setStatusText(
                NbBundle.getMessage(GoToDecoratorAtCaretAction.class,
                        "LBL_EnabledDecoratorsNotFound"),        // NOI18N
                StatusDisplayer.IMPORTANCE_ERROR_HIGHLIGHT);
        return;
    }
    
    if (enabledDecorators.size() == 1) {
        final ElementHandle<TypeElement> handle = ElementHandle
                .create(enabledDecorators.iterator().next());
        final ClasspathInfo classpathInfo = model
                .getCompilationController().getClasspathInfo();
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                ElementOpen.open(classpathInfo, handle);
            }
        });
    }
    else  {
        final CompilationController controller = model
                .getCompilationController();
        if (SwingUtilities.isEventDispatchThread()) {
            showPopup(enabledDecorators, controller, metaModel, component);
        }
        else {
            SwingUtilities.invokeLater(new Runnable() {

                @Override
                public void run() {
                    showPopup(enabledDecorators, controller, metaModel, component);
                }
            });
        }
    }
}
 
源代码18 项目: lucene-solr   文件: AnalysisSPILoader.java
/** 
 * Reloads the internal SPI list from the given {@link ClassLoader}.
 * Changes to the service list are visible after the method ends, all
 * iterators (e.g., from {@link #availableServices()},...) stay consistent. 
 * 
 * <p><b>NOTE:</b> Only new service providers are added, existing ones are
 * never removed or replaced.
 * 
 * <p><em>This method is expensive and should only be called for discovery
 * of new service providers on the given classpath/classloader!</em>
 */
public synchronized void reload(ClassLoader classloader) {
  Objects.requireNonNull(classloader, "classloader");
  final LinkedHashMap<String,Class<? extends S>> services = new LinkedHashMap<>(this.services);
  final LinkedHashSet<String> originalNames = new LinkedHashSet<>(this.originalNames);
  ServiceLoader.load(clazz, classloader).stream().map(ServiceLoader.Provider::type).forEachOrdered(service -> {
    String name = null;
    String originalName = null;
    Throwable cause = null;
    try {
      originalName = lookupSPIName(service);
      name = originalName.toLowerCase(Locale.ROOT);
      if (!isValidName(originalName)) {
        throw new ServiceConfigurationError("The name " + originalName + " for " + service.getName() +
            " is invalid: Allowed characters are (English) alphabet, digits, and underscore. It should be started with an alphabet.");
      }
    } catch (NoSuchFieldException | IllegalAccessException | IllegalStateException e) {
      cause = e;
    }
    if (name == null) {
      throw new ServiceConfigurationError("The class name " + service.getName() +
          " has no service name field: [public static final String NAME]", cause);
    }
    // only add the first one for each name, later services will be ignored
    // this allows to place services before others in classpath to make 
    // them used instead of others
    //
    // TODO: Should we disallow duplicate names here?
    // Allowing it may get confusing on collisions, as different packages
    // could contain same factory class, which is a naming bug!
    // When changing this be careful to allow reload()!
    if (!services.containsKey(name)) {
      services.put(name, service);
      // preserve (case-sensitive) original name for reference
      originalNames.add(originalName);
    }
  });

  // make sure that the number of lookup keys is same to the number of original names.
  // in fact this constraint should be met in existence checks of the lookup map key,
  // so this is more like an assertion rather than a status check.
  if (services.keySet().size() != originalNames.size()) {
    throw new ServiceConfigurationError("Service lookup key set is inconsistent with original name set!");
  }

  this.services = Map.copyOf(services);
  this.originalNames = Set.copyOf(originalNames);
}
 
源代码19 项目: ignite   文件: IgniteCachePartitionMapUpdateTest.java
/**
 * @throws Exception If failed.
 */
@Test
public void testRandom() throws Exception {
    Random rnd = new Random();

    final int NODE_CNT = 10;

    for (int iter = 0; iter < 1; iter++) {
        log.info("Iteration: " + iter);

        for (int i = 0; i < NODE_CNT; i++) {
            cache1 = rnd.nextBoolean();
            cache2 = rnd.nextBoolean();

            log.info("Start node [idx=" + i + ", cache1=" + cache1 + ", cache2=" + cache2 + ']');

            startGrid(i);

            awaitPartitionMapExchange();
        }

        LinkedHashSet<Integer> stopSeq = new LinkedHashSet<>();

        while (stopSeq.size() != NODE_CNT)
            stopSeq.add(rnd.nextInt(NODE_CNT));

        log.info("Stop sequence: " + stopSeq + ", seed=" + U.field(rnd, "seed"));

        for (Integer idx : stopSeq) {
            log.info("Stop node: " + idx);

            stopGrid(idx);

            awaitPartitionMapExchange();
        }
    }
}
 
public static void testCoreGenePredictionPerformance(Depict2Options options) throws IOException {

		DoubleMatrixDataset<String, String> gwasCoreGenePredictions = DoubleMatrixDataset.loadDoubleBinaryData(options.getGwasZscoreMatrixPath());
		List<PathwayDatabase> pathwayDatabases = options.getPathwayDatabases();

		ArrayList<String> genesWithPrediciton = gwasCoreGenePredictions.getRowObjects();

		for (PathwayDatabase pathwayDatabase : pathwayDatabases) {

			final DoubleMatrixDatasetFastSubsetLoader pathwayMatrixLoader = new DoubleMatrixDatasetFastSubsetLoader(pathwayDatabase.getLocation());

			Set<String> pathwayGenes = pathwayMatrixLoader.getOriginalRowMap().keySet();

			final LinkedHashSet<String> sharedGenes = new LinkedHashSet<>();

			for (String gene : genesWithPrediciton) {
				if (pathwayGenes.contains(gene)) {
					sharedGenes.add(gene);
				}
			}

			final int sharedGenesCount = sharedGenes.size();

			final DoubleMatrixDataset<String, String> pathwayMatrix = pathwayMatrixLoader.loadSubsetOfRowsBinaryDoubleData(sharedGenes);
			final DoubleMatrixDataset<String, String> gwasCoreGenePredictionsMatched = gwasCoreGenePredictions.viewRowSelection(sharedGenes);

			
			final DoubleMatrixDataset<String, String> outputMatrix = new DoubleMatrixDataset<>(pathwayMatrix.getHashCols(), gwasCoreGenePredictionsMatched.getHashCols());

			final ArrayList<String> pathwayNames = pathwayMatrix.getColObjects();
			
			try (ProgressBar pb = new ProgressBar(pathwayDatabase.getName(), pathwayMatrix.columns(), ProgressBarStyle.ASCII)) {

				for (int pathwayI = 0; pathwayI < pathwayMatrix.columns(); ++pathwayI) {

					final DoubleMatrix1D pathwayAnnotation = pathwayMatrix.getCol(pathwayI);
					final int annotatedGenesCount = pathwayAnnotation.cardinality();

					final int pathwayI2 = pathwayI;

					if (annotatedGenesCount < 10) {
						if(LOGGER.isDebugEnabled()){
							LOGGER.debug("Skipping " + pathwayNames.get(pathwayI) + " " + annotatedGenesCount + " genes annotated");
						}
						pb.step();
						continue;
					}
					
					final int pathwayI_2 = pathwayI;

					IntStream.range(0, gwasCoreGenePredictionsMatched.columns()).parallel().forEach(traitI -> {

						final MannWhitneyUTest2 uTest = new MannWhitneyUTest2();

						final DoubleMatrix1D coreGeneScore = gwasCoreGenePredictionsMatched.getCol(traitI);

						final double[] coreGeneScoresAnnotatedGenes = new double[annotatedGenesCount];
						final double[] coreGeneScoresOtherGenes = new double[sharedGenesCount - annotatedGenesCount];

						int x = 0;
						int y = 0;

						for (int g = 0; g < sharedGenesCount; g++) {
							if (pathwayAnnotation.getQuick(g) > 0) {
								coreGeneScoresAnnotatedGenes[x++] = coreGeneScore.get(g);
							} else {
								coreGeneScoresOtherGenes[y++] = coreGeneScore.get(g);
							}
						}

						uTest.setData(coreGeneScoresAnnotatedGenes, coreGeneScoresOtherGenes);

						final double auc = uTest.getAuc();
						
						if(LOGGER.isDebugEnabled() && Double.isNaN(auc)){
							LOGGER.debug(pathwayNames.get(pathwayI_2) + " NaN AUC " + Arrays.toString(coreGeneScoresAnnotatedGenes));
						}
						
						outputMatrix.setElementQuick(pathwayI2, traitI, auc);

					});
					
					pb.step();

				}

				outputMatrix.save(options.getOutputBasePath() + "_" + pathwayDatabase.getName() + ".txt");

			}
		}

	}