Example usage for javafx.util Pair Pair

List of usage examples for javafx.util Pair Pair

Introduction

In this page you can find the example usage for javafx.util Pair Pair.

Prototype

public Pair(@NamedArg("key") K key, @NamedArg("value") V value) 

Source Link

Document

Creates a new pair

Usage

From source file:ai.grakn.engine.tasks.manager.StandaloneTaskManager.java

@Override
public void addTask(TaskState taskState) {
    stateStorage.newState(taskState);/*from  w  w w  .j  a v a 2  s  . c om*/

    // Schedule task to run.
    Instant now = Instant.now();
    TaskSchedule schedule = taskState.schedule();
    long delay = Duration.between(now, schedule.runAt()).toMillis();
    try {
        stateStorage.updateState(taskState.markScheduled());

        // Instantiate task.
        BackgroundTask task = taskState.taskClass().newInstance();

        ScheduledFuture<?> future = schedule.interval()
                .map(interval -> schedulingService.scheduleAtFixedRate(runTask(taskState.getId(), task, true),
                        delay, interval.toMillis(), MILLISECONDS))
                .orElseGet(() -> (ScheduledFuture) schedulingService
                        .schedule(runTask(taskState.getId(), task, false), delay, MILLISECONDS));

        instantiatedTasks.put(taskState.getId(), new Pair<>(future, task));
    } catch (Throwable throwable) {
        LOG.error(getFullStackTrace(throwable));
        stateStorage.updateState(taskState.markFailed(throwable));
        instantiatedTasks.remove(taskState.getId());
    }
}

From source file:ai.grakn.engine.backgroundtasks.standalone.StandaloneTaskManager.java

public String scheduleTask(BackgroundTask task, String createdBy, Date runAt, long period,
        JSONObject configuration) {//w  ww.ja v a  2 s.c om
    Boolean recurring = (period != 0);
    String id = stateStorage.newState(task.getClass().getName(), createdBy, runAt, recurring, period,
            configuration);

    // Schedule task to run.
    Date now = new Date();
    long delay = now.getTime() - runAt.getTime();

    try {
        stateStorage.updateState(id, SCHEDULED, this.getClass().getName(), null, null, null, null);

        ScheduledFuture<?> future;
        if (recurring)
            future = schedulingService.scheduleAtFixedRate(runTask(id, task, true), delay, period,
                    MILLISECONDS);
        else
            future = schedulingService.schedule(runTask(id, task, false), delay, MILLISECONDS);

        instantiatedTasks.put(id, new Pair<>(future, task));

    } catch (Throwable t) {
        LOG.error(getFullStackTrace(t));
        stateStorage.updateState(id, FAILED, this.getClass().getName(), null, t, null, null);
        instantiatedTasks.remove(id);
        return null;
    }

    return id;
}

From source file:com.walmart.gatling.repository.ServerRepository.java

public Optional<ReportExecutor.ReportResult> generateReport(String trackingId) {

    TaskEvent taskEvent = new TaskEvent();
    taskEvent.setJobName("gatling");
    taskEvent.setRoleName("report");
    taskEvent.setParameters(Arrays.asList(new Pair<>("0", "-ro")));
    Object result = sendToMaster(new Master.Report(trackingId, taskEvent), 180);

    log.info("Report generated {}", result);
    if (result != null && result instanceof ReportExecutor.ReportResult) {
        log.info("Report generated accurately {}", result);
        return Optional.of((ReportExecutor.ReportResult) result);
    }/*from  w w w  .  j  a v  a  2s  . c o  m*/
    return Optional.empty();
}

From source file:it.matjaz.jnumerus.RomanCharMapFactoryTest.java

@Test
public void pairsArrayContainsOnlyRomanCharsAndValuesSortedInverselyByChar() {
    Pair[] pairsArray = new Pair[] { new Pair("M", 1000), new Pair("CM", 900), new Pair("D", 500),
            new Pair("CD", 400), new Pair("C", 100), new Pair("XC", 90), new Pair("L", 50), new Pair("XL", 40),
            new Pair("X", 10), new Pair("IX", 9), new Pair("V", 5), new Pair("IV", 4), new Pair("I", 1) };
    assertArrayEquals(charPairs, pairsArray);
}

