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

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

Introduction

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

Prototype

public abstract R getRight();

Source Link

Document

Gets the right element from this pair.

When treated as a key-value pair, this is the value.

Usage

From source file:com.tussle.motion.MotionSystem.java

public CollisionTriad ecbHit(Map<StageElement<CollisionStadium>, CollisionStadium> beforeBoxes,
        Map<StageElement<CollisionStadium>, CollisionStadium> afterBoxes,
        Map<StageElement, CollisionShape> beforeSurfaces, Map<StageElement, CollisionShape> afterSurfaces,
        CollisionMap fores) {/*  ww  w .ja  v a  2  s .c  om*/
    if (fores.isEmpty())
        return null;

    //Split the given surfaces into two groups: those which are not worth timestep subdividing,
    //and those which are
    Predicate<Pair<StageElement<CollisionStadium>, StageElement>> splitHeuristic = (
            Pair<StageElement<CollisionStadium>, StageElement> m) -> {
        StageElement<CollisionStadium> c = m.getLeft();
        StageElement s = m.getRight();
        double[] velocity = Utility.displacementDiff(beforeSurfaces.get(s), afterSurfaces.get(s),
                beforeBoxes.get(c), afterBoxes.get(c));
        return FastMath.hypot(velocity[0], velocity[1]) >= PIXEL_STEP;
    };

    if (fores.keySet().stream().anyMatch(splitHeuristic)) {
        //Split in half, and run
        Map<StageElement<CollisionStadium>, CollisionStadium> middleBoxes = LazyMap.lazyMap(new HashMap<>(),
                (StageElement<CollisionStadium> c) -> beforeBoxes.get(c).interpolate(afterBoxes.get(c)));
        Map<StageElement, CollisionShape> middleSurfaces = LazyMap.lazyMap(new HashMap<>(),
                (StageElement s) -> beforeSurfaces.get(s).interpolate(afterSurfaces.get(s)));
        CollisionTriad latestHit = ecbHit(beforeBoxes, middleBoxes, beforeSurfaces, middleSurfaces, fores);

        Map<StageElement<CollisionStadium>, CollisionStadium> postMiddleBoxes;
        Map<StageElement<CollisionStadium>, CollisionStadium> postAfterBoxes;
        Map<StageElement, CollisionShape> postMiddleSurfaces;
        Map<StageElement, CollisionShape> postAfterSurfaces;
        if (latestHit != null) {
            double xDisp = latestHit.cumulativeX;
            double yDisp = latestHit.cumulativeY;
            postMiddleBoxes = LazyMap.lazyMap(new HashMap<>(),
                    (StageElement<CollisionStadium> c) -> middleBoxes.get(c).displacementBy(xDisp, yDisp));
            postAfterBoxes = LazyMap.lazyMap(new HashMap<>(),
                    (StageElement<CollisionStadium> c) -> afterBoxes.get(c).displacementBy(xDisp, yDisp));
            postMiddleSurfaces = LazyMap.lazyMap(new HashMap<>(),
                    (StageElement s) -> middleSurfaces.get(s).displacementBy(xDisp, yDisp));
            postAfterSurfaces = LazyMap.lazyMap(new HashMap<>(),
                    (StageElement s) -> afterSurfaces.get(s).displacementBy(xDisp, yDisp));
        } else {
            postMiddleBoxes = middleBoxes;
            postAfterBoxes = afterBoxes;
            postMiddleSurfaces = middleSurfaces;
            postAfterSurfaces = afterSurfaces;
        }

        //Populate a new collision map for the second half
        CollisionMap mids = new CollisionMap();
        for (Map.Entry<Pair<StageElement<CollisionStadium>, StageElement>, ProjectionVector> foreEntry : fores
                .entrySet()) {
            StageElement<CollisionStadium> c = foreEntry.getKey().getLeft();
            StageElement s = foreEntry.getKey().getRight();
            mids.put(c, s, s.getBefore().interpolate(s.getAfter()).depth(postMiddleBoxes.get(c)));
        }
        CollisionTriad secondHalfHit = ecbHit(postMiddleBoxes, postAfterBoxes, postMiddleSurfaces,
                postAfterSurfaces, mids);
        if (secondHalfHit != null)
            latestHit = latestHit == null ? secondHalfHit : new CollisionTriad(latestHit, secondHalfHit);
        return latestHit;
    } else {
        //Take the whole step at once
        CollisionMap afts = new CollisionMap();
        for (Pair<StageElement<CollisionStadium>, StageElement> foreKey : fores.keySet()) {
            if (foreKey.getRight().getBefore().collidesWith(beforeBoxes.get(foreKey.getLeft()))
                    || foreKey.getRight().getAfter().collidesWith(afterBoxes.get(foreKey.getLeft()))) {
                afts.put(foreKey, foreKey.getRight().getAfter().depth(afterBoxes.get(foreKey.getLeft())));
            }
        }
        ProjectionVector combinedVectors = Utility.combineProjections(Utility.prunedProjections(afts.values()));
        return combinedVectors == null ? null : new CollisionTriad(combinedVectors);
    }
}

