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

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

Introduction

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

Prototype

@Override
public R getValue() 

Source Link

Document

Gets the value from this pair.

This method implements the Map.Entry interface returning the right element as the value.

Usage

From source file:com.bluepowermod.part.tube.TubeLogic.java

public boolean retrieveStack(TileEntity target, ForgeDirection dirToRetrieveInto, ItemStack filter,
        TubeColor color) {/*ww w.  j ava2s  .co  m*/

    if (tube.getWorld() == null)
        return false;
    TubeStack stack = new TubeStack(filter, null, color);
    stack.setTarget(target, dirToRetrieveInto);

    Pair<ForgeDirection, TileEntity> result = getHeadingForItem(stack, false);
    if (result == null)
        return false;

    int fuzzySetting = 0;
    if (target instanceof IFuzzyRetrieving) {
        fuzzySetting = ((IFuzzyRetrieving) target).getFuzzySetting();
    }

    ItemStack extractedItem = null;
    if (result.getValue() instanceof TileManager) {// Exception for managers, the result can only end up as a manager if the pulling inventory was
        // a manager.
        TileEntity managedInventory = ((TileManager) result.getValue())
                .getTileCache(((TileManager) result.getValue()).getFacingDirection());
        extractedItem = IOHelper.extract(managedInventory, result.getKey().getOpposite(), filter, false, false,
                fuzzySetting);
    } else if (filter != null) {
        extractedItem = IOHelper.extract(result.getValue(), result.getKey().getOpposite(), filter,
                !(target instanceof TileManager), false, fuzzySetting);
    } else {
        extractedItem = IOHelper.extract(result.getValue(), result.getKey().getOpposite(), false);
    }
    if (extractedItem == null)
        throw new IllegalArgumentException("This isn't possible!");

    stack = new TubeStack(extractedItem, result.getKey().getOpposite(), color);
    stack.setTarget(target, dirToRetrieveInto);

    PneumaticTube tube = MultipartCompatibility.getPart(this.tube.getWorld(),
            result.getValue().xCoord - result.getKey().offsetX,
            result.getValue().yCoord - result.getKey().offsetY,
            result.getValue().zCoord - result.getKey().offsetZ, PneumaticTube.class);
    if (tube == null)
        throw new IllegalArgumentException("wieeeeerd!");
    return tube.getLogic().injectStack(stack, result.getKey().getOpposite(), false);
}

From source file:com.splicemachine.derby.stream.function.merge.AbstractMergeJoinFlatMapFunction.java

