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

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

Introduction

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

Prototype

public static <L, R> Pair<L, R> of(final L left, final R right) 

Source Link

Document

Obtains an immutable pair of from two objects inferring the generic types.

This factory allows the pair to be created using inference to obtain the generic types.

Usage

From source file:com.teambrmodding.neotech.common.tiles.machines.processors.TileAlloyer.java

/**
 * Used to tell if this tile is able to process
 *
 * @return True if you are able to process
 *///from w  w w  .  j a  v  a  2 s .  c om
@Override
public boolean canProcess() {
    if (energyStorage.getEnergyStored() >= getEnergyCostPerTick()) {
        return tanks[INPUT_TANK_1].getFluid() != null && tanks[INPUT_TANK_2].getFluid() != null && // Has inputs
                RecipeManager.getHandler(RecipeManager.RecipeType.ALLOYER)
                        .isValidInput(Pair.of(tanks[INPUT_TANK_1].getFluid(), tanks[INPUT_TANK_2].getFluid()))
                && // Is Recipe
                (tanks[OUTPUT_TANK].getFluid() == null || // Has nothing in output
                        ((AlloyerRecipeHandler) RecipeManager.getHandler(RecipeManager.RecipeType.ALLOYER))
                                .getOutput(Pair.of(tanks[INPUT_TANK_1].getFluid(),
                                        tanks[INPUT_TANK_2].getFluid())).amount
                                + tanks[OUTPUT_TANK].getFluidAmount() <= tanks[OUTPUT_TANK].getCapacity()); // Can fill output
    }
    failCoolDown = 40;
    return false;
}

From source file:alfio.test.util.IntegrationTestUtil.java

public static Pair<Event, String> initEvent(List<TicketCategoryModification> categories,
        OrganizationRepository organizationRepository, UserManager userManager, EventManager eventManager,
        EventRepository eventRepository) {

    String organizationName = UUID.randomUUID().toString();
    String username = UUID.randomUUID().toString();
    String eventName = UUID.randomUUID().toString();

    userManager.createOrganization(organizationName, "org", "email@example.com");
    Organization organization = organizationRepository.findByName(organizationName).get();
    userManager.insertUser(organization.getId(), username, "test", "test", "test@example.com", Role.OPERATOR,
            User.Type.INTERNAL);
    userManager.insertUser(organization.getId(), username + "_owner", "test", "test", "test@example.com",
            Role.OWNER, User.Type.INTERNAL);

    LocalDateTime expiration = LocalDateTime.now().plusDays(5).plusHours(1);

    Map<String, String> desc = new HashMap<>();
    desc.put("en", "muh description");
    desc.put("it", "muh description");
    desc.put("de", "muh description");

    EventModification em = new EventModification(null, Event.EventType.INTERNAL, "url", "url", "url", "url",
            null, eventName, "event display name", organization.getId(), "muh location", "0.0", "0.0",
            ZoneId.systemDefault().getId(), desc,
            new DateTimeModification(LocalDate.now().plusDays(5), LocalTime.now()),
            new DateTimeModification(expiration.toLocalDate(), expiration.toLocalTime()), BigDecimal.TEN, "CHF",
            AVAILABLE_SEATS, BigDecimal.ONE, true, Collections.singletonList(PaymentProxy.OFFLINE), categories,
            false, new LocationDescriptor("", "", "", ""), 7, null, null);
    eventManager.createEvent(em);//  ww w. j  a v a  2 s  .com
    Event event = eventManager.getSingleEvent(eventName, username);
    Assert.assertEquals(AVAILABLE_SEATS, eventRepository.countExistingTickets(event.getId()).intValue());
    return Pair.of(event, username);
}

From source file:mase.spec.BasicHybridExchanger.java

