Return documents near the given point
162001
def near(self, x, y, max_distance=None):
        
        expr = {
            self : {'$near' : [x, y]}
        }
        if max_distance is not None:
            expr[self]['$maxDistance'] = max_distance
        # if bucket_size is not None:
        #     expr['$bucketSize'] = max_distance
        return QueryExpression(expr)
431721
function(db) {

		function get_documents(data, config, plv8, ERROR, WARNING) {

			function get_document(id) {
				return plv8.execute("SELECT * FROM documents WHERE id = $1 LIMIT 1", [id])[0];
			}

			function get_type(id) {
				return plv8.execute("SELECT * FROM types WHERE id = $1 LIMIT 1", [id])[0];
			}

			function error(msg) {
				plv8.elog(ERROR, msg);
			}

			function warn(msg) {
				plv8.elog(WARNING, msg);
			}

			function is_object(a) {
				return a && (typeof a === 'object');
			}

			function is_array(a) {
				return a && (a instanceof Array);
			}

			function is_string(a) {
				return a && (typeof a === 'string');
			}

			function is_uuid(obj) {
				return /^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/.test(obj);
			}

			function get_property_step(last, current) {
				return is_object(last) ? last[current] : undefined;
			}

			/** Get value of property from provided object using a path.
			 * @param obj {object} The object from where to find the value.
			 * @param path {string} The path to the value in object.
			 * @returns {mixed} The value from the object at the end of path or `undefined` if any part is missing.
			 */
			function get_property(obj, path) {
				if(!is_object(obj)) { return error('get_property(obj, ...) not object: '+ obj); }
				if(!is_string(path)) { return error('get_property(..., path) not string: '+ path); }
				return path.split('.').reduce(get_property_step, obj);
			}

			/** Get document by UUID */
			function fetch_object_by_uuid(data, prop, uuid) {
				if(!is_object(data)) { return error('fetch_object_by_uuid(data, ..., ...) not object: '+ data); }
				if(!is_string(prop)) { return error('fetch_object_by_uuid(..., prop, ...) not string: '+ prop); }
				if(!is_uuid(uuid)) { return warn('Property ' + prop + ' was not uuid: ' + uuid); }
				if(data.documents[uuid] === undefined) {
					data.documents[uuid] = get_document(uuid);
				} else {
					return warn('Document already fetched: ' + uuid);
				}
			}

			/* */
			function fetch_object(data, prop) {
				var uuid = get_property(data, prop);
				if(is_array(uuid)) {
					return uuid.forEach(fetch_object_by_uuid.bind(undefined, data, prop));
				}
				return fetch_object_by_uuid(data, prop, uuid);
			}

			// Check for bad input

			if(!is_object(data)) { return error("get_documents(data, ...) not object"); }
			if(!is_array(config)) { return error("get_documents(..., config) not array"); }

			//var types_id = data.types_id;
			//if(!is_uuid(types_id)) { return error("data.types_id not valid UUID: " + types_id); }

			// Get document type
			//var type = get_type(types_id);
			//if(!is_object(type)) { return error("type not valid object: " + type); }

			//var relations = type.relations || {};
			//if(!is_object(relations)) { return error("type.relations not valid object: " + relations); }

			// Populate documents from `config`
			data.documents = {};
			config.forEach( fetch_object.bind(undefined, data) );
			return data.documents;
		}

		return db.query('CREATE OR REPLACE FUNCTION get_documents(data json, config json) RETURNS json LANGUAGE plv8 VOLATILE AS ' + NoPg._escapeFunction(get_documents, ["data", "config", "plv8", "ERROR", "WARNING"]));
	}
668769
def within(self, lat, lon, radius):
		''''''
		return self.filter(filter_helpers.within_(lat, lon, radius))
1316984
def _query_near(*, session=None, **kwargs):
    """"""
    url_endpoint = 'http://calib.org/marine/index.html'
    if session is not None:
        resp = session.get(url_endpoint, params=kwargs)
    else:
        with requests.Session() as s:
            # Need to get the index page before query. Otherwise get bad query response that seems legit.
            s.get('http://calib.org/marine/index.html')
            resp = s.get(url_endpoint, params=kwargs)
    return resp
1173593
def query(options, collection_name, num_to_skip, num_to_return,
          query, field_selector, opts, check_keys=False, ctx=None):
    """"""
    if ctx:
        return _query_compressed(options, collection_name, num_to_skip,
                                 num_to_return, query, field_selector,
                                 opts, check_keys, ctx)
    return _query_uncompressed(options, collection_name, num_to_skip,
                               num_to_return, query, field_selector, opts,
                               check_keys)
300641
def _closest_location(self, location_map, target):
        """"""

        def dist(a, b):
            return math.sqrt(sum((a[k] - b[k]) ** 2 for k in a.keys()))

        paths = iter(location_map.keys())
        closest = next(paths)
        closest_dist = dist(target, location_map[closest])
        for path in paths:
            cur_dist = dist(target, location_map[path])
            if cur_dist < closest_dist:
                closest = path
                closest_dist = cur_dist
        return closest
38042
def _get_documents(self):
        """"""
        documents = self.tree.execute("$.documents")
        for doc in documents:
            sentences = {s['@id']: s['text'] for s in doc.get('sentences', [])}
            self.document_dict[doc['@id']] = {'sentences': sentences,
                                              'location': doc['location']}