protected void initRightScan(PeekingIterator<LocatedRow> leftPeekingIterator) throws StandardException {
    ExecRow firstHashRow = joinOperation.getKeyRow(leftPeekingIterator.peek().getRow());
    ExecRow startPosition = joinOperation.getRightResultSet().getStartPosition();
    int[] columnOrdering = getColumnOrdering(joinOperation.getRightResultSet());
    int nCols = startPosition != null ? startPosition.nColumns() : 0;
    ExecRow scanStartOverride = null;/*from  w  w w  .  j  a  v a 2  s  .c  om*/
    int[] scanKeys = null;
    // If start row of right table scan has as many columns as key colummns of the table, cannot further
    // narrow down scan space, so return right tabel scan start row.
    if (nCols == columnOrdering.length) {
        scanStartOverride = startPosition;
        scanKeys = columnOrdering;
    } else {
        int[] rightHashKeys = joinOperation.getRightHashKeys();
        // Find valid hash column values to narrow down right scan. The valid hash columns must:
        // 1) not be used as a start key for inner table scan
        // 2) be consecutive
        // 3) be a key column
        LinkedList<Pair<Integer, Integer>> hashColumnIndexList = new LinkedList<>();
        for (int i = 0; i < rightHashKeys.length; ++i) {
            if (rightHashKeys[i] > nCols - 1) {
                if ((hashColumnIndexList.isEmpty()
                        || hashColumnIndexList.getLast().getValue() == rightHashKeys[i] - 1)
                        && isKeyColumn(columnOrdering, rightHashKeys[i])) {
                    hashColumnIndexList.add(new ImmutablePair<Integer, Integer>(i, rightHashKeys[i]));
                } else {
                    break;
                }
            }
        }

        scanStartOverride = new ValueRow(nCols + hashColumnIndexList.size());
        if (startPosition != null) {
            for (int i = 1; i <= startPosition.nColumns(); ++i) {
                scanStartOverride.setColumn(i, startPosition.getColumn(i));
            }
        }
        for (int i = 0; i < hashColumnIndexList.size(); ++i) {
            Pair<Integer, Integer> hashColumnIndex = hashColumnIndexList.get(i);
            int index = hashColumnIndex.getKey();
            scanStartOverride.setColumn(nCols + i + 1, firstHashRow.getColumn(index + 1));
        }

        // Scan key should include columns
        // 1) preceding the first hash column, these columns are in the form of "col=constant"
        // 2) all hash columns that are key columns
        scanKeys = new int[hashColumnIndexList.size() + rightHashKeys[0]];
        for (int i = 0; i < rightHashKeys[0]; ++i) {
            scanKeys[i] = i;
        }
        for (int i = 0; i < hashColumnIndexList.size(); ++i) {
            Pair<Integer, Integer> hashColumnIndex = hashColumnIndexList.get(i);
            int colPos = hashColumnIndex.getValue();
            scanKeys[rightHashKeys[0] + i] = colPos;
        }
    }

    ((BaseActivation) joinOperation.getActivation()).setScanStartOverride(scanStartOverride);
    ((BaseActivation) joinOperation.getActivation()).setScanKeys(scanKeys);
    if (startPosition != null) {
        ((BaseActivation) joinOperation.getActivation()).setScanStopOverride(startPosition);
    }

}

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//w w w  .  j av a 2s.  co 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:net.mindengine.galen.specs.reader.SpecReader.java