From source file:ai.grakn.engine.backgroundtasks.taskstorage.GraknStateStorage.java

public Set<Pair<String, TaskState>> getTasks(TaskStatus taskStatus, String taskClassName, String createdBy,
        int limit, int offset, Boolean recurring) {
    Var matchVar = var(TASK_VAR).isa(SCHEDULED_TASK);

    if (taskStatus != null)
        matchVar.has(STATUS, taskStatus.toString());
    if (taskClassName != null)
        matchVar.has(TASK_CLASS_NAME, taskClassName);
    if (createdBy != null)
        matchVar.has(CREATED_BY, createdBy);
    if (recurring != null)
        matchVar.has(RECURRING, recurring);

    Optional<Set<Pair<String, TaskState>>> result = attemptCommitToSystemGraph((graph) -> {
        MatchQuery q = graph.graql().match(matchVar);

        if (limit > 0)
            q.limit(limit);//  w ww.j  a  v a  2 s  . c o m
        if (offset > 0)
            q.offset(offset);

        List<Map<String, Concept>> res = q.execute();

        // Create Set of pairs with IDs &
        Set<Pair<String, TaskState>> out = new HashSet<>();
        for (Map<String, Concept> m : res) {
            Concept c = m.values().stream().findFirst().orElse(null);
            if (c != null) {
                String id = c.getId();
                out.add(new Pair<>(id, instanceToState(graph, c.asInstance())));
            }
        }

        return out;
    }, false);

    return result.isPresent() ? result.get() : new HashSet<>();
}

From source file:org.fineract.module.stellar.horizonadapter.HorizonServerUtilities.java

public void adjustOffer(final char[] stellarAccountPrivateKey, final StellarAccountId vaultAccountId,
        final String assetCode) throws InvalidConfigurationException, StellarOfferAdjustmentFailedException {
    logger.info("HorizonServerUtilities.adjustOffer");

    final KeyPair accountKeyPair = KeyPair.fromSecretSeed(stellarAccountPrivateKey);

    final Account account = accounts.getUnchecked(accountKeyPair.getAccountId());

    final Asset vaultAsset = StellarAccountHelpers.getAsset(assetCode, vaultAccountId);

    final StellarAccountHelpers accountHelper = getAccount(accountKeyPair);
    final BigDecimal balanceOfVaultAsset = accountHelper.getBalanceOfAsset(vaultAsset);
    final BigDecimal remainingTrustInVaultAsset = accountHelper.getRemainingTrustInAsset(vaultAsset);

    final Pair<String, StellarAccountId> offerKey = new Pair<>(accountKeyPair.getAccountId(), vaultAccountId);
    offers.refresh(offerKey);/*w w  w.j  a  v a  2 s.  c  o m*/
    final Map<VaultOffer, Long> vaultOffers = offers.getUnchecked(offerKey);

    final Transaction.Builder transactionBuilder = new Transaction.Builder(account);
    accountHelper.getAllNonnativeBalancesStream(assetCode, vaultAsset)
            .filter(balance -> !balance.getAssetIssuer().equals(vaultAccountId.getPublicKey()))
            .map(balance -> offerOperation(accountKeyPair, StellarAccountHelpers.getAssetOfBalance(balance),
                    vaultAsset,
                    determineOfferAmount(balanceOfVaultAsset, remainingTrustInVaultAsset,
                            StellarAccountHelpers.stellarBalanceToBigDecimal(balance.getBalance())),
                    determineOfferId(vaultOffers, balance)))
            .forEach(transactionBuilder::addOperation);

    if (transactionBuilder.getOperationsCount() != 0) {
        submitTransaction(account, transactionBuilder, accountKeyPair,
                StellarOfferAdjustmentFailedException::new);
    }
}

From source file:org.fineract.module.stellar.horizonadapter.HorizonServerUtilities.java

