Example usage for org.apache.commons.lang3.tuple ImmutablePair getLeft

List of usage examples for org.apache.commons.lang3.tuple ImmutablePair getLeft

Introduction

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

Prototype

@Override
public L getLeft() 

Source Link

Usage

From source file:org.apache.drill.exec.server.options.SessionOptionManager.java

private boolean withinRange(final OptionValue value) {
    final int queryNumber = session.getQueryCount();
    final ImmutablePair<Integer, Integer> pair = shortLivedOptions.get(value.name);
    final int start = pair.getLeft();
    final int end = pair.getRight();
    return start <= queryNumber && queryNumber < end;
}

From source file:org.apache.drill.exec.server.rest.profile.OperatorWrapper.java

public String getContent() {
    TableBuilder builder = new TableBuilder(OPERATOR_COLUMNS);

    for (ImmutablePair<OperatorProfile, Integer> ip : ops) {
        int minor = ip.getRight();
        OperatorProfile op = ip.getLeft();

        String path = new OperatorPathBuilder().setMajor(major).setMinor(minor).setOperator(op).build();
        builder.appendCell(path, null);// www.  j  a  v  a 2s  . c  o  m
        builder.appendNanos(op.getSetupNanos(), null);
        builder.appendNanos(op.getProcessNanos(), null);
        builder.appendNanos(op.getWaitNanos(), null);

        long maxBatches = Long.MIN_VALUE;
        long maxRecords = Long.MIN_VALUE;
        for (StreamProfile sp : op.getInputProfileList()) {
            maxBatches = Math.max(sp.getBatches(), maxBatches);
            maxRecords = Math.max(sp.getRecords(), maxRecords);
        }

        builder.appendFormattedInteger(maxBatches, null);
        builder.appendFormattedInteger(maxRecords, null);
        builder.appendBytes(op.getPeakLocalMemoryAllocated(), null);
    }
    return builder.build();
}

From source file:org.apache.drill.exec.server.rest.profile.OperatorWrapper.java

public void addSummary(TableBuilder tb) {

    String path = new OperatorPathBuilder().setMajor(major).setOperator(firstProfile).build();
    tb.appendCell(path, null);//  www.j  a v a 2s .c  om
    tb.appendCell(operatorType == null ? "UNKNOWN_OPERATOR" : operatorType.toString(), null);

    double setupSum = 0.0;
    double processSum = 0.0;
    double waitSum = 0.0;
    double memSum = 0.0;
    for (ImmutablePair<OperatorProfile, Integer> ip : ops) {
        OperatorProfile profile = ip.getLeft();
        setupSum += profile.getSetupNanos();
        processSum += profile.getProcessNanos();
        waitSum += profile.getWaitNanos();
        memSum += profile.getPeakLocalMemoryAllocated();
    }

    final ImmutablePair<OperatorProfile, Integer> shortSetup = Collections.min(ops, Comparators.setupTime);
    final ImmutablePair<OperatorProfile, Integer> longSetup = Collections.max(ops, Comparators.setupTime);
    tb.appendNanos(shortSetup.getLeft().getSetupNanos(), String.format(format, shortSetup.getRight()));
    tb.appendNanos(Math.round(setupSum / size), null);
    tb.appendNanos(longSetup.getLeft().getSetupNanos(), String.format(format, longSetup.getRight()));

    final ImmutablePair<OperatorProfile, Integer> shortProcess = Collections.min(ops, Comparators.processTime);
    final ImmutablePair<OperatorProfile, Integer> longProcess = Collections.max(ops, Comparators.processTime);
    tb.appendNanos(shortProcess.getLeft().getProcessNanos(), String.format(format, shortProcess.getRight()));
    tb.appendNanos(Math.round(processSum / size), null);
    tb.appendNanos(longProcess.getLeft().getProcessNanos(), String.format(format, longProcess.getRight()));

    final ImmutablePair<OperatorProfile, Integer> shortWait = Collections.min(ops, Comparators.waitTime);
    final ImmutablePair<OperatorProfile, Integer> longWait = Collections.max(ops, Comparators.waitTime);
    tb.appendNanos(shortWait.getLeft().getWaitNanos(), String.format(format, shortWait.getRight()));
    tb.appendNanos(Math.round(waitSum / size), null);
    tb.appendNanos(longWait.getLeft().getWaitNanos(), String.format(format, longWait.getRight()));

    final ImmutablePair<OperatorProfile, Integer> peakMem = Collections.max(ops,
            Comparators.operatorPeakMemory);
    tb.appendBytes(Math.round(memSum / size), null);
    tb.appendBytes(peakMem.getLeft().getPeakLocalMemoryAllocated(), null);
}