From source file:com.github.tddts.jet.service.impl.SearchOperationsImpl.java

@Override
@SendSearchEvents(before = SEARCHING_FOR_ROUTES, after = FINISHED)
public List<OrderSearchRow> searchForRoutes(Pair<List<ResultOrder>, Map<Integer, String>> searchPair) {
    List<ResultOrder> searchResults = searchPair.getLeft();
    Map<Integer, String> typeNames = searchPair.getRight();

    return searchResults.stream().map(searchResult -> findRoute(searchResult, searchParams.getRouteOption(),
            typeNames.get(searchResult.getTypeId()))).collect(Collectors.toList());
}

From source file:com.linkedin.pinot.integration.tests.BaseClusterIntegrationTest.java

public static Future<Map<File, File>> buildSegmentsFromAvro(final List<File> avroFiles, Executor executor,
        int baseSegmentIndex, final File baseDirectory, final File segmentTarDir, final String tableName,
        final boolean createStarTreeIndex, final com.linkedin.pinot.common.data.Schema inputPinotSchema) {
    int segmentCount = avroFiles.size();
    LOGGER.info("Building " + segmentCount + " segments in parallel");
    List<ListenableFutureTask<Pair<File, File>>> futureTasks = new ArrayList<ListenableFutureTask<Pair<File, File>>>();

    for (int i = 1; i <= segmentCount; ++i) {
        final int segmentIndex = i - 1;
        final int segmentNumber = i + baseSegmentIndex;

        final ListenableFutureTask<Pair<File, File>> buildSegmentFutureTask = ListenableFutureTask
                .<Pair<File, File>>create(new Callable<Pair<File, File>>() {
                    @Override//from w  w w . j  a v  a  2 s . c  o m
                    public Pair<File, File> call() throws Exception {
                        try {
                            // Build segment
                            LOGGER.info("Starting to build segment " + segmentNumber);
                            File outputDir = new File(baseDirectory, "segment-" + segmentNumber);
                            final File inputAvroFile = avroFiles.get(segmentIndex);
                            final SegmentGeneratorConfig genConfig = SegmentTestUtils
                                    .getSegmentGenSpecWithSchemAndProjectedColumns(inputAvroFile, outputDir,
                                            TimeUnit.DAYS, tableName, inputPinotSchema);

                            if (inputPinotSchema != null) {
                                genConfig.setSchema(inputPinotSchema);
                            }

                            // jfim: We add a space and a special character to do a regression test for PINOT-3296 Segments with spaces
                            // in their filename don't work properly
                            genConfig.setSegmentNamePostfix(Integer.toString(segmentNumber) + " %");
                            genConfig.setEnableStarTreeIndex(createStarTreeIndex);

                            // Enable off heap star tree format in the integration test.
                            StarTreeIndexSpec starTreeIndexSpec = null;
                            if (createStarTreeIndex) {
                                starTreeIndexSpec = new StarTreeIndexSpec();
                                starTreeIndexSpec.setEnableOffHeapFormat(true);
                            }
                            genConfig.setStarTreeIndexSpec(starTreeIndexSpec);

                            final SegmentIndexCreationDriver driver = SegmentCreationDriverFactory.get(null);
                            driver.init(genConfig);
                            driver.build();

                            // Tar segment
                            String segmentName = outputDir.list()[0];
                            final String tarGzPath = TarGzCompressionUtils.createTarGzOfDirectory(
                                    outputDir.getAbsolutePath() + "/" + segmentName,
                                    new File(segmentTarDir, segmentName).getAbsolutePath());
                            LOGGER.info("Completed segment " + segmentNumber + " : " + segmentName
                                    + " from file " + inputAvroFile.getName());
                            return new ImmutablePair<File, File>(inputAvroFile, new File(tarGzPath));
                        } catch (Exception e) {
                            LOGGER.error("Exception while building segment input: {} output {} ",
                                    avroFiles.get(segmentIndex), "segment-" + segmentNumber);
                            throw new RuntimeException(e);
                        }
                    }
                });

        futureTasks.add(buildSegmentFutureTask);
        executor.execute(buildSegmentFutureTask);
    }

    ListenableFuture<List<Pair<File, File>>> pairListFuture = Futures.allAsList(futureTasks);
    return Futures.transform(pairListFuture, new AsyncFunction<List<Pair<File, File>>, Map<File, File>>() {
        @Override
        public ListenableFuture<Map<File, File>> apply(List<Pair<File, File>> input) throws Exception {
            Map<File, File> avroToSegmentMap = new HashMap<File, File>();
            for (Pair<File, File> avroToSegmentPair : input) {
                avroToSegmentMap.put(avroToSegmentPair.getLeft(), avroToSegmentPair.getRight());
            }
            return Futures.immediateFuture(avroToSegmentMap);
        }
    });
}

