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:it.uniroma1.bdc.tesi.piccioli.giraphstandalone.ksimplecycle.KSimpleCyclePlusPlus.java

@Override
public void compute(Vertex<LongWritable, LongWritable, NullWritable> vertex,
        Iterable<CustomMessageWithPathPlusPlus> messages) throws IOException {

    int k = 3; //circuiti chiusi di lunghezza k
    k += 2; //add supersep aggiuntivi

    Iterable<Edge<LongWritable, NullWritable>> edges = vertex.getEdges();
    if (getSuperstep() == 0) {
        //calcolo degree e invio a vertici vicini
        LongWritable degree = new LongWritable(Iterables.size(edges));
        vertex.setValue(degree);/*w w w  .j a v a 2 s  . c o m*/

        for (Edge<LongWritable, NullWritable> edge : edges) {
            this.sendMessage(edge.getTargetVertexId(),
                    new CustomMessageWithPathPlusPlus(vertex.getId(), degree));
        }

    } else if (getSuperstep() == 1) {

        //Ricevo Degree dai nodi vicini, elimino edge che collegano nodi "< degree minori"
        for (CustomMessageWithPathPlusPlus message : messages) {

            LongWritable messageValue = message.getValue();
            LongWritable vertexValue = vertex.getValue();
            LongWritable messageId = message.getId();
            LongWritable vertexId = vertex.getId();

            if ((messageValue.compareTo(vertexValue) < 0)
                    || ((messageValue.compareTo(vertexValue) == 0) && (messageId.compareTo(vertexId) < 0))) {
                this.removeEdgesRequest(messageId, vertexId);
            }
        }
    } else if (getSuperstep() == 2) {

        for (Edge<LongWritable, NullWritable> edge : vertex.getEdges()) {

            CustomMessageWithPathPlusPlus msg = new CustomMessageWithPathPlusPlus();

            msg.getVisitedVertex().add(vertex.getId());
            msg.setId(vertex.getId());

            sendMessage(edge.getTargetVertexId(), msg);
        }
    } else if (getSuperstep() > 2 && getSuperstep() < k) {

        for (CustomMessageWithPathPlusPlus message : messages) {
            if (!message.getVisitedVertex().contains(vertex.getId())) {
                for (Edge<LongWritable, NullWritable> edge : vertex.getEdges()) {
                    message.getVisitedVertex().add(vertex.getId());
                    sendMessage(edge.getTargetVertexId(), message);
                }
            }
        }

    } else if (getSuperstep() == k) {

        Long T = (long) 0;
        for (CustomMessageWithPathPlusPlus message : messages) {
            if (message.getId().compareTo(vertex.getId()) == 0) {
                T++;
            }

        }

        //            T = T / (2 * k);

        vertex.setValue(new LongWritable(T));
        vertex.voteToHalt();
        //            aggregate(SOMMA, new DoubleWritable(T));

    }
}

From source file:com.stratio.decision.functions.SaveToMongoActionExecutionFunction.java

@Override
public void process(Iterable<StratioStreamingMessage> messages) throws Exception {

    Integer partitionSize = maxBatchSize;

    if (partitionSize == null || partitionSize <= 0) {
        partitionSize = Iterables.size(messages);
    }//from w  ww .j av  a 2 s .co  m

    Iterable<List<StratioStreamingMessage>> partitionIterables = Iterables.partition(messages, partitionSize);

    try {

        for (List<StratioStreamingMessage> messageList : partitionIterables) {

            Map<String, BulkWriteOperation> elementsToInsert = new HashMap<String, BulkWriteOperation>();

            for (StratioStreamingMessage event : messageList) {
                BasicDBObject object = new BasicDBObject(TIMESTAMP_FIELD, event.getTimestamp());
                for (ColumnNameTypeValue columnNameTypeValue : event.getColumns()) {
                    object.append(columnNameTypeValue.getColumn(), columnNameTypeValue.getValue());
                }

                BulkWriteOperation bulkInsertOperation = elementsToInsert.get(event.getStreamName());

                if (bulkInsertOperation == null) {
                    bulkInsertOperation = getDB().getCollection(event.getStreamName())
                            .initializeUnorderedBulkOperation();

                    elementsToInsert.put(event.getStreamName(), bulkInsertOperation);
                    getDB().getCollection(event.getStreamName())
                            .createIndex(new BasicDBObject(TIMESTAMP_FIELD, -1));
                }

                bulkInsertOperation.insert(object);
            }

            for (Entry<String, BulkWriteOperation> stratioStreamingMessage : elementsToInsert.entrySet()) {
                stratioStreamingMessage.getValue().execute();
            }
        }

    } catch (Exception e) {
        log.error("Error saving in Mongo: " + e.getMessage());
    }
}