From source file:org.apache.drill.exec.server.rest.profile.ProfileWrapper.java

public ProfileWrapper(final QueryProfile profile) {
    this.profile = profile;
    this.id = QueryIdHelper.getQueryId(profile.getId());

    final List<FragmentWrapper> fragmentProfiles = new ArrayList<>();

    final List<MajorFragmentProfile> majors = new ArrayList<>(profile.getFragmentProfileList());
    Collections.sort(majors, Comparators.majorId);

    for (final MajorFragmentProfile major : majors) {
        fragmentProfiles.add(new FragmentWrapper(major, profile.getStart()));
    }/*from www . j  a v  a2 s .  co m*/
    this.fragmentProfiles = fragmentProfiles;

    final List<OperatorWrapper> ows = new ArrayList<>();
    // temporary map to store (major_id, operator_id) -> [(op_profile, minor_id)]
    final Map<ImmutablePair<Integer, Integer>, List<ImmutablePair<OperatorProfile, Integer>>> opmap = new HashMap<>();

    Collections.sort(majors, Comparators.majorId);
    for (final MajorFragmentProfile major : majors) {

        final List<MinorFragmentProfile> minors = new ArrayList<>(major.getMinorFragmentProfileList());
        Collections.sort(minors, Comparators.minorId);
        for (final MinorFragmentProfile minor : minors) {

            final List<OperatorProfile> ops = new ArrayList<>(minor.getOperatorProfileList());
            Collections.sort(ops, Comparators.operatorId);
            for (final OperatorProfile op : ops) {

                final ImmutablePair<Integer, Integer> ip = new ImmutablePair<>(major.getMajorFragmentId(),
                        op.getOperatorId());
                if (!opmap.containsKey(ip)) {
                    final List<ImmutablePair<OperatorProfile, Integer>> l = new ArrayList<>();
                    opmap.put(ip, l);
                }
                opmap.get(ip).add(new ImmutablePair<>(op, minor.getMinorFragmentId()));
            }
        }
    }

    final List<ImmutablePair<Integer, Integer>> keys = new ArrayList<>(opmap.keySet());
    Collections.sort(keys);

    for (final ImmutablePair<Integer, Integer> ip : keys) {
        ows.add(new OperatorWrapper(ip.getLeft(), opmap.get(ip)));
    }
    this.operatorProfiles = ows;
}

From source file:org.apache.drill.exec.server.rest.ProfileWrapper.java

public List<OperatorWrapper> getOperatorProfiles() {
    List<OperatorWrapper> ows = Lists.newArrayList();
    Map<ImmutablePair<Integer, Integer>, List<ImmutablePair<OperatorProfile, Integer>>> opmap = Maps
            .newHashMap();/*from  w  w w  .  ja  v  a  2 s.co m*/

    List<MajorFragmentProfile> majors = new ArrayList<>(profile.getFragmentProfileList());
    Collections.sort(majors, Comparators.majorIdCompare);
    for (MajorFragmentProfile major : majors) {

        List<MinorFragmentProfile> minors = new ArrayList<>(major.getMinorFragmentProfileList());
        Collections.sort(minors, Comparators.minorIdCompare);
        for (MinorFragmentProfile minor : minors) {

            List<OperatorProfile> ops = new ArrayList<>(minor.getOperatorProfileList());
            Collections.sort(ops, Comparators.operatorIdCompare);
            for (OperatorProfile op : ops) {

                ImmutablePair<Integer, Integer> ip = new ImmutablePair<>(major.getMajorFragmentId(),
                        op.getOperatorId());
                if (!opmap.containsKey(ip)) {
                    List<ImmutablePair<OperatorProfile, Integer>> l = Lists.newArrayList();
                    opmap.put(ip, l);
                }
                opmap.get(ip).add(new ImmutablePair<>(op, minor.getMinorFragmentId()));
            }
        }
    }

    List<ImmutablePair<Integer, Integer>> keys = new ArrayList<>(opmap.keySet());
    Collections.sort(keys);
    ImmutablePair<OperatorProfile, Integer> val;
    for (ImmutablePair<Integer, Integer> ip : keys) {
        ows.add(new OperatorWrapper(ip.getLeft(), opmap.get(ip)));
    }

    return ows;
}