From source file:name.martingeisse.phunky.runtime.code.expression.array.ArrayConstructionExpression.java

@Override
public void dump(CodeDumper dumper) {
    dumper.print("array(");
    boolean first = true;
    for (Pair<Expression, Expression> element : elements) {
        if (first) {
            first = false;/*w  ww. j a v a 2s  .co  m*/
        } else {
            dumper.print(", ");
        }
        if (element.getLeft() != null) {
            element.getLeft().dump(dumper);
            dumper.print(" => ");
        }
        element.getRight().dump(dumper);
    }
    dumper.print(')');
}

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/*from  w  w  w. ja  v a2s  . c o  m*/
 */
@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:idc.storyalbum.fetcher.FilterService.java

public Set<Photo> filter(Set<Photo> photos, Set<String> tags)
        throws ExecutionException, InterruptedException, FlickrException {
    log.info("Removing from {} photos photos without tags {}", photos.size(), tags);
    ExecutorService executorService = Executors.newFixedThreadPool(20);
    List<Future<Pair<Photo, Photo>>> futures = new ArrayList<>();
    for (Photo photo : photos) {
        futures.add(executorService.submit(new FilterTagTask(photo, tags)));
    }//from  www . j av  a2  s.c  o m
    executorService.shutdown();
    Set<Photo> result = new HashSet<>();
    for (Future<Pair<Photo, Photo>> future : futures) {
        Pair<Photo, Photo> photoBooleanPair = future.get();
        Photo photo = photoBooleanPair.getLeft();
        String url;
        try {
            url = photo.getOriginalUrl();
        } catch (Exception e) {
            url = photo.getUrl();
        }
        Photo detailedPhoto = photoBooleanPair.getRight();
        if (detailedPhoto == null) {
            log.info("Filtered {}", url);
            photos.remove(photo);
        } else {
            result.add(detailedPhoto);
        }
    }
    return result;

}

From source file:com.twosigma.beakerx.scala.serializers.ScalaTableDeSerializer.java

@SuppressWarnings("unchecked")
@Override/*from ww  w .j  a v  a 2s  .co  m*/
public Object deserialize(JsonNode n, ObjectMapper mapper) {
    org.apache.commons.lang3.tuple.Pair<String, Object> deserializeObject = TableDisplayDeSerializer
            .getDeserializeObject(parent, n, mapper);
    String subtype = deserializeObject.getLeft();
    if (subtype != null && subtype.equals(TableDisplay.DICTIONARY_SUBTYPE)) {
        return JavaConverters.mapAsScalaMapConverter((Map<String, Object>) deserializeObject.getRight())
                .asScala().toMap(Predef.<Tuple2<String, Object>>conforms());
    } else if (subtype != null && subtype.equals(TableDisplay.LIST_OF_MAPS_SUBTYPE)) {
        List<Map<String, Object>> rows = (List<Map<String, Object>>) deserializeObject.getRight();
        List<Object> oo = new ArrayList<Object>();
        for (Map<String, Object> row : rows) {
            oo.add(JavaConverters.mapAsScalaMapConverter(row).asScala()
                    .toMap(Predef.<Tuple2<String, Object>>conforms()));
        }
        return scala.collection.JavaConversions.collectionAsScalaIterable(oo);
    } else if (subtype != null && subtype.equals(TableDisplay.MATRIX_SUBTYPE)) {
        List<List<?>> matrix = (List<List<?>>) deserializeObject.getRight();
        ArrayList<Object> ll = new ArrayList<Object>();
        for (List<?> ob : matrix) {
            ll.add(scala.collection.JavaConversions.asScalaBuffer(ob).toList());
        }
        return scala.collection.JavaConversions.asScalaBuffer(ll).toList();
    }

    return deserializeObject.getRight();
}