From source file:org.apache.giraph.utils.CollectionUtils.java

/**
 * Helper method to check if iterables are equal.  Supports the case
 * where the iterable next() returns a reused object.  We do assume that
 * iterator() produces the objects in the same order across repeated calls,
 * if the object doesn't change.   This is very expensive (n^2) and should
 * be used for testing only.//ww  w . j a  va 2  s  .co  m
 *
 * @param first First iterable
 * @param second Second iterable
 * @param <T> Type to compare
 * @return True if equal, false otherwise
 */
public static <T> boolean isEqual(Iterable<T> first, Iterable<T> second) {
    // Relies on elements from the iterator arriving in the same order.
    // For every element in first, check elements on the second iterable by
    // marking the ones seen that have been found.  Then ensure that all
    // the elements of the second have been seen as well.
    int firstSize = Iterables.size(first);
    int secondSize = Iterables.size(second);
    boolean[] usedSecondArray = new boolean[secondSize];
    Iterator<T> firstIterator = first.iterator();
    while (firstIterator.hasNext()) {
        T firstValue = firstIterator.next();
        boolean foundFirstValue = false;
        Iterator<T> secondIterator = second.iterator();
        for (int i = 0; i < usedSecondArray.length; ++i) {
            T secondValue = secondIterator.next();
            if (!usedSecondArray[i]) {
                if (firstValue.equals(secondValue)) {
                    usedSecondArray[i] = true;
                    foundFirstValue = true;
                    break;
                }
            }
        }

        if (!foundFirstValue) {
            LOG.error("isEqual: Couldn't find element from first (" + firstValue + ") in second " + second
                    + "(size=" + secondSize + ")");
            return false;
        }
    }

    Iterator<T> secondIterator = second.iterator();
    for (int i = 0; i < usedSecondArray.length; ++i) {
        T secondValue = secondIterator.next();
        if (!usedSecondArray[i]) {
            LOG.error("isEqual: Element " + secondValue + " (index " + i + ") in second " + second + "(size="
                    + secondSize + ") not found in " + first + " (size=" + firstSize + ")");
            return false;
        }
    }

    return true;
}

From source file:eu.numberfour.n4js.ui.preferences.ExternalLibraryTreeContentProvider.java

@Override
public void updateElement(final Object parent, final int index) {
    if (treeViewerRef.isPresent()) {
        final TreeViewer treeViewer = treeViewerRef.get();
        if (parent instanceof Iterable) {
            final Object child = Iterables.get((Iterable<?>) parent, index);
            treeViewer.replace(parent, index, child);
            if (child instanceof URI) {
                treeViewer.setChildCount(child, Iterables.size(getProjects((URI) child)));
            }//from  www  .  ja v a  2 s  .  c  o m
        } else if (parent instanceof URI) {
            final IN4JSProject child = Iterables.get(getProjects((URI) parent), index);
            treeViewer.replace(parent, index, child);
        }
    }
}

From source file:org.polymap.core.project.ui.util.SelectionAdapter.java

public <T> int size(Class<T> type) {
    return Iterables.size(elementsOfType(type));
}

From source file:org.jon.ivmark.graphit.core.graph.node.repository.ConcurrentNodeIdRepository.java

@Override
public int size() {
    // Very inefficient. TODO: Fix this.
    return Iterables.size(getNodes());
}

From source file:com.spotify.helios.servicescommon.RiemannSupport.java

