Java Code Examples for com.google.common.collect.Iterables#size()

The following examples show how to use com.google.common.collect.Iterables#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: UntilCombineMatcher.java    From flink-spector with Apache License 2.0 6 votes vote down vote up
@Override
public boolean matchesSafely(T object, Description mismatch) {
    int matches = 0;
    int possibleMatches = Iterables.size(matchers);

    for (Matcher<? super T> matcher : matchers) {
        if (!matcher.matches(object)) {
            if (!mismatch.toString().endsWith("but: ")) {
                mismatch.appendText("\n          ");
            }
            matcher.describeMismatch(object, mismatch);
        } else {
            matches++;
            if (validWhen(matches, possibleMatches)) {
                return true;
            }
        }
    }
    return false;
}
 
Example 2
Source File: StrategoAnalyzer.java    From spoofax with Apache License 2.0 5 votes vote down vote up
@Override public ISpoofaxAnalyzeResults analyzeAll(Iterable<ISpoofaxParseUnit> inputs, IContext context,
    IProgress progress, ICancel cancel) throws AnalysisException, InterruptedException {
    cancel.throwIfCancelled();
    
    final ILanguageImpl language = context.language();

    final FacetContribution<AnalysisFacet> facetContribution = language.facetContribution(AnalysisFacet.class);
    if(facetContribution == null) {
        logger.debug("No analysis required for {}", language);
        return new SpoofaxAnalyzeResults(context);
    }
    final AnalysisFacet facet = facetContribution.facet;

    cancel.throwIfCancelled();
    final HybridInterpreter runtime;
    try {
        runtime = runtimeService.runtime(facetContribution.contributor, context);
    } catch(MetaborgException e) {
        throw new AnalysisException(context, "Failed to get Stratego runtime", e);
    }

    final int size = Iterables.size(inputs);
    progress.setWorkRemaining(size);
    final Collection<ISpoofaxAnalyzeUnit> results = Lists.newArrayListWithCapacity(size);
    for(ISpoofaxParseUnit input : inputs) {
        cancel.throwIfCancelled();
        if(!input.valid()) {
            logger.warn("Parse input for {} is invalid, cannot analyze", input.source());
            // TODO: throw exception instead?
            progress.work(1);
            continue;
        }
        final ISpoofaxAnalyzeUnit result = analyze(input, context, runtime, facet.strategyName, termFactory);
        results.add(result);
        progress.work(1);
    }
    return new SpoofaxAnalyzeResults(results, context);
}
 
Example 3
Source File: Neo4jGraphDatabase.java    From graphdb-benchmarks with Apache License 2.0 5 votes vote down vote up
@Override
public double getNodeCommunityWeight(int nodeCommunity)
{
    double nodeCommunityWeight = 0;
    try (final Transaction tx = beginUnforcedTransaction())
    {
        try
        {
            ResourceIterable<Node> iter = neo4jGraph.findNodesByLabelAndProperty(NODE_LABEL, NODE_COMMUNITY,
                nodeCommunity);
            if (Iterables.size(iter) > 1)
            {
                for (Node n : iter)
                {
                    nodeCommunityWeight += getNodeOutDegree(n);
                }
            }
            tx.success();
        }
        catch (Exception e)
        {
            tx.failure();
            throw new BenchmarkingException("unable to get node community weight", e);
        }
    }

    return nodeCommunityWeight;
}
 
Example 4
Source File: CheckValidatorExtensionHelper.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean isExtensionUpdateRequired(final CheckCatalog catalog, final IPluginExtension extension, final Iterable<IPluginElement> elements) {
  // CHECKSTYLE:OFF
  // @Format-Off
  final boolean result = extension.getPoint().equals(CHECK_EXTENSION_POINT_ID)
      && (!extensionNameMatches(extension, catalog)
      || Iterables.size(elements) != 1
      || !targetClassMatches(Iterables.get(elements, 0), getTargetClassName(catalog))
      || catalog.getGrammar() == null && Iterables.get(elements, 0).getAttribute(LANGUAGE_ELEMENT_TAG) != null
      || catalog.getGrammar() != null && !languageNameMatches(Iterables.get(elements, 0), catalog.getGrammar().getName())
  );
  return result;
  // @Format-On
  // CHECKSTYLE:ON
}
 
Example 5
Source File: SGenJavaValidator.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
@Check
public void checkDuplicateFeatureParameter(final FeatureParameterValue value) {
	FeatureConfiguration entry = (FeatureConfiguration) value.eContainer();
	Iterable<FeatureParameterValue> filter = Iterables.filter(entry.getParameterValues(),
			new Predicate<FeatureParameterValue>() {
				public boolean apply(FeatureParameterValue input) {
					return (input.getParameter().getName().equals(value.getParameter().getName()));
				}
			});
	if (Iterables.size(filter) > 1) {
		error(DUPLICATE_PARAMETER, SGenPackage.Literals.FEATURE_PARAMETER_VALUE__PARAMETER);
	}
}
 