private void initSpecs() {

    putSpec("absent", new SimpleSpecProcessor(new SpecInit() {
        public Spec init() {
            return new SpecAbsent();
        }//from   w w w . ja va2  s  .  co  m
    }));

    putSpec("visible", new SimpleSpecProcessor(new SpecInit() {
        public Spec init() {
            return new SpecVisible();
        }
    }));

    putSpec("contains(\\s+partly)?", new SpecListProccessor(new SpecListInit() {
        public Spec init(String specName, List<String> list) {
            String arguments = specName.substring("contains".length()).trim();

            boolean isPartly = (!arguments.isEmpty() && arguments.equals("partly"));
            return new SpecContains(list, isPartly);
        }
    }));

    putSpec("width", new SpecComplexProcessor(expectThese(range()), new SpecComplexInit() {
        public Spec init(String specName, String paramsText, String contextPath, Object[] args) {
            return new SpecWidth((Range) args[0]);
        }
    }));

    putSpec("height", new SpecComplexProcessor(expectThese(range()), new SpecComplexInit() {
        public Spec init(String specName, String paramsText, String contextPath, Object[] args) {
            return new SpecHeight((Range) args[0]);
        }
    }));

    putSpec("text\\s+.*", new SpecProcessor() {
        @Override
        public Spec processSpec(String specName, String paramsText, String contextPath) {
            String arguments = specName.substring("text".length()).trim();

            List<String> allWords = Expectations.readAllWords(arguments);

            if (allWords.size() > 0) {
                String type = allWords.get(allWords.size() - 1);

                allWords.remove(allWords.size() - 1);
                return new SpecText(SpecText.Type.fromString(type), paramsText.trim()).withOperations(allWords);
            } else
                throw new SyntaxException("Missing validation type (is, starts, ends, contains, matches)");
        }
    });

    putSpec("css.*", new SpecProcessor() {
        @Override
        public Spec processSpec(String specName, String paramsText, String contextPath) {
            String arguments = specName.substring("css".length()).trim();

            StringCharReader reader = new StringCharReader(arguments);

            String cssPropertyName = Expectations.word().read(reader);
            String typeString = Expectations.word().read(reader);

            if (cssPropertyName.isEmpty()) {
                throw new SyntaxException("Missing css property name");
            }
            if (typeString.isEmpty()) {
                throw new SyntaxException("Missing validation type (is, contains, starts, ends, matches)");
            }
            return new SpecCss(cssPropertyName, SpecText.Type.fromString(typeString), paramsText.trim());
        }
    });

    putSpec("inside.*", new SpecComplexProcessor(expectThese(objectName(), locations()), new SpecComplexInit() {
        @SuppressWarnings("unchecked")
        @Override
        public Spec init(String specName, String paramsText, String contextPath, Object[] args) {
            String leftoverName = specName.substring(6).trim();

            String objectName = (String) args[0];
            List<Location> locations = (List<Location>) args[1];

            SpecInside spec = new SpecInside(objectName, locations);

            if (leftoverName.equals("partly")) {
                spec.setPartly(true);
            }
            return spec;
        }
    }));

    putSpec("near", new SpecComplexProcessor(expectThese(objectName(), locations()), new SpecComplexInit() {
        @SuppressWarnings("unchecked")
        @Override
        public Spec init(String specName, String paramsText, String contextPath, Object[] args) {
            String objectName = (String) args[0];
            List<Location> locations = (List<Location>) args[1];

            if (locations == null || locations.size() == 0) {
                throw new SyntaxException(UNKNOWN_LINE, "There is no location defined");
            }
            return new SpecNear(objectName, locations);
        }
    }));

    putSpec("(above|below)", new SpecProcessor() {
        @Override
        public Spec processSpec(String specName, String paramsText, String contextPath) throws IOException {

            StringCharReader reader = new StringCharReader(paramsText.trim());
            String objectName = new ExpectWord().read(reader);

            Range range;
            if (reader.hasMore()) {
                range = Expectations.range().read(reader);
            } else {
                range = Range.greaterThan(-1.0);
            }

            if (specName.equals("above")) {
                return new SpecAbove(objectName, range);
            } else
                return new SpecBelow(objectName, range);
        }
    });

    putSpec("(left\\s+of|right\\s+of)", new SpecProcessor() {
        @Override
        public Spec processSpec(String specName, String paramsText, String contextPath) throws IOException {

            String direction = Expectations.word().read(new StringCharReader(specName));

            StringCharReader reader = new StringCharReader(paramsText.trim());
            String objectName = new ExpectWord().read(reader);

            Range range;
            if (reader.hasMore()) {
                range = Expectations.range().read(reader);
            } else {
                range = Range.greaterThan(-1.0);
            }

            if (direction.equals("left")) {
                return new SpecLeftOf(objectName, range);
            } else {
                return new SpecRightOf(objectName, range);
            }

        }
    });

    putSpec("aligned\\s+.*", new SpecObjectAndErrorRateProcessor(new SpecObjectAndErrorRateInit() {

        @Override
        public Spec init(String specName, String objectName, Integer errorRate) {
            String arguments = specName.substring("aligned".length()).trim();

            StringCharReader reader = new StringCharReader(arguments);

            String[] words = ExpectWord.readAllWords(reader);

            if (words.length == 0) {
                throw new SyntaxException(
                        "Alignment is not defined. Should be either 'vertically' either 'horizonally'");
            }
            String type = words[0];

            Alignment alignment = Alignment.ALL;
            if (words.length > 1) {
                alignment = Alignment.parse(words[1]);
            }

            if (errorRate == null) {
                errorRate = 0;
            }

            if (type.equals("horizontally")) {
                if (alignment.isOneOf(CENTERED, TOP, BOTTOM, ALL)) {
                    return new SpecHorizontally(alignment, objectName).withErrorRate(errorRate);
                } else {
                    throw new SyntaxException(UNKNOWN_LINE,
                            "Horizontal alignment doesn't allow this side: " + alignment.toString());
                }
            } else if (type.equals("vertically")) {
                if (alignment.isOneOf(CENTERED, LEFT, RIGHT, ALL)) {
                    return new SpecVertically(alignment, objectName).withErrorRate(errorRate);
                } else {
                    throw new SyntaxException(UNKNOWN_LINE,
                            "Verticall alignment doesn't allow this side: " + alignment.toString());
                }
            } else {
                throw new SyntaxException("Unknown alignment: " + type);
            }
        }
    }));

    putSpec("centered\\s.*", new SpecObjectAndErrorRateProcessor(new SpecObjectAndErrorRateInit() {

        @Override
        public Spec init(String specName, String objectName, Integer errorRate) {
            specName = specName.replace("centered", "").trim();
            String args[] = specName.split(" ");

            SpecCentered.Alignment alignment = SpecCentered.Alignment.ALL;
            SpecCentered.Location location = null;
            if (args.length == 1) {
                location = SpecCentered.Location.fromString(args[0]);
            } else {
                alignment = SpecCentered.Alignment.fromString(args[0]);
                location = SpecCentered.Location.fromString(args[1]);
            }

            // Setting default 2 px error rate in case it was not provided in page spec
            if (errorRate == null) {
                errorRate = 2;
            }

            return new SpecCentered(objectName, alignment, location).withErrorRate(errorRate);
        }
    }));

    putSpec("(on\\s.*|on)",
            new SpecComplexProcessor(expectThese(objectName(), locations()), new SpecComplexInit() {
                @SuppressWarnings("unchecked")
                @Override
                public Spec init(String specName, String paramsText, String contextPath, Object[] args) {
                    String objectName = (String) args[0];

                    String[] words = ExpectWord.readAllWords(new StringCharReader(specName));

                    if (words.length > 3) {
                        throw new SyntaxException("Too many sides. Should use only 2");
                    }

                    Side sideHorizontal = Side.TOP;
                    Side sideVertical = Side.LEFT;

                    boolean isFirstHorizontal = false;
                    if (words.length > 1) {
                        Side side = Side.fromString(words[1]);
                        if (side == Side.TOP || side == Side.BOTTOM) {
                            isFirstHorizontal = true;
                            sideHorizontal = side;
                        } else
                            sideVertical = side;
                    }

                    if (words.length > 2) {
                        Side side = Side.fromString(words[2]);
                        if (side == Side.TOP || side == Side.BOTTOM) {
                            if (isFirstHorizontal) {
                                throw new SyntaxException(
                                        "Cannot use theses sides: " + words[1] + " " + words[2]);
                            }
                            sideHorizontal = side;
                        } else {
                            if (!isFirstHorizontal) {
                                throw new SyntaxException(
                                        "Cannot use theses sides: " + words[1] + " " + words[2]);
                            }
                            sideVertical = side;
                        }
                    }

                    List<Location> locations = (List<Location>) args[1];
                    if (locations == null || locations.size() == 0) {
                        throw new SyntaxException(UNKNOWN_LINE, "There is no location defined");
                    }

                    return new SpecOn(objectName, sideHorizontal, sideVertical, locations);
                }
            }));

    putSpec("component.*", new SpecProcessor() {

        @Override
        public Spec processSpec(String specName, String paramsText, String contextPath) throws IOException {

            String childFilePath = paramsText.trim();
            if (childFilePath.isEmpty()) {
                throw new SyntaxException("File path to component spec is not specified");
            }

            String fullFilePath = childFilePath;
            if (contextPath != null) {
                fullFilePath = contextPath + File.separator + childFilePath;
            }

            SpecComponent spec = new SpecComponent();
            spec.setSpecPath(fullFilePath);

            if (getSecondWord(specName).equals("frame")) {
                spec.setFrame(true);
            }

            return spec;
        }
    });

    putSpec("color\\s+scheme", new SpecComplexProcessor(expectThese(colorRanges()), new SpecComplexInit() {
        @SuppressWarnings("unchecked")
        @Override
        public Spec init(String specName, String paramsText, String contextPath, Object[] args) {

            List<ColorRange> colorRanges = (List<ColorRange>) args[0];
            if (colorRanges == null || colorRanges.size() == 0) {
                throw new SyntaxException("There are no colors defined");
            }

            SpecColorScheme spec = new SpecColorScheme();
            spec.setColorRanges(colorRanges);
            return spec;
        }
    }));

    putSpec("image",
            new SpecComplexProcessor(expectThese(commaSeparatedRepeatedKeyValues()), new SpecComplexInit() {
                @Override
                public Spec init(String specName, String paramsText, String contextPath, Object[] args) {
                    List<Pair<String, String>> parameters = (List<Pair<String, String>>) args[0];

                    SpecImage spec = new SpecImage();
                    spec.setImagePaths(new LinkedList<String>());
                    spec.setStretch(false);
                    spec.setErrorRate(GalenConfig.getConfig().getImageSpecDefaultErrorRate());
                    spec.setTolerance(GalenConfig.getConfig().getImageSpecDefaultTolerance());

                    for (Pair<String, String> parameter : parameters) {
                        if ("file".equals(parameter.getKey())) {
                            if (contextPath != null) {
                                spec.getImagePaths().add(contextPath + File.separator + parameter.getValue());
                            } else {
                                spec.getImagePaths().add(parameter.getValue());
                            }
                        } else if ("error".equals(parameter.getKey())) {
                            spec.setErrorRate(SpecImage.ErrorRate.fromString(parameter.getValue()));
                        } else if ("tolerance".equals(parameter.getKey())) {
                            spec.setTolerance(parseIntegerParameter("tolerance", parameter.getValue()));
                        } else if ("stretch".equals(parameter.getKey())) {
                            spec.setStretch(true);
                        } else if ("area".equals(parameter.getKey())) {
                            spec.setSelectedArea(parseRect(parameter.getValue()));
                        } else if ("filter".equals(parameter.getKey())) {
                            ImageFilter filter = parseImageFilter(parameter.getValue());
                            spec.getOriginalFilters().add(filter);
                            spec.getSampleFilters().add(filter);
                        } else if ("filter-a".equals(parameter.getKey())) {
                            ImageFilter filter = parseImageFilter(parameter.getValue());
                            spec.getOriginalFilters().add(filter);
                        } else if ("filter-b".equals(parameter.getKey())) {
                            ImageFilter filter = parseImageFilter(parameter.getValue());
                            spec.getSampleFilters().add(filter);
                        } else if ("map-filter".equals(parameter.getKey())) {
                            ImageFilter filter = parseImageFilter(parameter.getValue());
                            spec.getMapFilters().add(filter);
                        } else if ("crop-if-outside".equals(parameter.getKey())) {
                            spec.setCropIfOutside(true);
                        } else {
                            throw new SyntaxException("Unknown parameter: " + parameter.getKey());
                        }
                    }

                    if (spec.getImagePaths() == null || spec.getImagePaths().size() == 0) {
                        throw new SyntaxException("There are no images defined");
                    }
                    return spec;
                }
            }));

}

