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:io.cloudslang.lang.runtime.steps.ParallelLoopExecutionData.java

public void addBranches(
        @Param(ScoreLangConstants.PARALLEL_LOOP_STATEMENT_KEY) LoopStatement parallelLoopStatement,
        @Param(ScoreLangConstants.RUN_ENV) RunEnvironment runEnv,
        @Param(EXECUTION_RUNTIME_SERVICES) ExecutionRuntimeServices executionRuntimeServices,
        @Param(ScoreLangConstants.NODE_NAME_KEY) String nodeName,

        //CHECKSTYLE:OFF: checkstyle:parametername
        @Param(ExecutionParametersConsts.RUNNING_EXECUTION_PLAN_ID) Long RUNNING_EXECUTION_PLAN_ID,
        //CHECKSTYLE:ON

        @Param(ScoreLangConstants.NEXT_STEP_ID_KEY) Long nextStepId,
        @Param(ScoreLangConstants.BRANCH_BEGIN_STEP_ID_KEY) Long branchBeginStep,
        @Param(ScoreLangConstants.REF_ID) String refId) {

    try {/*from   w  w w .  j a  v a2  s. co  m*/
        Context flowContext = runEnv.getStack().popContext();

        List<Value> splitData = parallelLoopBinding.bindParallelLoopList(parallelLoopStatement, flowContext,
                runEnv.getSystemProperties(), nodeName);

        fireEvent(executionRuntimeServices, ScoreLangConstants.EVENT_SPLIT_BRANCHES,
                "parallel loop expression bound", runEnv.getExecutionPath().getCurrentPath(),
                LanguageEventData.StepType.STEP, nodeName, flowContext.getImmutableViewOfVariables(),
                Pair.of(LanguageEventData.BOUND_PARALLEL_LOOP_EXPRESSION, (Serializable) splitData));

        runEnv.putNextStepPosition(nextStepId);
        runEnv.getExecutionPath().down();

        for (Value splitItem : splitData) {
            Context branchContext = (Context) SerializationUtils.clone(flowContext);

            // first fire event
            fireEvent(executionRuntimeServices, ScoreLangConstants.EVENT_BRANCH_START,
                    "parallel loop branch created", runEnv.getExecutionPath().getCurrentPath(),
                    LanguageEventData.StepType.STEP, nodeName, branchContext.getImmutableViewOfVariables(),
                    Pair.of(ScoreLangConstants.REF_ID, refId),
                    Pair.of(RuntimeConstants.SPLIT_ITEM_KEY, splitItem));
            // take path down one level
            runEnv.getExecutionPath().down();

            RunEnvironment branchRuntimeEnvironment = (RunEnvironment) SerializationUtils.clone(runEnv);
            branchRuntimeEnvironment.resetStacks();

            if (parallelLoopStatement instanceof ListLoopStatement) {
                branchContext.putVariable(((ListLoopStatement) parallelLoopStatement).getVarName(), splitItem);
            } else if (parallelLoopStatement instanceof MapLoopStatement) {
                branchContext.putVariable(((MapLoopStatement) parallelLoopStatement).getKeyName(),
                        (Value) ((ImmutablePair) splitItem.get()).getLeft());
                branchContext.putVariable(((MapLoopStatement) parallelLoopStatement).getValueName(),
                        (Value) ((ImmutablePair) splitItem.get()).getRight());
            }
            updateCallArgumentsAndPushContextToStack(branchRuntimeEnvironment, branchContext,
                    new HashMap<String, Value>());

            createBranch(branchRuntimeEnvironment, executionRuntimeServices, refId, branchBeginStep);

            // take path up level
            runEnv.getExecutionPath().up();

            // forward for next branch
            runEnv.getExecutionPath().forward();
        }

        updateCallArgumentsAndPushContextToStack(runEnv, flowContext, new HashMap<String, Value>());
    } catch (RuntimeException e) {
        logger.error("There was an error running the add branches execution step of: \'" + nodeName
                + "\'. Error is: " + e.getMessage());
        throw new RuntimeException("Error running: " + nodeName + ": " + e.getMessage(), e);
    }

}