Example 6
Source File: MethodHierarchyReaderTest.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetLeafMethods() {
  Iterable<Method> methods = methodReader.getLeafMethods();

  TestHelper helper = new TestHelper(Iterables.size(methods));
  for (Method method : methods) {
    helper.verifySingleMethod(method);
  }
  helper.verifyAllMethodsSeen();
}
 
Example 7
Source File: SerializerTester.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected ISerializationContext getContext(EObject semanticObject) {
	Iterable<ISerializationContext> contexts = contextFinder.findByContentsAndContainer(semanticObject, null);
	if (Iterables.size(contexts) != 1) {
		StringBuilder msg = new StringBuilder();
		msg.append("One context is expected, but " + Iterables.size(contexts) + " have been found\n");
		msg.append("Contexts: " + Joiner.on(", ").join(contexts));
		msg.append("Semantic Object: " + EmfFormatter.objPath(semanticObject));
		Assert.fail(msg.toString());
	}
	return contexts.iterator().next();
}
 
Example 8
Source File: AssertableDiagnostics.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
public AssertableDiagnostics assertDiagnosticsCount(int size) {
	int count = Iterables.size(getAllDiagnostics());
	if (count == size)
		return this;
	fail("There are " + count + " diagnostics, but " + size + " are expected.");
	return this;
}
 
Example 9
Source File: OutputWithSize.java    From flink-spector with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean matchesSafely(Iterable<T> item, Description mismatchDescription) {
    int size = Iterables.size(item);
    boolean matches = sizeMatcher.matches(size);
    if (!matches) {
        sizeMatcher.describeMismatch(size, mismatchDescription);
    }
    return matches;
}
 
Example 10
Source File: SimpleTopNProjectorTest.java    From crate with Apache License 2.0 5 votes vote down vote up
@Test
public void testProjectLimitLessThanLimitUpStream() throws Throwable {
    Projector projector = prepareProjector(10, TopN.NO_OFFSET);
    BatchIterator<Row> batchIterator = projector.apply(TestingBatchIterators.range(0, 5));
    consumer.accept(batchIterator, null);
    Bucket projected = consumer.getBucket();
    assertThat(projected.size(), is(5));

    int iterateLength = Iterables.size(consumer.getBucket());
    assertThat(iterateLength, is(5));
}
 
Example 11
Source File: Neo4jGraphDatabase.java    From graphdb-benchmarks with Apache License 2.0 5 votes vote down vote up
@Override
public double getCommunityWeight(int community)
{
    double communityWeight = 0;
    try (final Transaction tx = beginUnforcedTransaction())
    {
        try
        {
            ResourceIterable<Node> iter = neo4jGraph.findNodesByLabelAndProperty(NODE_LABEL, COMMUNITY, community);
            if (Iterables.size(iter) > 1)
            {
                for (Node n : iter)
                {
                    communityWeight += getNodeOutDegree(n);
                }
            }
            tx.success();
        }
        catch (Exception e)
        {
            tx.failure();
            throw new BenchmarkingException("unable to get community weight", e);
        }
    }

    return communityWeight;
}
 
Example 12
Source File: TestH4readAndCount.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void count(Group g) {
  ndims += g.getDimensions().size();
  nvars += g.getVariables().size();
  ngatts += Iterables.size(g.attributes());
  ngroups += g.getGroups().size();

  for (Variable v : g.getVariables()) {
    natts += Iterables.size(v.attributes());
    if (v instanceof Structure) {
      nstructFields += ((Structure) v).getVariables().size();
    }
  }
  for (Group ng : g.getGroups())
    count(ng);
}
 
Example 13
Source File: ParallelFromStreamRecordsFunction.java    From flink-spector with Apache License 2.0 5 votes vote down vote up
public ParallelFromStreamRecordsFunction(TypeSerializer<StreamRecord<T>> serializer,
                                         Iterable<StreamRecord<T>> input,
                                         Boolean flushOpenWindows
) throws IOException {
    this.serializer = serializer;
    elementsSerialized = serializeOutput(input, serializer).toByteArray();
    numElements = Iterables.size(input);
    this.flushOpenWindows = flushOpenWindows;
}
 
Example 14
Source File: CheckPreferencesExtensionHelper.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean isExtensionUpdateRequired(final CheckCatalog catalog, final IPluginExtension extension, final Iterable<IPluginElement> elements) {
  // @Format-Off
  final boolean result = extension.getPoint().equals(PREFERENCES_EXTENSION_POINT_ID)
      && (!extensionNameMatches(extension, catalog)
      || Iterables.size(elements) != 2
      || !initializerClassMatches(getInitializerElement(elements), getTargetClassName(catalog)));
  return result;
  // @Format-On
}
 
Example 15
Source File: FeatureCollection.java    From activitystreams with Apache License 2.0 4 votes vote down vote up
public int size() {
  return Iterables.size(features());
}
 