From source file:io.anserini.rerank.lib.AxiomReranker.java

/**
 * Calculate the scores (weights) of each term that occured in the reranking pool.
 * The Process:/*w  w  w.  j a  v  a2 s .  c  om*/
 * 1. For each query term, calculate its score for each term in the reranking pool. the score
 * is calcuated as
 * <pre>
 * P(both occurs)*log{P(both occurs)/P(t1 occurs)/P(t2 occurs)}
 * + P(both not occurs)*log{P(both not occurs)/P(t1 not occurs)/P(t2 not occurs)}
 * + P(t1 occurs t2 not occurs)*log{P(t1 occurs t2 not occurs)/P(t1 occurs)/P(t2 not occurs)}
 * + P(t1 not occurs t2 occurs)*log{P(t1 not occurs t2 occurs)/P(t1 not occurs)/P(t2 occurs)}
 * </pre>
 * 2. For each query term the scores of every other term in the reranking pool are stored in a
 * PriorityQueue, only the top {@code K} are kept.
 * 3. Add the scores of the same term together and pick the top {@code M} ones.
 *
 * @param termInvertedList A Map of <term -> Set<docId>> where the Set of docIds is where the term occurs
 * @param context An instance of RerankerContext
 * @return Map<String, Double> Top terms and their weight scores in a HashMap
 */
