Example usage for org.apache.commons.lang3.tuple Pair getRight

List of usage examples for org.apache.commons.lang3.tuple Pair getRight

Introduction

In this page you can find the example usage for org.apache.commons.lang3.tuple Pair getRight.

Prototype

public abstract R getRight();

Source Link

Document

Gets the right element from this pair.

When treated as a key-value pair, this is the value.

Usage

From source file:com.quartercode.jtimber.rh.agent.asm.InsertChildAccessorsClassAdapter.java

private void generateGetChildCountMethod() {

    GeneratorAdapter mg = new GeneratorAdapter(ACC_PUBLIC, GET_CHILD_COUNT_METHOD, null, null, cv);

    // Push the initial counter; if the superclass is a node, call the getChildCount() method on the superclass and use the result as the initial counter
    if (hasNodeAsSuperclass) {
        mg.loadThis();/*from w ww .  j a v  a 2  s.  co  m*/
        mg.invokeConstructor(superclassType, GET_CHILD_COUNT_METHOD);
    } else {
        mg.push(0);
    }

    // ----- Stack: [counter]

    // Increment the counter for all fields which are not null
    for (Pair<String, Type> field : fields) {
        // Push the current field value
        ASMUtils.generateGetField(mg, classType, field.getLeft(), field.getRight());

        // ----- Stack: [counter, fieldValue]

        // Calculate the amount of children the current field value represents; the called static method executes some checks and handles wrappers
        // For example, null counts as 0 while a wrapper might represent multiple children
        mg.invokeStatic(FUNCS_CLASS, FUNC_COUNT_ACTUAL_CHILDREN);

        // ----- Stack: [counter, specificFieldCount]

        // Add the calculated amount of children to the counter
        mg.visitInsn(IADD);

        // ----- Stack: [counter]
    }

    // Return the counter
    mg.returnValue();

    mg.endMethod();
}

From source file:hu.ppke.itk.nlpg.purepos.model.internal.NGramModelTest.java

@Test
public void testMaxFinder() {
    model = new NGramModel<Integer>(3);
    Integer f = 0;/*  w  w  w. j  av a2s . com*/
    IntTrieNode<Integer> n0 = new IntTrieNode<Integer>(-1, 0);
    IntTrieNode<Integer> n1 = new IntTrieNode<Integer>(-1, 0);
    n1.addWord(0);
    IntTrieNode<Integer> n2 = new IntTrieNode<Integer>(-1, 0);
    n2.addWord(5);
    n2.addWord(0);
    ArrayList<TrieNode<Integer, Integer, Integer>> l = new ArrayList<TrieNode<Integer, Integer, Integer>>();
    // MutablePair<ArrayList<IntTrieNode<Integer>>, Integer> arg = new
    // MutablePair<ArrayList<IntTrieNode<Integer>>, Integer>(
    // l, f);
    Pair<Integer, Double> ret = model.findMax(l, f);
    Assert.assertEquals(ret.getLeft(), null);
    Assert.assertEquals(ret.getRight(), null);

    l.add(n0);
    ret = model.findMax(l, f);
    Assert.assertEquals((Integer) (-1), ret.getLeft());
    Assert.assertEquals(0.0, ret.getRight());

    l.add(n2);
    ret = model.findMax(l, f);
    Assert.assertEquals((Integer) 1, ret.getLeft());
    Assert.assertEquals(0.5, ret.getRight());

    l.add(n1);
    ret = model.findMax(l, f);
    Assert.assertEquals((Integer) 2, ret.getLeft());
    Assert.assertEquals(1.0, ret.getRight());
}

From source file:com.act.lcms.AnimateNetCDFAroundMass.java

private List<XYZ> getSpectra(Iterator<LCMSSpectrum> spectraIt, Double time, Double tWin, Double mz,
        Double mzWin) {/*from  ww  w  .j  av a  2  s .c  o m*/
    double mzLow = mz - mzWin;
    double mzHigh = mz + mzWin;
    double timeLow = time - tWin;
    double timeHigh = time + tWin;

    List<XYZ> spectra = new ArrayList<>();

    while (spectraIt.hasNext()) {
        LCMSSpectrum timepoint = spectraIt.next();

        if (timepoint.getTimeVal() < timeLow || timepoint.getTimeVal() > timeHigh)
            continue;

        // get all (mz, intensity) at this timepoint
        for (Pair<Double, Double> mz_int : timepoint.getIntensities()) {
            double mzHere = mz_int.getLeft();
            double intensity = mz_int.getRight();

            if (mzHere < mzLow || mzHere > mzHigh)
                continue;

            spectra.add(new XYZ(timepoint.getTimeVal(), mzHere, intensity));
        }
    }

    return spectra;
}

From source file:com.twitter.distributedlog.logsegment.TestLogSegmentCache.java

