List of usage examples for org.apache.commons.lang3.tuple Pair getLeft
public abstract L getLeft();
Gets the left element from this pair.
When treated as a key-value pair, this is the key.
From source file:it.polimi.diceH2020.SPACE4CloudWS.core.CoarseGrainedOptimizer.java
private List<Triple<Integer, Optional<Double>, Boolean>> alterUntilBreakPoint(SolutionPerJob solPerJob, Function<Integer, Integer> updateFunction, Function<Double, Double> fromResult, Predicate<Double> feasibilityCheck, Predicate<Double> stoppingCondition, BiPredicate<Double, Double> incrementCheck, Predicate<Integer> vmCheck) { List<Triple<Integer, Optional<Double>, Boolean>> lst = new ArrayList<>(); Optional<Double> previous = Optional.empty(); boolean shouldKeepGoing = true; while (shouldKeepGoing) { Pair<Optional<Double>, Long> simulatorResult = dataProcessor.simulateClass(solPerJob); Optional<Double> maybeResult = simulatorResult.getLeft(); Optional<Double> interestingMetric = maybeResult.map(fromResult); Integer nVM = solPerJob.getNumberVM(); lst.add(new ImmutableTriple<>(nVM, maybeResult, interestingMetric.filter(feasibilityCheck).isPresent())); boolean terminationCriterion = !checkState(); logger.trace("terminationCriterion is " + terminationCriterion + " after checkState()"); terminationCriterion |= vmCheck.test(nVM); logger.trace("terminationCriterion is " + terminationCriterion + " after vmCheck.test()"); terminationCriterion |= interestingMetric.filter(stoppingCondition).isPresent(); logger.trace("terminationCriterion is " + terminationCriterion + " after filter"); if (previous.isPresent() && interestingMetric.isPresent() && (dataService.getScenario().getTechnology() != Technology.STORM || interestingMetric.get() == 0.0)) { terminationCriterion |= incrementCheck.test(previous.get(), interestingMetric.get()); }// ww w .j a va2s.c o m shouldKeepGoing = !terminationCriterion; previous = interestingMetric; if (dataService.getScenario().getTechnology() == Technology.STORM) { logger.trace(interestingMetric.orElse(Double.NaN) + " vs. " + solPerJob.getJob().getU()); } else { logger.trace(interestingMetric.orElse(Double.NaN) + " vs. " + solPerJob.getJob().getD()); } if (shouldKeepGoing) { String message = String.format("class %s -> num VM: %d, simulator result: %f, metric: %f", solPerJob.getId(), nVM, maybeResult.orElse(Double.NaN), interestingMetric.orElse(Double.NaN)); logger.info(message); solPerJob.updateNumberVM(updateFunction.apply(nVM)); } } return lst; }
From source file:com.netflix.spinnaker.clouddriver.kubernetes.v2.caching.view.provider.KubernetesV2InstanceProvider.java
@Override public KubernetesV2Instance getInstance(String account, String location, String fullName) { Pair<KubernetesKind, String> parsedName; try {//from w w w . j a v a 2 s.c o m parsedName = KubernetesManifest.fromFullResourceName(fullName); } catch (Exception e) { return null; } KubernetesKind kind = parsedName.getLeft(); String name = parsedName.getRight(); String key = Keys.infrastructure(kind, account, location, name); Optional<CacheData> optionalInstanceData = cacheUtils.getSingleEntry(kind.toString(), key); if (!optionalInstanceData.isPresent()) { return null; } CacheData instanceData = optionalInstanceData.get(); return KubernetesV2Instance.fromCacheData(instanceData); }
From source file:edu.uci.ics.hyracks.api.rewriter.runtime.SuperActivityOperatorNodePushable.java
public void init() throws HyracksDataException { Map<ActivityId, IOperatorNodePushable> startOperatorNodePushables = new HashMap<ActivityId, IOperatorNodePushable>(); Queue<Pair<Pair<IActivity, Integer>, Pair<IActivity, Integer>>> childQueue = new LinkedList<Pair<Pair<IActivity, Integer>, Pair<IActivity, Integer>>>(); List<IConnectorDescriptor> outputConnectors = null; /**/* www . jav a 2 s.c o m*/ * Set up the source operators */ for (Entry<ActivityId, IActivity> entry : startActivities.entrySet()) { IOperatorNodePushable opPushable = entry.getValue().createPushRuntime(ctx, recordDescProvider, partition, nPartitions); startOperatorNodePushables.put(entry.getKey(), opPushable); operatprNodePushablesBFSOrder.add(opPushable); operatorNodePushables.put(entry.getKey(), opPushable); inputArity += opPushable.getInputArity(); outputConnectors = parent.getActivityOutputMap().get(entry.getKey()); if (outputConnectors != null) { for (IConnectorDescriptor conn : outputConnectors) { childQueue.add(parent.getConnectorActivityMap().get(conn.getConnectorId())); } } } /** * Using BFS (breadth-first search) to construct to runtime execution * DAG; */ while (childQueue.size() > 0) { /** * expend the executing activities further to the downstream */ if (outputConnectors != null && outputConnectors.size() > 0) { for (IConnectorDescriptor conn : outputConnectors) { if (conn != null) { childQueue.add(parent.getConnectorActivityMap().get(conn.getConnectorId())); } } } /** * construct the source to destination information */ Pair<Pair<IActivity, Integer>, Pair<IActivity, Integer>> channel = childQueue.poll(); ActivityId sourceId = channel.getLeft().getLeft().getActivityId(); int outputChannel = channel.getLeft().getRight(); ActivityId destId = channel.getRight().getLeft().getActivityId(); int inputChannel = channel.getRight().getRight(); IOperatorNodePushable sourceOp = operatorNodePushables.get(sourceId); IOperatorNodePushable destOp = operatorNodePushables.get(destId); if (destOp == null) { destOp = channel.getRight().getLeft().createPushRuntime(ctx, recordDescProvider, partition, nPartitions); operatprNodePushablesBFSOrder.add(destOp); operatorNodePushables.put(destId, destOp); } /** * construct the dataflow connection from a producer to a consumer */ sourceOp.setOutputFrameWriter(outputChannel, destOp.getInputFrameWriter(inputChannel), recordDescProvider.getInputRecordDescriptor(destId, inputChannel)); /** * traverse to the child of the current activity */ outputConnectors = parent.getActivityOutputMap().get(destId); } }
From source file:io.cloudslang.lang.compiler.modeller.MetadataModellerImpl.java
private Pair<List<StepMetadata>, List<RuntimeException>> transformStepsData( Map<String, ParsedDescriptionSection> stepsData) { List<StepMetadata> stepsMetadata = new ArrayList<>(); List<RuntimeException> errors = new ArrayList<>(); for (Map.Entry<String, ParsedDescriptionSection> entry : stepsData.entrySet()) { String stepName = entry.getKey(); ParsedDescriptionSection parsedData = entry.getValue(); Pair<StepMetadata, List<RuntimeException>> transformResult = transformToStepMetadata(stepName, parsedData.getData());/*from w ww . ja va2s. c o m*/ stepsMetadata.add(transformResult.getLeft()); errors.addAll(transformResult.getRight()); } return new ImmutablePair<>(stepsMetadata, errors); }
From source file:com.epam.ngb.cli.manager.command.handler.http.FileRegistrationHandler.java
protected List<BiologicalDataItem> registerItems() { List<BiologicalDataItem> items = new ArrayList<>(files.size()); List<Pair<String, String>> failed = new ArrayList<>(files.size()); for (Pair<String, String> file : files) { BiologicalDataItemFormat format = BiologicalDataItemFormat.getByFilePath(file.getLeft()); String url = String.format(getRequestUrl(), format.name().toLowerCase()); HttpRequestBase request = getRequest(url); setDefaultHeader(request);/*w ww . j a v a 2s. co m*/ if (isSecure()) { addAuthorizationToRequest(request); } RegistrationRequest registration = createRegistrationRequest(file, format); String result = getPostResult(registration, (HttpPost) request); try { ResponseResult<BiologicalDataItem> responseResult = getMapper().readValue(result, getMapper().getTypeFactory().constructParametrizedType(ResponseResult.class, ResponseResult.class, BiologicalDataItem.class)); if (ERROR_STATUS.equals(responseResult.getStatus())) { LOGGER.error(responseResult.getMessage()); failed.add(file); } else { items.add(responseResult.getPayload()); } } catch (IOException e) { throw new ApplicationException(e.getMessage(), e); } } if (!failed.isEmpty()) { LOGGER.error(MessageConstants.getMessage(ERROR_FILES_NOT_REGISTERED, failed.stream().map(Pair::getLeft).collect(Collectors.joining(",")))); } return items; }
From source file:enumj.StreamComparator.java
public void build() { if (built) {//from w ww .ja va2s . c o m return; } for (int i = 0; i < length; ++i) { final Pair<Function<Stream<T>, Stream<T>>, Function<E, E>> transf = getFuns(); lhs = transf.getLeft().apply(lhs); rhs = transf.getRight().apply(rhs); } built = true; }
From source file:eu.crydee.alignment.aligner.ae.MetricsOneVsOneC.java
@Override public void collectionProcessComplete() throws AnalysisEngineProcessException { try {//from ww w .java2 s . co m String template = IOUtils.toString(getClass() .getResourceAsStream("/eu/crydee/alignment/aligner/ae/" + "metrics-one-vs-one-template.html")); template = template.replace("@@TITLE@@", "Metrics comparator" + LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME)); template = template.replace("@@LEFTALGO@@", leftAlgoName); template = template.replace("@@RIGHTALGO@@", rightAlgoName); StringBuilder sb = new StringBuilder(); sb.append("<table class=\"table table-condensed\">\n").append(" <thead>\n") .append(" <tr>\n").append(" <th>Document\\Metric</th>\n"); for (String key : keys) { sb.append(" <th colspan=\"2\">").append(methodsMetadata.get(key).getRight()) .append("</th>\n"); } sb.append(" <tr>\n").append(" </thead>\n").append(" <tbody>\n") .append(" <tr>\n").append(" <td>\n") .append(" <strong>Total</strong>\n") .append(" </td>\n"); for (String key : keys) { SummaryStatistics ss1 = new SummaryStatistics(), ss2 = new SummaryStatistics(); List<Pair<Double, Double>> column = results.column(key).values().stream().peek(p -> { ss1.addValue(p.getLeft()); ss2.addValue(p.getRight()); }).collect(Collectors.toList()); boolean significant = TestUtils.pairedTTest(column.stream().mapToDouble(p -> p.getLeft()).toArray(), column.stream().mapToDouble(p -> p.getRight()).toArray(), 0.05); double mean1 = ss1.getMean(), mean2 = ss2.getMean(); boolean above = mean1 > mean2; String summary1 = String.format("%.3f", mean1) + "<small class=\"text-muted\">" + "" + String.format("%.3f", ss1.getStandardDeviation()) + "</small>", summary2 = String.format("%.3f", mean2) + "<small class=\"text-muted\">" + "" + String.format("%.3f", ss2.getStandardDeviation()) + "</small>"; sb.append(" <td class=\"") .append(significant ? (above ? "success" : "danger") : "warning").append("\">") .append(summary1).append("</td>\n"); sb.append(" <td class=\"") .append(significant ? (!above ? "success" : "danger") : "warning").append("\">") .append(summary2).append("</td>\n"); } sb.append(" </tr>\n"); SortedSet<String> rows = new TreeSet<>(results.rowKeySet()); for (String row : rows) { sb.append(" <tr>\n").append(" <td>").append(row) .append("</td>\n"); for (String key : keys) { Pair<Double, Double> r = results.get(row, key); sb.append(" <td>").append(String.format("%.3f", r.getLeft())) .append("</td>\n").append(" <td>") .append(String.format("%.3f", r.getRight())).append("</td>\n"); } sb.append(" </tr>\n"); } sb.append(" </tbody>\n").append(" </table>"); FileUtils.write(new File(htmlFilepath), template.replace("@@TABLE@@", sb.toString()), StandardCharsets.UTF_8); } catch (IOException ex) { logger.error("IO problem with the HTML output."); throw new AnalysisEngineProcessException(ex); } }
From source file:com.netflix.spinnaker.clouddriver.kubernetes.v2.caching.view.provider.KubernetesV2LoadBalancerProvider.java
@Override public List<LoadBalancerProvider.Details> byAccountAndRegionAndName(String account, String namespace, String fullName) {// w ww. ja va 2s. c om Pair<KubernetesKind, String> parsedName; try { parsedName = KubernetesManifest.fromFullResourceName(fullName); } catch (Exception e) { return null; } KubernetesKind kind = parsedName.getLeft(); String name = parsedName.getRight(); String key = Keys.infrastructure(kind, account, name, name); Optional<CacheData> optionalLoadBalancerData = cacheUtils.getSingleEntry(kind.toString(), key); if (!optionalLoadBalancerData.isPresent()) { return null; } CacheData loadBalancerData = optionalLoadBalancerData.get(); return new ArrayList<>(fromLoadBalancerCacheData(Collections.singletonList(loadBalancerData))); }
From source file:io.cloudslang.lang.compiler.parser.MetadataParser.java
private void handleDescriptionLineVariableDeclarationOnlySyntax(DescriptionBuilder descriptionBuilder, String currentLine) {//from www . j av a 2 s . c om // if description is opened if (descriptionBuilder.descriptionOpened()) { // add Pair<String, String> data = descriptionPatternMatcher .getDescriptionVariableLineDataDeclarationOnly(currentLine); descriptionBuilder.addToDescription(data.getLeft(), data.getRight()); } // otherwise ignore }
From source file:it.polimi.diceH2020.SPACE4CloudWS.core.CoarseGrainedOptimizer.java
private boolean hillClimbing(SolutionPerJob solPerJob, Technology technology) { boolean success = false; Pair<Optional<Double>, Long> simulatorResult = dataProcessor.simulateClass(solPerJob); Optional<Double> maybeResult = simulatorResult.getLeft(); if (maybeResult.isPresent()) { success = true;/*from www . ja v a 2 s . c om*/ PerformanceSolver currentSolver = dataProcessor.getPerformanceSolver(); Function<Double, Double> fromResult = currentSolver.transformationFromSolverResult(solPerJob, technology); Predicate<Double> feasibilityCheck = currentSolver.feasibilityCheck(solPerJob, technology); Consumer<Double> metricUpdater = currentSolver.metricUpdater(solPerJob, technology); final double tolerance = settings.getOptimization().getTolerance(); BiPredicate<Double, Double> incrementCheck; Function<Integer, Integer> updateFunction; Predicate<Double> stoppingCondition; Predicate<Integer> vmCheck; double responseTime = fromResult.apply(maybeResult.get()); if (feasibilityCheck.test(responseTime)) { updateFunction = n -> n - 1; stoppingCondition = feasibilityCheck.negate(); vmCheck = n -> n == 1; incrementCheck = (prev, curr) -> false; } else { updateFunction = n -> n + 1; stoppingCondition = feasibilityCheck; vmCheck = n -> false; incrementCheck = (prev, curr) -> Math.abs((prev - curr) / prev) < tolerance; } List<Triple<Integer, Optional<Double>, Boolean>> resultsList = alterUntilBreakPoint(solPerJob, updateFunction, fromResult, feasibilityCheck, stoppingCondition, incrementCheck, vmCheck); Optional<Triple<Integer, Optional<Double>, Boolean>> result = resultsList.parallelStream() .filter(t -> t.getRight() && t.getMiddle().isPresent()) .min(Comparator.comparing(Triple::getLeft)); result.ifPresent(triple -> triple.getMiddle().ifPresent(output -> { int nVM = triple.getLeft(); switch (technology) { case HADOOP: case SPARK: solPerJob.setThroughput(output); break; case STORM: break; default: throw new RuntimeException("Unexpected technology"); } solPerJob.updateNumberVM(nVM); double metric = fromResult.apply(output); metricUpdater.accept(metric); logger.info(String.format( "class%s-> MakeFeasible ended, result = %f, other metric = %f, obtained with: %d VMs", solPerJob.getId(), output, metric, nVM)); })); } else { logger.info("class" + solPerJob.getId() + "-> MakeFeasible ended with ERROR"); solPerJob.setFeasible(false); } return success; }