Example usage for com.google.common.collect Iterables size

List of usage examples for com.google.common.collect Iterables size

Introduction

In this page you can find the example usage for com.google.common.collect Iterables size.

Prototype

public static int size(Iterable<?> iterable) 

Source Link

Document

Returns the number of elements in iterable .

Usage

From source file:edu.sabanciuniv.sentilab.sare.controllers.setcover.SetCoverFactory.java

private DocumentSetCover createSpecific(DocumentSetCover setcover, PersistentDocumentStore store,
        TokenizingOptions tokenizingOptions, double weightCoverage) {
    Validate.notNull(store, CannedMessages.NULL_ARGUMENT, "store");

    if (tokenizingOptions == null) {
        tokenizingOptions = new TokenizingOptions();
    }//  w w  w . j  av  a  2s.  co m

    double progress = 0.0;
    int storeSize = Iterables.size(store.getDocuments());

    // create a dummy set cover to keep the extra stuff in.
    DocumentSetCover dummySetCover = new DocumentSetCover(store);

    List<PersistentDocument> corpusDocuments = Lists.newArrayList(store.getDocuments());
    List<SetCoverDocument> setCoverDocuments = Lists.newArrayList(setcover.getAllDocuments());

    // for each store document.
    for (PersistentDocument document : corpusDocuments) {
        // create a copy of the current document as a set cover document.
        SetCoverDocument workingDocument = (SetCoverDocument) new SetCoverDocument(document)
                .setTokenizingOptions(tokenizingOptions).setStore(dummySetCover);

        // loop through all set cover documents.
        for (int index = 0; index < setCoverDocuments.size(); index++) {
            SetCoverDocument setCoverDocument = setCoverDocuments.get(index);

            // create a working reference to the set cover document.
            SetCoverDocument workingSCDocument = setCoverDocument;

            // get merge weights on both directions.
            double forwardMerge = workingSCDocument.getMergedWeight(workingDocument);
            double backwardMerge = workingDocument.getMergedWeight(workingSCDocument);

            // if we get more weight on the backward merge, swap the documents.
            if (forwardMerge < backwardMerge) {
                setCoverDocuments.add(setCoverDocuments.indexOf(workingSCDocument), workingDocument);
                setCoverDocuments.remove(workingSCDocument);

                SetCoverDocument tmpSCDocument = workingDocument;
                workingDocument = workingSCDocument;
                workingSCDocument = tmpSCDocument;
            }

            // perform the merge.
            workingSCDocument.merge(workingDocument);

            // if the entire document has been consumed, then we are done with it.
            if (workingDocument.getTotalTokenWeight() == 0) {
                break;
            }
        }

        setCoverDocuments.add(workingDocument);

        // if the document was completely consumed, then we mark it as uncovered.
        if (workingDocument.getTotalTokenWeight() == 0) {
            workingDocument.setCovered(false);
        }

        progress += 1.0 / storeSize;
        this.notifyProgress(progress, "create");
    }

    setcover.setDocuments(setCoverDocuments);

    // get rid of the dummy.
    dummySetCover.setBaseStore(null);

    return setcover.adjustCoverage(weightCoverage).setTokenizingOptions(tokenizingOptions);
}

From source file:org.janusgraph.graphdb.relations.CacheEdge.java

@Override
public InternalRelation it() {
    InternalRelation it = null;//from  w  ww.  j  a va 2s  . com
    InternalVertex startVertex = getVertex(0);

    if (startVertex.hasAddedRelations() && startVertex.hasRemovedRelations()) {
        //Test whether this relation has been replaced
        final long id = super.longId();
        Iterable<InternalRelation> previous = startVertex.getAddedRelations(new Predicate<InternalRelation>() {
            @Override
            public boolean apply(@Nullable InternalRelation internalRelation) {
                return (internalRelation instanceof StandardEdge)
                        && ((StandardEdge) internalRelation).getPreviousID() == id;
            }
        });
        assert Iterables.size(previous) <= 1 || (isLoop() && Iterables.size(previous) == 2);
        it = Iterables.getFirst(previous, null);
    }

    if (it != null)
        return it;

    return super.it();
}

From source file:com.googlecode.blaisemath.util.Points.java

/**
 * Compute the average location of a set of points.
 * @param locs points//from  w  w  w .j  a va 2  s .  com
 * @return average loc
 */
public static Point2D average(Iterable<? extends Point2D> locs) {
    checkArgument(Iterables.size(locs) > 0);
    double sumx = 0;
    double sumy = 0;
    int count = 0;
    for (Point2D p : locs) {
        sumx += p.getX();
        sumy += p.getY();
        count++;
    }
    return new Point2D.Double(sumx / count, sumy / count);
}

From source file:org.dyndns.jkiddo.dmp.chunks.media.Listing.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public ListingItem getSingleListingItem(Predicate predicate) {
    Iterable<ListingItem> filteredItems = Iterables.filter(getListingItems(), predicate);

    if (Iterables.size(filteredItems) < 1) {
        throw new NoSuchElementException("Found no ListingItems fullfilling predicate");
    }//from w  ww  .  ja va2s  .c o  m
    if (Iterables.size(filteredItems) > 1) {
        logger.info("Found more than one ListingItem fullfilling predicate - returning the first one");
    }

    return filteredItems.iterator().next();
}

From source file:org.eclipse.sirius.tests.swtbot.sequence.condition.CheckReturnMessageNumber.java