From source file:com.yahoo.bullet.result.MetadataTest.java

@Test
public void testConceptKeyExtractionWithMetadataNotEnabled() {
    Map<String, Object> configuration = new HashMap<>();
    configuration.put(BulletConfig.RESULT_METADATA_METRICS,
            asMetadataEntries(Pair.of("Estimated Result", "foo")));

    Set<Concept> concepts = new HashSet<>(singletonList(Concept.ESTIMATED_RESULT));

    Assert.assertEquals(Metadata.getConceptNames(configuration, concepts), Collections.emptyMap());
}

From source file:cherry.goods.telno.SoumuExcelParser.java

/**
 * ?//ww w . ja  v a  2 s . c  o  m
 * 
 * @param in ?
 * @return ?????? (6?)?????
 * @throws InvalidFormatException ???
 * @throws IOException ??
 */
public Map<String, Pair<String, String>> parse(InputStream in) throws InvalidFormatException, IOException {
    Map<String, Pair<String, String>> map = new LinkedHashMap<>();
    try (Workbook workbook = WorkbookFactory.create(in)) {
        for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
            Sheet sheet = workbook.getSheetAt(i);
            Integer numberCol = null;
            Integer areaCodeCol = null;
            Integer localCodeCol = null;
            boolean preparing = true;
            for (Row row : sheet) {
                if (preparing) {
                    for (Cell cell : row) {
                        String value = cell.getStringCellValue();
                        if (numberLabel.equals(value)) {
                            numberCol = cell.getColumnIndex();
                        }
                        if (areaCodeLabel.equals(value)) {
                            areaCodeCol = cell.getColumnIndex();
                        }
                        if (localCodeLabel.equals(value)) {
                            localCodeCol = cell.getColumnIndex();
                        }
                    }
                    if (numberCol != null && areaCodeCol != null && localCodeCol != null) {
                        preparing = false;
                    }
                } else {
                    String number = getCellValue(row, numberCol.intValue());
                    String areaCode = getCellValue(row, areaCodeCol.intValue());
                    String localCode = getCellValue(row, localCodeCol.intValue());
                    if (isNotEmpty(number) && isNotEmpty(areaCode) && isNotEmpty(localCode)) {
                        map.put(number, Pair.of(areaCode, localCode));
                    }
                }
            }
        }
    }
    return map;
}

From source file:enumj.StreamComparator.java

private Pair<Function<Stream<T>, Stream<T>>, Function<E, E>> getFilterFuns() {
    final int seed = rnd.nextInt();
    final Predicate<T> filter = predicateOfSeed.apply(seed);
    final Function<Stream<T>, Stream<T>> lhs = s -> s.filter(filter);
    final Function<E, E> rhs = e -> filter(e, filter);
    if (statistics != null) {
        statistics.filter();//from   w  w  w. j  a v a  2  s  .c  o m
    }
    return Pair.of(lhs, rhs);
}

From source file:com.formkiq.core.service.ArchiveServiceImplTest.java

/**
 * testGet01()./*from   w w  w .jav a2  s  . c  o  m*/
 * reset UUID workflow
 * @throws IOException IOException
 */
