Query the most similar objects, abstract version.

@param obj Query object
@param scores Score storage (must be initialized with zeros!)
@param cands Non-zero objects set (must be empty)
@return Result
546980
private double naiveQuery(V obj, WritableDoubleDataStore scores, HashSetModifiableDBIDs cands) {
    if(obj instanceof SparseNumberVector) {
      return naiveQuerySparse((SparseNumberVector) obj, scores, cands);
    }
    else {
      return naiveQueryDense(obj, scores, cands);
    }
  }
296659
@Override
    public int compareTo(Object obj) throws ClassCastException {

        URI another = (URI) obj;
        if (!equals(_authority, another.getRawAuthority())) { 
            return -1;
        }
        return toString().compareTo(another.toString());
    }
1249659
def _get_num_similar_objects(self, obj):
        """"""
        return StatementLine.objects.filter(
            date=obj.date, amount=obj.amount, description=obj.description
        ).count()
1186751
public static int addBest(float[] scores, Object[] predList, float score, Object pred) {
		int n = scores.length;
		int i;
		for (i = 0; i < n; i++) {
			if (score > scores[i])
				break;
		}
		if (i >= n)
			return -1;
		for (int k = n - 2; k >= i; k--) {
			scores[k + 1] = scores[k];
			predList[k + 1] = predList[k];
		}
		scores[i] = score;
		predList[i] = pred;
		return i;
	}
340288
public Collection<Record> findCandidateMatches(Record record) {
    if (DEBUG)
      System.out.println("---------------------------------------------------------------------------");
    
    // do lookup on all tokens from all lookup properties
    // (we only identify the buckets for now. later we decide how to process
    // them)
    List<Bucket> buckets = lookup(record);
    
    // preprocess the list of buckets
    Collections.sort(buckets);
    double score_sum = 0.0;
    for (Bucket b : buckets)
      score_sum += b.getScore();
      
    double score_so_far = 0.0;
    int threshold = buckets.size() - 1;
    for (; (score_so_far / score_sum) < min_relevance; threshold--) {
      score_so_far += buckets.get(threshold).getScore();
      if (DEBUG)
        System.out.println("score_so_far: " + (score_so_far/score_sum) + " (" +
                           threshold + ")");
    }
    // bucket.get(threshold) made us go over the limit, so we need to step
    // one back
    threshold++;
    if (DEBUG)
      System.out.println("Threshold: " + threshold);
    
    // the collection of candidates
    Map<Long, Score> candidates = new HashMap();

    // go through the buckets that we're going to collect candidates from
    int next_bucket = collectCandidates(candidates, buckets, threshold);

    // there might still be some buckets left below the threshold. for
    // these we go through the existing candidates and check if we can
    // find them in the buckets.
    bumpScores(candidates, buckets, next_bucket);

    if (DEBUG)
      System.out.println("candidates: " + candidates.size());
    
    // if the cutoff properties are not set we can stop right here
    // FIXME: it's possible to make this a lot cleaner
    if (max_search_hits > candidates.size() && min_relevance == 0.0) {
      Collection<Record> cands = new ArrayList(candidates.size());
      for (Long id : candidates.keySet())
        cands.add(store.findRecordById(id));
      if (DEBUG)
        System.out.println("final: " + cands.size());
      return cands;
    }
    
    // flatten candidates into an array, prior to sorting etc
    int ix = 0;
    Score[] scores = new Score[candidates.size()];
    double max_score = 0.0;
    for (Score s : candidates.values()) {
      scores[ix++] = s;
      if (s.score > max_score)
        max_score = s.score;
      if (DEBUG && false)
        System.out.println("" + s.id + ": " + s.score);
    }

    // allow map to be GC-ed
    candidates = null;

    // filter candidates with min_relevance and max_search_hits. do
    // this by turning the scores[] array into a priority queue (on
    // .score), then retrieving the best candidates. (gives a big
    // performance improvement over sorting the array.)
    PriorityQueue pq = new PriorityQueue(scores);
    int count = Math.min(scores.length, max_search_hits);
    Collection<Record> records = new ArrayList(count);
    for (ix = 0; ix < count; ix++) {
      Score s = pq.next();
      if (s.score >= min_relevance)
        records.add(store.findRecordById(s.id));
    }

    if (DEBUG)
      System.out.println("final: " + records.size());
    return records;
  }