Example 16
Source File: ImmutableRTreeTest.java    From bytebuffer-collections with Apache License 2.0 4 votes vote down vote up
public void showBenchmarks()
{
  final int start = 1;
  final int factor = 10;
  final int end = 10000000;
  final int radius = 10;

  for (int numPoints = start; numPoints <= end; numPoints *= factor) {
    try {
      BitmapFactory bf = new ConciseBitmapFactory();
      RTree tree = new RTree(2, new LinearGutmanSplitStrategy(0, 50, bf), bf);

      Stopwatch stopwatch = Stopwatch.createStarted();
      Random rand = new Random();
      for (int i = 0; i < numPoints; i++) {
        tree.insert(new float[]{(float) (rand.nextDouble() * 100), (float) (rand.nextDouble() * 100)}, i);
      }
      long stop = stopwatch.elapsed(TimeUnit.MILLISECONDS);
      System.out.printf("[%,d]: insert = %,d ms%n", numPoints, stop);

      stopwatch.reset().start();
      ImmutableRTree searchTree = ImmutableRTree.newImmutableFromMutable(tree);
      stop = stopwatch.elapsed(TimeUnit.MILLISECONDS);
      System.out.printf("[%,d]: size = %,d bytes%n", numPoints, searchTree.toBytes().length);
      System.out.printf("[%,d]: buildImmutable = %,d ms%n", numPoints, stop);

      stopwatch.reset().start();

      Iterable<ImmutableBitmap> points = searchTree.search(new RadiusBound(new float[]{50, 50}, radius));

      Iterables.size(points);
      stop = stopwatch.elapsed(TimeUnit.MILLISECONDS);

      System.out.printf("[%,d]: search = %,dms%n", numPoints, stop);

      stopwatch.reset().start();

      ImmutableBitmap finalSet = bf.union(points);

      stop = stopwatch.elapsed(TimeUnit.MILLISECONDS);
      System.out.printf("[%,d]: union of %,d points in %,d ms%n", numPoints, finalSet.size(), stop);
    }
    catch (Exception e) {
      throw Throwables.propagate(e);
    }
  }
}
 
Example 17
Source File: ExcelRepository.java    From molgenis with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public long count() {
  return Iterables.size(this);
}
 
Example 18
Source File: ErrorSafeExtensions.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
public <T extends EObject> void forEachSafely(ITreeAppendable appendable, Iterable<T> elements,
		Procedure1<? super LoopParams> loopInitializer, Procedure2<? super T, ? super ITreeAppendable> body) {
	if (Iterables.isEmpty(elements)) {
		return;
	}
	LoopParams loopParams = ObjectExtensions.operator_doubleArrow(new LoopParams(), loopInitializer);
	boolean allElementsBroken = Iterables
			.size(Iterables.<T>filter(elements, (T it) -> hasErrors(it))) == Iterables.size(elements);
	ITreeAppendable currentAppendable = null;
	if (allElementsBroken) {
		currentAppendable = openErrorAppendable(appendable, null);
	} else {
		currentAppendable = appendable;
	}
	loopParams.appendPrefix(currentAppendable);
	boolean isFirst = true;
	boolean isFirstBroken = true;
	for (T element : elements) {
		if (!hasErrors(element)) {
			currentAppendable = closeErrorAppendable(appendable, currentAppendable);
			if (!isFirst) {
				loopParams.appendSeparator(appendable);
			}
			isFirst = false;
			body.apply(element, appendable);
		} else {
			if (!allElementsBroken) {
				currentAppendable = openErrorAppendable(appendable, currentAppendable);
			}
			if (!isFirst || !isFirstBroken) {
				loopParams.appendSeparator(currentAppendable);
			}
			isFirstBroken = false;
			try {
				body.apply(element, currentAppendable);
			} catch (Exception ignoreMe) {
			}
		}
	}
	if (!allElementsBroken) {
		currentAppendable = closeErrorAppendable(appendable, currentAppendable);
	}
	loopParams.appendSuffix(currentAppendable);
	closeErrorAppendable(appendable, currentAppendable);
}
 
Example 19
Source File: N3streamWriter.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private int writeAtts(DataOutputStream stream, Iterable<Attribute> atts) throws IOException {
  int natts = Iterables.size(atts);
  if (null != stream) {
    if (natts == 0) {
      stream.writeInt(0);
      stream.writeInt(0);
    } else {
      stream.writeInt(N3header.MAGIC_ATT);
      stream.writeInt(natts);
    }
  }
  int hsize = 8;

  for (Attribute att : atts) {
    hsize += writeString(stream, N3iosp.makeValidNetcdfObjectName(att.getShortName()));
    int type = N3header.getType(att.getDataType());
    if (null != stream) {
      stream.writeInt(type);
    }
    hsize += 4;

    if (type == 2) {
      hsize += writeStringValues(stream, att);
    } else {
      int nelems = att.getLength();
      if (null != stream) {
        stream.writeInt(nelems);
      }
      hsize += 4;

      int nbytes = 0;
      for (int j = 0; j < nelems; j++) {
        nbytes += writeAttributeValue(stream, att.getNumericValue(j));
      }
      hsize += nbytes;

      hsize += pad(stream, nbytes, (byte) 0);
    }
  }

  return hsize;
}
 
Example 20
Source File: BuilderUtil.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
/***/
public static int countResourcesInIndex() {
	return Iterables.size(getAllResourceDescriptions());
}