private static int getReturnMessageNumber(SWTBotSiriusDiagramEditor editor) {
    List<SWTBotGefConnectionEditPart> connections = editor.getConnectionsEditPart();
    Function<SWTBotGefConnectionEditPart, ConnectionEditPart> getEditPart = new Function<SWTBotGefConnectionEditPart, ConnectionEditPart>() {
        public ConnectionEditPart apply(SWTBotGefConnectionEditPart from) {
            return from.part();
        }// w ww . ja  v  a 2  s.com
    };

    Predicate<ConnectionEditPart> isReturnMessage = new Predicate<ConnectionEditPart>() {
        public boolean apply(ConnectionEditPart input) {
            if (input instanceof SequenceMessageEditPart) {
                SequenceMessageEditPart smep = (SequenceMessageEditPart) input;

                Option<Message> message = ISequenceElementAccessor.getMessage(smep.getNotationView());
                if (Message.viewpointElementPredicate().apply(smep.resolveDiagramElement()) && message.some()) {
                    return Message.Kind.REPLY.equals(message.get().getKind());
                }
            }
            return false;
        }
    };
    return Iterables.size(Iterables.filter(Iterables.transform(connections, getEditPart), isReturnMessage));
}

From source file:org.apache.brooklyn.entity.stock.BasicStartableImpl.java

@Override
public void start(Collection<? extends Location> locations) {
    try {//from  ww w .ja  v a  2  s  .  c om
        ServiceStateLogic.setExpectedState(this, Lifecycle.STARTING);

        addLocations(locations);
        locations = Locations.getLocationsCheckingAncestors(locations, this);
        log.info("Starting entity " + this + " at " + locations);

        // essentially does StartableMethods.start(this, locations),
        // but optionally filters locations for each child

        Locations.LocationsFilter filter = getConfig(LOCATIONS_FILTER);
        Iterable<Entity> startables = filterStartableManagedEntities(getChildren());
        if (!Iterables.isEmpty(startables)) {
            List<Task<?>> tasks = Lists.newArrayListWithCapacity(Iterables.size(startables));
            for (final Entity entity : startables) {
                Collection<? extends Location> l2 = locations;
                if (filter != null) {
                    l2 = filter.filterForContext(new ArrayList<Location>(locations), entity);
                    log.debug("Child " + entity + " of " + this + " being started in filtered location list: "
                            + l2);
                }
                tasks.add(Entities.invokeEffectorWithArgs(this, entity, Startable.START, l2));
            }
            for (Task<?> t : tasks) {
                t.getUnchecked();
            }
        }
        sensors().set(Attributes.SERVICE_UP, true);
        ServiceStateLogic.setExpectedState(this, Lifecycle.RUNNING);
    } catch (Throwable t) {
        ServiceStateLogic.setExpectedState(this, Lifecycle.ON_FIRE);
        throw Exceptions.propagate(t);
    }
}

From source file:net.freifunk.autodeploy.device.DeviceServiceImpl.java

@Override
public Device findSupportedDevice(final String deviceString) {
    final Iterable<Device> matches = Iterables.filter(_deployersByDevice.keySet(), new Predicate<Device>() {

        @Override/*  www .  j  a va  2s  .  c o m*/
        public boolean apply(final Device device) {
            return device != null && device.asString().equals(deviceString);
        }
    });

    if (Iterables.size(matches) > 1) {
        throw new IllegalStateException("More than one device found: " + deviceString);
    }
    return Iterables.getFirst(matches, null);
}

From source file:com.google.devtools.build.lib.bazel.rules.genrule.GenRule.java

private Artifact getExecutable(RuleContext ruleContext, NestedSet<Artifact> filesToBuild) {
    if (Iterables.size(filesToBuild) == 1) {
        Artifact out = Iterables.getOnlyElement(filesToBuild);
        if (ruleContext.attributes().get("executable", Type.BOOLEAN)) {
            return out;
        }/*w ww. j  a  va 2s.  c o m*/
    }
    return null;
}

From source file:eu.interedition.collatex.util.VariantGraphTraversal.java

@Override
public Iterator<VariantGraph.Vertex> iterator() {
    return new AbstractIterator<VariantGraph.Vertex>() {
        private final Map<VariantGraph.Vertex, Integer> encountered = Maps.newHashMap();
        private final Queue<VariantGraph.Vertex> queue = new ArrayDeque<VariantGraph.Vertex>(
                singleton(graph.getStart()));

        @Override// w ww.  j ava2 s .  co  m
        protected VariantGraph.Vertex computeNext() {
            if (queue.isEmpty()) {
                return endOfData();
            }
            final VariantGraph.Vertex next = queue.remove();
            for (VariantGraph.Edge edge : next.outgoing(witnesses)) {
                final VariantGraph.Vertex end = edge.to();

                final int endEncountered = Objects.firstNonNull(encountered.get(end), 0);
                final int endIncoming = Iterables.size(end.incoming(witnesses));

                if (endIncoming == endEncountered) {
                    throw new IllegalStateException(
                            String.format("Encountered cycle traversing %s to %s", edge, end));
                } else if ((endIncoming - endEncountered) == 1) {
                    queue.add(end);
                }

                encountered.put(end, endEncountered + 1);
            }
            return next;
        }
    };
}

From source file:org.apache.provisionr.amazon.core.ImageTable.java

static <K, V> Iterable<Map.Entry<K, V>> zip(Iterable<K> first, Iterable<V> second) {
    checkArgument(Iterables.size(first) == Iterables.size(second), "iterables don't have the same size");

    final Iterator<K> iterator = first.iterator();
    return newArrayList(transform(second, new Function<V, Map.Entry<K, V>>() {
        @Override//from   w ww .  j ava2s  .  co m
        public Map.Entry<K, V> apply(V input) {
            return Maps.immutableEntry(iterator.next(), input);
        }
    }));
}