@Test(timeout = 60000)
public void testDiff() {
    LogSegmentCache cache = new LogSegmentCache("test-diff");
    // add 5 completed log segments
    for (int i = 1; i <= 5; i++) {
        LogSegmentMetadata metadata = DLMTestUtil.completedLogSegment("/segment" + i, i, i, i * 100L, 100, i,
                99L, 0L);//  w w w.j a  va2 s  .  co  m
        String name = DLMTestUtil.completedLedgerZNodeNameWithLogSegmentSequenceNumber(i);
        cache.add(name, metadata);
    }
    // add one inprogress log segment
    LogSegmentMetadata inprogress = DLMTestUtil.inprogressLogSegment("/inprogress-6", 6, 600L, 6);
    String name = DLMTestUtil.inprogressZNodeName(6);
    cache.add(name, inprogress);

    // deleted first 2 completed log segments and completed the last one
    Set<String> segmentRemoved = Sets.newHashSet();
    for (int i = 1; i <= 2; i++) {
        segmentRemoved.add(DLMTestUtil.completedLedgerZNodeNameWithLogSegmentSequenceNumber(i));
    }
    segmentRemoved.add((DLMTestUtil.inprogressZNodeName(6)));
    Set<String> segmentReceived = Sets.newHashSet();
    Set<String> segmentAdded = Sets.newHashSet();
    for (int i = 3; i <= 6; i++) {
        segmentReceived.add(DLMTestUtil.completedLedgerZNodeNameWithLogSegmentSequenceNumber(i));
        if (i == 6) {
            segmentAdded.add(DLMTestUtil.completedLedgerZNodeNameWithLogSegmentSequenceNumber(i));
        }
    }

    Pair<Set<String>, Set<String>> segmentChanges = cache.diff(segmentReceived);
    assertTrue("Should remove " + segmentRemoved + ", but removed " + segmentChanges.getRight(),
            Sets.difference(segmentRemoved, segmentChanges.getRight()).isEmpty());
    assertTrue("Should add " + segmentAdded + ", but added " + segmentChanges.getLeft(),
            Sets.difference(segmentAdded, segmentChanges.getLeft()).isEmpty());
}

From source file:de.hasait.clap.impl.CLAPParseContext.java

public String[] getOptionArgs(final CLAPOptionNode<?> pOptionNode) {
    final List<String> result = new ArrayList<String>();
    boolean anyFound = false;
    for (final Pair<? extends AbstractCLAPNode, ? extends Object> entry : _nodeContextMap) {
        if (entry.getLeft().equals(pOptionNode)) {
            result.addAll((List<String>) entry.getRight());
            anyFound = true;/*  ww w. ja v a2  s .c  o  m*/
        }
    }
    return anyFound ? result.toArray(new String[result.size()]) : null;
}

From source file:com.netflix.spinnaker.clouddriver.kubernetes.v2.caching.view.provider.KubernetesV2InstanceProvider.java

@Override
public String getConsoleOutput(String account, String location, String fullName) {
    KubernetesNamedAccountCredentials<KubernetesV2Credentials> credentials;
    try {// www .java 2  s  .co m
        credentials = (KubernetesNamedAccountCredentials) accountCredentialsRepository.getOne(account);
    } catch (Exception e) {
        log.warn("Failure getting account {}", account);
        return null;
    }

    if (credentials == null || credentials.getProviderVersion() != ProviderVersion.v2) {
        return null;
    }

    Pair<KubernetesKind, String> parsedName;
    try {
        parsedName = KubernetesManifest.fromFullResourceName(fullName);
    } catch (Exception e) {
        return null;
    }

    String name = parsedName.getRight();

    V1Pod pod = KubernetesCacheDataConverter
            .getResource(credentials.getCredentials().get(KubernetesKind.POD, location, name), V1Pod.class);

    StringBuilder result = new StringBuilder();

    // Make live calls rather than abuse the cache for storing all logs
    for (V1Container container : pod.getSpec().getContainers()) {
        result.append("====== " + container.getName() + " ======\n\n");
        try {
            result.append(credentials.getCredentials().logs(location, name, container.getName()));
        } catch (KubectlJobExecutor.KubectlException e) {
            // Typically happens if the container/pod isn't running yet
            result.append(e.getMessage());
        }
        result.append("\n\n");
    }

    return result.toString();
}

From source file:com.streamsets.pipeline.stage.destination.kinesis.KinesisTarget.java