@Test
public void testGet01() throws IOException {
    // given
    boolean resetUUID = true;
    String folder = UUID.randomUUID().toString();

    String sha1hash = UUID.randomUUID().toString();
    FormJSON form = TestDataBuilder.createSimpleForm();

    WorkflowOutputForm output1 = new WorkflowOutputForm();
    output1.setForm(form.getName(), form.getUUID());

    WorkflowOutputDocx output2 = new WorkflowOutputDocx();
    WorkflowOutputFormField outfield = new WorkflowOutputFormField();
    outfield.setForm(form.getName() + "[" + form.getUUID() + "]");
    output2.setFields(Arrays.asList(outfield));

    Workflow workflow = TestDataBuilder.createWorkflow(form);
    workflow.setOutputs(Arrays.asList(output1, output2));
    String uuid = workflow.getUUID();

    ArchiveDTO archive = new ArchiveDTO();
    archive.setWorkflow(workflow);
    archive.addForm(form);

    byte[] data = this.service.createZipFile(archive);

    // when
    expect(this.folderService.findFormData(folder, uuid)).andReturn(Pair.of(data, sha1hash));

    replayAll();
    ArchiveDTO result = this.service.get(folder, uuid, resetUUID).getLeft();

    // then
    verifyAll();

    assertNull(workflow.getParentUUID());
    Workflow resultWorkflow = result.getWorkflow();
    assertNotEquals(workflow.getUUID(), resultWorkflow.getUUID());
    assertEquals(workflow.getUUID(), resultWorkflow.getParentUUID());

    assertNull(form.getParentUUID());

    Map<String, FormJSON> forms = result.getForms();
    assertEquals(1, forms.size());
    FormJSON resultform = forms.values().iterator().next();
    assertNotEquals(form.getUUID(), resultform.getUUID());
    assertEquals(form.getUUID(), resultform.getSourceFormUUID());

    assertFalse(result.getForms().containsKey(form.getUUID()));
    assertTrue(result.getForms().containsKey(resultform.getUUID()));

    assertFalse(resultWorkflow.getSteps().contains(form.getUUID()));
    assertTrue(resultWorkflow.getSteps().contains(resultform.getUUID()));

    assertFalse(resultWorkflow.getPrintsteps().contains(form.getUUID()));
    assertTrue(resultWorkflow.getPrintsteps().contains(resultform.getUUID()));

    WorkflowOutputForm wof = (WorkflowOutputForm) result.getWorkflow().getOutputs().get(0);
    assertNotEquals(output1.getForm(), wof.getForm());

    WorkflowOutputDocument w = (WorkflowOutputDocument) result.getWorkflow().getOutputs().get(1);
    assertNotEquals(output2.getFields().get(0).getForm(), w.getFields().get(0).getForm());
}

From source file:com.netflix.imfutility.itunes.audio.ChannelsMapper.java

/**
 * Prepare channels layout by order./*from w w w  .j a v a 2  s .c  om*/
 */
private void prepareChannelsByOrder() {
    SequenceTemplateParameterContext sequenceContext = contextProvider.getSequenceContext();

    channelsByOrder.clear();

    for (SequenceUUID seqUuid : sequenceContext.getUuids(SequenceType.AUDIO)) {
        ContextInfo contextInfo = new ContextInfoBuilder().setSequenceType(SequenceType.AUDIO)
                .setSequenceUuid(seqUuid).build();
        String channelsNum = sequenceContext.getParameterValue(SequenceContextParameters.CHANNELS_NUM,
                contextInfo);

        IntStream.rangeClosed(1, Integer.parseInt(channelsNum)).mapToObj(i -> Pair.of(seqUuid, i))
                .forEachOrdered(channelsByOrder::add);
    }
}

From source file:cc.kave.commons.model.groum.SubGroum.java

private Set<Pair<Node, Node>> getAllEdges() {
    Set<Pair<Node, Node>> edges = new HashSet<>();
    for (Node node : nodes) {
        Set<Node> successors = parent.getSuccessors(node);
        for (Node suc : successors) {
            if (nodes.contains(suc)) {
                edges.add(Pair.of(node, suc));
            }/* ww  w. j ava 2  s  .c om*/
        }
    }
    return edges;
}

From source file:com.netflix.imfutility.itunes.audio.ChannelsMapperTest.java

@Test
public void testSurroundWithStereo() throws Exception {
    TemplateParameterContextProvider contextProvider = AudioUtils.createContext(
            new FFmpegAudioChannels[][] { { FL, FR, FC, LFE, SL, SR }, { FL, FR } },
            new String[] { "en", "en" });

    ChannelsMapper mapper = new ChannelsMapper(contextProvider);
    mapper.mapChannels(createLayoutOptions(new LayoutType[] { SURROUND }, new String[] { "en" }));

    List<Pair<SequenceUUID, Integer>> channels = mapper.getChannels(Pair.of(SURROUND, "en"));

    assertChannelEquals(channels.get(0), 0, 1);
    assertChannelEquals(channels.get(1), 0, 2);
    assertChannelEquals(channels.get(2), 0, 3);
    assertChannelEquals(channels.get(3), 0, 4);
    assertChannelEquals(channels.get(4), 0, 5);
    assertChannelEquals(channels.get(5), 0, 6);

    assertChannelEquals(channels.get(6), 1, 1);
    assertChannelEquals(channels.get(7), 1, 2);

    assertEquals(8, channels.size());// w ww. j a  v  a2  s . c om
}