private Map<String, Double> computeTermScore(Map<String, Set<Integer>> termInvertedList,
        RerankerContext<T> context) throws IOException {
    class ScoreComparator implements Comparator<Pair<String, Double>> {
        public int compare(Pair<String, Double> a, Pair<String, Double> b) {
            int cmp = Double.compare(b.getRight(), a.getRight());
            if (cmp == 0) {
                return a.getLeft().compareToIgnoreCase(b.getLeft());
            } else {
                return cmp;
            }
        }
    }

    // get collection statistics so that we can get idf later on.
    IndexReader reader;
    if (this.externalIndexPath != null) {
        Path indexPath = Paths.get(this.externalIndexPath);
        if (!Files.exists(indexPath) || !Files.isDirectory(indexPath) || !Files.isReadable(indexPath)) {
            throw new IllegalArgumentException(
                    this.externalIndexPath + " does not exist or is not a directory.");
        }
        reader = DirectoryReader.open(FSDirectory.open(indexPath));
    } else {
        IndexSearcher searcher = context.getIndexSearcher();
        reader = searcher.getIndexReader();
    }
    final long docCount = reader.numDocs() == -1 ? reader.maxDoc() : reader.numDocs();

    //calculate the Mutual Information between term with each query term
    List<String> queryTerms = context.getQueryTokens();
    Map<String, Integer> queryTermsCounts = new HashMap<>();
    for (String qt : queryTerms) {
        queryTermsCounts.put(qt, queryTermsCounts.getOrDefault(qt, 0) + 1);
    }

    Set<Integer> allDocIds = new HashSet<>();
    for (Set<Integer> s : termInvertedList.values()) {
        allDocIds.addAll(s);
    }
    int docIdsCount = allDocIds.size();

    // Each priority queue corresponds to a query term: The p-queue itself stores all terms
    // in the reranking pool and their reranking scores to the query term.
    List<PriorityQueue<Pair<String, Double>>> allTermScoresPQ = new ArrayList<>();
    for (Map.Entry<String, Integer> q : queryTermsCounts.entrySet()) {
        String queryTerm = q.getKey();
        long df = reader.docFreq(new Term(LuceneDocumentGenerator.FIELD_BODY, queryTerm));
        if (df == 0L) {
            continue;
        }
        float idf = (float) Math.log((1 + docCount) / df);
        int qtf = q.getValue();
        if (termInvertedList.containsKey(queryTerm)) {
            PriorityQueue<Pair<String, Double>> termScorePQ = new PriorityQueue<>(new ScoreComparator());
            double selfMI = computeMutualInformation(termInvertedList.get(queryTerm),
                    termInvertedList.get(queryTerm), docIdsCount);
            for (Map.Entry<String, Set<Integer>> termEntry : termInvertedList.entrySet()) {
                double score;
                if (termEntry.getKey().equals(queryTerm)) { // The mutual information to itself will always be 1
                    score = idf * qtf;
                } else {
                    double crossMI = computeMutualInformation(termInvertedList.get(queryTerm),
                            termEntry.getValue(), docIdsCount);
                    score = idf * beta * qtf * crossMI / selfMI;
                }
                termScorePQ.add(Pair.of(termEntry.getKey(), score));
            }
            allTermScoresPQ.add(termScorePQ);
        }
    }

    Map<String, Double> aggTermScores = new HashMap<>();
    for (PriorityQueue<Pair<String, Double>> termScores : allTermScoresPQ) {
        for (int i = 0; i < Math.min(termScores.size(), this.K); i++) {
            Pair<String, Double> termScore = termScores.poll();
            String term = termScore.getLeft();
            Double score = termScore.getRight();
            if (score - 0.0 > 1e-8) {
                aggTermScores.put(term, aggTermScores.getOrDefault(term, 0.0) + score);
            }
        }
    }
    PriorityQueue<Pair<String, Double>> termScoresPQ = new PriorityQueue<>(new ScoreComparator());
    for (Map.Entry<String, Double> termScore : aggTermScores.entrySet()) {
        termScoresPQ.add(Pair.of(termScore.getKey(), termScore.getValue() / queryTerms.size()));
    }
    Map<String, Double> resultTermScores = new HashMap<>();
    for (int i = 0; i < Math.min(termScoresPQ.size(), this.M); i++) {
        Pair<String, Double> termScore = termScoresPQ.poll();
        String term = termScore.getKey();
        double score = termScore.getValue();
        resultTermScores.put(term, score);
    }

    return resultTermScores;
}