protected Pair<MetaPopulation, MetaPopulation> findNextMerge(double[][] distanceMatrix, EvolutionState state) {
    MetaPopulation closeI = null, closeJ = null;
    double closest = 0;
    for (int i = 0; i < metaPops.size(); i++) {
        for (int j = i + 1; j < metaPops.size(); j++) {
            double d = distanceMatrix[i][j];
            if (metaPops.get(i).age >= stabilityTime && metaPops.get(j).age >= stabilityTime
                    && (closeI == null || d < closest)) {
                closeI = metaPops.get(i);
                closeJ = metaPops.get(j);
                closest = d;//www . j  a  v a2  s  .c o m
            }
        }
    }
    if (closeI != null) {
        state.output.message("Closest: " + closeI + " " + closeJ + " -- " + closest);
    }
    if (closeI != null && closest <= mergeThreshold) {
        return Pair.of(closeI, closeJ);
    }
    return null;
}

From source file:com.formkiq.core.form.FormFinder.java

/**
 * Finds Value by Key./*from   w  w  w.jav a2  s  .c o m*/
 *
 * @param form {@link FormJSON}
 * @param id int
 * @return {@link Optional}
 */
public static Optional<Pair<FormJSONSection, FormJSONField>> findSectionAndField(final FormJSON form,
        final int id) {

    for (FormJSONSection section : form.getSections()) {

        for (FormJSONField field : section.getFields()) {

            if (field.getId() == id) {
                return Optional.of(Pair.of(section, field));
            }
        }
    }

    return Optional.empty();
}

From source file:mase.mason.world.DistanceSensorArcs.java

/**
 * Very efficient implementation using an ordered TreeMap Should ensure
 * scalability when large numbers of objects are present, as there is no
 * need to check angles with objects that are farther than the closest
 * object in the given cone. Potential limitation (unlikely): if there are
 * two objects at exactly the same distance but at different angles, only
 * one of them will be considered, as the distance is used as key in the
 * TreeMap//ww  w .ja  va 2 s . com
 */
@Override
public double[] readValues() {
    lastDistances = new double[valueCount()];
    Arrays.fill(lastDistances, Double.POSITIVE_INFINITY);
    Arrays.fill(closestObjects, null);
    if (range < 0.001) {
        return lastDistances;
    }
    double rangeNoiseAbs = Double.isInfinite(range) ? rangeNoise * fieldDiagonal : range * rangeNoise;

    WorldObject[] candidates = getCandidates();

    // TODO: replace treemap with collection-sort
    Pair<Double, WorldObject>[] distances = new Pair[candidates.length];
    int index = 0;
    for (WorldObject o : candidates) {
        if (!centerToCenter && o.isInside(ag.getLocation())) {
            Arrays.fill(lastDistances, 0);
            Arrays.fill(closestObjects, o);
            return lastDistances;
        }

        double dist = centerToCenter ? ag.getLocation().distance(o.getLocation())
                : Math.max(0, ag.distanceTo(o));
        if (rangeNoiseAbs > 0) {
            dist += rangeNoiseAbs
                    * (noiseType == UNIFORM ? state.random.nextDouble() * 2 - 1 : state.random.nextGaussian());
            dist = Math.max(dist, 0);
        }
        if (dist <= range) {
            distances[index++] = Pair.of(dist, o);
        }
    }
    if (index < distances.length) {
        distances = Arrays.copyOf(distances, index);
    }

    Arrays.sort(distances, new Comparator<Pair<Double, WorldObject>>() {
        @Override
        public int compare(Pair<Double, WorldObject> a, Pair<Double, WorldObject> b) {
            return Double.compare(a.getLeft(), b.getLeft());
        }
    });

    int filled = 0;
    for (Pair<Double, WorldObject> e : distances) {
        if (filled == arcStart.length) {
            break;
        }
        double angle = ag.angleTo(e.getRight().getLocation());
        if (orientationNoise > 0) {
            angle += orientationNoise
                    * (noiseType == UNIFORM ? state.random.nextDouble() * 2 - 1 : state.random.nextGaussian());
            angle = EmboddiedAgent.normalizeAngle(angle);
        }
        for (int a = 0; a < arcStart.length; a++) {
            if (Double.isInfinite(lastDistances[a]) && ((angle >= arcStart[a] && angle <= arcEnd[a])
                    || (arcStart[a] > arcEnd[a] && (angle >= arcStart[a] || angle <= arcEnd[a])))) {
                filled++;
                lastDistances[a] = e.getKey();
                closestObjects[a] = e.getValue();
            }
        }
    }
    return lastDistances;
}