@Override
public void write(Batch batch) throws StageException {
    Iterator<Record> batchIterator = batch.getRecords();

    List<Pair<ListenableFuture<UserRecordResult>, String>> putFutures = new LinkedList<>();

    int i = 0;//from w ww .j a va  2 s. com
    while (batchIterator.hasNext()) {
        Record record = batchIterator.next();
        ByteArrayOutputStream bytes = new ByteArrayOutputStream(ONE_MB);
        try {
            DataGenerator generator = generatorFactory.getGenerator(bytes);
            generator.write(record);
            generator.close();

            ByteBuffer data = ByteBuffer.wrap(bytes.toByteArray());

            Object partitionerKey;
            if (conf.partitionStrategy == PartitionStrategy.EXPRESSION) {
                RecordEL.setRecordInContext(partitionVars, record);
                try {
                    partitionerKey = partitionEval.eval(partitionVars, conf.partitionExpression, Object.class);
                } catch (ELEvalException e) {
                    throw new StageException(Errors.KINESIS_06, conf.partitionExpression,
                            record.getHeader().getSourceId(), e.toString());
                }
            } else {
                partitionerKey = i;
            }

            String partitionKey = partitioner.partition(partitionerKey, numShards);

            // To preserve ordering we flush after each record.
            if (conf.preserveOrdering) {
                Future<UserRecordResult> resultFuture = kinesisProducer.addUserRecord(conf.streamName,
                        partitionKey, data);
                getAndCheck(resultFuture, partitionKey);
                kinesisProducer.flushSync();
            } else {
                putFutures.add(Pair.of(kinesisProducer.addUserRecord(conf.streamName, partitionKey, data),
                        partitionKey));
            }

            ++i;
        } catch (IOException e) {
            LOG.error(Errors.KINESIS_05.getMessage(), record, e.toString(), e);
            handleFailedRecord(record, e.toString());
        }
    }

    // This has no effect when preserveOrdering is true because the list is empty.
    for (Pair<ListenableFuture<UserRecordResult>, String> pair : putFutures) {
        getAndCheck(pair.getLeft(), pair.getRight());
    }
    kinesisProducer.flushSync();
}

From source file:forge.game.combat.CombatUtil.java

public static boolean validateAttackers(final Combat combat) {
    final AttackConstraints constraints = combat.getAttackConstraints();
    final Pair<Map<Card, GameEntity>, Integer> bestAttack = constraints.getLegalAttackers();
    final int myViolations = constraints.countViolations(combat.getAttackersAndDefenders());
    if (myViolations == -1) {
        return false;
    }/* w  w w.j  av  a2 s .c o  m*/
    return myViolations <= bestAttack.getRight().intValue();
}

From source file:de.hasait.clap.impl.CLAPParseContext.java

public AbstractCLAPNode getDecision(final AbstractCLAPDecision pDecisionNode) {
    AbstractCLAPNode lastBranchNode = null;
    for (final Pair<? extends AbstractCLAPNode, ? extends Object> entry : _nodeContextMap) {
        if (entry.getLeft().equals(pDecisionNode)) {
            lastBranchNode = (AbstractCLAPNode) entry.getRight();
        }/*ww w. j ava 2  s  .com*/
    }
    return lastBranchNode;
}

From source file:alfio.manager.WaitingQueueProcessorIntegrationTest.java

@Test
public void testAddSeatsAfterSoldOutWithoutUnbounded() throws InterruptedException {
    Pair<String, Event> pair = initSoldOutEvent(false);
    Event event = pair.getRight();
    EventModification eventModification = new EventModification(event.getId(), event.getType(),
            event.getWebsiteUrl(), event.getExternalUrl(), event.getTermsAndConditionsUrl(),
            event.getImageUrl(), event.getFileBlobId(), event.getShortName(), event.getDisplayName(),
            event.getOrganizationId(), event.getLocation(), event.getLatitude(), event.getLongitude(),
            event.getZoneId().getId(), emptyMap(), fromZonedDateTime(event.getBegin()),
            fromZonedDateTime(event.getEnd()), event.getRegularPrice(), event.getCurrency(),
            eventRepository.countExistingTickets(event.getId()) + 1, event.getVat(), event.isVatIncluded(),
            event.getAllowedPaymentProxies(), Collections.emptyList(), event.isFreeOfCharge(), null,
            event.getLocales(), Collections.emptyList(), Collections.emptyList());
    eventManager.updateEventPrices(event, eventModification, "admin");
    //that should create an additional "RELEASED" ticket, but it won't be linked to any category, so the following call won't have any effect
    waitingQueueSubscriptionProcessor.distributeAvailableSeats(event);
    List<WaitingQueueSubscription> subscriptions = waitingQueueRepository.loadAll(event.getId());
    assertEquals(0, subscriptions.stream().filter(w -> StringUtils.isNotBlank(w.getReservationId())).count());

    //explicitly expand the category
    TicketCategory category = eventManager.loadTicketCategories(event).get(0);
    eventManager.updateCategory(category.getId(), event.getId(),
            new TicketCategoryModification(category.getId(), category.getName(), category.getMaxTickets() + 1,
                    fromZonedDateTime(category.getInception(event.getZoneId())),
                    fromZonedDateTime(category.getExpiration(event.getZoneId())), emptyMap(),
                    category.getPrice(), category.isAccessRestricted(), "", category.isBounded(), null, null,
                    null, null, null),/*ww w  .j  ava  2 s . com*/
            "admin");

    //now the waiting queue processor should create the reservation for the first in line
    waitingQueueSubscriptionProcessor.distributeAvailableSeats(event);
    subscriptions = waitingQueueRepository.loadAll(event.getId());
    assertEquals(1, subscriptions.stream().filter(w -> StringUtils.isNotBlank(w.getReservationId())).count());
    Optional<WaitingQueueSubscription> first = subscriptions.stream()
            .filter(w -> w.getStatus().equals(WaitingQueueSubscription.Status.PENDING)).findFirst();
    assertTrue(first.isPresent());
    assertEquals("Giuseppe Garibaldi", first.get().getFullName());
}