From source file:com.htmlhifive.pitalium.core.model.ScreenshotArgumentBuilderTest.java

/**
 * addNewTargetByXxx????????//from  w  w  w .  j  ava  2 s . c o  m
 */
@Test
public void addNewTargetByXxx() throws Exception {
    Class<ScreenshotArgumentBuilder> clss = ScreenshotArgumentBuilder.class;
    for (Pair<String, SelectorType> mapping : TYPE_MAPPINGS) {
        Method method = clss.getMethod("addNewTargetBy" + mapping.getKey(), String.class);

        ScreenshotArgumentBuilder builder = new ScreenshotArgumentBuilder("ssid");
        method.invoke(builder, "target");

        ScreenshotArgument arg = builder.build();

        assertThat(arg.getScreenshotId(), is("ssid"));
        assertThat(arg.getTargets().size(), is(1));
        assertThat(arg.getHiddenElementSelectors().isEmpty(), is(true));

        assertThat(arg.getTargets().get(0), is(new CompareTarget(ScreenArea.of(mapping.getValue(), "target"))));
    }
}

From source file:com.htmlhifive.pitalium.core.model.ScreenshotArgumentBuilderTest.java

/**
 * AddHiddenElementsByXxx...//from   ww w .j a va  2 s .com
 */
@Test
public void addHiddenElementsByXxx() throws Exception {
    for (Pair<String, SelectorType> mapping : TYPE_MAPPINGS) {
        ScreenshotArgumentBuilder builder = new ScreenshotArgumentBuilder("ssid");

        ScreenshotArgumentBuilder.class.getMethod("addHiddenElementsBy" + mapping.getKey(), String.class)
                .invoke(builder, "value");
        ScreenshotArgument arg = builder.build();

        assertThat(arg.getScreenshotId(), is("ssid"));
        assertThat(arg.getTargets().isEmpty(), is(true));
        assertThat(arg.getHiddenElementSelectors().size(), is(1));

        assertThat(arg.getHiddenElementSelectors().get(0), is(new DomSelector(mapping.getValue(), "value")));
    }
}