From source file:org.ballerinalang.langserver.command.executors.CreateTestExecutor.java

/**
 * {@inheritDoc}//from  w w w. j av  a 2s.c  o m
 */
@Override
public Object execute(LSContext context) throws LSCommandExecutorException {
    String docUri = null;
    int line = -1;
    int column = -1;

    for (Object arg : context.get(ExecuteCommandKeys.COMMAND_ARGUMENTS_KEY)) {
        String argKey = ((JsonObject) arg).get(ARG_KEY).getAsString();
        String argVal = ((JsonObject) arg).get(ARG_VALUE).getAsString();
        switch (argKey) {
        case CommandConstants.ARG_KEY_DOC_URI:
            docUri = argVal;
            context.put(DocumentServiceKeys.FILE_URI_KEY, docUri);
            break;
        case CommandConstants.ARG_KEY_NODE_LINE:
            line = Integer.parseInt(argVal);
            break;
        case CommandConstants.ARG_KEY_NODE_COLUMN:
            column = Integer.parseInt(argVal);
            break;
        default:
        }
    }

    if (line == -1 || column == -1 || docUri == null) {
        throw new LSCommandExecutorException("Invalid parameters received for the create test command!");
    }

    WorkspaceDocumentManager docManager = context.get(ExecuteCommandKeys.DOCUMENT_MANAGER_KEY);
    LSCompiler lsCompiler = context.get(ExecuteCommandKeys.LS_COMPILER_KEY);

    // Compile the source file
    BLangPackage builtSourceFile = null;
    try {
        builtSourceFile = lsCompiler.getBLangPackage(context, docManager, false, null, false);
    } catch (LSCompilerException e) {
        throw new LSCommandExecutorException("Couldn't compile the source", e);
    }

    // Generate test file and notify Client
    BallerinaLanguageServer ballerinaLanguageServer = context.get(ExecuteCommandKeys.LANGUAGE_SERVER_KEY);
    ExtendedLanguageClient client = ballerinaLanguageServer.getClient();
    BallerinaWorkspaceService workspace = (BallerinaWorkspaceService) ballerinaLanguageServer
            .getWorkspaceService();
    try {
        if (builtSourceFile == null || builtSourceFile.diagCollector.hasErrors()) {
            String message = "Test generation failed due to compilation errors!";
            if (client != null) {
                client.showMessage(new MessageParams(MessageType.Error, message));
            }
            throw new LSCommandExecutorException(message);
        }

        // Check for tests folder, if not exists create a new folder
        Path filePath = Paths.get(URI.create(docUri));
        ImmutablePair<Path, Path> testDirs = createTestFolderIfNotExists(filePath);
        File testsDir = testDirs.getRight().toFile();

        // Generate a unique name for the tests file
        File testFile = testsDir.toPath().resolve(generateTestFileName(filePath)).toFile();

        // Generate test content edits
        String pkgRelativeSourceFilePath = testDirs.getLeft().relativize(filePath).toString();
        Pair<BLangNode, Object> bLangNodePair = getBLangNode(line, column, docUri, docManager, lsCompiler,
                context);

        Position position = new Position(0, 0);
        Range focus = new Range(position, position);
        BiConsumer<Integer, Integer> focusLineAcceptor = (focusLine, incrementer) -> {
            if (focusLine != null) {
                position.setLine(focusLine);
            }
            position.setLine(position.getLine() + incrementer);
        };
        List<TextEdit> content = TestGenerator.generate(docManager, bLangNodePair, focusLineAcceptor,
                builtSourceFile, pkgRelativeSourceFilePath, testFile);

        // Send edits
        List<Either<TextDocumentEdit, ResourceOperation>> edits = new ArrayList<>();
        VersionedTextDocumentIdentifier identifier = new VersionedTextDocumentIdentifier();
        identifier.setUri(testFile.toPath().toUri().toString());
        edits.add(Either.forRight(new CreateFile(testFile.toPath().toUri().toString())));

        TextDocumentEdit textEdit = new TextDocumentEdit(identifier, content);
        edits.add(Either.forLeft(textEdit));

        WorkspaceEdit workspaceEdit = new WorkspaceEdit(edits);
        ApplyWorkspaceEditParams editParams = new ApplyWorkspaceEditParams(workspaceEdit);
        if (client != null) {
            client.applyEdit(editParams);
            String message = "Tests generated into the file:" + testFile.toString();
            client.showMessage(new MessageParams(MessageType.Info, message));
            if (workspace.getExperimentalClientCapabilities().get(SHOW_TEXT_DOCUMENT.getValue())) {
                Location location = new Location(identifier.getUri(), focus);
                client.showTextDocument(location);
            }
        }
        return editParams;
    } catch (TestGeneratorException e) {
        String message = "Test generation failed!: " + e.getMessage();
        if (client != null) {
            client.showMessage(new MessageParams(MessageType.Error, message));
        }
        throw new LSCommandExecutorException(message, e);
    }
}

