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

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

Introduction

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

Prototype

public static <T> Iterable<T> skip(final Iterable<T> iterable, final int numberToSkip) 

Source Link

Document

Returns a view of iterable that skips its first numberToSkip elements.

Usage

From source file:org.onos.yangtools.yang.data.impl.schema.InstanceIdToCompositeNodes.java

@Override
@SuppressWarnings("unchecked")
public final NormalizedNode<?, ?> create(final YangInstanceIdentifier instanceId,
        final Optional<NormalizedNode<?, ?>> lastChild,
        final Optional<Map.Entry<QName, ModifyAction>> operation) {
    checkNotNull(instanceId);/*from w  ww.j a  v  a2 s  .  c o m*/
    final Iterator<PathArgument> iterator = instanceId.getPathArguments().iterator();
    final PathArgument legacyData = iterator.next();

    if (!isMixin() && getIdentifier().getNodeType() != null) {
        checkArgument(getIdentifier().getNodeType().equals(legacyData.getNodeType()),
                "Node QName must be %s was %s", getIdentifier().getNodeType(), legacyData.getNodeType());
    }
    final NormalizedNodeContainerBuilder builder = createBuilder(legacyData);

    if (iterator.hasNext()) {
        final PathArgument childPath = iterator.next();
        final InstanceIdToNodes<?> childOp = getChildOperation(childPath);

        final YangInstanceIdentifier childId = YangInstanceIdentifier
                .create(Iterables.skip(instanceId.getPathArguments(), 1));
        builder.addChild(childOp.create(childId, lastChild, operation));
    } else {
        if (lastChild.isPresent()) {
            builder.withValue(Lists.newArrayList((Collection<?>) lastChild.get().getValue()));
        }
        if (operation.isPresent()) {
            Preconditions.checkArgument(builder instanceof AttributesBuilder<?>);
            addModifyOpIfPresent(operation, ((AttributesBuilder<?>) builder));
        }
    }

    return builder.build();
}

From source file:google.registry.tools.CreateAuctionCreditsCommand.java

/**
 * Parses the provided CSV file of data from the auction provider and returns a multimap mapping
 * each registrar to the collection of auction credit amounts from this TLD's auctions that should
 * be awarded to this registrar, and validating that every credit amount's currency is in the
 * specified TLD-wide currency./*from  w ww . j  a  v  a 2 s.c  o m*/
 */
private static ImmutableMultimap<Registrar, BigMoney> parseCreditsFromCsv(Path csvFile, String tld)
        throws IOException {
    List<String> lines = Files.readAllLines(csvFile, StandardCharsets.UTF_8);
    checkArgument(CsvHeader.getHeaders().equals(splitCsvLine(lines.get(0))),
            "Expected CSV header line not present");
    ImmutableMultimap.Builder<Registrar, BigMoney> builder = new ImmutableMultimap.Builder<>();
    for (String line : Iterables.skip(lines, 1)) {
        List<String> fields = splitCsvLine(line);
        checkArgument(CsvHeader.getHeaders().size() == fields.size(), "Wrong number of fields");
        try {
            String registrarId = fields.get(CsvHeader.AFFILIATE.ordinal());
            Registrar registrar = checkNotNull(Registrar.loadByClientId(registrarId), "Registrar %s not found",
                    registrarId);
            CurrencyUnit tldCurrency = Registry.get(tld).getCurrency();
            CurrencyUnit currency = CurrencyUnit.of((fields.get(CsvHeader.CURRENCY_CODE.ordinal())));
            checkArgument(tldCurrency.equals(currency), "Credit in wrong currency (%s should be %s)", currency,
                    tldCurrency);
            // We use BigDecimal and BigMoney to preserve fractional currency units when computing the
            // total amount of each credit (since auction credits are percentages of winning bids).
            BigDecimal creditAmount = new BigDecimal(fields.get(CsvHeader.COMMISSIONS.ordinal()));
            BigMoney credit = BigMoney.of(currency, creditAmount);
            builder.put(registrar, credit);
        } catch (IllegalArgumentException | IndexOutOfBoundsException e) {
            throw new IllegalArgumentException("Error in line: " + line, e);
        }
    }
    return builder.build();
}

