_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q257400
extract_contours
validation
def extract_contours(array, tile, interval=100, field='elev', base=0): """ Extract contour lines from an array. Parameters ---------- array : array input elevation data tile : Tile tile covering the array interval : integer elevation value interval when drawing conto...
python
{ "resource": "" }
q257401
_get_contour_values
validation
def _get_contour_values(min_val, max_val, base=0, interval=100): """Return a list of values between min and max within an interval.""" i = base out = [] if min_val < base: while i >= min_val: i -= interval while i <= max_val: if i >= min_val: out.append(i) ...
python
{ "resource": "" }
q257402
create
validation
def create( mapchete_file, process_file, out_format, out_path=None, pyramid_type=None, force=False ): """Create an empty Mapchete and process file in a given directory.""" if os.path.isfile(process_file) or os.path.isfile(mapchete_file): if not force: raise IOError("f...
python
{ "resource": "" }
q257403
OutputData.get_path
validation
def get_path(self, tile): """ Determine target file path. Parameters ---------- tile : ``BufferedTile`` must be member of output ``TilePyramid`` Returns ------- path : string """ return os.path.join(*[ self.path, ...
python
{ "resource": "" }
q257404
OutputData.prepare_path
validation
def prepare_path(self, tile): """ Create directory and subdirectory if necessary. Parameters ---------- tile : ``BufferedTile`` must be member of output ``TilePyramid`` """ makedirs(os.path.dirname(self.get_path(tile)))
python
{ "resource": "" }
q257405
OutputData.output_is_valid
validation
def output_is_valid(self, process_data): """ Check whether process output is allowed with output driver. Parameters ---------- process_data : raw process output Returns ------- True or False """ if self.METADATA["data_type"] == "raster": ...
python
{ "resource": "" }
q257406
OutputData.output_cleaned
validation
def output_cleaned(self, process_data): """ Return verified and cleaned output. Parameters ---------- process_data : raw process output Returns ------- NumPy array or list of features. """ if self.METADATA["data_type"] == "raster": ...
python
{ "resource": "" }
q257407
OutputData.extract_subset
validation
def extract_subset(self, input_data_tiles=None, out_tile=None): """ Extract subset from multiple tiles. input_data_tiles : list of (``Tile``, process data) tuples out_tile : ``Tile`` Returns ------- NumPy array or list of features. """ if self.ME...
python
{ "resource": "" }
q257408
calculate_slope_aspect
validation
def calculate_slope_aspect(elevation, xres, yres, z=1.0, scale=1.0): """ Calculate slope and aspect map. Return a pair of arrays 2 pixels smaller than the input elevation array. Slope is returned in radians, from 0 for sheer face to pi/2 for flat ground. Aspect is returned in radians, counterclock...
python
{ "resource": "" }
q257409
hillshade
validation
def hillshade(elevation, tile, azimuth=315.0, altitude=45.0, z=1.0, scale=1.0): """ Return hillshaded numpy array. Parameters ---------- elevation : array input elevation data tile : Tile tile covering the array z : float vertical exaggeration factor scale : floa...
python
{ "resource": "" }
q257410
BufferedTilePyramid.tile
validation
def tile(self, zoom, row, col): """ Return ``BufferedTile`` object of this ``BufferedTilePyramid``. Parameters ---------- zoom : integer zoom level row : integer tile matrix row col : integer tile matrix column Returns...
python
{ "resource": "" }
q257411
BufferedTilePyramid.tiles_from_bounds
validation
def tiles_from_bounds(self, bounds, zoom): """ Return all tiles intersecting with bounds. Bounds values will be cleaned if they cross the antimeridian or are outside of the Northern or Southern tile pyramid bounds. Parameters ---------- bounds : tuple ...
python
{ "resource": "" }
q257412
BufferedTilePyramid.tiles_from_bbox
validation
def tiles_from_bbox(self, geometry, zoom): """ All metatiles intersecting with given bounding box. Parameters ---------- geometry : ``shapely.geometry`` zoom : integer zoom level Yields ------ intersecting tiles : generator ...
python
{ "resource": "" }
q257413
BufferedTilePyramid.tiles_from_geom
validation
def tiles_from_geom(self, geometry, zoom): """ Return all tiles intersecting with input geometry. Parameters ---------- geometry : ``shapely.geometry`` zoom : integer zoom level Yields ------ intersecting tiles : ``BufferedTile`` ...
python
{ "resource": "" }
q257414
BufferedTilePyramid.intersecting
validation
def intersecting(self, tile): """ Return all BufferedTiles intersecting with tile. Parameters ---------- tile : ``BufferedTile`` another tile """ return [ self.tile(*intersecting_tile.id) for intersecting_tile in self.tile_pyra...
python
{ "resource": "" }
q257415
BufferedTilePyramid.to_dict
validation
def to_dict(self): """ Return dictionary representation of pyramid parameters. """ return dict( grid=self.grid.to_dict(), metatiling=self.metatiling, tile_size=self.tile_size, pixelbuffer=self.pixelbuffer )
python
{ "resource": "" }
q257416
BufferedTile.get_neighbors
validation
def get_neighbors(self, connectedness=8): """ Return tile neighbors. Tile neighbors are unique, i.e. in some edge cases, where both the left and right neighbor wrapped around the antimeridian is the same. Also, neighbors ouside the northern and southern TilePyramid boundaries ar...
python
{ "resource": "" }
q257417
BufferedTile.is_on_edge
validation
def is_on_edge(self): """Determine whether tile touches or goes over pyramid edge.""" return ( self.left <= self.tile_pyramid.left or # touches_left self.bottom <= self.tile_pyramid.bottom or # touches_bottom self.right >= self.tile_pyramid.right or # touches...
python
{ "resource": "" }
q257418
execute
validation
def execute( mp, resampling="nearest", scale_method=None, scales_minmax=None ): """ Read, stretch and return raster data. Inputs: ------- raster raster file Parameters: ----------- resampling : str rasterio.Resampling method scale_method : str ...
python
{ "resource": "" }
q257419
OutputData.open
validation
def open(self, tile, process, **kwargs): """ Open process output as input for other process. Parameters ---------- tile : ``Tile`` process : ``MapcheteProcess`` kwargs : keyword arguments """ return InputTile(tile, process, kwargs.get("resampling"...
python
{ "resource": "" }
q257420
OutputData.for_web
validation
def for_web(self, data): """ Convert data to web output. Parameters ---------- data : array Returns ------- web data : array """ rgba = self._prepare_array_for_png(data) data = ma.masked_where(rgba == self.nodata, rgba) re...
python
{ "resource": "" }
q257421
serve
validation
def serve( mapchete_file, port=None, internal_cache=None, zoom=None, bounds=None, overwrite=False, readonly=False, memory=False, input_file=None, debug=False, logfile=None ): """ Serve a Mapchete process. Creates the Mapchete host and serves both web page with Op...
python
{ "resource": "" }
q257422
create_app
validation
def create_app( mapchete_files=None, zoom=None, bounds=None, single_input_file=None, mode="continue", debug=None ): """Configure and create Flask app.""" from flask import Flask, render_template_string app = Flask(__name__) mapchete_processes = { os.path.splitext(os.path.basename(mapchet...
python
{ "resource": "" }
q257423
read_raster_window
validation
def read_raster_window( input_files, tile, indexes=None, resampling="nearest", src_nodata=None, dst_nodata=None, gdal_opts=None ): """ Return NumPy arrays from an input raster. NumPy arrays are reprojected and resampled to tile properties from input raster. If tile boundarie...
python
{ "resource": "" }
q257424
_get_warped_array
validation
def _get_warped_array( input_file=None, indexes=None, dst_bounds=None, dst_shape=None, dst_crs=None, resampling=None, src_nodata=None, dst_nodata=None ): """Extract a numpy array from a raster file.""" try: return _rasterio_read( input_file=input_file, ...
python
{ "resource": "" }
q257425
write_raster_window
validation
def write_raster_window( in_tile=None, in_data=None, out_profile=None, out_tile=None, out_path=None, tags=None, bucket_resource=None ): """ Write a window from a numpy array to an output file. Parameters ---------- in_tile : ``BufferedTile`` ``BufferedTile`` with a data attribute ho...
python
{ "resource": "" }
q257426
extract_from_array
validation
def extract_from_array(in_raster=None, in_affine=None, out_tile=None): """ Extract raster data window array. Parameters ---------- in_raster : array or ReferencedRaster in_affine : ``Affine`` required if in_raster is an array out_tile : ``BufferedTile`` Returns ------- extracte...
python
{ "resource": "" }
q257427
resample_from_array
validation
def resample_from_array( in_raster=None, in_affine=None, out_tile=None, in_crs=None, resampling="nearest", nodataval=0 ): """ Extract and resample from array to target tile. Parameters ---------- in_raster : array in_affine : ``Affine`` out_tile : ``BufferedTile`` ...
python
{ "resource": "" }
q257428
bounds_to_ranges
validation
def bounds_to_ranges(out_bounds=None, in_affine=None, in_shape=None): """ Return bounds range values from geolocated input. Parameters ---------- out_bounds : tuple left, bottom, right, top in_affine : Affine input geolocation in_shape : tuple input shape Return...
python
{ "resource": "" }
q257429
tiles_to_affine_shape
validation
def tiles_to_affine_shape(tiles): """ Return Affine and shape of combined tiles. Parameters ---------- tiles : iterable an iterable containing BufferedTiles Returns ------- Affine, Shape """ if not tiles: raise TypeError("no tiles provided") pixel_size = til...
python
{ "resource": "" }
q257430
_shift_required
validation
def _shift_required(tiles): """Determine if distance over antimeridian is shorter than normal distance.""" if tiles[0][0].tile_pyramid.is_global: # get set of tile columns tile_cols = sorted(list(set([t[0].col for t in tiles]))) # if tile columns are an unbroken sequence, tiles are conne...
python
{ "resource": "" }
q257431
memory_file
validation
def memory_file(data=None, profile=None): """ Return a rasterio.io.MemoryFile instance from input. Parameters ---------- data : array array to be written profile : dict rasterio profile for MemoryFile """ memfile = MemoryFile() profile.update(width=data.shape[-2], he...
python
{ "resource": "" }
q257432
prepare_array
validation
def prepare_array(data, masked=True, nodata=0, dtype="int16"): """ Turn input data into a proper array for further usage. Outut array is always 3-dimensional with the given data type. If the output is masked, the fill_value corresponds to the given nodata value and the nodata value will be burned i...
python
{ "resource": "" }
q257433
reproject_geometry
validation
def reproject_geometry( geometry, src_crs=None, dst_crs=None, error_on_clip=False, validity_check=True, antimeridian_cutting=False ): """ Reproject a geometry to target CRS. Also, clips geometry if it lies outside the destination CRS boundary. Supported destination CRSes for clipping: 4326 (WGS...
python
{ "resource": "" }
q257434
segmentize_geometry
validation
def segmentize_geometry(geometry, segmentize_value): """ Segmentize Polygon outer ring by segmentize value. Just Polygon geometry type supported. Parameters ---------- geometry : ``shapely.geometry`` segmentize_value: float Returns ------- geometry : ``shapely.geometry`` "...
python
{ "resource": "" }
q257435
read_vector_window
validation
def read_vector_window(input_files, tile, validity_check=True): """ Read a window of an input vector dataset. Also clips geometry. Parameters: ----------- input_file : string path to vector file tile : ``Tile`` tile extent to read data from validity_check : bool ...
python
{ "resource": "" }
q257436
write_vector_window
validation
def write_vector_window( in_data=None, out_schema=None, out_tile=None, out_path=None, bucket_resource=None ): """ Write features to GeoJSON file. Parameters ---------- in_data : features out_schema : dictionary output schema for fiona out_tile : ``BufferedTile`` tile use...
python
{ "resource": "" }
q257437
clean_geometry_type
validation
def clean_geometry_type(geometry, target_type, allow_multipart=True): """ Return geometry of a specific type if possible. Filters and splits up GeometryCollection into target types. This is necessary when after clipping and/or reprojecting the geometry types from source geometries change (i.e. a Po...
python
{ "resource": "" }
q257438
multipart_to_singleparts
validation
def multipart_to_singleparts(geom): """ Yield single part geometries if geom is multipart, otherwise yield geom. Parameters: ----------- geom : shapely geometry Returns: -------- shapely single part geometries """ if isinstance(geom, base.BaseGeometry): if hasattr(geom,...
python
{ "resource": "" }
q257439
execute
validation
def execute( mp, td_resampling="nearest", td_matching_method="gdal", td_matching_max_zoom=None, td_matching_precision=8, td_fallback_to_higher_zoom=False, clip_pixelbuffer=0, **kwargs ): """ Convert and optionally clip input raster data. Inputs: ------- raster ...
python
{ "resource": "" }
q257440
get_best_zoom_level
validation
def get_best_zoom_level(input_file, tile_pyramid_type): """ Determine the best base zoom level for a raster. "Best" means the maximum zoom level where no oversampling has to be done. Parameters ---------- input_file : path to raster file tile_pyramid_type : ``TilePyramid`` projection (``ge...
python
{ "resource": "" }
q257441
tile_to_zoom_level
validation
def tile_to_zoom_level(tile, dst_pyramid=None, matching_method="gdal", precision=8): """ Determine the best zoom level in target TilePyramid from given Tile. Parameters ---------- tile : BufferedTile dst_pyramid : BufferedTilePyramid matching_method : str ('gdal' or 'min') gdal: Us...
python
{ "resource": "" }
q257442
path_is_remote
validation
def path_is_remote(path, s3=True): """ Determine whether file path is remote or local. Parameters ---------- path : path to file Returns ------- is_remote : bool """ prefixes = ("http://", "https://", "/vsicurl/") if s3: prefixes += ("s3://", "/vsis3/") return p...
python
{ "resource": "" }
q257443
path_exists
validation
def path_exists(path): """ Check if file exists either remote or local. Parameters: ----------- path : path to file Returns: -------- exists : bool """ if path.startswith(("http://", "https://")): try: urlopen(path).info() return True exc...
python
{ "resource": "" }
q257444
absolute_path
validation
def absolute_path(path=None, base_dir=None): """ Return absolute path if path is local. Parameters: ----------- path : path to file base_dir : base directory used for absolute path Returns: -------- absolute path """ if path_is_remote(path): return path else: ...
python
{ "resource": "" }
q257445
relative_path
validation
def relative_path(path=None, base_dir=None): """ Return relative path if path is local. Parameters: ----------- path : path to file base_dir : directory where path sould be relative to Returns: -------- relative path """ if path_is_remote(path) or not os.path.isabs(path): ...
python
{ "resource": "" }
q257446
write_json
validation
def write_json(path, params): """Write local or remote.""" logger.debug("write %s to %s", params, path) if path.startswith("s3://"): bucket = get_boto3_bucket(path.split("/")[2]) key = "/".join(path.split("/")[3:]) logger.debug("upload %s", key) bucket.put_object( ...
python
{ "resource": "" }
q257447
read_json
validation
def read_json(path): """Read local or remote.""" if path.startswith(("http://", "https://")): try: return json.loads(urlopen(path).read().decode()) except HTTPError: raise FileNotFoundError("%s not found", path) elif path.startswith("s3://"): bucket = get_boto...
python
{ "resource": "" }
q257448
Webhook.hook
validation
def hook(self, event_type='push'): """ Registers a function as a hook. Multiple hooks can be registered for a given type, but the order in which they are invoke is unspecified. :param event_type: The event type this hook will be invoked for. """ def decorator(func): ...
python
{ "resource": "" }
q257449
Webhook._get_digest
validation
def _get_digest(self): """Return message digest if a secret key was provided""" return hmac.new( self._secret, request.data, hashlib.sha1).hexdigest() if self._secret else None
python
{ "resource": "" }
q257450
Webhook._postreceive
validation
def _postreceive(self): """Callback from Flask""" digest = self._get_digest() if digest is not None: sig_parts = _get_header('X-Hub-Signature').split('=', 1) if not isinstance(digest, six.text_type): digest = six.text_type(digest) if (len(si...
python
{ "resource": "" }
q257451
long_description
validation
def long_description(): """Generate .rst document for PyPi.""" import argparse parser = argparse.ArgumentParser() parser.add_argument('--doc', dest="doc", action="store_true", default=False) args, sys.argv = parser.parse_known_args(sys.argv) if args.doc: import doc2md, pypand...
python
{ "resource": "" }
q257452
unindent
validation
def unindent(lines): """ Remove common indentation from string. Unlike doctrim there is no special treatment of the first line. """ try: # Determine minimum indentation: indent = min(len(line) - len(line.lstrip()) for line in lines if line) except ValueErro...
python
{ "resource": "" }
q257453
find_sections
validation
def find_sections(lines): """ Find all section names and return a list with their names. """ sections = [] for line in lines: if is_heading(line): sections.append(get_heading(line)) return sections
python
{ "resource": "" }
q257454
make_toc
validation
def make_toc(sections, maxdepth=0): """ Generate table of contents for array of section names. """ if not sections: return [] outer = min(n for n,t in sections) refs = [] for ind,sec in sections: if maxdepth and ind-outer+1 > maxdepth: continue ref = sec.l...
python
{ "resource": "" }
q257455
doc2md
validation
def doc2md(docstr, title, min_level=1, more_info=False, toc=True, maxdepth=0): """ Convert a docstring to a markdown text. """ text = doctrim(docstr) lines = text.split('\n') sections = find_sections(lines) if sections: level = min(n for n,t in sections) - 1 else: level ...
python
{ "resource": "" }
q257456
mod2md
validation
def mod2md(module, title, title_api_section, toc=True, maxdepth=0): """ Generate markdown document from module, including API section. """ docstr = module.__doc__ text = doctrim(docstr) lines = text.split('\n') sections = find_sections(lines) if sections: level = min(n for n,t ...
python
{ "resource": "" }
q257457
ProfileBlockAnalyzer.largest_finite_distance
validation
def largest_finite_distance(self): """ Compute the maximum temporal distance. Returns ------- max_temporal_distance : float """ block_start_distances = [block.distance_start for block in self._profile_blocks if block.distance_star...
python
{ "resource": "" }
q257458
ProfileBlockAnalyzer._temporal_distance_cdf
validation
def _temporal_distance_cdf(self): """ Temporal distance cumulative density function. Returns ------- x_values: numpy.array values for the x-axis cdf: numpy.array cdf values """ distance_split_points = set() for block in sel...
python
{ "resource": "" }
q257459
ProfileBlockAnalyzer._temporal_distance_pdf
validation
def _temporal_distance_pdf(self): """ Temporal distance probability density function. Returns ------- non_delta_peak_split_points: numpy.array non_delta_peak_densities: numpy.array len(density) == len(temporal_distance_split_points_ordered) -1 delta_p...
python
{ "resource": "" }
q257460
remove_all_trips_fully_outside_buffer
validation
def remove_all_trips_fully_outside_buffer(db_conn, center_lat, center_lon, buffer_km, update_secondary_data=True): """ Not used in the regular filter process for the time being. Parameters ---------- db_conn: sqlite3.Connection connection to the GTFS object center_lat: float center_...
python
{ "resource": "" }
q257461
remove_dangling_shapes
validation
def remove_dangling_shapes(db_conn): """ Remove dangling entries from the shapes directory. Parameters ---------- db_conn: sqlite3.Connection connection to the GTFS object """ db_conn.execute(DELETE_SHAPES_NOT_REFERENCED_IN_TRIPS_SQL) SELECT_MIN_MAX_SHAPE_BREAKS_BY_TRIP_I_SQL = ...
python
{ "resource": "" }
q257462
compute_pseudo_connections
validation
def compute_pseudo_connections(transit_connections, start_time_dep, end_time_dep, transfer_margin, walk_network, walk_speed): """ Given a set of transit events and the static walk network, "transform" the static walking network into a set of "pse...
python
{ "resource": "" }
q257463
SpreadingStop.get_min_visit_time
validation
def get_min_visit_time(self): """ Get the earliest visit time of the stop. """ if not self.visit_events: return float('inf') else: return min(self.visit_events, key=lambda event: event.arr_time_ut).arr_time_ut
python
{ "resource": "" }
q257464
SpreadingStop.can_infect
validation
def can_infect(self, event): """ Whether the spreading stop can infect using this event. """ if event.from_stop_I != self.stop_I: return False if not self.has_been_visited(): return False else: time_sep = event.dep_time_ut-self.get_min...
python
{ "resource": "" }
q257465
DayTripsMaterializer.make_views
validation
def make_views(cls, conn): """Create day_trips and day_stop_times views. day_trips: day_trips2 x trips = days x trips day_stop_times: day_trips2 x trips x stop_times = days x trips x stop_times """ conn.execute('DROP VIEW IF EXISTS main.day_trips') conn.execute('CREATE...
python
{ "resource": "" }
q257466
createcolorbar
validation
def createcolorbar(cmap, norm): """Create a colourbar with limits of lwr and upr""" cax, kw = matplotlib.colorbar.make_axes(matplotlib.pyplot.gca()) c = matplotlib.colorbar.ColorbarBase(cax, cmap=cmap, norm=norm) return c
python
{ "resource": "" }
q257467
write_temporal_networks_by_route_type
validation
def write_temporal_networks_by_route_type(gtfs, extract_output_dir): """ Write temporal networks by route type to disk. Parameters ---------- gtfs: gtfspy.GTFS extract_output_dir: str """ util.makedirs(extract_output_dir) for route_type in route_types.TRANSIT_ROUTE_TYPES: pa...
python
{ "resource": "" }
q257468
_write_stop_to_stop_network_edges
validation
def _write_stop_to_stop_network_edges(net, file_name, data=True, fmt=None): """ Write out a network Parameters ---------- net: networkx.DiGraph base_name: str path to the filename (without extension) data: bool, optional whether or not to write out any edge data present ...
python
{ "resource": "" }
q257469
write_gtfs
validation
def write_gtfs(gtfs, output): """ Write out the database according to the GTFS format. Parameters ---------- gtfs: gtfspy.GTFS output: str Path where to put the GTFS files if output ends with ".zip" a ZIP-file is created instead. Returns ------- None """ out...
python
{ "resource": "" }
q257470
_remove_I_columns
validation
def _remove_I_columns(df): """ Remove columns ending with I from a pandas.DataFrame Parameters ---------- df: dataFrame Returns ------- None """ all_columns = list(filter(lambda el: el[-2:] == "_I", df.columns)) for column in all_columns: del df[column]
python
{ "resource": "" }
q257471
ConnectionScanProfiler._scan_footpaths_to_departure_stop
validation
def _scan_footpaths_to_departure_stop(self, connection_dep_stop, connection_dep_time, arrival_time_target): """ A helper method for scanning the footpaths. Updates self._stop_profiles accordingly""" for _, neighbor, data in self._walk_network.edges_iter(nbunch=[connection_dep_stop], ...
python
{ "resource": "" }
q257472
create_file
validation
def create_file(fname=None, fname_tmp=None, tmpdir=None, save_tmpfile=False, keepext=False): """Context manager for making files with possibility of failure. If you are creating a file, it is possible that the code will fail and leave a corrupt intermediate file. This is especially damagin...
python
{ "resource": "" }
q257473
execute
validation
def execute(cur, *args): """Utility function to print sqlite queries before executing. Use instead of cur.execute(). First argument is cursor. cur.execute(stmt) becomes util.execute(cur, stmt) """ stmt = args[0] if len(args) > 1: stmt = stmt.replace('%', '%%').replace('?', '%r...
python
{ "resource": "" }
q257474
makedirs
validation
def makedirs(path): """ Create directories if they do not exist, otherwise do nothing. Return path for convenience """ if not os.path.isdir(path): os.makedirs(path) return path
python
{ "resource": "" }
q257475
MultiObjectivePseudoCSAProfiler._finalize_profiles
validation
def _finalize_profiles(self): """ Deal with the first walks by joining profiles to other stops within walking distance. """ for stop, stop_profile in self._stop_profiles.items(): assert (isinstance(stop_profile, NodeProfileMultiObjective)) neighbor_label_bags = []...
python
{ "resource": "" }
q257476
validate_day_start_ut
validation
def validate_day_start_ut(conn): """This validates the day_start_ut of the days table.""" G = GTFS(conn) cur = conn.execute('SELECT date, day_start_ut FROM days') for date, day_start_ut in cur: #print date, day_start_ut assert day_start_ut == G.get_day_start_ut(date)
python
{ "resource": "" }
q257477
main_make_views
validation
def main_make_views(gtfs_fname): """Re-create all views. """ print("creating views") conn = GTFS(fname_or_conn=gtfs_fname).conn for L in Loaders: L(None).make_views(conn) conn.commit()
python
{ "resource": "" }
q257478
ImportValidator._validate_no_null_values
validation
def _validate_no_null_values(self): """ Loads the tables from the gtfs object and counts the number of rows that have null values in fields that should not be null. Stores the number of null rows in warnings_container """ for table in DB_TABLE_NAMES: null_not_ok_warni...
python
{ "resource": "" }
q257479
ImportValidator._validate_danglers
validation
def _validate_danglers(self): """ Checks for rows that are not referenced in the the tables that should be linked stops <> stop_times using stop_I stop_times <> trips <> days, using trip_I trips <> routes, using route_I :return: """ for query, warning in ...
python
{ "resource": "" }
q257480
print_coords
validation
def print_coords(rows, prefix=''): """Print coordinates within a sequence. This is only used for debugging. Printed in a form that can be pasted into Python for visualization.""" lat = [row['lat'] for row in rows] lon = [row['lon'] for row in rows] print('COORDS'+'-' * 5) print("%slat, %sl...
python
{ "resource": "" }
q257481
find_segments
validation
def find_segments(stops, shape): """Find corresponding shape points for a list of stops and create shape break points. Parameters ---------- stops: stop-sequence (list) List of stop points shape: list of shape points shape-sequence of shape points Returns ------- break_...
python
{ "resource": "" }
q257482
return_segments
validation
def return_segments(shape, break_points): """Break a shape into segments between stops using break_points. This function can use the `break_points` outputs from `find_segments`, and cuts the shape-sequence into pieces corresponding to each stop. """ # print 'xxx' # print stops # print s...
python
{ "resource": "" }
q257483
get_trip_points
validation
def get_trip_points(cur, route_id, offset=0, tripid_glob=''): """Get all scheduled stops on a particular route_id. Given a route_id, return the trip-stop-list with latitude/longitudes. This is a bit more tricky than it seems, because we have to go from table route->trips->stop_times. This functio...
python
{ "resource": "" }
q257484
interpolate_shape_times
validation
def interpolate_shape_times(shape_distances, shape_breaks, stop_times): """ Interpolate passage times for shape points. Parameters ---------- shape_distances: list list of cumulative distances along the shape shape_breaks: list list of shape_breaks stop_times: list l...
python
{ "resource": "" }
q257485
NodeProfileSimple.evaluate_earliest_arrival_time_at_target
validation
def evaluate_earliest_arrival_time_at_target(self, dep_time, transfer_margin): """ Get the earliest arrival time at the target, given a departure time. Parameters ---------- dep_time : float, int time in unix seconds transfer_margin: float, int tr...
python
{ "resource": "" }
q257486
Spreader._run
validation
def _run(self): """ Run the actual simulation. """ if self._has_run: raise RuntimeError("This spreader instance has already been run: " "create a new Spreader object for a new run.") i = 1 while self.event_heap.size() > 0 and len...
python
{ "resource": "" }
q257487
add_walk_distances_to_db_python
validation
def add_walk_distances_to_db_python(gtfs, osm_path, cutoff_distance_m=1000): """ Computes the walk paths between stops, and updates these to the gtfs database. Parameters ---------- gtfs: gtfspy.GTFS or str A GTFS object or a string representation. osm_path: str path to the Open...
python
{ "resource": "" }
q257488
stop_to_stop_network_for_route_type
validation
def stop_to_stop_network_for_route_type(gtfs, route_type, link_attributes=None, start_time_ut=None, end_time_ut=None): """ Get a stop-to-stop network de...
python
{ "resource": "" }
q257489
combined_stop_to_stop_transit_network
validation
def combined_stop_to_stop_transit_network(gtfs, start_time_ut=None, end_time_ut=None): """ Compute stop-to-stop networks for all travel modes and combine them into a single network. The modes of transport are encoded to a single network. The network consists of multiple links corresponding to each trave...
python
{ "resource": "" }
q257490
temporal_network
validation
def temporal_network(gtfs, start_time_ut=None, end_time_ut=None, route_type=None): """ Compute the temporal network of the data, and return it as a pandas.DataFrame Parameters ---------- gtfs : gtfspy.GTFS start_time_ut: int | None ...
python
{ "resource": "" }
q257491
NodeProfileAnalyzerTime.plot_temporal_distance_cdf
validation
def plot_temporal_distance_cdf(self): """ Plot the temporal distance cumulative density function. Returns ------- fig: matplotlib.Figure """ xvalues, cdf = self.profile_block_analyzer._temporal_distance_cdf() fig = plt.figure() ax = fig.add_subplo...
python
{ "resource": "" }
q257492
ForwardJourney.get_transfer_stop_pairs
validation
def get_transfer_stop_pairs(self): """ Get stop pairs through which transfers take place Returns ------- transfer_stop_pairs: list """ transfer_stop_pairs = [] previous_arrival_stop = None current_trip_id = None for leg in self.legs: ...
python
{ "resource": "" }
q257493
GTFS.from_directory_as_inmemory_db
validation
def from_directory_as_inmemory_db(cls, gtfs_directory): """ Instantiate a GTFS object by computing Parameters ---------- gtfs_directory: str path to the directory for importing the database """ # this import is here to avoid circular imports (which tu...
python
{ "resource": "" }
q257494
GTFS.get_main_database_path
validation
def get_main_database_path(self): """ Should return the path to the database Returns ------- path : unicode path to the database, empty string for in-memory databases """ cur = self.conn.cursor() cur.execute("PRAGMA database_list") row...
python
{ "resource": "" }
q257495
GTFS.get_shape_distance_between_stops
validation
def get_shape_distance_between_stops(self, trip_I, from_stop_seq, to_stop_seq): """ Get the distance along a shape between stops Parameters ---------- trip_I : int trip_ID along which we travel from_stop_seq : int the sequence number of the 'origi...
python
{ "resource": "" }
q257496
GTFS.get_timezone_name
validation
def get_timezone_name(self): """ Get name of the GTFS timezone Returns ------- timezone_name : str name of the time zone, e.g. "Europe/Helsinki" """ tz_name = self.conn.execute('SELECT timezone FROM agencies LIMIT 1').fetchone() if tz_name is ...
python
{ "resource": "" }
q257497
GTFS.get_trip_trajectories_within_timespan
validation
def get_trip_trajectories_within_timespan(self, start, end, use_shapes=True, filter_name=None): """ Get complete trip data for visualizing public transport operation based on gtfs. Parameters ---------- start: number Earliest position data to return (in unix time) ...
python
{ "resource": "" }
q257498
GTFS.get_stop_count_data
validation
def get_stop_count_data(self, start_ut, end_ut): """ Get stop count data. Parameters ---------- start_ut : int start time in unixtime end_ut : int end time in unixtime Returns ------- stopData : pandas.DataFrame ...
python
{ "resource": "" }
q257499
GTFS.get_all_route_shapes
validation
def get_all_route_shapes(self, use_shapes=True): """ Get the shapes of all routes. Parameters ---------- use_shapes : bool, optional by default True (i.e. use shapes as the name of the function indicates) if False (fall back to lats and longitudes) ...
python
{ "resource": "" }