From source file:org.cbioportal.service.impl.GenesetHierarchyServiceImpl.java

private void calculateAndSetRepresentativeScoreAndPvalue(Geneset geneset,
        Map<String, List<GenesetMolecularData>> genesetScoresMap,
        Map<String, List<GenesetMolecularData>> genesetPvaluesMap, Integer percentile) {

    List<GenesetMolecularData> genesetScoreData = genesetScoresMap.get(geneset.getGenesetId());
    List<GenesetMolecularData> genesetPvalueData = genesetPvaluesMap.get(geneset.getGenesetId());

    //lists to hold the score and p-value pairs:
    List<ImmutablePair<Double, Double>> positiveScoresAndPvalues = new ArrayList<ImmutablePair<Double, Double>>();
    List<ImmutablePair<Double, Double>> negativeScoresAndPvalues = new ArrayList<ImmutablePair<Double, Double>>();

    //return the maximum absolute value found:
    double max = 0;
    double pvalueOfMax = 1;
    for (int i = 0; i < genesetScoreData.size(); i++) {
        String scoreString = genesetScoreData.get(i).getValue();
        String pvalueString = genesetPvalueData.get(i).getValue();

        if (!NumberUtils.isNumber(scoreString))
            continue;

        double score = Double.parseDouble(scoreString);
        double pvalue = 1.0;
        if (NumberUtils.isNumber(pvalueString))
            pvalue = Double.parseDouble(pvalueString);
        if (score >= 0) {
            positiveScoresAndPvalues.add(new ImmutablePair<Double, Double>(score, pvalue));
        } else {//from   ww  w  .  jav  a 2s  .  c  om
            negativeScoresAndPvalues.add(new ImmutablePair<Double, Double>(score, pvalue));
        }

        //keep track of max, in case percentile is null
        if (Math.abs(score) > Math.abs(max)) {
            max = score; //here no abs, since we want to get the raw score (could be negative)
            pvalueOfMax = pvalue;
        }
    }

    if (percentile == null) {
        geneset.setRepresentativeScore(max);
        geneset.setRepresentativePvalue(pvalueOfMax);
    } else {
        //sort scores (NB: .getLeft() returns the score, .getRight() returns the pvalue of each pair):
        positiveScoresAndPvalues.sort((ImmutablePair<Double, Double> o1,
                ImmutablePair<Double, Double> o2) -> Double.compare(o1.getLeft(), o2.getLeft()));
        //negative scores descending:
        negativeScoresAndPvalues.sort((ImmutablePair<Double, Double> o1,
                ImmutablePair<Double, Double> o2) -> Double.compare(o2.getLeft(), o1.getLeft()));

        //use percentile:
        ImmutablePair<Double, Double> representativePositiveScoreAndPvalue = new ImmutablePair<Double, Double>(
                0.0, 1.0);
        ImmutablePair<Double, Double> representativeNegativeScoreAndPvalue = new ImmutablePair<Double, Double>(
                0.0, 1.0);
        if (positiveScoresAndPvalues.size() > 0) {
            int idxPositiveScores = (int) Math.round(percentile * positiveScoresAndPvalues.size() / 100.0);
            if (idxPositiveScores == 0) { //(can happen when positiveScoresAndPvalues.size() is small)
                idxPositiveScores = 1;
            }
            representativePositiveScoreAndPvalue = positiveScoresAndPvalues.get(idxPositiveScores - 1);
        }
        if (negativeScoresAndPvalues.size() > 0) {
            int idxNegativeScores = (int) Math.round(percentile * negativeScoresAndPvalues.size() / 100.0);
            if (idxNegativeScores == 0) { //(can happen when positiveScoresAndPvalues.size() is small)
                idxNegativeScores = 1;
            }
            representativeNegativeScoreAndPvalue = negativeScoresAndPvalues.get(idxNegativeScores - 1);
        }

        //set best one:
        if (Math.abs(representativePositiveScoreAndPvalue.getLeft()) > Math
                .abs(representativeNegativeScoreAndPvalue.getLeft())) {
            geneset.setRepresentativeScore(representativePositiveScoreAndPvalue.getLeft());
            geneset.setRepresentativePvalue(representativePositiveScoreAndPvalue.getRight());
        } else {
            geneset.setRepresentativeScore(representativeNegativeScoreAndPvalue.getLeft());
            geneset.setRepresentativePvalue(representativeNegativeScoreAndPvalue.getRight());
        }
    }
}