private Optional<Pair<Asset, Asset>> findAnyMatchingAssetPair(final BigDecimal amount,
        final Set<Asset> sourceAssets, final Set<Asset> targetAssets, final KeyPair sourceAccountKeyPair,
        final KeyPair targetAccountKeyPair) {
    if (sourceAssets.isEmpty())
        return Optional.empty();

    for (final Asset targetAsset : targetAssets) {
        Page<PathResponse> paths;// ww w  .j a  v  a2  s .c o m
        try {
            paths = server.paths().sourceAccount(sourceAccountKeyPair).destinationAccount(targetAccountKeyPair)
                    .destinationAsset(targetAsset)
                    .destinationAmount(StellarAccountHelpers.bigDecimalToStellarBalance(amount)).execute();
        } catch (final IOException e) {
            return Optional.empty();
        }

        while (paths != null && paths.getRecords() != null) {
            for (final PathResponse path : paths.getRecords()) {
                if (StellarAccountHelpers.stellarBalanceToBigDecimal(path.getSourceAmount())
                        .compareTo(amount) <= 0) {
                    if (sourceAssets.contains(path.getSourceAsset())) {
                        return Optional.of(new Pair<>(path.getSourceAsset(), targetAsset));
                    }
                }
            }

            try {
                paths = ((paths.getLinks() == null) || (paths.getLinks().getNext() == null)) ? null
                        : paths.getNextPage();
            } catch (final URISyntaxException e) {
                throw new UnexpectedException();
            } catch (final IOException e) {
                return Optional.empty();
            }
        }
    }

    return Optional.empty();
}

From source file:org.mskcc.shenkers.control.alignment.chain.ChainGFFAlignmentSource1.java

/**
 *
 * @return a local alignment restricted to the given query interval
 *//* www. jav  a2s. c o  m*/
public static Optional<LocalAlignment> getAlignedBlocks(final ChainContext chain, GenomeSpan interval) {

    List<Integer> queryGaps = chain.getQueryGaps();
    List<Integer> targetGaps = chain.getTargetGaps();
    List<Integer> blockLengths = chain.getBlockLengths();

    List<Pair<Integer, Integer>> fromBlocks = new ArrayList<>();
    List<Pair<Integer, Integer>> toBlocks = new ArrayList<>();

    boolean hasIntersection = false;

    int qPos = chain.getStart();
    int tPos = chain.getToNegativeStrand() ? chain.getTargetEnd() : chain.getTargetStart();

    int start = interval.getStart();
    int end = interval.getEnd();

    int nBlocks = blockLengths.size();
    for (int i = 0; i < nBlocks; ++i) {

        int length = blockLengths.get(i);

        // get the boundaries of the current block in the query
        int qStart = qPos;
        int qEnd = qStart + length - 1;

        // get the boundaries of the current block in the target
        int tStart = chain.getToNegativeStrand() ? tPos - length + 1 : tPos;
        int tEnd = chain.getToNegativeStrand() ? tPos : tPos + length - 1;

        if (qStart > end) {
            logger.info("breaking");
            break;
        }
        if (qEnd >= start) {
            logger.info("overlaps");
            hasIntersection = true;

            // determine if the query interval is offset from the block
            int fromStart = start > qStart ? start : qStart;
            int fromEnd = qEnd > end ? end : qEnd;

            int startOffset = (start > qStart) ? start - qStart : 0;

            int offsetFromEnd = (qEnd > end) ? qEnd - end : 0;

            // apply the offset to the interval in the target genome
            int toStart = tStart + (chain.getToNegativeStrand() ? offsetFromEnd : startOffset);
            int toEnd = tEnd - (chain.getToNegativeStrand() ? startOffset : offsetFromEnd);

            fromBlocks.add(new Pair<>(fromStart, fromEnd));
            toBlocks.add(new Pair<>(toStart, toEnd));
        }

        if (i < nBlocks - 1) {
            int qGap = queryGaps.get(i);
            int tGap = targetGaps.get(i);

            qPos += length + qGap;
            tPos += chain.getToNegativeStrand() ? -(length + tGap) : length + tGap;
        }

    }

    Optional<LocalAlignment> alignment = hasIntersection ? Optional.of(new LocalAlignment(chain.getChr(),
            chain.getTargetChr(), chain.getToNegativeStrand(), fromBlocks, toBlocks)) : Optional.empty();

    return alignment;
}

