Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def _get_footer_size(file_obj): file_obj.seek(-8, 2) tup = struct.unpack(b"<i", file_obj.read(4)) return tup[0]
[ "Read the footer size in bytes, which is serialized as little endian." ]
Please provide a description of the function:def _read_footer(file_obj): footer_size = _get_footer_size(file_obj) if logger.isEnabledFor(logging.DEBUG): logger.debug("Footer size in bytes: %s", footer_size) file_obj.seek(-(8 + footer_size), 2) # seek to beginning of footer tin = TFileTrans...
[ "Read the footer from the given file object and returns a FileMetaData object.\n\n This method assumes that the fo references a valid parquet file.\n " ]
Please provide a description of the function:def _read_page_header(file_obj): tin = TFileTransport(file_obj) pin = TCompactProtocolFactory().get_protocol(tin) page_header = parquet_thrift.PageHeader() page_header.read(pin) return page_header
[ "Read the page_header from the given fo." ]
Please provide a description of the function:def read_footer(filename): with open(filename, 'rb') as file_obj: if not _check_header_magic_bytes(file_obj) or \ not _check_footer_magic_bytes(file_obj): raise ParquetFormatException("{0} is not a valid parquet file " ...
[ "Read the footer and return the FileMetaData for the specified filename." ]
Please provide a description of the function:def _get_offset(cmd): dict_offset = cmd.dictionary_page_offset data_offset = cmd.data_page_offset if dict_offset is None or data_offset < dict_offset: return data_offset return dict_offset
[ "Return the offset into the cmd based upon if it's a dictionary page or a data page." ]
Please provide a description of the function:def dump_metadata(filename, show_row_group_metadata, out=sys.stdout): def println(value): out.write(value + "\n") footer = read_footer(filename) println("File Metadata: {0}".format(filename)) println(" Version: {0}".format(footer.versio...
[ "Dump metadata about the parquet object with the given filename.\n\n Dump human-readable metadata to specified `out`. Optionally dump the row group metadata as well.\n ", "Write a new line containing `value` to `out`." ]
Please provide a description of the function:def _read_page(file_obj, page_header, column_metadata): bytes_from_file = file_obj.read(page_header.compressed_page_size) codec = column_metadata.codec if codec is not None and codec != parquet_thrift.CompressionCodec.UNCOMPRESSED: if column_metadata...
[ "Read the data page from the given file-object and convert it to raw, uncompressed bytes (if necessary)." ]
Please provide a description of the function:def _read_data(file_obj, fo_encoding, value_count, bit_width): vals = [] if fo_encoding == parquet_thrift.Encoding.RLE: seen = 0 while seen < value_count: values = encoding.read_rle_bit_packed_hybrid(file_obj, bit_width) i...
[ "Read data from the file-object using the given encoding.\n\n The data could be definition levels, repetition levels, or actual values.\n " ]
Please provide a description of the function:def read_data_page(file_obj, schema_helper, page_header, column_metadata, dictionary): daph = page_header.data_page_header raw_bytes = _read_page(file_obj, page_header, column_metadata) io_obj = io.BytesIO(raw_bytes) vals = [] debu...
[ "Read the data page from the given file-like object based upon the parameters.\n\n Metadata in the the schema_helper, page_header, column_metadata, and (optional) dictionary\n are used for parsing data.\n\n Returns a list of values.\n " ]
Please provide a description of the function:def _read_dictionary_page(file_obj, schema_helper, page_header, column_metadata): raw_bytes = _read_page(file_obj, page_header, column_metadata) io_obj = io.BytesIO(raw_bytes) values = encoding.read_plain( io_obj, column_metadata.type, ...
[ "Read a page containing dictionary data.\n\n Consumes data using the plain encoding and returns an array of values.\n " ]
Please provide a description of the function:def DictReader(file_obj, columns=None): # pylint: disable=invalid-name footer = _read_footer(file_obj) keys = columns if columns else [s.name for s in footer.schema if s.type] for row in reader(file_obj, columns): ...
[ "\n Reader for a parquet file object.\n\n This function is a generator returning an OrderedDict for each row\n of data in the parquet file. Nested values will be flattend into the\n top-level dict and can be referenced with '.' notation (e.g. 'foo' -> 'bar'\n is referenced as 'foo.bar')\n\n :param...
Please provide a description of the function:def reader(file_obj, columns=None): if hasattr(file_obj, 'mode') and 'b' not in file_obj.mode: logger.error("parquet.reader requires the fileobj to be opened in binary mode!") footer = _read_footer(file_obj) schema_helper = schema.SchemaHelper(footer...
[ "\n Reader for a parquet file object.\n\n This function is a generator returning a list of values for each row\n of data in the parquet file.\n\n :param file_obj: the file containing parquet data\n :param columns: the columns to include. If None (default), all columns\n are include...
Please provide a description of the function:def _dump(file_obj, options, out=sys.stdout): # writer and keys are lazily loaded. We don't know the keys until we have # the first item. And we need the keys for the csv writer. total_count = 0 writer = None keys = None for row in DictReader(fil...
[ "Dump to fo with given options." ]
Please provide a description of the function:def dump(filename, options, out=sys.stdout): with open(filename, 'rb') as file_obj: return _dump(file_obj, options=options, out=out)
[ "Dump parquet file with given filename using options to `out`." ]
Please provide a description of the function:def writerow(self, row): json_text = json.dumps(row) if isinstance(json_text, bytes): json_text = json_text.decode('utf-8') self._out.write(json_text) self._out.write(u'\n')
[ "Write a single row." ]
Please provide a description of the function:def read_plain_boolean(file_obj, count): # for bit packed, the count is stored shifted up. But we want to pass in a count, # so we shift up. # bit width is 1 for a single-bit boolean. return read_bitpacked(file_obj, count << 1, 1, logger.isEnabledFor(log...
[ "Read `count` booleans using the plain encoding." ]
Please provide a description of the function:def read_plain_int32(file_obj, count): length = 4 * count data = file_obj.read(length) if len(data) != length: raise EOFError("Expected {} bytes but got {} bytes".format(length, len(data))) res = struct.unpack("<{}i".format(count).encode("utf-8")...
[ "Read `count` 32-bit ints using the plain encoding." ]
Please provide a description of the function:def read_plain_int64(file_obj, count): return struct.unpack("<{}q".format(count).encode("utf-8"), file_obj.read(8 * count))
[ "Read `count` 64-bit ints using the plain encoding." ]
Please provide a description of the function:def read_plain_int96(file_obj, count): items = struct.unpack(b"<" + b"qi" * count, file_obj.read(12 * count)) return [q << 32 | i for (q, i) in zip(items[0::2], items[1::2])]
[ "Read `count` 96-bit ints using the plain encoding." ]
Please provide a description of the function:def read_plain_float(file_obj, count): return struct.unpack("<{}f".format(count).encode("utf-8"), file_obj.read(4 * count))
[ "Read `count` 32-bit floats using the plain encoding." ]
Please provide a description of the function:def read_plain_double(file_obj, count): return struct.unpack("<{}d".format(count).encode("utf-8"), file_obj.read(8 * count))
[ "Read `count` 64-bit float (double) using the plain encoding." ]
Please provide a description of the function:def read_plain_byte_array(file_obj, count): return [file_obj.read(struct.unpack(b"<i", file_obj.read(4))[0]) for i in range(count)]
[ "Read `count` byte arrays using the plain encoding." ]
Please provide a description of the function:def read_plain(file_obj, type_, count): if count == 0: return [] conv = DECODE_PLAIN[type_] return conv(file_obj, count)
[ "Read `count` items `type` from the fo using the plain encoding." ]
Please provide a description of the function:def read_unsigned_var_int(file_obj): result = 0 shift = 0 while True: byte = struct.unpack(b"<B", file_obj.read(1))[0] result |= ((byte & 0x7F) << shift) if (byte & 0x80) == 0: break shift += 7 return result
[ "Read a value using the unsigned, variable int encoding." ]
Please provide a description of the function:def read_rle(file_obj, header, bit_width, debug_logging): count = header >> 1 zero_data = b"\x00\x00\x00\x00" width = (bit_width + 7) // 8 data = file_obj.read(width) data = data + zero_data[len(data):] value = struct.unpack(b"<i", data)[0] i...
[ "Read a run-length encoded run from the given fo with the given header and bit_width.\n\n The count is determined from the header and the width is used to grab the\n value that's repeated. Yields the value repeated count times.\n " ]
Please provide a description of the function:def read_bitpacked(file_obj, header, width, debug_logging): num_groups = header >> 1 count = num_groups * 8 byte_count = (width * count) // 8 if debug_logging: logger.debug("Reading a bit-packed run with: %s groups, count %s, bytes %s", ...
[ "Read a bitpacked run of the rle/bitpack hybrid.\n\n Supports width >8 (crossing bytes).\n " ]
Please provide a description of the function:def read_bitpacked_deprecated(file_obj, byte_count, count, width, debug_logging): raw_bytes = array.array(ARRAY_BYTE_STR, file_obj.read(byte_count)).tolist() mask = _mask_for_bits(width) index = 0 res = [] word = 0 bits_in_word = 0 while len...
[ "Read `count` values from `fo` using the deprecated bitpacking encoding." ]
Please provide a description of the function:def read_rle_bit_packed_hybrid(file_obj, width, length=None): debug_logging = logger.isEnabledFor(logging.DEBUG) io_obj = file_obj if length is None: length = read_plain_int32(file_obj, 1)[0] raw_bytes = file_obj.read(length) if raw_b...
[ "Read values from `fo` using the rel/bit-packed hybrid encoding.\n\n If length is not specified, then a 32-bit int is read first to grab the\n length of the encoded data.\n " ]
Please provide a description of the function:def _convert_unsigned(data, fmt): num = len(data) return struct.unpack( "{}{}".format(num, fmt.upper()).encode("utf-8"), struct.pack("{}{}".format(num, fmt).encode("utf-8"), *data) )
[ "Convert data from signed to unsigned in bulk." ]
Please provide a description of the function:def convert_column(data, schemae): ctype = schemae.converted_type if ctype == parquet_thrift.ConvertedType.DECIMAL: scale_factor = Decimal("10e-{}".format(schemae.scale)) if schemae.type == parquet_thrift.Type.INT32 or schemae.type == parquet_thr...
[ "Convert known types from primitive to rich." ]
Please provide a description of the function:def setup_logging(options=None): level = logging.DEBUG if options is not None and options.debug \ else logging.WARNING console = logging.StreamHandler() console.setLevel(level) formatter = logging.Formatter('%(name)s: %(levelname)-8s %(message)s'...
[ "Configure logging based on options." ]
Please provide a description of the function:def main(argv=None): argv = argv or sys.argv[1:] parser = argparse.ArgumentParser('parquet', description='Read parquet files') parser.add_argument('--metadata', action='store_true', help='show met...
[ "Run parquet utility application." ]
Please provide a description of the function:def is_required(self, name): return self.schema_element(name).repetition_type == parquet_thrift.FieldRepetitionType.REQUIRED
[ "Return true iff the schema element with the given name is required." ]
Please provide a description of the function:def max_repetition_level(self, path): max_level = 0 for part in path: element = self.schema_element(part) if element.repetition_type == parquet_thrift.FieldRepetitionType.REQUIRED: max_level += 1 return...
[ "Get the max repetition level for the given schema path." ]
Please provide a description of the function:def optional_assignment_tag(func=None, takes_context=None, name=None): def dec(func): params, varargs, varkw, defaults = getargspec(func) class AssignmentNode(TagHelperNode): def __init__(self, takes_context, args, kwargs, target_var=Non...
[ "\n https://groups.google.com/forum/?fromgroups=#!topic/django-developers/E0XWFrkRMGc\n new template tags type\n " ]
Please provide a description of the function:def do_fake( formatter, *args, **kwargs ): return Faker.getGenerator().format( formatter, *args, **kwargs )
[ "\n call a faker format\n uses:\n\n {% fake \"formatterName\" *args **kwargs as myvar %}\n {{ myvar }}\n\n or:\n {% fake 'name' %}\n\n " ]
Please provide a description of the function:def do_fake_filter( formatter, arg=None ): args = [] if not arg is None: args.append(arg) return Faker.getGenerator().format( formatter, *args )
[ "\n call a faker format\n uses:\n\n {{ 'randomElement'|fake:mylist }}\n {% if 'boolean'|fake:30 %} .. {% endif %}\n {% for word in 'words'|fake:times %}{{ word }}\\n{% endfor %}\n\n " ]
Please provide a description of the function:def do_or_fake_filter( value, formatter ): if not value: value = Faker.getGenerator().format( formatter ) return value
[ "\n call a faker if value is None\n uses:\n\n {{ myint|or_fake:'randomInt' }}\n\n " ]
Please provide a description of the function:def addEntity(self, model, number, customFieldFormatters=None): if not isinstance(model, ModelPopulator): model = ModelPopulator(model) model.fieldFormatters = model.guessFieldFormatters( self.generator ) if customFieldFormatters...
[ "\n Add an order for the generation of $number records for $entity.\n\n :param model: mixed A Django Model classname, or a faker.orm.django.EntityPopulator instance\n :type model: Model\n :param number: int The number of entities to populate\n :type number: integer\n :param...
Please provide a description of the function:def execute(self, using=None): if not using: using = self.getConnection() insertedEntities = {} for klass in self.orders: number = self.quantities[klass] if klass not in insertedEntities: i...
[ "\n Populate the database using all the Entity classes previously added.\n\n :param using A Django database connection name\n :rtype: A list of the inserted PKs\n " ]
Please provide a description of the function:def getConnection(self): klass = self.entities.keys() if not klass: raise AttributeError('No class found from entities. Did you add entities to the Populator ?') klass = list(klass)[0] return klass.objects._db
[ "\n use the first connection available\n :rtype: Connection\n " ]
Please provide a description of the function:def getCodename(locale=None, providers=None): from django.conf import settings # language locale = locale or getattr(settings,'FAKER_LOCALE', getattr(settings,'LANGUAGE_CODE', None)) # providers providers = providers or getatt...
[ "\n codename = locale[-Provider]*\n " ]
Please provide a description of the function:def getGenerator(cls, locale=None, providers=None, codename=None): codename = codename or cls.getCodename(locale, providers) if codename not in cls.generators: from faker import Faker as FakerGenerator # initialize with fake...
[ "\n use a codename to cache generators\n " ]
Please provide a description of the function:def guessFormat(self, name): name = name.lower() generator = self.generator if re.findall(r'^is[_A-Z]', name): return lambda x:generator.boolean() if re.findall(r'(_a|A)t$', name): return lambda x:generator.dateTime() if name...
[ "\n :param name:\n :type name: str\n " ]
Please provide a description of the function:def linestrings_intersect(line1, line2): intersects = [] for i in range(0, len(line1['coordinates']) - 1): for j in range(0, len(line2['coordinates']) - 1): a1_x = line1['coordinates'][i][1] a1_y = line1['coordinates'][i][0] ...
[ "\n To valid whether linestrings from geojson are intersected with each other.\n reference: http://www.kevlindev.com/gui/math/intersection/Intersection.js\n\n Keyword arguments:\n line1 -- first line geojson object\n line2 -- second line geojson object\n\n if(line1 intersects with other) return in...
Please provide a description of the function:def _bbox_around_polycoords(coords): x_all = [] y_all = [] for first in coords[0]: x_all.append(first[1]) y_all.append(first[0]) return [min(x_all), min(y_all), max(x_all), max(y_all)]
[ "\n bounding box\n " ]
Please provide a description of the function:def _point_in_bbox(point, bounds): return not(point['coordinates'][1] < bounds[0] or point['coordinates'][1] > bounds[2] or point['coordinates'][0] < bounds[1] or point['coordinates'][0] > bounds[3])
[ "\n valid whether the point is inside the bounding box\n " ]
Please provide a description of the function:def _pnpoly(x, y, coords): vert = [[0, 0]] for coord in coords: for node in coord: vert.append(node) vert.append(coord[0]) vert.append([0, 0]) inside = False i = 0 j = len(vert) - 1 while i < len(vert): ...
[ "\n the algorithm to judge whether the point is located in polygon\n reference: https://www.ecse.rpi.edu/~wrf/Research/Short_Notes/pnpoly.html#Explanation\n " ]
Please provide a description of the function:def point_in_polygon(point, poly): coords = [poly['coordinates']] if poly[ 'type'] == 'Polygon' else poly['coordinates'] return _point_in_polygon(point, coords)
[ "\n valid whether the point is located in a polygon\n\n Keyword arguments:\n point -- point geojson object\n poly -- polygon geojson object\n\n if(point inside poly) return true else false\n " ]
Please provide a description of the function:def point_in_multipolygon(point, multipoly): coords_array = [multipoly['coordinates']] if multipoly[ 'type'] == "MultiPolygon" else multipoly['coordinates'] for coords in coords_array: if _point_in_polygon(point, coords): return True...
[ "\n valid whether the point is located in a mulitpolygon (donut polygon is not supported)\n\n Keyword arguments:\n point -- point geojson object\n multipoly -- multipolygon geojson object\n\n if(point inside multipoly) return true else false\n " ]
Please provide a description of the function:def draw_circle(radius_in_meters, center_point, steps=15): steps = steps if steps > 15 else 15 center = [center_point['coordinates'][1], center_point['coordinates'][0]] dist = (radius_in_meters / 1000) / 6371 # convert meters to radiant rad_center = ...
[ "\n get a circle shape polygon based on centerPoint and radius\n\n Keyword arguments:\n point1 -- point one geojson object\n point2 -- point two geojson object\n\n if(point inside multipoly) return true else false\n " ]
Please provide a description of the function:def rectangle_centroid(rectangle): bbox = rectangle['coordinates'][0] xmin = bbox[0][0] ymin = bbox[0][1] xmax = bbox[2][0] ymax = bbox[2][1] xwidth = xmax - xmin ywidth = ymax - ymin return {'type': 'Point', 'coordinates': [xmin + xwidth...
[ "\n get the centroid of the rectangle\n\n Keyword arguments:\n rectangle -- polygon geojson object\n\n return centroid\n " ]
Please provide a description of the function:def point_distance(point1, point2): lon1 = point1['coordinates'][0] lat1 = point1['coordinates'][1] lon2 = point2['coordinates'][0] lat2 = point2['coordinates'][1] deg_lat = number2radius(lat2 - lat1) deg_lon = number2radius(lon2 - lon1) a = ...
[ "\n calculate the distance between two points on the sphere like google map\n reference http://www.movable-type.co.uk/scripts/latlong.html\n\n Keyword arguments:\n point1 -- point one geojson object\n point2 -- point two geojson object\n\n return distance\n " ]
Please provide a description of the function:def point_distance_ellipsode(point1,point2): a = 6378137 f = 1/298.25722 b = a - a*f e = math.sqrt((a*a-b*b)/(a*a)) lon1 = point1['coordinates'][0] lat1 = point1['coordinates'][1] lon2 = point1['coordinates'][0] lat2 = point2['coordinates...
[ "\n calculate the distance between two points on the ellipsode based on point1\n \n Keyword arguments:\n point1 -- point one geojson object\n point2 -- point two geojson object\n \n return distance\n " ]
Please provide a description of the function:def geometry_within_radius(geometry, center, radius): if geometry['type'] == 'Point': return point_distance(geometry, center) <= radius elif geometry['type'] == 'LineString' or geometry['type'] == 'Polygon': point = {} # it's enough to ch...
[ "\n To valid whether point or linestring or polygon is inside a radius around a center\n\n Keyword arguments:\n geometry -- point/linstring/polygon geojson object\n center -- point geojson object\n radius -- radius\n\n if(geometry inside radius) return true else false\n " ]
Please provide a description of the function:def area(poly): poly_area = 0 # TODO: polygon holes at coordinates[1] points = poly['coordinates'][0] j = len(points) - 1 count = len(points) for i in range(0, count): p1_x = points[i][1] p1_y = points[i][0] p2_x = points...
[ "\n calculate the area of polygon\n\n Keyword arguments:\n poly -- polygon geojson object\n\n return polygon area\n " ]
Please provide a description of the function:def centroid(poly): f_total = 0 x_total = 0 y_total = 0 # TODO: polygon holes at coordinates[1] points = poly['coordinates'][0] j = len(points) - 1 count = len(points) for i in range(0, count): p1_x = points[i][1] p1_y = ...
[ "\n get the centroid of polygon\n adapted from http://paulbourke.net/geometry/polyarea/javascript.txt\n\n Keyword arguments:\n poly -- polygon geojson object\n\n return polygon centroid\n " ]
Please provide a description of the function:def destination_point(point, brng, dist): dist = float(dist) / 6371 # convert dist to angular distance in radians brng = number2radius(brng) lon1 = number2radius(point['coordinates'][0]) lat1 = number2radius(point['coordinates'][1]) lat2 = math.as...
[ "\n Calculate a destination Point base on a base point and a distance\n\n Keyword arguments:\n pt -- polygon geojson object\n brng -- an angle in degrees\n dist -- distance in Kilometer between destination and base point\n\n return destination point object\n\n " ]
Please provide a description of the function:def simplify(source, kink=20): source_coord = map(lambda o: {"lng": o.coordinates[0], "lat": o.coordinates[1]}, source) # count, n_stack, n_dest, start, end, i, sig; # dev_sqr, max_dev_sqr, band_sqr; # x12, y12, d12, x13, y13, d13, x23, y23, d23; F ...
[ "\n source[] array of geojson points\n kink\tin metres, kinks above this depth kept\n kink depth is the height of the triangle abc where a-b and b-c are two consecutive line segments\n " ]
Please provide a description of the function:def geocode(address): geocoding = {'s': 'rsv3', 'key': key, 'city': '全国', 'address': address} res = requests.get( "http://restapi.amap.com/v3/geocode/geo", params=geocoding) if res.status_code == 200...
[ "\n 利用百度geocoding服务解析地址获取位置坐标\n :param address:需要解析的地址\n :return:\n " ]
Please provide a description of the function:def gcj02tobd09(lng, lat): z = math.sqrt(lng * lng + lat * lat) + 0.00002 * math.sin(lat * x_pi) theta = math.atan2(lat, lng) + 0.000003 * math.cos(lng * x_pi) bd_lng = z * math.cos(theta) + 0.0065 bd_lat = z * math.sin(theta) + 0.006 return [bd_lng,...
[ "\n 火星坐标系(GCJ-02)转百度坐标系(BD-09)\n 谷歌、高德——>百度\n :param lng:火星坐标经度\n :param lat:火星坐标纬度\n :return:\n " ]
Please provide a description of the function:def bd09togcj02(bd_lon, bd_lat): x = bd_lon - 0.0065 y = bd_lat - 0.006 z = math.sqrt(x * x + y * y) - 0.00002 * math.sin(y * x_pi) theta = math.atan2(y, x) - 0.000003 * math.cos(x * x_pi) gg_lng = z * math.cos(theta) gg_lat = z * math.sin(theta)...
[ "\n 百度坐标系(BD-09)转火星坐标系(GCJ-02)\n 百度——>谷歌、高德\n :param bd_lat:百度坐标纬度\n :param bd_lon:百度坐标经度\n :return:转换后的坐标列表形式\n " ]
Please provide a description of the function:def wgs84togcj02(lng, lat): if out_of_china(lng, lat): # 判断是否在国内 return lng, lat dlat = transformlat(lng - 105.0, lat - 35.0) dlng = transformlng(lng - 105.0, lat - 35.0) radlat = lat / 180.0 * pi magic = math.sin(radlat) magic = 1 - ee ...
[ "\n WGS84转GCJ02(火星坐标系)\n :param lng:WGS84坐标系的经度\n :param lat:WGS84坐标系的纬度\n :return:\n " ]
Please provide a description of the function:def out_of_china(lng, lat): if lng < 72.004 or lng > 137.8347: return True if lat < 0.8293 or lat > 55.8271: return True return False
[ "\n 判断是否在国内,不在国内不做偏移\n :param lng:\n :param lat:\n :return:\n " ]
Please provide a description of the function:def convertor(geometry, method="wgs2gcj"): if geometry['type'] == 'Point': coords = geometry['coordinates'] coords[0], coords[1] = methods[method](coords[0], coords[1]) elif geometry['type'] == 'LineString' or geometry['type'] == 'MutliPoint': ...
[ "\n convert wgs84 to gcj\n referencing by https://github.com/wandergis/coordTransform_py\n " ]
Please provide a description of the function:def merge_featurecollection(*jsons): features = [] for json in jsons: if json['type'] == 'FeatureCollection': for feature in json['features']: features.append(feature) return {"type":'FeatureCollection', "features":feature...
[ "\n merge features into one featurecollection\n\n Keyword arguments:\n jsons -- jsons object list \n\n return geojson featurecollection\n " ]
Please provide a description of the function:def simplify_other(major, minor, dist): result = deepcopy(major) if major['type'] == 'FeatureCollection' and minor['type'] == 'FeatureCollection': arc = dist/6371000*180/math.pi*2 for minorfeature in minor['features']: minorgeom = min...
[ "\n Simplify the point featurecollection of poi with another point features accoording by distance.\n Attention: point featurecollection only\n\n Keyword arguments:\n major -- major geojson\n minor -- minor geojson\n dist -- distance \n\n return a geojson featurecollection with two pa...
Please provide a description of the function:def trace_dispatch(self, frame, event, arg): if hasattr(self, 'vimpdb'): return self.vimpdb.trace_dispatch(frame, event, arg) else: return self._orig_trace_dispatch(frame, event, arg)
[ "allow to switch to Vimpdb instance" ]
Please provide a description of the function:def hook(klass): if not hasattr(klass, 'do_vim'): setupMethod(klass, trace_dispatch) klass.__bases__ += (SwitcherToVimpdb, )
[ "\n monkey-patch pdb.Pdb class\n\n adds a 'vim' (and 'v') command:\n it switches to debugging with vimpdb\n " ]
Please provide a description of the function:def trace_dispatch(self, frame, event, arg): if hasattr(self, 'pdb'): return self.pdb.trace_dispatch(frame, event, arg) else: return Pdb.trace_dispatch(self, frame, event, arg)
[ "allow to switch to Pdb instance" ]
Please provide a description of the function:def do_pdb(self, line): self.from_vim.closeSocket() self.pdb = get_hooked_pdb() self.pdb.set_trace_without_step(self.botframe) if self.has_gone_up(): self.pdb.update_state(self) self.pdb.print_current_stack_ent...
[ "\n 'pdb' command:\n switches back to debugging with (almost) standard pdb.Pdb\n except for added 'vim' command.\n " ]
Please provide a description of the function:def do_vim(self, arg): self.vimpdb = make_instance() self.vimpdb.set_trace_without_step(self.botframe) if self.has_gone_up(): self.vimpdb.update_state(self) self.vimpdb.cmdloop() else: self.vimpdb.i...
[ "v(im)\n switch to debugging with vimpdb" ]
Please provide a description of the function:def _get_specified_sub_menu_template_name(self, level): ideal_index = level - 2 return self._option_vals.sub_menu_template_name or \ get_item_by_index_or_last_item( self._option_vals.sub_menu_template_names, ideal_index) o...
[ "\n Called by get_sub_menu_template(). Iterates through the various ways in\n which developers can specify potential sub menu templates for a menu,\n and returns the name of the most suitable template for the\n ``current_level``. Values are checked in the following order:\n\n 1. ...
Please provide a description of the function:def get_sub_menu_template_names(self): template_names = [] menu_name = self.menu_short_name site = self._contextual_vals.current_site level = self._contextual_vals.current_level if settings.SITE_SPECIFIC_TEMPLATE_DIRS and site...
[ "Return a list of template paths/names to search when rendering a\n sub menu for this menu instance. The list should beordered with most\n specific names first, since the first template found to exist will be\n used for rendering" ]
Please provide a description of the function:def get_context_data(self, **kwargs): data = {} if self._contextual_vals.current_level == 1 and self.max_levels > 1: data['sub_menu_template'] = self.sub_menu_template.template.name data.update(kwargs) return super().get_c...
[ "\n Include the name of the sub menu template in the context. This is\n purely for backwards compatibility. Any sub menus rendered as part of\n this menu will call `sub_menu_template` on the original menu instance\n to get an actual `Template`\n " ]
Please provide a description of the function:def render_from_tag( cls, context, max_levels=None, use_specific=None, apply_active_classes=True, allow_repeating_parents=True, use_absolute_page_urls=False, add_sub_menus_inline=None, template_name='', **kwargs ): instanc...
[ "\n A template tag should call this method to render a menu.\n The ``Context`` instance and option values provided are used to get or\n create a relevant menu instance, prepare it, then render it and it's\n menu items to an appropriate template.\n\n It shouldn't be neccessary to o...
Please provide a description of the function:def _get_render_prepared_object(cls, context, **option_values): ctx_vals = cls._create_contextualvals_obj_from_context(context) opt_vals = cls._create_optionvals_obj_from_values(**option_values) if issubclass(cls, models.Model): ...
[ "\n Returns a fully prepared, request-aware menu object that can be used\n for rendering. ``context`` could be a ``django.template.Context``\n object passed to ``render_from_tag()`` by a menu tag.\n " ]
Please provide a description of the function:def _create_contextualvals_obj_from_context(cls, context): context_processor_vals = context.get('wagtailmenus_vals', {}) return ContextualVals( context, context['request'], get_site_from_request(context['request'])...
[ "\n Gathers all of the 'contextual' data needed to render a menu instance\n and returns it in a structure that can be conveniently referenced\n throughout the process of preparing the menu and menu items and\n for rendering.\n " ]
Please provide a description of the function:def _create_optionvals_obj_from_values(cls, **kwargs): return OptionVals( kwargs.pop('max_levels'), kwargs.pop('use_specific'), kwargs.pop('apply_active_classes'), kwargs.pop('allow_repeating_parents'), ...
[ "\n Takes all of the options passed to the class's ``render_from_tag()``\n method and returns them in a structure that can be conveniently\n referenced throughout the process of rendering.\n\n Any additional options supplied by custom menu tags will be available\n as a dictionary ...
Please provide a description of the function:def prepare_to_render(self, request, contextual_vals, option_vals): self._contextual_vals = contextual_vals self._option_vals = option_vals self.set_request(request)
[ "\n Before calling ``render_to_template()``, this method is called to give\n the instance opportunity to prepare itself. For example,\n ``AbstractMainMenu`` and ``AbstractFlatMenu`` needs to call\n ``set_max_levels()`` and ``set_use_specific()`` to update the\n ``max_levels`` and ...
Please provide a description of the function:def render_to_template(self): context_data = self.get_context_data() template = self.get_template() context_data['current_template'] = template.template.name return template.render(context_data)
[ "\n Render the current menu instance to a template and return a string\n " ]
Please provide a description of the function:def get_common_hook_kwargs(self, **kwargs): opt_vals = self._option_vals hook_kwargs = self._contextual_vals._asdict() hook_kwargs.update({ 'menu_instance': self, 'menu_tag': self.related_templatetag_name, ...
[ "\n Returns a dictionary of common values to be passed as keyword\n arguments to methods registered as 'hooks'.\n " ]
Please provide a description of the function:def get_page_children_dict(self, page_qs=None): children_dict = defaultdict(list) for page in page_qs or self.pages_for_display: children_dict[page.path[:-page.steplen]].append(page) return children_dict
[ "\n Returns a dictionary of lists, where the keys are 'path' values for\n pages, and the value is a list of children pages for that page.\n " ]
Please provide a description of the function:def get_context_data(self, **kwargs): ctx_vals = self._contextual_vals opt_vals = self._option_vals data = self.create_dict_from_parent_context() data.update(ctx_vals._asdict()) data.update({ 'apply_active_classes'...
[ "\n Return a dictionary containing all of the values needed to render the\n menu instance to a template, including values that might be used by\n the 'sub_menu' tag to render any additional levels.\n " ]
Please provide a description of the function:def get_menu_items_for_rendering(self): items = self.get_raw_menu_items() # Allow hooks to modify the raw list for hook in hooks.get_hooks('menus_modify_raw_menu_items'): items = hook(items, **self.common_hook_kwargs) # ...
[ "\n Return a list of 'menu items' to be included in the context for\n rendering the current level of the menu.\n\n The responsibility for sourcing, priming, and modifying menu items is\n split between three methods: ``get_raw_menu_items()``,\n ``prime_menu_items()`` and ``modify_m...
Please provide a description of the function:def _replace_with_specific_page(page, menu_item): if type(page) is Page: page = page.specific if isinstance(menu_item, MenuItem): menu_item.link_page = page else: menu_item = page re...
[ "\n If ``page`` is a vanilla ``Page` object, replace it with a 'specific'\n version of itself. Also update ``menu_item``, depending on whether it's\n a ``MenuItem`` object or a ``Page`` object.\n " ]
Please provide a description of the function:def prime_menu_items(self, menu_items): for item in menu_items: item = self._prime_menu_item(item) if item is not None: yield item
[ "\n A generator method that takes a list of ``MenuItem`` or ``Page``\n objects and sets a number of additional attributes on each item that\n are useful in menu templates.\n " ]
Please provide a description of the function:def get_template_names(self): site = self._contextual_vals.current_site template_names = [] menu_str = self.menu_short_name if settings.SITE_SPECIFIC_TEMPLATE_DIRS and site: hostname = site.hostname template_na...
[ "Return a list (or tuple) of template names to search for when\n rendering an instance of this class. The list should be ordered\n with most specific names first, since the first template found to\n exist will be used for rendering." ]
Please provide a description of the function:def get_pages_for_display(self): parent_page = self.parent_page_for_menu_items pages = self.get_base_page_queryset().filter( depth__gt=parent_page.depth, depth__lte=parent_page.depth + self.max_levels, path__starts...
[ "Return all pages needed for rendering all sub-levels for the current\n menu" ]
Please provide a description of the function:def get_children_for_page(self, page): if self.max_levels == 1: # If there's only a single level of pages to display, skip the # dict creation / lookup and just return the QuerySet result return self.pages_for_display ...
[ "Return a list of relevant child pages for a given page" ]
Please provide a description of the function:def modify_menu_items(self, menu_items): parent_page = self.parent_page_for_menu_items modifier_method = getattr(parent_page, 'modify_submenu_items', None) if not self.use_specific or not modifier_method: return menu_items ...
[ "\n If the 'use_specific' value on the menu instance indicates that the\n behaviour is desired, and the 'parent page' has a\n 'modify_submenu_items()' method, send the menu items to that for\n further modification and return the modified result.\n\n The supplied ``menu_items`` mig...
Please provide a description of the function:def get_top_level_items(self): menu_items = self.get_base_menuitem_queryset() # Identify which pages to fetch for the top level items page_ids = tuple( obj.link_page_id for obj in menu_items if obj.link_page_id ) ...
[ "Return a list of menu items with link_page objects supplemented with\n 'specific' pages where appropriate.", "\n The menu is being generated with a specificity level of\n TOP_LEVEL or ALWAYS, so we use PageQuerySet.specific() to fetch\n specific page instances ...
Please provide a description of the function:def get_pages_for_display(self): # Start with an empty queryset, and expand as needed all_pages = Page.objects.none() if self.max_levels == 1: # If no additional sub-levels are needed, return empty queryset return al...
[ "Return all pages needed for rendering all sub-levels for the current\n menu" ]
Please provide a description of the function:def add_menu_items_for_pages(self, pagequeryset=None, allow_subnav=True): item_manager = self.get_menu_items_manager() item_class = item_manager.model item_list = [] i = item_manager.count() for p in pagequeryset.all(): ...
[ "Add menu items to this menu, linking to each page in `pagequeryset`\n (which should be a PageQuerySet instance)" ]
Please provide a description of the function:def get_for_site(cls, site): instance, created = cls.objects.get_or_create(site=site) return instance
[ "Return the 'main menu' instance for the provided site" ]
Please provide a description of the function:def get_for_site(cls, handle, site, fall_back_to_default_site_menus=False): queryset = cls.objects.filter(handle__exact=handle) site_q = Q(site=site) if fall_back_to_default_site_menus: site_q |= Q(site__is_default_site=True) ...
[ "Return a FlatMenu instance with a matching ``handle`` for the\n provided ``site``, or for the default site (if suitable). If no\n match is found, returns None." ]
Please provide a description of the function:def get_template_names(self): site = self._contextual_vals.current_site handle = self.handle template_names = [] if settings.SITE_SPECIFIC_TEMPLATE_DIRS and site: hostname = site.hostname template_names.extend(...
[ "Returns a list of template names to search for when rendering a\n a specific flat menu object (making use of self.handle)" ]
Please provide a description of the function:def get_sub_menu_template_names(self): site = self._contextual_vals.current_site level = self._contextual_vals.current_level handle = self.handle template_names = [] if settings.SITE_SPECIFIC_TEMPLATE_DIRS and site: ...
[ "Returns a list of template names to search for when rendering a\n a sub menu for a specific flat menu object (making use of self.handle)\n " ]
Please provide a description of the function:def get_form_kwargs(self): kwargs = super().get_form_kwargs() if self.request.method == 'POST': data = copy(self.request.POST) i = 0 while(data.get('%s-%s-id' % ( settings.FLAT_MENU_ITEMS_RELATED_NA...
[ "\n When the form is posted, don't pass an instance to the form. It should\n create a new one out of the posted data. We also need to nullify any\n IDs posted for inline menu items, so that new instances of those are\n created too.\n " ]
Please provide a description of the function:def modify_submenu_items( self, menu_items, current_page, current_ancestor_ids, current_site, allow_repeating_parents, apply_active_classes, original_menu_tag, menu_instance=None, request=None, use_absolute_page_urls=False, ): if ...
[ "\n Make any necessary modifications to `menu_items` and return the list\n back to the calling menu tag to render in templates. Any additional\n items added should have a `text` and `href` attribute as a minimum.\n\n `original_menu_tag` should be one of 'main_menu', 'section_menu' or\n ...