Compute the most related pks to an object's pk.
420018
def compute_related(self, object_id, score=pearson_score):
        
        dataset = self.dataset
        object_vector = dataset.get(object_id)
        if not object_vector:
            return []

        object_related = {}
        for o_id, o_vector in dataset.items():
            if o_id != object_id:
                try:
                    object_related[o_id] = score(object_vector, o_vector)
                except ZeroDivisionError:
                    pass
        related = sorted(object_related.items(),
                         key=lambda k_v: (k_v[1], k_v[0]), reverse=True)
        return related
612971
def get_corresponding_chains(self, from_pdb_id, from_chain_id, to_pdb_id):
        ''''''
        chains = self.chain_map.get(from_pdb_id, {}).get(from_chain_id, {}).get(to_pdb_id, [])
        return sorted(chains)
1005206
def get_pks_for_filter(self, key, filter_type, value):
        
        start, end, __ = self.get_boundaries(filter_type, value)  # we have nothing to exclude
        return self.connection.zrangebyscore(key, start, end)
759231
def user_default_loader(self, pk):
        """"""
        try:
            obj = User.objects.get(pk=pk)
        except User.DoesNotExist:
            return None
        else:
            self.user_default_add_related_pks(obj)
            return obj
54497
def get_pk_descriptors(cls):
    """"""
    pk_fields = {
        name: descriptor
        for name, descriptor in vars_class(cls).items()
        if isinstance(descriptor, ObjectField) and is_pk_descriptor(descriptor)
    }
    alt_pk_fields = defaultdict(list)
    for name, descriptor in vars_class(cls).items():
        if isinstance(descriptor, ObjectField):
            if descriptor.alt_pk is True:
                alt_pk_fields[0].append((name, descriptor))
            elif type(descriptor.alt_pk) is int:
                alt_pk_fields[descriptor.alt_pk].append((name, descriptor))
    if len(pk_fields) == 1:
        return ((pk_fields.popitem(),), (alt_pk_fields[0],))
    elif len(pk_fields) > 1:
        unique_pk_fields = {
            name: descriptor
            for name, descriptor in pk_fields.items()
            if descriptor.pk is True
        }
        if unique_pk_fields:
            raise AttributeError(
                "more than one field is marked as unique primary key: %s" % (
                    ', '.join(sorted(pk_fields))))
        pk_descriptors = tuple(sorted((
            (name, descriptor)
            for name, descriptor in pk_fields.items()
        ), key=lambda item: item[1].pk))
        alt_pk_descriptors = tuple(
            alt_pk_fields[idx]
            for idx, (name, descriptor) in enumerate(pk_descriptors)
        )
        return pk_descriptors, alt_pk_descriptors
    else:
        return tuple(), tuple()
985812
def get_pks_for_filter(self, key, filter_type, value):
        
        start, end, exclude = self.get_boundaries(filter_type, value)
        members = self.connection.zrangebylex(key, start, end)
        if exclude is not None:
            # special case where we don't want the exact given value, but we cannot
            # exclude it from the sorted set directly
            return [
                member_pk
                for member_value, member_pk in
                [self._extract_value_from_storage(member) for member in members]
                if member_value != exclude
            ]
        else:
            return [self._extract_value_from_storage(member)[-1] for member in members]