From source file:net.lldp.checksims.algorithm.AlgorithmRunnerTest.java

@Test
public void TestRunAlgorithmAllPossiblePairs() throws ChecksimsException {
    Set<Pair<Submission, Submission>> submissions = setFromElements(Pair.of(a, b), Pair.of(a, c), Pair.of(a, d),
            Pair.of(b, c), Pair.of(b, d), Pair.of(c, d));
    Collection<AlgorithmResults> results = AlgorithmRunner.runAlgorithm(submissions, detectNothing, logger);

    AlgorithmUtils.checkResultsContainsPairs(results, submissions);
}

From source file:gobblin.ingestion.google.webmaster.UrlTriePostOrderIterator.java

@Override
public Pair<String, UrlTrieNode> next() {
    if (hasNext()) {
        _lastVisited = _toReturn;/*w w  w  . ja  va 2s.co  m*/
        _toReturn = null;
        return Pair.of(_currentPrefixSb.toString() + _lastVisited.getValue(), _lastVisited);
    }
    throw new NoSuchElementException();
}

From source file:com.money.manager.ex.investment.morningstar.MorningstarPriceUpdater.java

private void processSequentially(List<String> symbols) {
    compositeSubscription/*from  w  w w .j av a 2 s. com*/
            .add(Observable.from(symbols).subscribeOn(Schedulers.io()).map(new Func1<String, String>() {
                @Override
                public String call(String s) {
                    // get a Morningstar symbol
                    return symbolConverter.convert(s);
                }
            }).observeOn(Schedulers.io()) // Observe the network call on IO thread!
                    .flatMap(new Func1<String, Observable<Pair<String, String>>>() {
                        @Override
                        public Observable<Pair<String, String>> call(final String s) {
                            // download the price
                            return service.getPrice(s).doOnError(new Action1<Throwable>() {
                                @Override
                                public void call(Throwable throwable) {
                                    mCounter++;
                                    setProgress(mCounter);

                                    // report to the UI
                                    Timber.e(throwable, "fetching %s", s);
                                }
                            }).onErrorResumeNext(Observable.<String>empty())
                                    .map(new Func1<String, Pair<String, String>>() {
                                        @Override
                                        public Pair<String, String> call(String price) {
                                            return Pair.of(s, price);
                                        }
                                    });
                        }
                    }).map(new Func1<Pair<String, String>, PriceDownloadedEvent>() {
                        @Override
                        public PriceDownloadedEvent call(Pair<String, String> s) {
                            // parse the price
                            return parse(s.getLeft(), s.getRight());
                        }
                    }).doOnNext(new Action1<PriceDownloadedEvent>() {
                        @Override
                        public void call(PriceDownloadedEvent priceDownloadedEvent) {
                            // update to database
                            savePrice(priceDownloadedEvent);
                        }
                    }).observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<PriceDownloadedEvent>() {
                        @Override
                        public void onCompleted() {
                            closeProgressDialog();

                            new UIHelper(getContext()).showToast(R.string.download_complete);

                            compositeSubscription.unsubscribe();

                            // send event to reload the data.
                            EventBus.getDefault().post(new AllPricesDownloadedEvent());
                        }

                        @Override
                        public void onError(Throwable e) {
                            closeProgressDialog();

                            Timber.e(e, "downloading prices");
                        }

                        @Override
                        public void onNext(PriceDownloadedEvent event) {
                            mCounter++;
                            setProgress(mCounter);

                            // todo: update price in the UI?
                            // todo: remove the progress bar in that case.
                        }
                    }));
}

From source file:edu.umd.umiacs.clip.tools.classifier.LibSVMUtils.java