From source file:org.mskcc.shenkers.control.alignment.ChainParserNGTest.java

public static LocalAlignment trim(LocalAlignment blocks, GenomeSpan query_i, GenomeSpan target_i) {

    List<Pair<Integer, Integer>> fromBlocks = new ArrayList<>();
    List<Pair<Integer, Integer>> toBlocks = new ArrayList<>();

    for (int i = 0; i < blocks.fromBlocks.size(); i++) {

        Pair<Integer, Integer> fromBlock = blocks.fromBlocks.get(i);
        Pair<Integer, Integer> toBlock = blocks.toBlocks.get(i);

        assert IntervalTools.isContained(fromBlock.getKey(), fromBlock.getValue(), query_i.getStart(), query_i
                .getEnd()) : "it is assumed that all blocks in query will be contained in the query interval";

        // if this block overlaps it is either OK as is, or needs to be trimmed
        if (IntervalTools.overlaps(toBlock.getKey(), toBlock.getValue(), target_i.getStart(),
                target_i.getEnd())) {// w  w  w .ja  v a  2 s.  c  om
            if (IntervalTools.isContained(toBlock.getKey(), toBlock.getValue(), target_i.getStart(),
                    target_i.getEnd())) {
                fromBlocks.add(fromBlock);
                toBlocks.add(toBlock);
            } else {
                int offsetTargetStart = toBlock.getKey() < target_i.getStart()
                        ? target_i.getStart() - toBlock.getKey()
                        : 0;
                int offsetTargetEnd = toBlock.getValue() > target_i.getEnd()
                        ? toBlock.getKey() - target_i.getEnd()
                        : 0;

                Pair<Integer, Integer> offsetToBlock = new Pair<>(toBlock.getKey() + offsetTargetStart,
                        toBlock.getValue() - offsetTargetEnd);
                Pair<Integer, Integer> offsetFromBlock = blocks.toNegativeStrand
                        ? new Pair<>(fromBlock.getKey() + offsetTargetEnd,
                                fromBlock.getValue() - offsetTargetStart)
                        : new Pair<>(fromBlock.getKey() + offsetTargetStart,
                                fromBlock.getValue() - offsetTargetEnd);

                fromBlocks.add(offsetFromBlock);
                toBlocks.add(offsetToBlock);
            }
        }
    }

    return new LocalAlignment(blocks.fromSequenceName, blocks.toSequenceName, blocks.toNegativeStrand,
            fromBlocks, toBlocks);
}

From source file:org.mskcc.shenkers.view.IntervalViewNGTest.java

public void testRangeSetIntervalView() throws InterruptedException {
    System.out.println("testIntervalView");

    CountDownLatch l = new CountDownLatch(1);
    System.out.println("before");
    Platform.runLater(() -> {/* w w  w .  ja va2 s  .co m*/
        System.out.println("running");
        double[][] intervals = { { .1, .2 } };
        //                    Range r = null;
        RangeSet<Double> rs = TreeRangeSet.create();
        rs.add(Range.closed(.1, .2));
        rs.add(Range.closed(.2, .3));
        rs.add(Range.closed(.32, .35));
        rs.add(Range.closed(.6, .8));

        RangeSetIntervalView p = new RangeSetIntervalView(0, 100);
        p.setData(Arrays.asList(new Pair(10, 20), new Pair(20, 30), new Pair(32, 35), new Pair(60, 80)));

        //                    p.prefTileHeightProperty().bind(p.heightProperty());
        Stage stage = new Stage();
        stage.setOnHidden(e -> {
            l.countDown();
            System.out.println("count " + l.getCount());
        });
        Scene scene = new Scene(p, 300, 300, Color.GRAY);
        stage.setTitle("SimpleIntervalView");
        stage.setScene(scene);
        stage.show();

    });
    System.out.println("after");
    l.await();
    Thread.sleep(1000);
}