From source file:de.tuberlin.uebb.jbop.optimizer.var.LocalVarInliner.java

private AbstractInsnNode handleNode(final InsnList original, final AbstractInsnNode currentNode,
        final Map<Integer, Object> knownValues, final MethodNode methodNode) {
    final int opcode = currentNode.getOpcode();
    if (opcode >= ISTORE && opcode <= ASTORE) {
        handleStore(currentNode, knownValues);
    } else if (opcode >= ILOAD && opcode <= ALOAD) {
        return hanldeLoad(original, currentNode, knownValues).getNext();
    } else if (opcode == IINC) {
        handleIInc(currentNode, knownValues);
    } else if (NodeHelper.isIf(currentNode)) {
        return handleIf(currentNode, knownValues, original, methodNode);
    } else if (opcode == GOTO) {
        if (LoopMatcher.isGotoOfLoop(currentNode)) {
            final AbstractInsnNode skipVars = skipVars(currentNode, knownValues);
            final Pair<AbstractInsnNode, AbstractInsnNode> bodyBounds = LoopMatcher.getBodyBounds(currentNode);
            if (bodyBounds != null) {
                handleNodes(bodyBounds.getLeft(), bodyBounds.getRight(), original, new HashMap<>(knownValues),
                        methodNode);// ww w  .  j  ava 2 s  .  c o  m
            }
            return skipVars;
        }
        return currentNode.getNext();
    }
    return currentNode.getNext();
}

From source file:io.lavagna.service.ProjectServiceTest.java

@Test
public void testFindBoardsByUserActivityWithPermissionsOnTest() {
    Pair<Project, User> prep = prepareOneActivity();

    List<ProjectWithEventCounts> projects = projectService.findProjectsActivityByUserInProjects(
            prep.getRight().getId(), Arrays.asList(prep.getLeft().getId()));
    Assert.assertEquals(1, projects.size());
}

From source file:com.sludev.commons.vfs2.provider.s3.SS3FileObject.java

/**
 * Lists the children of this file.  Is only called if {@link #doGetType}
 * returns {@link FileType#FOLDER}.  The return value of this method
 * is cached, so the implementation can be expensive.<br />
 * @return a possible empty String array if the file is a directory or null or an exception if the
 * file is not a directory or can't be read.
 * @throws Exception if an error occurs.
 *///from  w w  w.  j  a  v  a 2s. c  o  m
@Override
protected String[] doListChildren() throws Exception {
    String[] res = null;

    Pair<String, String> path = getContainerAndPath();

    String prefix = path.getRight();
    if (prefix.endsWith("/") == false) {
        // We need folders ( prefixes ) to end with a slash
        prefix += "/";
    }
    ListObjectsRequest loReq = new ListObjectsRequest();
    loReq.withBucketName(path.getLeft());
    loReq.withPrefix(prefix);
    loReq.withDelimiter("/");

    ObjectListing blobs = fileSystem.getClient().listObjects(loReq);

    List<String> resList = new ArrayList<>();
    for (S3ObjectSummary osum : blobs.getObjectSummaries()) {
        String currBlobStr = osum.getKey();
        resList.add(String.format("/%s/%s", path.getLeft(), currBlobStr));
    }

    List<String> commPrefixes = blobs.getCommonPrefixes();
    if (commPrefixes != null) {
        for (String currFld : commPrefixes) {
            resList.add(String.format("/%s/%s", path.getLeft(), currFld));
        }
    }

    res = resList.toArray(new String[resList.size()]);

    return res;
}