public static Map<Integer, Pair<Float, Float>> learnScalingModel(List<String> training) {
    return training.stream().map(LibSVMUtils::split).map(Triple::getMiddle).flatMap(List::stream)
            .collect(groupingBy(Pair::getKey, ConcurrentHashMap::new,
                    reducing(Pair.of(0f, 0f), pair -> Pair.of(pair.getRight(), pair.getRight()),
                            (p1, p2) -> Pair
                                    .of(min(p1.getLeft(), p2.getLeft()), max(p1.getRight(), p2.getRight())))))
            .entrySet().stream()/*from  w ww . j  a  va2 s. c  o  m*/
            .filter(entry -> entry.getValue().getLeft().floatValue() != entry.getValue().getRight()
                    .floatValue())
            .collect(toMap(Entry::getKey, entry -> Pair.of(entry.getValue().getLeft(),
                    entry.getValue().getRight() - entry.getValue().getLeft())));
}

From source file:com.quartercode.eventbridge.test.def.bridge.module.DefaultStandardHandlerModuleTest.java

@SuppressWarnings("unchecked")
@Test//  w  ww  . j  av  a 2  s  .  c  o m
public void testHandlerStorage() {

    EventHandler<EmptyEvent1> handler1 = context.mock(EventHandler.class, "handler1");
    EventHandler<EmptyEvent2> handler2 = context.mock(EventHandler.class, "handler2");
    EventHandler<EmptyEvent2> handler3 = context.mock(EventHandler.class, "handler3");
    final EventPredicate<EmptyEvent1> predicate1 = context.mock(EventPredicate.class, "predicate1");
    final EventPredicate<EmptyEvent2> predicate2 = context.mock(EventPredicate.class, "predicate2");
    final EventPredicate<EmptyEvent2> predicate3 = context.mock(EventPredicate.class, "predicate3");

    Pair<EventHandler<EmptyEvent1>, EventPredicate<EmptyEvent1>> pair1 = Pair.of(handler1, predicate1);
    Pair<EventHandler<EmptyEvent2>, EventPredicate<EmptyEvent2>> pair2 = Pair.of(handler2, predicate2);
    Pair<EventHandler<EmptyEvent2>, EventPredicate<EmptyEvent2>> pair3 = Pair.of(handler3, predicate3);

    // @formatter:off
    context.checking(new Expectations() {
        {

            final Sequence handlerListModifications = context.sequence("handlerListModifications");
            oneOf(lowLevelHandlerModule).addHandler(with(aLowLevelHandlerWithThePredicate(predicate1)));
            inSequence(handlerListModifications);
            oneOf(lowLevelHandlerModule).addHandler(with(aLowLevelHandlerWithThePredicate(predicate2)));
            inSequence(handlerListModifications);
            oneOf(lowLevelHandlerModule).addHandler(with(aLowLevelHandlerWithThePredicate(predicate3)));
            inSequence(handlerListModifications);
            oneOf(lowLevelHandlerModule).removeHandler(with(aLowLevelHandlerWithThePredicate(predicate2)));
            inSequence(handlerListModifications);

        }
    });
    // @formatter:on

    assertHandlerListEmpty();

    module.removeHandler(handler1);
    assertHandlerListEmpty();

    module.addHandler(handler1, predicate1);
    assertMapEquals("Handlers that are stored inside the module are not correct", module.getHandlers(), pair1);
    assertMapEquals("Handlers that are stored inside the module changed on the second retrieval",
            module.getHandlers(), pair1);

    module.addHandler(handler2, predicate2);
    assertMapEquals("Handlers that are stored inside the module are not correct", module.getHandlers(), pair1,
            pair2);
    assertMapEquals("Handlers that are stored inside the module changed on the second retrieval",
            module.getHandlers(), pair1, pair2);

    module.addHandler(handler3, predicate3);
    assertMapEquals("Handlers that are stored inside the module are not correct", module.getHandlers(), pair1,
            pair2, pair3);
    assertMapEquals("Handlers that are stored inside the module changed on the second retrieval",
            module.getHandlers(), pair1, pair2, pair3);

    module.removeHandler(handler2);
    assertMapEquals("Handlers that are stored inside the module are not correct", module.getHandlers(), pair1,
            pair3);
    assertMapEquals("Handlers that are stored inside the module changed on the second retrieval",
            module.getHandlers(), pair1, pair3);
}