From source file:org.hawkular.rx.commands.common.AbstractHttpCommand.java

protected void initialize(InjectionPoint ip) {
    boolean annotationFound = false;
    for (Annotation annotation : ip.getQualifiers()) {
        if (annotation.annotationType().equals(WithValues.class)) {
            annotationFound = true;//  www  .j a v a  2 s.  c  om
            String[] values = ((WithValues) annotation).values();
            List<ImmutablePair<Class, Consumer>> setters = getSetters();
            if (values.length != setters.size()) {
                throw new IllegalStateException(
                        "@WithValues has different number of parameters than it's needed");
            }
            int index = 0;
            for (ImmutablePair<Class, Consumer> setter : setters) {
                if (values[index] == null) {
                    setter.getRight().accept(null);
                }
                if (setter.getLeft().equals(String.class)) {
                    setter.getRight().accept(values[index]);
                } else if (setter.getLeft().equals(int.class) || setter.getLeft().equals(Integer.class)) {
                    setter.getRight().accept(Integer.parseInt(values[index]));
                } else if (setter.getLeft().equals(boolean.class) || setter.getLeft().equals(Boolean.class)) {
                    setter.getRight().accept(Boolean.parseBoolean(values[index]));
                } else if (setter.getLeft().equals(long.class) || setter.getLeft().equals(Long.class)) {
                    setter.getRight().accept(Boolean.parseBoolean(values[index]));
                } else if (setter.getLeft().equals(double.class) || setter.getLeft().equals(Double.class)) {
                    setter.getRight().accept(Double.parseDouble(values[index]));
                }
                index++;
            }
            break;
        }
    }
    if (!annotationFound) {
        throw new IllegalStateException("No @WithValues on InjectionPoint");
    }
}

From source file:org.hoidla.stream.MankuMotwaniLossyCounting.java

@Override
public void add(Object value) {
    ++count;// ww w  . j  a v a  2  s  .  c o  m
    currentBucket = count / bucketSize + 1;

    //add
    ImmutablePair<ObjectCounter, Long> counterWithError = buckets.get(value);
    if (null == counterWithError) {
        currentBucket = count / bucketSize;
        counterWithError = new ImmutablePair<ObjectCounter, Long>(new SimpleObjectCounter(), currentBucket - 1);
        buckets.put(value, counterWithError);
    }
    counterWithError.getLeft().increment();

    //delete
    delete();
}

From source file:org.hoidla.stream.MankuMotwaniLossyCounting.java

@Override
public void add(Object value, long sequence) {
    //expire from window
    ImmutablePair<ObjectCounter, Long> counterWithError = null;
    if (null != expirer) {
        toBeRemoved.clear();/* www.ja  va 2 s . c om*/
        for (Object key : buckets.keySet()) {
            counterWithError = buckets.get(key);
            counterWithError.getLeft().expire(expirer, sequence);

            if (counterWithError.getLeft().isZero()) {
                toBeRemoved.add(key);
            }
        }
        for (Object item : toBeRemoved) {
            buckets.remove(item);
        }
    }

    ++count;
    currentBucket = count / bucketSize + 1;

    //add
    counterWithError = buckets.get(value);
    if (null == counterWithError) {
        currentBucket = count / bucketSize;
        counterWithError = new ImmutablePair<ObjectCounter, Long>(new SequencedObjectCounter(),
                currentBucket - 1);
        buckets.put(value, counterWithError);
    }
    counterWithError.getLeft().increment(sequence);

    //delete
    delete();
}