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

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

Introduction

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

Prototype

public static <T> Iterable<T> limit(final Iterable<T> iterable, final int limitSize) 

Source Link

Document

Creates an iterable with the first limitSize elements of the given iterable.

Usage

From source file:org.testfx.robot.impl.MoveRobotImpl.java

private void moveMouseStepwiseBetween(Point2D sourcePoint, Point2D targetPoint) {
    double pointDistance = calculateDistanceBetween(sourcePoint, targetPoint);
    int pointOffsetCount = (int) limitValueBetween(pointDistance, MIN_POINT_OFFSET_COUNT,
            MAX_POINT_OFFSET_COUNT);/*w w  w.jav a 2s  .  com*/
    List<Point2D> points = interpolatePointsBetween(sourcePoint, targetPoint, pointOffsetCount);
    for (Point2D point : Iterables.limit(points, points.size() - 1)) {
        mouseRobot.moveNoWait(point);
        sleepRobot.sleep(SLEEP_AFTER_MOVEMENT_STEP_IN_MILLIS);
    }
    mouseRobot.move(targetPoint);
}

From source file:org.apache.mahout.knn.search.ProjectionSearch3.java

public List<WeightedVector> search(final Vector query, int n) {
    // this is keyed by the underlying vector to make sure that comparisons
    // work right between different projections.  The value is a shallow copy of
    // the result vector so that we can set the weight to the actual distance from
    // the query// ww  w .  j av a  2 s  .co m
    Map<Vector, WeightedVector> distances = Maps.newHashMap();

    // for each projection
    Iterator<Vector> projections = basis.iterator();
    for (TreeSet<WeightedVector> v : vectors) {
        WeightedVector projectedQuery = WeightedVector.project(query, projections.next());

        // Collect nearby vectors
        List<WeightedVector> candidates = Lists.newArrayList();
        Iterables.addAll(candidates, Iterables.limit(v.tailSet(projectedQuery, true), searchSize));
        Iterables.addAll(candidates,
                Iterables.limit(v.headSet(projectedQuery, false).descendingSet(), searchSize));

        // find maximum projected distance in nearby values.
        // all unmentioned values will be at least that far away.
        // also collect a set of unmentioned values
        Set<Vector> unmentioned = Sets.newHashSet(distances.keySet());
        double maxDistance = 0;
        for (WeightedVector vector : candidates) {
            unmentioned.remove(vector.getVector());
            maxDistance = Math.max(maxDistance, vector.getWeight());
        }

        // all unmentioned vectors have to be put at least as far away as we can justify
        for (Vector vector : unmentioned) {
            WeightedVector x = distances.get(vector);
            if (maxDistance > x.getWeight()) {
                x.setWeight(maxDistance);
            }
        }

        // and all candidates get a real test
        for (WeightedVector candidate : candidates) {
            WeightedVector x = distances.get(candidate);
            if (x == null) {
                // have to copy here because we may mutate weights later on
                distances.put(candidate.getVector(),
                        new WeightedVector(candidate.getVector(), candidate.getWeight(), candidate.getIndex()));
            } else if (x.getWeight() < candidate.getWeight()) {
                x.setWeight(candidate.getWeight());
            }
        }
    }

    // now collect the results and sort by actual distance
    // TODO It doesn't seem to make a great gob of sense to collect the max projected distance and then toss it away
    List<WeightedVector> r = Lists.newArrayList();
    for (Vector key : distances.keySet()) {
        WeightedVector x = distances.get(key);
        x.setWeight(distance.distance(query, key));
        r.add(x);
    }

    Collections.sort(r);
    return r.subList(0, n);
}

From source file:org.apache.drill.exec.store.sys.store.LocalPersistentStore.java