From source file:alfio.manager.system.DataMigratorIntegrationTest.java

@Test
public void testUpdateDisplayName() {
    List<TicketCategoryModification> categories = Collections.singletonList(new TicketCategoryModification(null,
            "default", AVAILABLE_SEATS, new DateTimeModification(LocalDate.now(), LocalTime.now()),
            new DateTimeModification(LocalDate.now(), LocalTime.now()), DESCRIPTION, BigDecimal.TEN, false, "",
            false, null, null, null, null, null));
    Pair<Event, String> eventUsername = initEvent(categories, null);
    Event event = eventUsername.getKey();

    try {/*from   w w w .  jav a2s. c  om*/
        dataMigrator.migrateEventsToCurrentVersion();
        EventMigration eventMigration = eventMigrationRepository.loadEventMigration(event.getId());
        assertNotNull(eventMigration);
        //assertEquals(buildTimestamp, eventMigration.getBuildTimestamp().toString());
        assertEquals(currentVersion, eventMigration.getCurrentVersion());

        Event withDescription = eventRepository.findById(event.getId());
        assertNotNull(withDescription.getDisplayName());
        assertEquals(event.getShortName(), withDescription.getShortName());
        assertEquals(event.getShortName(), withDescription.getDisplayName());
    } finally {
        eventManager.deleteEvent(event.getId(), eventUsername.getValue());
    }
}