416485
public ScoreMetric getScoreForApplication(ScoreCollectorItem scoreApplication, ScoreCriteriaSettings scoreCriteriaSettings) {
    Dashboard dashboard = getDashboard(scoreApplication.getDashboardId());

    if (null == dashboard) {
      LOGGER.info("Dashboard with id " + scoreApplication.getDashboardId() + " is null!");
      return null;
    }

    LOGGER.info("Dashboard title:" + dashboard.getTitle() + ", type:" + dashboard.getType() + ", owner:" + dashboard.getOwner());

    if (null == dashboard.getType() || !dashboard.getType().equals(DashboardType.Team)) {
      return null;
    }

    LOGGER.info("dashboard.getTitle():" + dashboard.getTitle() + " " + dashboard.getOwner());

    ScoreWeight dashboardScore = getDashboardScoreFromWidgets(
      processWidgetScores(dashboard.getWidgets(), scoreCriteriaSettings)
      );

    LOGGER.info("dashboardScore: {}" + dashboardScore);
    ScoreMetric scoreMetric = ScoreCalculationUtils.generateScoreMetric(
      dashboardScore,
      scoreCriteriaSettings.getMaxScore(),
      scoreApplication.getId(),
      dashboard.getId()
      );

    LOGGER.info("ScoreMetric scoreMetric " + scoreMetric.toString());

    return scoreMetric;
  }
858948
private List<String> findMatchesWithLowestScore(final List<ScoredHost> scored) {
    final int minScore = scored.get(0).score;
    final ImmutableList.Builder<String> minScoreHosts = ImmutableList.builder();
    for (final ScoredHost score : scored) {
      if (score.score == minScore) {
        minScoreHosts.add(score.host);
      }
    }
    return minScoreHosts.build();
  }
563372
protected ScoreResult computeScore(DBIDs ids, DBIDs outlierIds, OutlierResult or) throws IllegalStateException {
    if(scaling instanceof OutlierScaling) {
      OutlierScaling oscaling = (OutlierScaling) scaling;
      oscaling.prepare(or);
    }

    final ScalingFunction innerScaling;
    // If we have useful (finite) min/max, use these for binning.
    double min = scaling.getMin();
    double max = scaling.getMax();
    if(Double.isInfinite(min) || Double.isNaN(min) || Double.isInfinite(max) || Double.isNaN(max)) {
      innerScaling = new IdentityScaling();
      // TODO: does the outlier score give us this guarantee?
      LOG.warning("JudgeOutlierScores expects values between 0.0 and 1.0, but we don't have such a guarantee by the scaling function: min:" + min + " max:" + max);
    }
    else {
      if(min == 0.0 && max == 1.0) {
        innerScaling = new IdentityScaling();
      }
      else {
        innerScaling = new LinearScaling(1.0 / (max - min), -min);
      }
    }

    double posscore = 0.0;
    double negscore = 0.0;
    // fill histogram with values of each object
    for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) {
      double result = or.getScores().doubleValue(iter);
      result = innerScaling.getScaled(scaling.getScaled(result));
      posscore += (1.0 - result);
    }
    for(DBIDIter iter = outlierIds.iter(); iter.valid(); iter.advance()) {
      double result = or.getScores().doubleValue(iter);
      result = innerScaling.getScaled(scaling.getScaled(result));
      negscore += result;
    }
    posscore /= ids.size();
    negscore /= outlierIds.size();

    LOG.verbose("Scores: " + posscore + " " + negscore);

    ArrayList<double[]> s = new ArrayList<>(1);
    s.add(new double[] { (posscore + negscore) * .5, posscore, negscore });
    return new ScoreResult(s);
  }