public RiemannSupport(final MetricRegistry metricsRegistry, final String hostPort, final String hostName,
        final String serviceName) {
    this.metricsRegistry = metricsRegistry;
    this.serviceName = serviceName;
    this.hostName = hostName;
    if (Strings.isNullOrEmpty(hostPort)) {
        host = null;//from ww  w . j a  va 2 s.c o m
        port = 0;
        proto = null;
        return;
    }
    final Iterable<String> parts = Splitter.on(":").split(hostPort);
    final int size = Iterables.size(parts);
    if (size > 3 || size < 2) {
        throw new RuntimeException("specification of riemann host port has wrong number of parts.  Should be"
                + " [proto:]host:port, where proto is udp or tcp");
    }
    if (size == 3) {
        this.proto = Iterables.get(parts, 0);
    } else {
        this.proto = "udp";
    }
    checkState("udp".equals(this.proto) || "tcp".equals(this.proto));
    host = Iterables.get(parts, size - 2);
    port = Integer.valueOf(Iterables.get(parts, size - 1));
}

From source file:org.sonar.server.computation.period.PeriodsHolderImpl.java

/**
 * Initializes the periods in the holder.
 *
 * @throws NullPointerException if the specified Iterable is {@code null}
 * @throws NullPointerException if the specified Iterable contains a {@code null}
 * @throws IllegalArgumentException if the specified Iterable has more than 5 elements
 * @throws IllegalStateException if the holder has already been initialized
 * @throws IllegalStateException if two Periods have the same index
 *///from ww w.  j  av  a2 s .  c  o  m
public void setPeriods(Iterable<Period> periods) {
    requireNonNull(periods, "Periods cannot be null");
    checkArgument(Iterables.size(periods) <= MAX_NUMBER_OF_PERIODS,
            String.format("There can not be more than %d periods", MAX_NUMBER_OF_PERIODS));
    checkState(this.periods == null, "Periods have already been initialized");

    Period[] newPeriods = new Period[MAX_NUMBER_OF_PERIODS];
    for (Period period : from(periods).filter(CheckNotNull.INSTANCE)) {
        int arrayIndex = period.getIndex() - 1;
        checkArgument(newPeriods[arrayIndex] == null,
                "More than one period has the index " + period.getIndex());
        newPeriods[arrayIndex] = period;
    }
    this.periods = newPeriods;
}

From source file:net.freifunk.autodeploy.firmware.FirmwareServiceImpl.java

@Override
public Firmware findSupportedFirmware(final String firmwareString) {
    final Iterable<Firmware> matches = Iterables.filter(_configurators.keySet(), new Predicate<Firmware>() {

        @Override/*from w  w  w  .j a v a 2 s.c  o m*/
        public boolean apply(final Firmware firmware) {
            return firmware != null && firmware.getName().equals(firmwareString);
        }
    });

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

From source file:org.apache.people.mreutegg.mhmp.RenderTask.java

public void run() {
    BukkitScheduler scheduler = plugin.getServer().getScheduler();
    World world = player.getWorld();// w  ww .j  av a  2 s .c  o  m
    Location currentLoc = player.getLocation().add(0, 50, 0);
    plugin.getLogger().info("Player location: " + currentLoc);
    long num = Iterables.size(coordinates);
    plugin.getLogger().info("Rendering " + num + " coordinates");
    Location origin = null;
    int count = 0;
    long lastP = 0;
    Map<Location, Material> locations = Maps.newHashMap();
    for (Coordinate coord : coordinates) {
        count++;
        if (origin == null) {
            origin = coord.asLocation(world, scale);
        }
        final Location loc = currentLoc.clone().add(coord.asLocation(world, scale).subtract(origin));
        final Material m = coord.getMaterial();
        locations.put(loc, m);
        if (count % 10000 == 0) {
            long p = 100L * count / num;
            if (p > lastP) {
                plugin.getLogger().info(p + "% done");
                lastP = p;
            }
        }
        if (locations.size() >= 5) {
            scheduleTask(scheduler, locations);
            locations.clear();
            while (scheduledTasks.get() > 10) {
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    // ignore
                }
            }
        }

    }
    if (!locations.isEmpty()) {
        scheduleTask(scheduler, locations);
    }
    if (lastP < 100) {
        plugin.getLogger().info("100% done");
    }
}