public void testBuilderAddAllMultiset() { Multiset<String> a = HashMultiset.create(asList("a", "b", "b")); Multiset<String> b = HashMultiset.create(asList("c", "b")); ImmutableMultiset<String> multiset = new ImmutableMultiset.Builder<String>().addAll(a).addAll(b).build(); assertEquals(HashMultiset.create(asList("a", "b", "b", "b", "c")), multiset); }
public String getInfo() { if (crossValidationResults != null) { return crossValidationResults.getInfo(); } else { StringBuffer result = new StringBuffer(); if (oneVsAllMode != OneVsAllMode.None) { Multiset<Float> cs = HashMultiset.create(); Multiset<KernelFunction> kernels = HashMultiset.create(); for (BinaryModel<L, P> binaryModel : oneVsAllModels.values()) { cs.add(binaryModel.param.C); kernels.add(binaryModel.param.kernel); } result.append("OneVsAll:C=" + cs + "; gamma=" + kernels + " "); } if (allVsAllMode != AllVsAllMode.None) { Multiset<Float> cs = HashMultiset.create(); Multiset<KernelFunction> kernels = HashMultiset.create(); for (BinaryModel<L, P> binaryModel : oneVsOneModels.values()) { cs.add(binaryModel.param.C); kernels.add(binaryModel.param.kernel); } result.append("AllVsAll:C=" + cs + "; gamma=" + kernels + " "); } return result.toString(); } // return ""; }
/** * Sorts lookups based on their dependencies with each other. Non-lookups (i.e. everything except * #match, #setChoice, and #mapChoice) are in no particular order in this ordering, since they can * always be inferred later to occur at the final step after all other variables are bound. * * @return */ private Stream<KApply> getSortedLookups() { List<Tuple2<KApply, KApply>> edges = new ArrayList<>(); for (KApply k1 : state) { Multiset<KVariable> rhsVars = HashMultiset.create(); if (k1.klabel().name().equals("Set:in")) { continue; } gatherVars(k1.klist().items().get(1), rhsVars); for (KApply k2 : state) { Multiset<KVariable> lhsVars = HashMultiset.create(); if (k2.klabel().name().equals("Set:in")) { continue; } gatherVars(k2.klist().items().get(0), lhsVars); for (KVariable var : rhsVars) { if (lhsVars.contains(var)) { if (k1 != k2) { edges.add(Tuple2.apply(k2, k1)); break; } } } } } List<KApply> topologicalSorted = mutable(TopologicalSort.tsort(immutable(edges)).toList()); return state .stream() .sorted((k1, k2) -> (topologicalSorted.indexOf(k1) - topologicalSorted.indexOf(k2))); }
public void testConstrainedMapLegal() { Map<String, Integer> map = Maps.newLinkedHashMap(); Map<String, Integer> constrained = MapConstraints.constrainedMap(map, TEST_CONSTRAINT); map.put(TEST_KEY, TEST_VALUE); constrained.put("foo", 1); map.putAll(ImmutableMap.of("bar", 2)); constrained.putAll(ImmutableMap.of("baz", 3)); assertTrue(map.equals(constrained)); assertTrue(constrained.equals(map)); assertEquals(map.entrySet(), constrained.entrySet()); assertEquals(map.keySet(), constrained.keySet()); assertEquals(HashMultiset.create(map.values()), HashMultiset.create(constrained.values())); assertFalse(map.values() instanceof Serializable); assertEquals(map.toString(), constrained.toString()); assertEquals(map.hashCode(), constrained.hashCode()); ASSERT .that(map.entrySet()) .has() .allOf( Maps.immutableEntry(TEST_KEY, TEST_VALUE), Maps.immutableEntry("foo", 1), Maps.immutableEntry("bar", 2), Maps.immutableEntry("baz", 3)) .inOrder(); }
public void testBuilderAddAllMultiset() { Multiset<String> a = HashMultiset.create(asList("a", "b", "b")); Multiset<String> b = HashMultiset.create(asList("c", "b")); ImmutableSortedMultiset<String> multiset = ImmutableSortedMultiset.<String>naturalOrder().addAll(a).addAll(b).build(); assertEquals(HashMultiset.create(asList("a", "b", "b", "b", "c")), multiset); }
/** Returns {@code true} if the second list is a permutation of the first. */ private static boolean isPermutation(List<?> first, List<?> second) { if (first.size() != second.size()) { return false; } Multiset<?> firstMultiset = HashMultiset.create(first); Multiset<?> secondMultiset = HashMultiset.create(second); return firstMultiset.equals(secondMultiset); }
public void addNode(int node) { maxVNum = Math.max(maxVNum, node); if (!nodeOutEdges.containsKey(node)) { nodeOutEdges.put(node, HashMultiset.<Integer>create()); nodeInEdges.put(node, HashMultiset.<Integer>create()); } }
@Override public boolean matchesSafely(final Iterable<? super K> actual) { final Multiset<?> comparisonMultiSet = HashMultiset.create(comparisonIterable); final Multiset<?> actualMultiSet = HashMultiset.create(actual); for (final Object key : actualMultiSet.elementSet()) { if (!comparisonMultiSet.contains(key) || comparisonMultiSet.count(key) < actualMultiSet.count(key)) { return false; } } return true; }
private static <T> int checkCounts(Collection<T> original) { Multiset<T> hashCounts = HashMultiset.create(); for (T v : original) { hashCounts.add(v); } Multiset<Integer> countCounts = HashMultiset.create(); for (T hash : hashCounts) { countCounts.add(hashCounts.count(hash)); } return original.size() - countCounts.count(1); }
private Iterable<?> notRepeated( Iterable<? super K> actual, Iterable<? super K> comparisonIterable) { final Multiset<?> comparisonMultiSet = HashMultiset.create(comparisonIterable); final Multiset<?> actualMultiSet = HashMultiset.create(actual); final Set<Object> notRepeated = newHashSet(); for (final Object key : actualMultiSet.elementSet()) { if (!comparisonMultiSet.contains(key) || comparisonMultiSet.count(key) < actualMultiSet.count(key)) { notRepeated.add(key); } } return notRepeated; }
public void testCreation_arrayOfArray() { String[] array = new String[] {"a"}; Multiset<String[]> multiset = ImmutableMultiset.<String[]>of(array); Multiset<String[]> expected = HashMultiset.create(); expected.add(array); assertEquals(expected, multiset); }
public void upload( @Observes ControllerFound event, MutableRequest request, MultipartConfig config, Validator validator) { if (!ServletFileUpload.isMultipartContent(request)) { return; } logger.info("Request contains multipart data. Try to parse with commons-upload."); final Multiset<String> indexes = HashMultiset.create(); final Multimap<String, String> params = LinkedListMultimap.create(); ServletFileUpload uploader = createServletFileUpload(config); UploadSizeLimit uploadSizeLimit = event.getMethod().getMethod().getAnnotation(UploadSizeLimit.class); uploader.setSizeMax( uploadSizeLimit != null ? uploadSizeLimit.sizeLimit() : config.getSizeLimit()); uploader.setFileSizeMax( uploadSizeLimit != null ? uploadSizeLimit.fileSizeLimit() : config.getFileSizeLimit()); logger.debug( "Setting file sizes: total={}, file={}", uploader.getSizeMax(), uploader.getFileSizeMax()); try { final List<FileItem> items = uploader.parseRequest(request); logger.debug( "Found {} attributes in the multipart form submission. Parsing them.", items.size()); for (FileItem item : items) { String name = item.getFieldName(); name = fixIndexedParameters(name, indexes); if (item.isFormField()) { logger.debug("{} is a field", name); params.put(name, getValue(item, request)); } else if (isNotEmpty(item)) { logger.debug("{} is a file", name); processFile(item, name, request); } else { logger.debug("A file field is empty: {}", item.getFieldName()); } } for (String paramName : params.keySet()) { Collection<String> paramValues = params.get(paramName); request.setParameter(paramName, paramValues.toArray(new String[paramValues.size()])); } } catch (final SizeLimitExceededException e) { reportSizeLimitExceeded(e, validator); } catch (FileUploadException e) { reportFileUploadException(e, validator); } }
/** * Map Corresponding Multiset Supports null elements HashMap HashMultiset Yes TreeMap TreeMultiset * Yes (if the comparator does) LinkedHashMap LinkedHashMultiset Yes ConcurrentHashMap * ConcurrentHashMultiset No ImmutableMap ImmutableMultiset No */ @Test public void testHashMultiset() { Multiset<String> m = HashMultiset.create(); loadTestData(m); System.out.println(m); // [b, -1, c, a x 3] }
@SuppressWarnings("unchecked") @Override public final void open() throws Exception { super.open(); timestampedCollector = new TimestampedCollector<>(output); if (inputSerializer == null) { throw new IllegalStateException("Input serializer was not set."); } // these could already be initialized from restoreState() if (watermarkTimers == null) { watermarkTimers = new HashSet<>(); watermarkTimersQueue = new PriorityQueue<>(100); } if (processingTimeTimers == null) { processingTimeTimers = new HashSet<>(); processingTimeTimerTimestamps = HashMultiset.create(); processingTimeTimersQueue = new PriorityQueue<>(100); } // ScheduledFutures are not checkpointed processingTimeTimerFutures = new HashMap<>(); context = new Context(null, null); if (windowAssigner instanceof MergingWindowAssigner) { mergingWindowsByKey = new HashMap<>(); } currentWatermark = Long.MIN_VALUE; }
private static void logStats(Collection<PsiFile> otherFiles, long start) { long time = System.currentTimeMillis() - start; final Multiset<String> stats = HashMultiset.create(); for (PsiFile file : otherFiles) { stats.add( StringUtil.notNullize(file.getViewProvider().getVirtualFile().getExtension()) .toLowerCase()); } List<String> extensions = ContainerUtil.newArrayList(stats.elementSet()); Collections.sort( extensions, new Comparator<String>() { @Override public int compare(String o1, String o2) { return stats.count(o2) - stats.count(o1); } }); String message = "Search in " + otherFiles.size() + " files with unknown types took " + time + "ms.\n" + "Mapping their extensions to an existing file type (e.g. Plain Text) might speed up the search.\n" + "Most frequent non-indexed file extensions: "; for (int i = 0; i < Math.min(10, extensions.size()); i++) { String extension = extensions.get(i); message += extension + "(" + stats.count(extension) + ") "; } LOG.info(message); }
private static void validateAnalyzerMessage( Map<IssueAttribute, String> attrs, AnalyzerMessage analyzerMessage) { Double effortToFix = analyzerMessage.getCost(); if (effortToFix != null) { assertEquals(Integer.toString(effortToFix.intValue()), attrs, IssueAttribute.EFFORT_TO_FIX); } AnalyzerMessage.TextSpan textSpan = analyzerMessage.primaryLocation(); assertEquals(normalizeColumn(textSpan.startCharacter), attrs, IssueAttribute.START_COLUMN); assertEquals(Integer.toString(textSpan.endLine), attrs, IssueAttribute.END_LINE); assertEquals(normalizeColumn(textSpan.endCharacter), attrs, IssueAttribute.END_COLUMN); if (attrs.containsKey(IssueAttribute.SECONDARY_LOCATIONS)) { List<AnalyzerMessage> secondaryLocations = analyzerMessage.secondaryLocations; Multiset<String> actualLines = HashMultiset.create(); for (AnalyzerMessage secondaryLocation : secondaryLocations) { actualLines.add(Integer.toString(secondaryLocation.getLine())); } List<String> expected = Lists.newArrayList( Splitter.on(",") .omitEmptyStrings() .trimResults() .split(attrs.get(IssueAttribute.SECONDARY_LOCATIONS))); List<String> unexpected = new ArrayList<>(); for (String actualLine : actualLines) { if (expected.contains(actualLine)) { expected.remove(actualLine); } else { unexpected.add(actualLine); } } if (!expected.isEmpty() || !unexpected.isEmpty()) { Fail.fail("Secondary locations: expected: " + expected + " unexpected:" + unexpected); } } }
/** * Populate the FeatureVector with Bag of Words. * * @param c * @param fv */ protected void populateFV(String text, FeatureVector<E> fv) { List<String> unnormalized = tokenizer.tokenize(text); Multiset<String> terms = HashMultiset.create(); for (String token : unnormalized) { String norm = Util.normalize(token); if (!norm.isEmpty()) { terms.add(norm); } } // sparse representation... no need to put in 0's for (String term : terms.elementSet()) { // rare words don't get included, so check first if (!integerFeatureNames && train.getMetadata().containsKey(term)) { DoubleFeature bagFeat = new DoubleFeature(term, (double) terms.count(term)); fv.put(term, bagFeat); } else if (integerFeatureNames && train.getMetadata().containsKey(String.valueOf(wordIndexMap.get(term)))) { String featureName = String.valueOf(wordIndexMap.get(term)); DoubleFeature bagFeat = new DoubleFeature(featureName, (double) terms.count(term)); fv.put(featureName, bagFeat); } } }
public void testCreateWithSize() { Multiset<String> multiset = HashMultiset.create(50); multiset.add("foo", 2); multiset.add("bar"); assertEquals(3, multiset.size()); assertEquals(2, multiset.count("foo")); }
private void restoreTimers(DataInputView in) throws IOException { int numWatermarkTimers = in.readInt(); watermarkTimers = new HashSet<>(numWatermarkTimers); watermarkTimersQueue = new PriorityQueue<>(Math.max(numWatermarkTimers, 1)); for (int i = 0; i < numWatermarkTimers; i++) { K key = keySerializer.deserialize(in); W window = windowSerializer.deserialize(in); long timestamp = in.readLong(); Timer<K, W> timer = new Timer<>(timestamp, key, window); watermarkTimers.add(timer); watermarkTimersQueue.add(timer); } int numProcessingTimeTimers = in.readInt(); processingTimeTimersQueue = new PriorityQueue<>(Math.max(numProcessingTimeTimers, 1)); processingTimeTimers = new HashSet<>(); for (int i = 0; i < numProcessingTimeTimers; i++) { K key = keySerializer.deserialize(in); W window = windowSerializer.deserialize(in); long timestamp = in.readLong(); Timer<K, W> timer = new Timer<>(timestamp, key, window); processingTimeTimersQueue.add(timer); processingTimeTimers.add(timer); } int numProcessingTimeTimerTimestamp = in.readInt(); processingTimeTimerTimestamps = HashMultiset.create(); for (int i = 0; i < numProcessingTimeTimerTimestamp; i++) { long timestamp = in.readLong(); int count = in.readInt(); processingTimeTimerTimestamps.add(timestamp, count); } }
public void testCopyOf_multisetContainingNull() { Multiset<String> c = HashMultiset.create(asList("a", null, "b")); try { ImmutableMultiset.copyOf(c); fail(); } catch (NullPointerException expected) { } }
@GwtIncompatible // SerializableTester public void testSerializationContainingSelf() { Multiset<Multiset<?>> multiset = HashMultiset.create(); multiset.add(multiset, 2); Multiset<Multiset<?>> copy = SerializableTester.reserialize(multiset); assertEquals(2, copy.size()); assertSame(copy, copy.iterator().next()); }
public static void main(String args[]) { // create a multiset collection Multiset<String> multiset = HashMultiset.create(); multiset.add("a"); multiset.add("b"); multiset.add("c"); multiset.add("d"); multiset.add("a"); multiset.add("b"); multiset.add("c"); multiset.add("b"); multiset.add("b"); multiset.add("b"); // print the occurrence of an element System.out.println("Occurrence of 'b' : " + multiset.count("b")); // print the total size of the multiset System.out.println("Total Size : " + multiset.size()); // get the distinct elements of the multiset as set Set<String> set = multiset.elementSet(); // display the elements of the set System.out.println("Set ["); for (String s : set) { System.out.println(s); } System.out.println("]"); // display all the elements of the multiset using iterator Iterator<String> iterator = multiset.iterator(); System.out.println("MultiSet ["); while (iterator.hasNext()) { System.out.println(iterator.next()); } System.out.println("]"); // display the distinct elements of the multiset with their occurrence count System.out.println("MultiSet ["); for (Multiset.Entry<String> entry : multiset.entrySet()) { System.out.println("Element: " + entry.getElement() + ", Occurrence(s): " + entry.getCount()); } System.out.println("]"); // remove extra occurrences multiset.remove("b", 2); // print the occurrence of an element System.out.println("Occurence of 'b' : " + multiset.count("b")); }
public void testBuilderSetCount() { ImmutableSortedMultiset<String> multiset = ImmutableSortedMultiset.<String>naturalOrder() .add("a") .setCount("a", 2) .setCount("b", 3) .build(); assertEquals(HashMultiset.create(asList("a", "a", "b", "b", "b")), multiset); }
@Test public void should_fail_if_expected_is_negative() { // given Multiset<String> actual = HashMultiset.create(); // expect expectException(IllegalArgumentException.class, "The maximum count should not be negative."); // when assertThat(actual).containsAtMost(-1, "test"); }
private Multiset<Rule> initRules( Map<RulePriority, Multiset<Rule>> rulesPerSeverity, RulePriority severity) { Multiset<Rule> rulesBag = rulesPerSeverity.get(severity); if (rulesBag == null) { rulesBag = HashMultiset.create(); rulesPerSeverity.put(severity, rulesBag); } return rulesBag; }
@Test public void should_pass_if_actual_contains_value_number_of_times_expected() { // given Multiset<String> actual = HashMultiset.create(); actual.add("test", 2); // when assertThat(actual).containsAtMost(2, "test"); // then pass }
@GwtIncompatible // SerializableTester public void testSerializationIndirectSelfReference() { Multiset<MultisetHolder> multiset = HashMultiset.create(); MultisetHolder holder = new MultisetHolder(multiset); multiset.add(holder, 2); Multiset<MultisetHolder> copy = SerializableTester.reserialize(multiset); assertEquals(2, copy.size()); assertSame(copy, copy.iterator().next().member); }
public void testBuilderAddCopies() { ImmutableMultiset<String> multiset = new ImmutableMultiset.Builder<String>() .addCopies("a", 2) .addCopies("b", 3) .addCopies("c", 0) .build(); assertEquals(HashMultiset.create(asList("a", "a", "b", "b", "b")), multiset); }
@Override public List<List<List<TPlayer>>> generateMatchups( List<TPlayer> players, int numRoles, int numMatches) { List<List<List<TPlayer>>> results = Lists.newArrayList(); Multiset<Set<TPlayer>> matchupsSoFar = HashMultiset.create(); for (int round = 0; round < numMatches; round++) { results.add(getNonFixedSumPlayerGroups(players, numRoles, matchupsSoFar)); } return results; }
@Test public void multisetTest() { Multiset<String> multiset = HashMultiset.create(); multiset.add("123"); multiset.add("123"); multiset.add("123"); multiset.add("1234"); System.out.println(multiset.count("123")); System.out.println(multiset); }