From source file:alfio.manager.EventManagerIntegrationTest.java

/**
 * When adding an unbounded category, we won't update the tickets status, because:
 * 1) if the unbounded category is using existing seats, the event cannot be already sold-out
 * 2) if the unbounded category has been added after an event edit (add seats), then the tickets are already "RELEASED"
 * 3) if there is another unbounded category, then it is safe not to update the tickets' status, in order to not
 *    interfere with the existing category
 *
 *//*  w  w  w  .j  a  v  a 2 s. c o  m*/
@Test
public void testAddUnboundedCategory() {
    List<TicketCategoryModification> categories = Collections.singletonList(new TicketCategoryModification(null,
            "default", 10, new DateTimeModification(LocalDate.now(), LocalTime.now()),
            new DateTimeModification(LocalDate.now(), LocalTime.now()), DESCRIPTION, BigDecimal.TEN, false, "",
            true, null, null, null, null, null));
    Pair<Event, String> pair = initEvent(categories, organizationRepository, userManager, eventManager,
            eventRepository);
    Event event = pair.getKey();
    TicketCategoryModification tcm = new TicketCategoryModification(null, "default", -1,
            new DateTimeModification(LocalDate.now(), LocalTime.now()),
            new DateTimeModification(LocalDate.now(), LocalTime.now()), DESCRIPTION, BigDecimal.TEN, false, "",
            false, null, null, null, null, null);
    eventManager.insertCategory(event.getId(), tcm, pair.getValue());
    List<Ticket> tickets = ticketRepository.findFreeByEventId(event.getId());
    assertNotNull(tickets);
    assertFalse(tickets.isEmpty());
    assertEquals(AVAILABLE_SEATS, tickets.size());
    assertEquals(10, tickets.stream().filter(t -> t.getCategoryId() == null).count());
}

From source file:alfio.manager.EventManagerIntegrationTest.java

@Test
public void testAddBoundedCategoryToUnboundedEvent() {
    List<TicketCategoryModification> categories = Collections.singletonList(new TicketCategoryModification(null,
            "default", 0, new DateTimeModification(LocalDate.now(), LocalTime.now()),
            new DateTimeModification(LocalDate.now(), LocalTime.now()), DESCRIPTION, BigDecimal.TEN, false, "",
            false, null, null, null, null, null));
    Pair<Event, String> pair = initEvent(categories, organizationRepository, userManager, eventManager,
            eventRepository);//from  w w w  .ja v  a  2  s.c  o m
    Event event = pair.getKey();
    TicketCategoryModification tcm = new TicketCategoryModification(null, "default", 10,
            new DateTimeModification(LocalDate.now(), LocalTime.now()),
            new DateTimeModification(LocalDate.now(), LocalTime.now()), DESCRIPTION, BigDecimal.TEN, false, "",
            true, null, null, null, null, null);
    Result<Integer> result = eventManager.insertCategory(event, tcm, pair.getValue());
    assertTrue(result.isSuccess());
    List<Ticket> tickets = ticketRepository.findFreeByEventId(event.getId());
    assertNotNull(tickets);
    assertFalse(tickets.isEmpty());
    assertEquals(10, tickets.size());
    assertEquals(10, tickets.stream().filter(t -> t.getCategoryId() == null).count());
    assertEquals(10,
            ticketRepository.countReleasedTicketInCategory(event.getId(), result.getData()).intValue());
}