468020
def get_pks_from_query(self, query):
        """"""
        where = query.where
        sql = None
        if where.connector == 'AND' and not where.negated and len(where.children) == 1:
            # simple cases are optimized, especially because a suboptimal
            # nested query based on the same table is not allowed by SF
            child = where.children[0]
            if (child.lookup_name in ('exact', 'in') and child.lhs.target.column == 'Id'
                    and not child.bilateral_transforms and child.lhs.target.model is self.query.model):
                pks = child.rhs
                if child.lookup_name == 'exact':
                    assert isinstance(pks, text_type)
                    return [pks]
                # lookup_name 'in'
                assert not child.bilateral_transforms
                if isinstance(pks, (tuple, list)):
                    return pks
                if DJANGO_111_PLUS:
                    assert isinstance(pks, Query) and type(pks).__name__ == 'SalesforceQuery'
                    # # alternative solution:
                    # return list(salesforce.backend.query.SalesforceQuerySet(pk.model, query=pk, using=pk._db))

                    sql, params = pks.get_compiler('salesforce').as_sql()
                else:
                    assert isinstance(pks, salesforce.backend.query.SalesforceQuerySet)
                    return [x.pk for x in pks]
        if not sql:
            # a subquery is necessary in this case
            where_sql, params = where.as_sql(query.get_compiler('salesforce'), self.db.connection)
            sql = "SELECT Id FROM {} WHERE {}".format(query.model._meta.db_table, where_sql)
        with self.db.cursor() as cur:
            cur.execute(sql, params)
            assert len(cur.description) == 1 and cur.description[0][0] == 'Id'
            return [x[0] for x in cur]
234631
def get_keys(self, lst):
        
        pk_name = self.get_pk_name()
        if self.is_pk_composite():
            return [[getattr(item, pk) for pk in pk_name] for item in lst]
        else:
            return [getattr(item, pk_name) for item in lst]
733960
def keys(self, key=None, reverse=False):
        """"""
        ks = sorted(list(dict.keys(self)), key=key, reverse=reverse)
        return ks
664623
protected void computePDists(Relation<O> relation, KNNQuery<O> knn, WritableDoubleDataStore pdists) {
    // computing PRDs
    FiniteProgress prdsProgress = LOG.isVerbose() ? new FiniteProgress("pdists", relation.size(), LOG) : null;
    for(DBIDIter iditer = relation.iterDBIDs(); iditer.valid(); iditer.advance()) {
      final KNNList neighbors = knn.getKNNForDBID(iditer, kreach + 1); // +
                                                                       // query
                                                                       // point
      // use first kref neighbors as reference set
      int ks = 0;
      double ssum = 0.;
      for(DoubleDBIDListIter neighbor = neighbors.iter(); neighbor.valid() && ks < kreach; neighbor.advance()) {
        if(DBIDUtil.equal(neighbor, iditer)) {
          continue;
        }
        final double d = neighbor.doubleValue();
        ssum += d * d;
        ks++;
      }
      double pdist = ks > 0 ? FastMath.sqrt(ssum / ks) : 0.;
      pdists.putDouble(iditer, pdist);
      LOG.incrementProcessed(prdsProgress);
    }
    LOG.ensureCompleted(prdsProgress);
  }
222761
def get_pks(self, field_vals):
        """"""
        field_name = self.schema.pk.name
        return self.in_field(field_name, field_vals).get()
872629
def _most_common(iterable):
    """"""
    data = Counter(iterable)
    return max(data, key=data.__getitem__)
901952
def connected_objects(self, from_obj):
        
        return self.to_content_type.get_all_objects_for_this_type(pk__in=self.connected_object_ids(from_obj))
1075187
def _getobjs_higher(self, idobj):
        """"""
        idobjs_higher = set(idobj.parents)
        for reltyp, relidobjs in idobj.relationship.items():
            if self.relationships is True or reltyp in self.relationships:
                idobjs_higher.update(relidobjs)
        return idobjs_higher
48538
def sortkey(x):
    """"""
    k = str(x[1]).zfill(3) + str(x[2]).zfill(3) + str(x[3]).zfill(3)
    return k
320026
def _pk(self, obj):
        
        pk_values = tuple(getattr(obj, c.name)
                          for c in obj.__mapper__.primary_key)
        if len(pk_values) == 1:
            return pk_values[0]
        return pk_values
786990
def _sorted_keys_items(dobj):
    """"""
    keys = sorted(dobj.keys())
    for key in keys:
        yield key, dobj[key]