587291
function findStoresInRange(location, range, callback) {
  db.collection(stores, function(err, collection) {
    if(err) return callback(err);

    var query = {loc: {$geoWithin: {$centerSphere:
        [[location.lng, location.lat] , range / 3959]}}} ;

    collection.find(query).toArray(function(err, docs) {
      if (err) return callback(err);
      callback(null, docs);
    });
  });
}
759985
function parseEndpoints(document) {
  const defaultParent = WORKSPACE_ID;

  const paths = Object.keys(document.paths);
  const endpointsSchemas = paths
    .map(path => {
      const schemasPerMethod = document.paths[path];
      const methods = Object.keys(schemasPerMethod);

      return methods
        .filter(method => method !== 'parameters')
        .map(method => Object.assign({}, schemasPerMethod[method], { path, method }));
    })
    .reduce((flat, arr) => flat.concat(arr), []); //flat single array

  const tags = document.tags || [];
  const folders = tags.map(tag => {
    return importFolderItem(tag, defaultParent);
  });
  const folderLookup = {};
  folders.forEach(folder => (folderLookup[folder.name] = folder._id));

  const requests = [];
  endpointsSchemas.map(endpointSchema => {
    let { tags } = endpointSchema;
    if (!tags || tags.length == 0) tags = [''];
    tags.forEach((tag, index) => {
      let id = endpointSchema.operationId
        ? `${endpointSchema.operationId}${index > 0 ? index : ''}`
        : `__REQUEST_${requestCount++}__`;
      let parentId = folderLookup[tag] || defaultParent;
      requests.push(importRequest(endpointSchema, id, parentId));
    });
  });

  return [...folders, ...requests];
}
560376
def _get_more(collection_name, num_to_return, cursor_id):
    """"""
    return b"".join([
        _ZERO_32,
        _make_c_string(collection_name),
        _pack_int(num_to_return),
        _pack_long_long(cursor_id)])
1349348
def documents(cls, filter=None, **kwargs):
        
        documents = [cls(document) for document in cls.find(filter, **kwargs)]
        return [document for document in documents if document.document]
718199
function findContext(doc, data) {
    var before = data.context.slice(0, data.contextOffset).split("\n");
    var startLine = data.start.line - (before.length - 1);
    var start = Pos(startLine, (before.length == 1 ? data.start.ch : doc.getLine(startLine).length) - before[0].length);

    var text = doc.getLine(startLine).slice(start.ch);
    for (var cur = startLine + 1; cur < doc.lineCount() && text.length < data.context.length; ++cur)
      text += "\n" + doc.getLine(cur);
    if (text.slice(0, data.context.length) == data.context) return data;

    var cursor = doc.getSearchCursor(data.context, 0, false);
    var nearest, nearestDist = Infinity;
    while (cursor.findNext()) {
      var from = cursor.from(), dist = Math.abs(from.line - start.line) * 10000;
      if (!dist) dist = Math.abs(from.ch - start.ch);
      if (dist < nearestDist) { nearest = from; nearestDist = dist; }
    }
    if (!nearest) return null;

    if (before.length == 1)
      nearest.ch += before[0].length;
    else
      nearest = Pos(nearest.line + (before.length - 1), before[before.length - 1].length);
    if (data.start.line == data.end.line)
      var end = Pos(nearest.line, nearest.ch + (data.end.ch - data.start.ch));
    else
      var end = Pos(nearest.line + (data.end.line - data.start.line), data.end.ch);
    return {start: nearest, end: end};
  }
1079045
def many(cls, filter=None, **kwargs):
        """"""
        from mongoframes.queries import Condition, Group, to_refs

        # Flatten the projection
        kwargs['projection'], references, subs = \
                cls._flatten_projection(
                    kwargs.get('projection', cls._default_projection)
                    )

        # Find the documents
        if isinstance(filter, (Condition, Group)):
            filter = filter.to_dict()

        documents = list(cls.get_collection().find(to_refs(filter), **kwargs))

        # Dereference the documents (if required)
        if references:
            cls._dereference(documents, references)

        # Add sub-frames to the documents (if required)
        if subs:
            cls._apply_sub_frames(documents, subs)

        return [cls(d) for d in documents]
144067
def _points_within_distance(self, pnt1, pnt2):
        """"""
        if self._get_distance(pnt1, pnt2) <= self.distance:
            return True
        return False
437973
def near_to_position(self, position, max_distance):
        ''''''
        end = self.ref_end_pos()
        return self.POS <= position <= end or abs(position - self.POS) <= max_distance or abs(position - end) <= max_distance
442479
def nearestPoint(self, pos):
        
        # lookup subpaths
        for x, y, path in self._subpaths:
            if path.contains(pos):
                return (x, y)
        
        return (None, None)
396258
def ApproximateDistanceBetweenStops(stop1, stop2):
  """"""
  if (stop1.stop_lat is None or stop1.stop_lon is None or
      stop2.stop_lat is None or stop2.stop_lon is None):
    return None
  return ApproximateDistance(stop1.stop_lat, stop1.stop_lon,
                             stop2.stop_lat, stop2.stop_lon)