From source file:edu.udo.scaffoldhunter.model.util.Subsets.java

/**
 * Creates the intersection of an arbitrary number of {@link Subsets}. The
 * {@link Session} is the same as the parents {@link Session}.
 * /*from  ww w.  j  a va2  s.c o m*/
 * @param parent
 *            the parent {@link Subset}, or null to use the first input
 *            {@link Subset}
 * @param subsets
 *            the input {@link Subset}s
 * 
 * @return the intersection {@link Subset}
 */
public static Subset intersection(Subset parent, Iterable<Subset> subsets) {
    Preconditions.checkNotNull(subsets);

    Set<Molecule> molecules = Sets.newHashSet(Iterables.get(subsets, 0));
    for (Subset s : Iterables.skip(subsets, 1)) {
        Set<Molecule> set = Sets.newHashSet(s);
        molecules.retainAll(set);
    }

    if (parent == null) {
        parent = Iterables.get(subsets, 0);
    }

    return new Subset(parent, "intersection subset", null, parent.getSession(), molecules, null);
}

From source file:org.opendaylight.yangtools.yang.data.impl.schema.InstanceIdToCompositeNodes.java

@Override
@SuppressWarnings("unchecked")
public final NormalizedNode<?, ?> create(final YangInstanceIdentifier instanceId,
        final Optional<NormalizedNode<?, ?>> lastChild,
        final Optional<Map.Entry<QName, ModifyAction>> operation) {
    checkNotNull(instanceId);/*from   w ww.  j ava 2 s .  c om*/
    final Iterator<PathArgument> iterator = instanceId.getPathArguments().iterator();
    final PathArgument legacyData = iterator.next();

    if (!isMixin() && getIdentifier().getNodeType() != null) {
        checkArgument(getIdentifier().getNodeType().equals(legacyData.getNodeType()),
                "Node QName must be %s was %s", getIdentifier().getNodeType(), legacyData.getNodeType());
    }
    @SuppressWarnings("rawtypes")
    final NormalizedNodeContainerBuilder builder = createBuilder(legacyData);

    if (iterator.hasNext()) {
        final PathArgument childPath = iterator.next();
        final InstanceIdToNodes<?> childOp = getChildOperation(childPath);

        final YangInstanceIdentifier childId = YangInstanceIdentifier
                .create(Iterables.skip(instanceId.getPathArguments(), 1));
        builder.addChild(childOp.create(childId, lastChild, operation));
    } else {
        if (lastChild.isPresent()) {
            builder.withValue(Lists.newArrayList((Collection<?>) lastChild.get().getValue()));
        }
        if (operation.isPresent()) {
            Preconditions.checkArgument(builder instanceof AttributesBuilder<?>);
            addModifyOpIfPresent(operation, ((AttributesBuilder<?>) builder));
        }
    }

    return builder.build();
}

From source file:com.google.errorprone.bugpatterns.ProtoRedundantSet.java

private Description describe(ProtoField protoField, Collection<FieldWithValue> locations, VisitorState state) {
    // We flag up all duplicate sets, but only suggest a fix if the setter is given the same
    // argument (based on source code). This is to avoid the temptation to apply the fix in
    // cases like,
    //   MyProto.newBuilder().setFoo(copy.getFoo()).setFoo(copy.getBar())
    // where the correct fix is probably to replace the second 'setFoo' with 'setBar'.
    SuggestedFix.Builder fix = SuggestedFix.builder();
    long values = locations.stream().map(l -> state.getSourceForNode(l.getArgument())).distinct().count();
    if (values == 1) {
        for (FieldWithValue field : Iterables.skip(locations, 1)) {
            MethodInvocationTree method = field.getMethodInvocation();
            int startPos = state.getEndPosition(ASTHelpers.getReceiver(method));
            int endPos = state.getEndPosition(method);
            fix.replace(startPos, endPos, "");
        }/*  w ww  .  j  ava2  s  .  com*/
    }
    return buildDescription(locations.iterator().next().getArgument()).setMessage(String.format(
            "%s was called %s with %s. Setting the same field multiple times is redundant, and "
                    + "could mask a bug.",
            protoField, nTimes(locations.size()), values == 1 ? "the same argument" : "different arguments"))
            .addFix(fix.build()).build();
}