@Override
public Iterator<Map.Entry<String, V>> getRange(int skip, int take) {
    try {//from w  ww .ja  v a2s. c  o m
        List<FileStatus> f = fs.list(false, basePath);
        if (f == null || f.isEmpty()) {
            return Collections.emptyIterator();
        }
        List<String> files = Lists.newArrayList();

        for (FileStatus stat : f) {
            String s = stat.getPath().getName();
            if (s.endsWith(DRILL_SYS_FILE_SUFFIX)) {
                files.add(s.substring(0, s.length() - DRILL_SYS_FILE_SUFFIX.length()));
            }
        }

        Collections.sort(files);
        return Iterables.transform(Iterables.limit(Iterables.skip(files, skip), take),
                new Function<String, Entry<String, V>>() {
                    @Nullable
                    @Override
                    public Entry<String, V> apply(String key) {
                        return new ImmutableEntry<>(key, get(key));
                    }
                }).iterator();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.sonar.java.model.DefaultJavaFileScannerContext.java

@Override
public void reportIssueWithFlow(JavaCheck javaCheck, Tree syntaxNode, String message,
        Iterable<List<Location>> flows, @Nullable Integer cost) {
    // FIXME SONARJAVA-2111 all flows should be reported for SE checks
    Iterable<List<Location>> reportedFlows = javaCheck instanceof SECheck ? Iterables.limit(flows, 1) : flows;
    sonarComponents.reportIssue(// w w w .ja v a2s.c om
            createAnalyzerMessage(file, javaCheck, syntaxNode, null, message, reportedFlows, cost));
}

From source file:ezbake.data.graph.blueprints.visibility.VisibilityFilterQuery.java

/**
 * If a limit is set on the query, limit the number of items returned.
 *
 * @param it iterable to limit//  w ww  .  ja  va  2 s .  com
 * @return iterable with at most a certain number of elements
 */
protected <T> Iterable<T> limitElements(Iterable<T> it) {
    if (limit >= 0) {
        return Iterables.limit(it, limit);
    } else {
        return it;
    }
}

From source file:de.faustedition.search.SearchResource.java

private List<LayerNode<JsonNode>> fulltextQuery(String term) {
    return Lists.newArrayList(Iterables.limit(verseManager.fulltextQuery(term), 15));
}

From source file:org.apache.mahout.clustering.ClusteringUtils.java

public static <T extends Vector> double estimateDistanceCutoff(Iterable<T> data,
        DistanceMeasure distanceMeasure, int sampleLimit) {
    return estimateDistanceCutoff(Lists.newArrayList(Iterables.limit(data, sampleLimit)), distanceMeasure);
}

From source file:de.faustedition.search.SearchResource.java

private List<Document> idnoQuery(String term) {
    return Lists.newArrayList(Iterables.limit(Document.find(db, term), 10));
}

From source file:org.opentestsystem.delivery.testreg.rest.ValidationHelper.java

private static List<FileValidationResult> buildValidationResult(
        final Map<String, List<ValidationMessage>> errorMap, final int errorCountThreshold) {
    final List<FileValidationResult> validationResults = new ArrayList<FileValidationResult>();
    for (final Map.Entry<String, List<ValidationMessage>> entry : errorMap.entrySet()) {
        final FileValidationResult validationResult = new FileValidationResult();
        validationResult.setFormatType(entry.getKey().toUpperCase());
        Collections.sort(entry.getValue());
        for (final ValidationMessage message : entry.getValue()) {
            validationResult.addError(message);
        }// w ww  .jav  a  2s.c o m
        if (!CollectionUtils.isEmpty(validationResult.getFatalErrors())
                && validationResult.getFatalErrors().size() > errorCountThreshold) {
            validationResult.setFatalErrorsTotalCount(validationResult.getFatalErrors().size());
            validationResult.setFatalErrors(Lists
                    .newArrayList(Iterables.limit(validationResult.getFatalErrors(), errorCountThreshold)));
        }
        if (!CollectionUtils.isEmpty(validationResult.getRecordErrors())
                && validationResult.getRecordErrors().size() > errorCountThreshold) {
            validationResult.setRecordErrorsTotalCount(validationResult.getRecordErrors().size());
            validationResult.setRecordErrors(Lists
                    .newArrayList(Iterables.limit(validationResult.getRecordErrors(), errorCountThreshold)));
        }
        if (!CollectionUtils.isEmpty(validationResult.getWarnings())
                && validationResult.getWarnings().size() > errorCountThreshold) {
            validationResult.setWarningsTotalCount(validationResult.getWarnings().size());
            validationResult.setWarnings(
                    Lists.newArrayList(Iterables.limit(validationResult.getWarnings(), errorCountThreshold)));
        }
        validationResults.add(validationResult);
    }
    return validationResults;
}

From source file:com.moz.fiji.commons.monitoring.RiemannNotifier.java

/** {@inheritDoc} */
@Override//  w  ww.  j  av  a2 s .  c  om
public void error(final String action, final Map<String, String> attributes, final Throwable error) {
    final Event.Builder event = Proto.Event.newBuilder();
    for (Map.Entry<String, String> entry : attributes.entrySet()) {
        event.addAttributes(
                Proto.Attribute.newBuilder().setKey(entry.getKey()).setValue(entry.getValue()).build());
    }

    event.setHost(mHost).setService("wibi.bblocks." + action).setTime(System.currentTimeMillis() / 1000L)
            .setState("error").addTags("error").addTags("notification").build();

    if (error != null) {
        final List<StackTraceElement> frames = Arrays.asList(error.getStackTrace());

        final StringBuilder description = new StringBuilder();

        description.append(error.getMessage());
        description.append('\n');
        Joiner.on('\n').appendTo(description, Iterables.limit(frames, 20));
        if (frames.size() > 20) {
            description.append("\n...");
        }
        event.setDescription(description.toString());
    }

    if (!mQueue.offer(event.build()) && mQueueFullLimiter.tryAcquire()) {
        LOG.error("Riemann queue full. Dropping notifications.");
    }
}