238113
function match (obj, query) {
  var queryKeys, queryKey, queryValue, i;

  // Primitive query against a primitive type
  // This is a bit of a hack since we construct an object with an arbitrary key only to dereference it later
  // But I don't have time for a cleaner implementation now
  if (isPrimitiveType(obj) || isPrimitiveType(query)) {
    return matchQueryPart({ needAKey: obj }, 'needAKey', query);
  }
    
  // Normal query
  queryKeys = Object.keys(query);
  for (i = 0; i < queryKeys.length; i += 1) {
    queryKey = queryKeys[i];
    queryValue = query[queryKey];
  
    if (queryKey[0] === '$') {
      if (!logicalOperators[queryKey]) { throw "Unknown logical operator " + queryKey; }
      if (!logicalOperators[queryKey](obj, queryValue)) { return false; }
    } else {
      if (!matchQueryPart(obj, queryKey, queryValue)) { return false; }
    }
  }

  return true;
}
808019
public static List<Object[]> queryObjectArrays(String sql, Object[] params)
      throws YankSQLException {

    return queryObjectArrays(YankPoolManager.DEFAULT_POOL_NAME, sql, params);
  }
155497
public int count(Pair<T> obj) {
        long index = getIndex(obj);
        int count = counts.get(index);
        count++;
        counts.put(index, count);
        sum++;
        return count;
    }
204390
@Override
    public int score(ODataRequestContext requestContext, QueryResult data) {
        if (data.getType() == QueryResult.ResultType.NOTHING || data.getType() != QueryResult.ResultType.EXCEPTION) {
            return DEFAULT_SCORE;
        }

        if (data.getData() instanceof ODataBatchException) {
            return MAXIMUM_FORMAT_SCORE;
        }

        List<MediaType> accept = requestContext.getRequest().getAccept();
        int batchAcceptScore = scoreByMediaType(accept, MediaType.MULTIPART);
        int contentTypeScore = scoreByContentType(requestContext, MULTIPART);
        int resultScore = max(batchAcceptScore, contentTypeScore);

        return resultScore > 0 ? (resultScore + ERROR_EXTRA_SCORE) : DEFAULT_SCORE;
    }
248360
public static double getValueForRank(int rank,double[] scores){
    double[] copy = new double[scores.length];
    System.arraycopy(scores,0,copy,0,scores.length);
    java.util.Arrays.sort(copy);
    rank = scores.length-rank;
    return copy[rank];
  }
1147642
@Override protected double[] score0(double[] data, double[] preds, double offset, int ntrees) {
    super.score0(data, preds, offset, ntrees);
    if (ntrees >= 1) preds[1] = preds[0] / ntrees;
    preds[0] = normalizePathLength(preds[0]);
    return preds;
  }
687514
private double naiveQueryDense(NumberVector obj, WritableDoubleDataStore scores, HashSetModifiableDBIDs cands) {
    double len = 0.; // Length of query object, for final normalization
    for(int dim = 0, max = obj.getDimensionality(); dim < max; dim++) {
      final double val = obj.doubleValue(dim);
      if(val == 0. || val != val) {
        continue;
      }
      len += val * val;
      // No matching documents in index:
      if(dim >= index.size()) {
        continue;
      }
      ModifiableDoubleDBIDList column = index.get(dim);
      for(DoubleDBIDListIter n = column.iter(); n.valid(); n.advance()) {
        scores.increment(n, n.doubleValue() * val);
        cands.add(n);
      }
    }
    return FastMath.sqrt(len);
  }
1175732
public JavaDoubleRDD scoreExamples(JavaRDD<DataSet> data, boolean includeRegularizationTerms) {
        return scoreExamplesMultiDataSet(data.map(new DataSetToMultiDataSetFn()), includeRegularizationTerms);
    }
916580
public int compareTo(Object obj) {
		LdapRdn that = (LdapRdn) obj;

        if(this.components.size() != that.components.size()) {
            return this.components.size() - that.components.size();
        }

        Set<Map.Entry<String,LdapRdnComponent>> theseEntries = this.components.entrySet();
        for (Map.Entry<String, LdapRdnComponent> oneEntry : theseEntries) {
            LdapRdnComponent thatEntry = that.components.get(oneEntry.getKey());
            if(thatEntry == null) {
                return -1;
            }

            int compared = oneEntry.getValue().compareTo(thatEntry);
            if(compared != 0) {
                return compared;
            }
        }

		return 0;
	}