From source file:alfio.model.modification.EventModification.java

public static EventModification fromEvent(Event event, List<TicketCategory> ticketCategories,
        Optional<String> mapsApiKey) {
    final ZoneId zoneId = event.getZoneId();
    return new EventModification(event.getId(), event.getWebsiteUrl(), event.getTermsAndConditionsUrl(),
            event.getImageUrl(), event.getShortName(), event.getOrganizationId(), event.getLocation(),
            event.getDescription(), DateTimeModification.fromZonedDateTime(event.getBegin()),
            DateTimeModification.fromZonedDateTime(event.getEnd()), event.getRegularPrice(),
            event.getCurrency(), event.getAvailableSeats(), event.getVat(), event.isVatIncluded(),
            event.getAllowedPaymentProxies(),
            ticketCategories.stream().map(tc -> TicketCategoryModification.fromTicketCategory(tc, zoneId))
                    .collect(toList()),//from  w  ww .  j  av  a 2 s . co  m
            event.isFreeOfCharge(), fromGeoData(Pair.of(event.getLatitude(), event.getLongitude()),
                    TimeZone.getTimeZone(zoneId), mapsApiKey));
}

From source file:com.github.steveash.jg2p.train.EncoderEval.java

public void evalAndPrint(List<InputRecord> inputs, PrintOpts opts) {

    totalPhones = 0;/*w w w. j a v a 2  s  . c o  m*/
    totalRightPhones = 0;
    totalWords = 0;
    totalRightWords = 0;
    noCodes = 0;
    rightAnswerInTop.clear();
    examples.clear();
    phoneEditHisto.clear();

    for (InputRecord input : inputs) {

        List<PhoneticEncoder.Encoding> encodings = encoder.encode(input.xWord);
        if (encodings.isEmpty()) {
            noCodes += 1;
            continue;
        }

        totalWords += 1;
        PhoneticEncoder.Encoding encoding = encodings.get(0);

        List<String> expected = input.yWord.getValue();
        int phonesDiff = ListEditDistance.editDistance(encoding.phones, expected, 100);
        totalPhones += expected.size();
        totalRightPhones += (expected.size() - phonesDiff);
        phoneEditHisto.add(phonesDiff);
        if (phonesDiff == 0) {
            totalRightWords += 1;
            rightAnswerInTop.add(0);
        }
        if (phonesDiff > 0) {
            // find out if the right encoding is in the top-k results
            for (int i = 1; i < encodings.size(); i++) {
                PhoneticEncoder.Encoding attempt = encodings.get(i);
                if (attempt.phones.equals(input.yWord.getValue())) {
                    rightAnswerInTop.add(i);
                    break;
                }
            }
        }
        if (collectExamples && phonesDiff > 0) {
            Pair<InputRecord, List<PhoneticEncoder.Encoding>> example = Pair.of(input, encodings);
            List<Pair<InputRecord, List<PhoneticEncoder.Encoding>>> examples = this.examples.get(phonesDiff);
            if (examples.size() < EXAMPLE_COUNT) {
                examples.add(example);
            } else {
                int victim = rand.nextInt(Ints.saturatedCast(totalWords));
                if (victim < EXAMPLE_COUNT) {
                    examples.set(victim, example);
                }
            }
        }

        if (totalWords % 500 == 0 && opts != PrintOpts.SIMPLE) {
            log.info("Processed " + totalWords + " ...");
            if (totalWords % 10_000 == 0) {
                printStats(opts);
            }
        }
    }
    printStats(opts);
}