From source file:org.sosy_lab.cpachecker.util.predicates.interpolation.strategy.NestedInterpolation.java

/** This function implements the paper "Nested Interpolants" with a small modification:
 * instead of a return-edge, we use dummy-edges with simple pathformula "true".
 * Actually the implementation does not use "true", but omits it completely and
 * returns the conjunction of the two interpolants (before and after the (non-existing) dummy edge).
 * TODO simplify this algorithm, it is soo ugly! Maybe it is 'equal' with the normal tree-interpolation. */
private BooleanFormula getNestedInterpolant(
        final List<Triple<BooleanFormula, AbstractState, T>> formulasWithStatesAndGroupdIds,
        final List<BooleanFormula> interpolants,
        final Deque<Triple<BooleanFormula, BooleanFormula, CFANode>> callstack,
        final InterpolationManager.Interpolator<T> interpolator, int positionOfA, BooleanFormula lastItp)
        throws InterruptedException, SolverException {

    // use a new prover, because we use several distinct queries
    try (final InterpolatingProverEnvironment<T> itpProver = interpolator.newEnvironment()) {

        final List<T> A = new ArrayList<>();
        final List<T> B = new ArrayList<>();

        // If we have entered or exited a function, update the stack of entry points
        final AbstractState abstractionState = checkNotNull(
                formulasWithStatesAndGroupdIds.get(positionOfA).getSecond());
        final CFANode node = AbstractStates.extractLocation(abstractionState);

        if (node instanceof FunctionEntryNode && callHasReturn(formulasWithStatesAndGroupdIds, positionOfA)) {
            // && (positionOfA > 0)) {
            // case 2 from paper
            final BooleanFormula call = formulasWithStatesAndGroupdIds.get(positionOfA).getFirst();
            callstack.addLast(Triple.of(lastItp, call, node));
            final BooleanFormula itp = bfmgr.makeBoolean(true);
            interpolants.add(itp);//from w  ww. j  a  va2s.  c o  m
            return itp; // PSIminus = True --> PSI = True, for the 3rd rule ITP is True
        }

        A.add(itpProver.push(lastItp));
        A.add(itpProver.push(formulasWithStatesAndGroupdIds.get(positionOfA).getFirst()));

        // add all remaining PHI_j
        for (Triple<BooleanFormula, AbstractState, T> t : Iterables.skip(formulasWithStatesAndGroupdIds,
                positionOfA + 1)) {
            B.add(itpProver.push(t.getFirst()));
        }

        // add all previous function calls
        for (Triple<BooleanFormula, BooleanFormula, CFANode> t : callstack) {
            B.add(itpProver.push(t.getFirst())); // add PSI_k
            B.add(itpProver.push(t.getSecond())); // ... and PHI_k
        }

        // update prover with new formulas.
        // this is the expensive step, that is distinct from other strategies.
        // TODO improve! example: reverse ordering of formulas for re-usage of the solver-stack
        boolean unsat = itpProver.isUnsat();
        assert unsat : "formulas were unsat before, they have to be unsat now.";

        // get interpolant of A and B, for B we use the complementary set of A
        final BooleanFormula itp = itpProver.getInterpolant(A);

        if (!callstack.isEmpty() && node instanceof FunctionExitNode) {
            // case 4, we are returning from a function, rule 4
            Triple<BooleanFormula, BooleanFormula, CFANode> scopingItp = callstack.removeLast();

            final InterpolatingProverEnvironment<T> itpProver2 = interpolator.newEnvironment();
            final List<T> A2 = new ArrayList<>();
            final List<T> B2 = new ArrayList<>();

            A2.add(itpProver2.push(itp));
            //A2.add(itpProver2.push(orderedFormulas.get(positionOfA).getFirst()));

            A2.add(itpProver2.push(scopingItp.getFirst()));
            A2.add(itpProver2.push(scopingItp.getSecond()));

            // add all remaining PHI_j
            for (Triple<BooleanFormula, AbstractState, T> t : Iterables.skip(formulasWithStatesAndGroupdIds,
                    positionOfA + 1)) {
                B2.add(itpProver2.push(t.getFirst()));
            }

            // add all previous function calls
            for (Triple<BooleanFormula, BooleanFormula, CFANode> t : callstack) {
                B2.add(itpProver2.push(t.getFirst())); // add PSI_k
                B2.add(itpProver2.push(t.getSecond())); // ... and PHI_k
            }

            boolean unsat2 = itpProver2.isUnsat();
            assert unsat2 : "formulas2 were unsat before, they have to be unsat now.";

            // get interpolant of A and B, for B we use the complementary set of A
            BooleanFormula itp2 = itpProver2.getInterpolant(A2);
            itpProver2.close();

            BooleanFormula rebuildItp = rebuildInterpolant(itp, itp2);
            if (!bfmgr.isTrue(scopingItp.getFirst())) {
                rebuildItp = bfmgr.and(rebuildItp, scopingItp.getFirst());
            }

            interpolants.add(rebuildItp);
            return itp2;

        } else {
            interpolants.add(itp);
            return itp;
        }
    }
}

