Adapted from the Mongo docs::

                session.query(Places).filter(Places.loc.within_radius_sphere(1, 2, 50)
764659
def within_radius_sphere(self, x, y, radius):
        
        return QueryExpression({
            self : {'$within' : {
                    '$centerSphere' : [[x, y], radius],
                }}
            })
479480
def nearbys(radius = 20, options = {})
      return nil unless geocoded?
      options.merge!(:exclude => self) unless send(self.class.primary_key).nil?
      self.class.near(self, radius, options)
    end
1288008
def count(self, filter, **kwargs):
        
        return mongo_count(self._collection, filter=filter, **kwargs)
1339836
function queryFilter(where) {
  if (where.$or) {
    return object =>
      _.reduce(where.$or, (result, subclause) => result ||
        queryFilter(subclause)(object), false);
  }

  // Go through each key in where clause
  return object => _.reduce(where, (result, whereParams, key) => {
    const match = evaluateObject(object, whereParams, key);
    return result && match;
  }, true);
}
638463
final List<Map.Entry<K, Float>> queryNearest(String query, int size)
    {
        if (query == null || query.length() == 0)
        {
            return Collections.emptyList();
        }
        try
        {
            return nearest(query(query), size);
        }
        catch (Exception e)
        {
            return Collections.emptyList();
        }
    }
973303
def _filter(self, environ, params):
        

        # Search for required query arguments
        if self.queries:
            # No query string available
            if 'QUERY_STRING' not in environ:
                return False

            # Extract the list of provided query arguments from the
            # QUERY_STRING
            available = set(qstr.partition('=')[0] for qstr in
                            environ['QUERY_STRING'].split('&'))

            # Check if we have the required query arguments
            required = set(self.queries)
            if not required.issubset(available):
                return False

        # Use only the parameters listed in use; we'll add the others
        # back later
        unused = {}
        for key, value in params.items():
            if key not in self.use:
                unused[key] = value

        # Do this in a separate step so we avoid changing a
        # dictionary during traversal
        for key in unused:
            del params[key]

        # First, we need to set up any additional params required to
        # get the bucket.  If the DeferLimit exception is thrown, no
        # further processing is performed.
        try:
            additional = self.filter(environ, params, unused) or {}
        except DeferLimit:
            return False

        # Compute the bucket key
        key = self.key(params)

        # Update the parameters...
        params.update(unused)
        params.update(additional)

        # Get the current time
        now = time.time()

        # Allow up to a minute to mutate the bucket record.  If no
        # bucket exists currently, this is essentially a no-op, and
        # the bucket won't expire anyway, once the update record is
        # pushed.
        self.db.expire(key, 60)

        # Push an update record
        update_uuid = str(uuid.uuid4())
        update = {
            'uuid': update_uuid,
            'update': {
                'params': params,
                'time': now,
            },
        }
        self.db.rpush(key, msgpack.dumps(update))

        # Now suck in the bucket
        records = self.db.lrange(key, 0, -1)
        loader = BucketLoader(self.bucket_class, self.db, self, key, records)

        # Determine if we should initialize the compactor algorithm on
        # this bucket
        if 'turnstile.conf' in environ:
            config = environ['turnstile.conf']['compactor']
            try:
                max_updates = int(config['max_updates'])
            except (KeyError, ValueError):
                max_updates = None
            try:
                max_age = int(config['max_age'])
            except (KeyError, ValueError):
                max_age = 600
            if max_updates and loader.need_summary(now, max_updates, max_age):
                # Add a summary record; we want to do this before
                # instructing the compactor to compact.  If we did the
                # compactor instruction first, and a crash occurred
                # before adding the summarize record, the lack of
                # quiesence could cause two compactor threads to run
                # on the same bucket, leading to a race condition that
                # could corrupt the bucket.  With this ordering, if a
                # crash occurs before the compactor instruction, the
                # maximum aging applied to summarize records will
                # cause this logic to eventually be retriggered, which
                # should allow the compactor instruction to be issued.
                summarize = dict(summarize=now, uuid=str(uuid.uuid4()))
                self.db.rpush(key, msgpack.dumps(summarize))

                # Instruct the compactor to compact this record
                compactor_key = config.get('compactor_key', 'compactor')
                self.db.zadd(compactor_key, int(math.ceil(now)), key)

        # Set the expire on the bucket
        self.db.expireat(key, loader.bucket.expire)

        # If we found a delay, store the particulars in the
        # environment; this will later be sorted and an error message
        # corresponding to the longest delay returned.
        if loader.delay is not None:
            environ.setdefault('turnstile.delay', [])
            environ['turnstile.delay'].append((loader.delay, self,
                                               loader.bucket))

        # Finally, if desired, add the bucket key to a desired
        # database set
        set_name = environ.get('turnstile.bucket_set')
        if set_name:
            self.db.zadd(set_name, loader.bucket.expire, key)

        # Should we continue the route scan?
        return not self.continue_scan
98846
def _query(self, request, filter=None):
        
        limit = None
        offset = None
        if 'maxfeatures' in request.params:
            limit = int(request.params['maxfeatures'])
        if 'limit' in request.params:
            limit = int(request.params['limit'])
        if 'offset' in request.params:
            offset = int(request.params['offset'])
        if filter is None:
            filter = create_filter(request, self.mapped_class, self.geom_attr)
        query = self.Session().query(self.mapped_class)
        if filter is not None:
            query = query.filter(filter)
        order_by = self._get_order_by(request)
        if order_by is not None:
            query = query.order_by(order_by)
        query = query.limit(limit).offset(offset)
        return query.all()
1680
def filter_by(self, **kwargs):
        
        query = self._copy()
        for field, value in kwargs.items():
            query.domain.append(
                (field, '=', value)
            )
        return query
815248
def in_adjacent(filter=nil, &block)
      r = self.collect {|v| v.in_adjacent(filter, &block) }
      VertexSet.new(r).flatten.uniq
    end
1211811
def find(self, start, end, limit=50, *args, **kwargs):
        
        # check if spec has been specified, build on top of it
        fc = kwargs.get('spec', dict())

        # filter _id on start and end dates
        fc['_id'] = {'$gte': ObjectId.from_datetime(start),
                     '$lte': ObjectId.from_datetime(end)}

        if not self.collection:
            collection_name = kwargs.get('collection_name',
                             MONGODB_DEFAULT_COLLECTION)
            self.set_collection(collection_name)

        return self.collection.find(fc, limit=limit)
548541
def near(self, key, point):
        
        if point is None:
            raise ValueError('near query does not accept None')

        self._add_condition(key, '$nearSphere', point)
        return self
640271
public Result<FindLocalNeighbourhoodResult> findLocalNeighbourhood(long startRef, float[] centerPos, float radius,
            QueryFilter filter) {

        // Validate input
        if (!m_nav.isValidPolyRef(startRef) || Objects.isNull(centerPos) || !vIsFinite(centerPos) || radius < 0
                || !Float.isFinite(radius) || Objects.isNull(filter)) {
            return Result.invalidParam();
        }

        List<Long> resultRef = new ArrayList<>();
        List<Long> resultParent = new ArrayList<>();

        m_tinyNodePool.clear();

        Node startNode = m_tinyNodePool.getNode(startRef);
        startNode.pidx = 0;
        startNode.id = startRef;
        startNode.flags = Node.DT_NODE_CLOSED;
        LinkedList<Node> stack = new LinkedList<>();
        stack.add(startNode);

        resultRef.add(startNode.id);
        resultParent.add(0L);

        float radiusSqr = sqr(radius);

        float[] pa = new float[m_nav.getMaxVertsPerPoly() * 3];
        float[] pb = new float[m_nav.getMaxVertsPerPoly() * 3];

        while (!stack.isEmpty()) {
            // Pop front.
            Node curNode = stack.pop();

            // Get poly and tile.
            // The API input has been cheked already, skip checking internal data.
            long curRef = curNode.id;
            Tupple2<MeshTile, Poly> tileAndPoly = m_nav.getTileAndPolyByRefUnsafe(curRef);
            MeshTile curTile = tileAndPoly.first;
            Poly curPoly = tileAndPoly.second;

            for (int i = curPoly.firstLink; i != NavMesh.DT_NULL_LINK; i = curTile.links.get(i).next) {
                Link link = curTile.links.get(i);
                long neighbourRef = link.ref;
                // Skip invalid neighbours.
                if (neighbourRef == 0) {
                    continue;
                }

                Node neighbourNode = m_tinyNodePool.getNode(neighbourRef);
                // Skip visited.
                if ((neighbourNode.flags & Node.DT_NODE_CLOSED) != 0) {
                    continue;
                }

                // Expand to neighbour
                tileAndPoly = m_nav.getTileAndPolyByRefUnsafe(neighbourRef);
                MeshTile neighbourTile = tileAndPoly.first;
                Poly neighbourPoly = tileAndPoly.second;

                // Skip off-mesh connections.
                if (neighbourPoly.getType() == Poly.DT_POLYTYPE_OFFMESH_CONNECTION) {
                    continue;
                }

                // Do not advance if the polygon is excluded by the filter.
                if (!filter.passFilter(neighbourRef, neighbourTile, neighbourPoly)) {
                    continue;
                }

                // Find edge and calc distance to the edge.
                Result<PortalResult> pp = getPortalPoints(curRef, curPoly, curTile, neighbourRef, neighbourPoly,
                        neighbourTile, 0, 0);
                if (pp.failed()) {
                    continue;
                }
                float[] va = pp.result.left;
                float[] vb = pp.result.right;

                // If the circle is not touching the next polygon, skip it.
                Tupple2<Float, Float> distseg = distancePtSegSqr2D(centerPos, va, vb);
                float distSqr = distseg.first;
                if (distSqr > radiusSqr) {
                    continue;
                }

                // Mark node visited, this is done before the overlap test so that
                // we will not visit the poly again if the test fails.
                neighbourNode.flags |= Node.DT_NODE_CLOSED;
                neighbourNode.pidx = m_tinyNodePool.getNodeIdx(curNode);

                // Check that the polygon does not collide with existing polygons.

                // Collect vertices of the neighbour poly.
                int npa = neighbourPoly.vertCount;
                for (int k = 0; k < npa; ++k) {
                    System.arraycopy(neighbourTile.data.verts, neighbourPoly.verts[k] * 3, pa, k * 3, 3);
                }

                boolean overlap = false;
                for (int j = 0; j < resultRef.size(); ++j) {
                    long pastRef = resultRef.get(j);

                    // Connected polys do not overlap.
                    boolean connected = false;
                    for (int k = curPoly.firstLink; k != NavMesh.DT_NULL_LINK; k = curTile.links.get(k).next) {
                        if (curTile.links.get(k).ref == pastRef) {
                            connected = true;
                            break;
                        }
                    }
                    if (connected) {
                        continue;
                    }

                    // Potentially overlapping.
                    tileAndPoly = m_nav.getTileAndPolyByRefUnsafe(pastRef);
                    MeshTile pastTile = tileAndPoly.first;
                    Poly pastPoly = tileAndPoly.second;

                    // Get vertices and test overlap
                    int npb = pastPoly.vertCount;
                    for (int k = 0; k < npb; ++k) {
                        System.arraycopy(pastTile.data.verts, pastPoly.verts[k] * 3, pb, k * 3, 3);
                    }

                    if (overlapPolyPoly2D(pa, npa, pb, npb)) {
                        overlap = true;
                        break;
                    }
                }
                if (overlap) {
                    continue;
                }

                resultRef.add(neighbourRef);
                resultParent.add(curRef);
                stack.add(neighbourNode);
            }
        }

        return Result.success(new FindLocalNeighbourhoodResult(resultRef, resultParent));
    }
827249
@Override
    public IDocumentQuery<T> withinRadiusOf(String fieldName, double radius, double latitude, double longitude) {
        return withinRadiusOf(fieldName, radius, latitude, longitude, null, Constants.Documents.Indexing.Spatial.DEFAULT_DISTANCE_ERROR_PCT);
    }
324931
def _friends_leaveoneout_radius(points, ftype):
    """"""

    # Construct KDTree to enable quick nearest-neighbor lookup for
    # our resampled objects.
    kdtree = spatial.KDTree(points)

    if ftype == 'balls':
        # Compute radius to two nearest neighbors (self + neighbor).
        dists, ids = kdtree.query(points, k=2, eps=0, p=2)
    elif ftype == 'cubes':
        # Compute half-side-length to two nearest neighbors (self + neighbor).
        dists, ids = kdtree.query(points, k=2, eps=0, p=np.inf)

    dist = dists[:, 1]  # distances to LOO nearest neighbor

    return dist
783886
def _convert_query(self, query):
        
        query = self.dictionary.doc2bow(self._tokenize_latex(query))
        sims = self.index[query]
        neighbors = sorted(sims, key=lambda item: -item[1])
        neighbors = {"neighbors":[{self.columns[0]: {"data": self.docs[n[0]], "fmt": "math"}, self.columns[1]: {"data": float(n[1])}} for n in neighbors]} if neighbors else {"neighbors": []}
        return neighbors
258636
def query(self, query, interpolations=None):
        
        return self._client.ts_query(self, query, interpolations)
561962
def find_near(lat, lon, *, n=10, session=None):
    """"""
    search_params = {'npoints': n, 'clat': lat, 'clon': lon, 
                     'Columns[]': ['Subregion', 'Notes', 'CollectionYear', 
                                   'ReservoirAge', 'ReservoirErr', 'C14age', 
                                   'C14err', 'LabID', 'Delta13C', 'nextime', 
                                   'Genus', 'Species', 'Feeding', 'Name']}
    resp = _query_near(session=session, **search_params)
    df = _response_to_dataframe(resp)
    df_clean = _clean_dataframe(df)
    return df_clean