From source file:brooklyn.entity.network.bind.BindDnsServerImpl.java

@Override
protected void preStart() {
    String reverse = getConfig(REVERSE_LOOKUP_NETWORK);
    if (Strings.isBlank(reverse))
        reverse = getAttribute(ADDRESS);
    setAttribute(REVERSE_LOOKUP_CIDR, new Cidr(reverse + "/24"));
    String reverseLookupDomain = Joiner.on('.')
            .join(Iterables.skip(Lists.reverse(Lists.newArrayList(Splitter.on('.').split(reverse))), 1))
            + ".in-addr.arpa";
    setAttribute(REVERSE_LOOKUP_DOMAIN, reverseLookupDomain);

    addPolicy(PolicySpec.create(MemberTrackingPolicy.class).displayName("Address tracker")
            .configure(AbstractMembershipTrackingPolicy.SENSORS_TO_TRACK,
                    ImmutableSet.<Sensor<?>>of(getConfig(HOSTNAME_SENSOR)))
            .configure(AbstractMembershipTrackingPolicy.GROUP, getEntities()));
}

From source file:org.fcrepo.kernel.utils.iterators.RdfStream.java

/**
 * As {@link Iterables#skip(Iterable, int)} while maintaining context.
 *
 * @param skipNum/*from  www.  j  a va2s  .co m*/
 * @return
 */
public RdfStream skip(final Integer skipNum) {
    if (skipNum < 0) {
        return this;
    }
    return withThisContext(Iterables.skip(this, skipNum));
}

From source file:org.apache.brooklyn.entity.network.bind.BindDnsServerImpl.java

@Override
protected void preStart() {
    String reverse = getConfig(REVERSE_LOOKUP_NETWORK);
    if (Strings.isBlank(reverse))
        reverse = getAttribute(ADDRESS);
    sensors().set(REVERSE_LOOKUP_CIDR, new Cidr(reverse + "/24"));
    String reverseLookupDomain = Joiner.on('.')
            .join(Iterables.skip(Lists.reverse(Lists.newArrayList(Splitter.on('.').split(reverse))), 1))
            + ".in-addr.arpa";
    sensors().set(REVERSE_LOOKUP_DOMAIN, reverseLookupDomain);

    policies().add(PolicySpec.create(MemberTrackingPolicy.class).displayName("Address tracker")
            .configure(AbstractMembershipTrackingPolicy.SENSORS_TO_TRACK,
                    ImmutableSet.<Sensor<?>>of(getConfig(HOSTNAME_SENSOR)))
            .configure(AbstractMembershipTrackingPolicy.GROUP, getEntities()));
}

From source file:org.apache.mahout.math.random.Multinomial.java

@Override
public Iterator<T> iterator() {
    return new AbstractIterator<T>() {
        Iterator<T> valuesIterator = Iterables.skip(values, 1).iterator();

        @Override//  w  w w .  j  av a  2 s .  c om
        protected T computeNext() {
            while (valuesIterator.hasNext()) {
                T next = valuesIterator.next();
                if (items.containsKey(next)) {
                    return next;
                }
            }
            return endOfData();
        }
    };
}