idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
31,000
def Plus ( self , other ) : return Point ( self . x + other . x , self . y + other . y , self . z + other . z )
Returns a new point which is the pointwise sum of self and other .
31,001
def Minus ( self , other ) : return Point ( self . x - other . x , self . y - other . y , self . z - other . z )
Returns a new point which is the pointwise subtraction of other from self .
31,002
def Times ( self , val ) : return Point ( self . x * val , self . y * val , self . z * val )
Returns a new point which is pointwise multiplied by val .
31,003
def Ortho ( self ) : ( index , val ) = self . LargestComponent ( ) index = index - 1 if index < 0 : index = 2 temp = Point ( 0.012 , 0.053 , 0.00457 ) if index == 0 : temp . x = 1 elif index == 1 : temp . y = 1 elif index == 2 : temp . z = 1 return self . CrossProd ( temp ) . Normalize ( )
Returns a unit - length point orthogonal to this point
31,004
def CrossProd ( self , other ) : return Point ( self . y * other . z - self . z * other . y , self . z * other . x - self . x * other . z , self . x * other . y - self . y * other . x )
Returns the cross product of self and other .
31,005
def Equals ( self , other ) : return ( self . _approxEq ( self . x , other . x ) and self . _approxEq ( self . y , other . y ) and self . _approxEq ( self . z , other . z ) )
Returns true of self and other are approximately equal .
31,006
def Angle ( self , other ) : return math . atan2 ( self . CrossProd ( other ) . Norm2 ( ) , self . DotProd ( other ) )
Returns the angle in radians between self and other .
31,007
def ToLatLng ( self ) : rad_lat = math . atan2 ( self . z , math . sqrt ( self . x * self . x + self . y * self . y ) ) rad_lng = math . atan2 ( self . y , self . x ) return ( rad_lat * 180.0 / math . pi , rad_lng * 180.0 / math . pi )
Returns that latitude and longitude that this point represents under a spherical Earth model .
31,008
def FromLatLng ( lat , lng ) : phi = lat * ( math . pi / 180.0 ) theta = lng * ( math . pi / 180.0 ) cosphi = math . cos ( phi ) return Point ( math . cos ( theta ) * cosphi , math . sin ( theta ) * cosphi , math . sin ( phi ) )
Returns a new point representing this latitude and longitude under a spherical Earth model .
31,009
def LengthMeters ( self ) : assert ( len ( self . _points ) > 0 ) length = 0 for i in range ( 0 , len ( self . _points ) - 1 ) : length += self . _points [ i ] . GetDistanceMeters ( self . _points [ i + 1 ] ) return length
Return length of this polyline in meters .
31,010
def CutAtClosestPoint ( self , p ) : ( closest , i ) = self . GetClosestPoint ( p ) tmp = [ closest ] tmp . extend ( self . _points [ i + 1 : ] ) return ( Poly ( self . _points [ 0 : i + 1 ] ) , Poly ( tmp ) )
Let x be the point on the polyline closest to p . Then CutAtClosestPoint returns two new polylines one representing the polyline from the beginning up to x and one representing x onwards to the end of the polyline . x is the first point returned in the second polyline .
31,011
def GreedyPolyMatchDist ( self , shape ) : tmp_shape = Poly ( shape . GetPoints ( ) ) max_radius = 0 for ( i , point ) in enumerate ( self . _points ) : tmp_shape = tmp_shape . CutAtClosestPoint ( point ) [ 1 ] dist = tmp_shape . GetPoint ( 0 ) . GetDistanceMeters ( point ) max_radius = max ( max_radius , dist ) return...
Tries a greedy matching algorithm to match self to the given shape . Returns the maximum distance in meters of any point in self to its matched point in shape under the algorithm .
31,012
def AddPoly ( self , poly , smart_duplicate_handling = True ) : inserted_name = poly . GetName ( ) if poly . GetName ( ) in self . _name_to_shape : if not smart_duplicate_handling : raise ShapeError ( "Duplicate shape found: " + poly . GetName ( ) ) print ( "Warning: duplicate shape id being added to collection: " + po...
Adds a new polyline to the collection .
31,013
def FindMatchingPolys ( self , start_point , end_point , max_radius = 150 ) : matches = [ ] for shape in self . _name_to_shape . itervalues ( ) : if start_point . GetDistanceMeters ( shape . GetPoint ( 0 ) ) < max_radius and end_point . GetDistanceMeters ( shape . GetPoint ( - 1 ) ) < max_radius : matches . append ( sh...
Returns a list of polylines in the collection that have endpoints within max_radius of the given start and end points .
31,014
def _ReconstructPath ( self , came_from , current_node ) : if current_node in came_from : ( previous_node , previous_edge ) = came_from [ current_node ] if previous_edge . GetPoint ( 0 ) == current_node : previous_edge = previous_edge . Reversed ( ) p = self . _ReconstructPath ( came_from , previous_node ) return Poly ...
Helper method for ShortestPath to reconstruct path .
31,015
def AddTableColumn ( self , table , column ) : if column not in self . _table_columns [ table ] : self . _table_columns [ table ] . append ( column )
Add column to table if it is not already there .
31,016
def AddTableColumns ( self , table , columns ) : table_columns = self . _table_columns . setdefault ( table , [ ] ) for attr in columns : if attr not in table_columns : table_columns . append ( attr )
Add columns to table if they are not already there .
31,017
def AddAgency ( self , name , url , timezone , agency_id = None ) : agency = self . _gtfs_factory . Agency ( name , url , timezone , agency_id ) self . AddAgencyObject ( agency ) return agency
Adds an agency to this schedule .
31,018
def GetDefaultAgency ( self ) : if not self . _default_agency : if len ( self . _agencies ) == 0 : self . NewDefaultAgency ( ) elif len ( self . _agencies ) == 1 : self . _default_agency = self . _agencies . values ( ) [ 0 ] return self . _default_agency
Return the default Agency . If no default Agency has been set select the default depending on how many Agency objects are in the Schedule . If there are 0 make a new Agency the default if there is 1 it becomes the default if there is more than 1 then return None .
31,019
def NewDefaultAgency ( self , ** kwargs ) : agency = self . _gtfs_factory . Agency ( ** kwargs ) if not agency . agency_id : agency . agency_id = util . FindUniqueId ( self . _agencies ) self . _default_agency = agency self . SetDefaultAgency ( agency , validate = False ) return agency
Create a new Agency object and make it the default agency for this Schedule
31,020
def SetDefaultAgency ( self , agency , validate = True ) : assert isinstance ( agency , self . _gtfs_factory . Agency ) self . _default_agency = agency if agency . agency_id not in self . _agencies : self . AddAgencyObject ( agency , validate = validate )
Make agency the default and add it to the schedule if not already added
31,021
def GetDefaultServicePeriod ( self ) : if not self . _default_service_period : if len ( self . service_periods ) == 0 : self . NewDefaultServicePeriod ( ) elif len ( self . service_periods ) == 1 : self . _default_service_period = self . service_periods . values ( ) [ 0 ] return self . _default_service_period
Return the default ServicePeriod . If no default ServicePeriod has been set select the default depending on how many ServicePeriod objects are in the Schedule . If there are 0 make a new ServicePeriod the default if there is 1 it becomes the default if there is more than 1 then return None .
31,022
def NewDefaultServicePeriod ( self ) : service_period = self . _gtfs_factory . ServicePeriod ( ) service_period . service_id = util . FindUniqueId ( self . service_periods ) self . SetDefaultServicePeriod ( service_period , validate = False ) return service_period
Create a new ServicePeriod object make it the default service period and return it . The default service period is used when you create a trip without providing an explict service period .
31,023
def AddStop ( self , lat , lng , name , stop_id = None ) : if stop_id is None : stop_id = util . FindUniqueId ( self . stops ) stop = self . _gtfs_factory . Stop ( stop_id = stop_id , lat = lat , lng = lng , name = name ) self . AddStopObject ( stop ) return stop
Add a stop to this schedule .
31,024
def AddStopObject ( self , stop , problem_reporter = None ) : assert stop . _schedule is None if not problem_reporter : problem_reporter = self . problem_reporter if not stop . stop_id : return if stop . stop_id in self . stops : problem_reporter . DuplicateID ( 'stop_id' , stop . stop_id ) return stop . _schedule = we...
Add Stop object to this schedule if stop_id is non - blank .
31,025
def AddRoute ( self , short_name , long_name , route_type , route_id = None ) : if route_id is None : route_id = util . FindUniqueId ( self . routes ) route = self . _gtfs_factory . Route ( short_name = short_name , long_name = long_name , route_type = route_type , route_id = route_id ) route . agency_id = self . GetDe...
Add a route to this schedule .
31,026
def AddFareObject ( self , fare , problem_reporter = None ) : warnings . warn ( "No longer supported. The Fare class was renamed to " "FareAttribute, and all related functions were renamed " "accordingly." , DeprecationWarning ) self . AddFareAttributeObject ( fare , problem_reporter )
Deprecated . Please use AddFareAttributeObject .
31,027
def GetNearestStops ( self , lat , lon , n = 1 ) : dist_stop_list = [ ] for s in self . stops . values ( ) : dist = ( s . stop_lat - lat ) ** 2 + ( s . stop_lon - lon ) ** 2 if len ( dist_stop_list ) < n : bisect . insort ( dist_stop_list , ( dist , s ) ) elif dist < dist_stop_list [ - 1 ] [ 0 ] : bisect . insort ( dis...
Return the n nearest stops to lat lon
31,028
def GetStopsInBoundingBox ( self , north , east , south , west , n ) : stop_list = [ ] for s in self . stops . values ( ) : if ( s . stop_lat <= north and s . stop_lat >= south and s . stop_lon <= east and s . stop_lon >= west ) : stop_list . append ( s ) if len ( stop_list ) == n : break return stop_list
Return a sample of up to n stops in a bounding box
31,029
def ValidateFeedStartAndExpirationDates ( self , problems , first_date , last_date , first_date_origin , last_date_origin , today ) : warning_cutoff = today + datetime . timedelta ( days = 60 ) if last_date < warning_cutoff : problems . ExpirationDate ( time . mktime ( last_date . timetuple ( ) ) , last_date_origin ) i...
Validate the start and expiration dates of the feed . Issue a warning if it only starts in the future or if it expires within 60 days .
31,030
def ValidateServiceGaps ( self , problems , validation_start_date , validation_end_date , service_gap_interval ) : if service_gap_interval is None : return departures = self . GenerateDateTripsDeparturesList ( validation_start_date , validation_end_date ) first_day_without_service = validation_start_date last_day_witho...
Validate consecutive dates without service in the feed . Issue a warning if it finds service gaps of at least service_gap_interval consecutive days in the date range [ validation_start_date last_service_date )
31,031
def ValidateStopTimesForTrip ( self , problems , trip , stop_times ) : prev_departure_secs = - 1 consecutive_stop_times_with_potentially_same_time = 0 consecutive_stop_times_with_fully_specified_same_time = 0 def CheckSameTimeCount ( ) : if ( prev_departure_secs != - 1 and consecutive_stop_times_with_fully_specified_sa...
Checks for the stop times of a trip .
31,032
def Draw ( self , stoplist = None , triplist = None , height = 520 ) : output = str ( ) if not triplist : triplist = [ ] if not stoplist : stoplist = [ ] if not self . _cache or triplist or stoplist : self . _gheight = height self . _tlist = triplist self . _slist = stoplist self . _decorators = [ ] self . _stations = ...
Main interface for drawing the marey graph .
31,033
def _BuildStations ( self , stoplist ) : stations = [ ] dists = self . _EuclidianDistances ( stoplist ) stations = self . _CalculateYLines ( dists ) return stations
Dispatches the best algorithm for calculating station line position .
31,034
def _EuclidianDistances ( self , slist ) : e_dists2 = [ transitfeed . ApproximateDistanceBetweenStops ( stop , tail ) for ( stop , tail ) in itertools . izip ( slist , slist [ 1 : ] ) ] return e_dists2
Calculate euclidian distances between stops .
31,035
def _CalculateYLines ( self , dists ) : tot_dist = sum ( dists ) if tot_dist > 0 : pixel_dist = [ float ( d * ( self . _gheight - 20 ) ) / tot_dist for d in dists ] pixel_grid = [ 0 ] + [ int ( pd + sum ( pixel_dist [ 0 : i ] ) ) for i , pd in enumerate ( pixel_dist ) ] else : pixel_grid = [ ] return pixel_grid
Builds a list with y - coordinates for the horizontal lines in the graph .
31,036
def _TravelTimes ( self , triplist , index = 0 ) : def DistanceInTravelTime ( dep_secs , arr_secs ) : t_dist = arr_secs - dep_secs if t_dist < 0 : t_dist = self . _DUMMY_SEPARATOR return t_dist if not triplist : return [ ] if 0 < index < len ( triplist ) : trip = triplist [ index ] else : trip = triplist [ 0 ] t_dists2...
Calculate distances and plot stops .
31,037
def _DrawTrips ( self , triplist , colpar = "" ) : stations = [ ] if not self . _stations and triplist : self . _stations = self . _CalculateYLines ( self . _TravelTimes ( triplist ) ) if not self . _stations : self . _AddWarning ( "Failed to use traveltimes for graph" ) self . _stations = self . _CalculateYLines ( sel...
Generates svg polylines for each transit trip .
31,038
def _Uniform ( self , triplist ) : longest = max ( [ len ( t . GetTimeStops ( ) ) for t in triplist ] ) return [ 100 ] * longest
Fallback to assuming uniform distance between stations
31,039
def _DrawHours ( self ) : tmpstrs = [ ] for i in range ( 0 , self . _gwidth , self . _min_grid ) : if i % self . _hour_grid == 0 : tmpstrs . append ( '<polyline class="FullHour" points="%d,%d, %d,%d" />' % ( i + .5 + 20 , 20 , i + .5 + 20 , self . _gheight ) ) tmpstrs . append ( '<text class="Label" x="%d" y="%d">%d</t...
Generates svg to show a vertical hour and sub - hour grid
31,040
def AddStationDecoration ( self , index , color = "#f00" ) : tmpstr = str ( ) num_stations = len ( self . _stations ) ind = int ( index ) if self . _stations : if 0 < ind < num_stations : y = self . _stations [ ind ] tmpstr = '<polyline class="Dec" stroke="%s" points="%s,%s,%s,%s" />' % ( color , 20 , 20 + y + .5 , sel...
Flushes existing decorations and highlights the given station - line .
31,041
def AddTripDecoration ( self , triplist , color = "#f00" ) : tmpstr = self . _DrawTrips ( triplist , color ) self . _decorators . append ( tmpstr )
Flushes existing decorations and highlights the given trips .
31,042
def ChangeScaleFactor ( self , newfactor ) : if float ( newfactor ) > 0 and float ( newfactor ) < self . _MAX_ZOOM : self . _zoomfactor = newfactor
Changes the zoom of the graph manually .
31,043
def _CreateFolder ( self , parent , name , visible = True , description = None ) : folder = ET . SubElement ( parent , 'Folder' ) name_tag = ET . SubElement ( folder , 'name' ) name_tag . text = name if description is not None : desc_tag = ET . SubElement ( folder , 'description' ) desc_tag . text = description if not ...
Create a KML Folder element .
31,044
def _CreateStyleForRoute ( self , doc , route ) : style_id = 'route_%s' % route . route_id style = ET . SubElement ( doc , 'Style' , { 'id' : style_id } ) linestyle = ET . SubElement ( style , 'LineStyle' ) width = ET . SubElement ( linestyle , 'width' ) type_to_width = { 0 : '3' , 1 : '3' , 2 : '5' , 3 : '1' } width ....
Create a KML Style element for the route .
31,045
def _CreatePlacemark ( self , parent , name , style_id = None , visible = True , description = None ) : placemark = ET . SubElement ( parent , 'Placemark' ) placemark_name = ET . SubElement ( placemark , 'name' ) placemark_name . text = name if description is not None : desc_tag = ET . SubElement ( placemark , 'descrip...
Create a KML Placemark element .
31,046
def _CreateLineString ( self , parent , coordinate_list ) : if not coordinate_list : return None linestring = ET . SubElement ( parent , 'LineString' ) tessellate = ET . SubElement ( linestring , 'tessellate' ) tessellate . text = '1' if len ( coordinate_list [ 0 ] ) == 3 : altitude_mode = ET . SubElement ( linestring ...
Create a KML LineString element .
31,047
def _CreateLineStringForShape ( self , parent , shape ) : coordinate_list = [ ( longitude , latitude ) for ( latitude , longitude , distance ) in shape . points ] return self . _CreateLineString ( parent , coordinate_list )
Create a KML LineString using coordinates from a shape .
31,048
def _CreateStopsFolder ( self , schedule , doc ) : if not schedule . GetStopList ( ) : return None stop_folder = self . _CreateFolder ( doc , 'Stops' ) stop_folder_selection = self . _StopFolderSelectionMethod ( stop_folder ) stop_style_selection = self . _StopStyleSelectionMethod ( doc ) stops = list ( schedule . GetS...
Create a KML Folder containing placemarks for each stop in the schedule .
31,049
def _StopFolderSelectionMethod ( self , stop_folder ) : if not self . show_stop_hierarchy : return lambda stop : ( stop_folder , None ) station_folder = self . _CreateFolder ( stop_folder , 'Stations' ) platform_folder = self . _CreateFolder ( stop_folder , 'Platforms' ) platform_connections = self . _CreateFolder ( pl...
Create a method to determine which KML folder a stop should go in .
31,050
def _StopStyleSelectionMethod ( self , doc ) : if not self . show_stop_hierarchy : return lambda stop : ( None , None ) self . _CreateStyle ( doc , 'stop_entrance' , { 'IconStyle' : { 'color' : 'ff0000ff' } } ) self . _CreateStyle ( doc , 'entrance_connection' , { 'LineStyle' : { 'color' : 'ff0000ff' , 'width' : '2' } ...
Create a method to determine which style to apply to a stop placemark .
31,051
def _CreateRoutePatternsFolder ( self , parent , route , style_id = None , visible = True ) : pattern_id_to_trips = route . GetPatternIdTripDict ( ) if not pattern_id_to_trips : return None pattern_trips = pattern_id_to_trips . values ( ) pattern_trips . sort ( lambda a , b : cmp ( len ( b ) , len ( a ) ) ) folder = se...
Create a KML Folder containing placemarks for each pattern in the route .
31,052
def _CreateRouteShapesFolder ( self , schedule , parent , route , style_id = None , visible = True ) : shape_id_to_trips = { } for trip in route . trips : if trip . shape_id : shape_id_to_trips . setdefault ( trip . shape_id , [ ] ) . append ( trip ) if not shape_id_to_trips : return None shape_id_to_trips_items = shap...
Create a KML Folder for the shapes of a route .
31,053
def _CreateRouteTripsFolder ( self , parent , route , style_id = None , schedule = None ) : if not route . trips : return None trips = list ( route . trips ) trips . sort ( key = lambda x : x . trip_id ) trips_folder = self . _CreateFolder ( parent , 'Trips' , visible = False ) for trip in trips : if ( self . date_filt...
Create a KML Folder containing all the trips in the route .
31,054
def _CreateRoutesFolder ( self , schedule , doc , route_type = None ) : def GetRouteName ( route ) : name_parts = [ ] if route . route_short_name : name_parts . append ( '<b>%s</b>' % route . route_short_name ) if route . route_long_name : name_parts . append ( route . route_long_name ) return ' - ' . join ( name_parts...
Create a KML Folder containing routes in a schedule .
31,055
def _CreateShapesFolder ( self , schedule , doc ) : if not schedule . GetShapeList ( ) : return None shapes_folder = self . _CreateFolder ( doc , 'Shapes' ) shapes = list ( schedule . GetShapeList ( ) ) shapes . sort ( key = lambda x : x . shape_id ) for shape in shapes : placemark = self . _CreatePlacemark ( shapes_fo...
Create a KML Folder containing all the shapes in a schedule .
31,056
def _CreateShapePointFolder ( self , shapes_folder , shape ) : folder_name = shape . shape_id + ' Shape Points' folder = self . _CreateFolder ( shapes_folder , folder_name , visible = False ) for ( index , ( lat , lon , dist ) ) in enumerate ( shape . points ) : placemark = self . _CreatePlacemark ( folder , str ( inde...
Create a KML Folder containing all the shape points in a shape .
31,057
def Write ( self , schedule , output_file ) : root = ET . Element ( 'kml' ) root . attrib [ 'xmlns' ] = 'http://earth.google.com/kml/2.1' doc = ET . SubElement ( root , 'Document' ) open_tag = ET . SubElement ( doc , 'open' ) open_tag . text = '1' self . _CreateStopsFolder ( schedule , doc ) if self . split_routes : ro...
Writes out a feed as KML .
31,058
def RunValidationOutputFromOptions ( feed , options ) : if options . output . upper ( ) == "CONSOLE" : return RunValidationOutputToConsole ( feed , options ) else : return RunValidationOutputToFilename ( feed , options , options . output )
Validate feed output results per options and return an exit code .
31,059
def RunValidationOutputToFilename ( feed , options , output_filename ) : try : output_file = open ( output_filename , 'w' ) exit_code = RunValidationOutputToFile ( feed , options , output_file ) output_file . close ( ) except IOError as e : print ( 'Error while writing %s: %s' % ( output_filename , e ) ) output_filenam...
Validate feed save HTML at output_filename and return an exit code .
31,060
def RunValidationOutputToFile ( feed , options , output_file ) : accumulator = HTMLCountingProblemAccumulator ( options . limit_per_type , options . error_types_ignore_list ) problems = transitfeed . ProblemReporter ( accumulator ) schedule , exit_code = RunValidation ( feed , options , problems ) if isinstance ( feed ...
Validate feed write HTML to output_file and return an exit code .
31,061
def RunValidationOutputToConsole ( feed , options ) : accumulator = CountingConsoleProblemAccumulator ( options . error_types_ignore_list ) problems = transitfeed . ProblemReporter ( accumulator ) _ , exit_code = RunValidation ( feed , options , problems ) return exit_code
Validate feed print reports and return an exit code .
31,062
def RunValidation ( feed , options , problems ) : util . CheckVersion ( problems , options . latest_version ) if options . extension : try : __import__ ( options . extension ) extension_module = sys . modules [ options . extension ] except ImportError : print ( "Could not import extension %s! Please ensure it is a prop...
Validate feed returning the loaded Schedule and exit code .
31,063
def RunValidationFromOptions ( feed , options ) : if options . performance : return ProfileRunValidationOutputFromOptions ( feed , options ) else : return RunValidationOutputFromOptions ( feed , options )
Validate feed run in profiler if in options and return an exit code .
31,064
def ProfileRunValidationOutputFromOptions ( feed , options ) : import cProfile import pstats locals_for_exec = locals ( ) cProfile . runctx ( 'rv = RunValidationOutputFromOptions(feed, options)' , globals ( ) , locals_for_exec , 'validate-stats' ) import resource print ( "Time: %d seconds" % ( resource . getrusage ( re...
Run RunValidationOutputFromOptions print profile and return exit code .
31,065
def FormatType ( self , level_name , class_problist ) : class_problist . sort ( ) output = [ ] for classname , problist in class_problist : output . append ( '<h4 class="issueHeader"><a name="%s%s">%s</a></h4><ul>\n' % ( level_name , classname , UnCamelCase ( classname ) ) ) for e in problist . problems : self . Format...
Write the HTML dumping all problems of one type .
31,066
def FormatTypeSummaryTable ( self , level_name , name_to_problist ) : output = [ ] output . append ( '<table>' ) for classname in sorted ( name_to_problist . keys ( ) ) : problist = name_to_problist [ classname ] human_name = MaybePluralizeWord ( problist . count , UnCamelCase ( classname ) ) output . append ( '<tr><td...
Return an HTML table listing the number of problems by class name .
31,067
def FormatException ( self , e , output ) : d = e . GetDictToFormat ( ) for k in ( 'file_name' , 'feedname' , 'column_name' ) : if k in d . keys ( ) : d [ k ] = '<code>%s</code>' % d [ k ] if 'url' in d . keys ( ) : d [ 'url' ] = '<a href="%(url)s">%(url)s</a>' % d problem_text = e . FormatProblem ( d ) . replace ( '\n...
Append HTML version of e to list output .
31,068
def GetDateRange ( self ) : start = self . start_date end = self . end_date for date , ( exception_type , _ ) in self . date_exceptions . items ( ) : if exception_type == self . _EXCEPTION_TYPE_REMOVE : continue if not start or ( date < start ) : start = date if not end or ( date > end ) : end = date if start is None :...
Return the range over which this ServicePeriod is valid .
31,069
def GetCalendarFieldValuesTuple ( self ) : if self . start_date and self . end_date : return [ getattr ( self , fn ) for fn in self . _FIELD_NAMES ]
Return the tuple of calendar . txt values or None if this ServicePeriod should not be in calendar . txt .
31,070
def GenerateCalendarDatesFieldValuesTuples ( self ) : for date , ( exception_type , _ ) in self . date_exceptions . items ( ) : yield ( self . service_id , date , unicode ( exception_type ) )
Generates tuples of calendar_dates . txt values . Yield zero tuples if this ServicePeriod should not be in calendar_dates . txt .
31,071
def GetCalendarDatesFieldValuesTuples ( self ) : result = [ ] for date_tuple in self . GenerateCalendarDatesFieldValuesTuples ( ) : result . append ( date_tuple ) result . sort ( ) return result
Return a list of date execeptions
31,072
def HasDateExceptionOn ( self , date , exception_type = _EXCEPTION_TYPE_ADD ) : if date in self . date_exceptions : return exception_type == self . date_exceptions [ date ] [ 0 ] return False
Test if this service period has a date exception of the given type .
31,073
def IsActiveOn ( self , date , date_object = None ) : if date in self . date_exceptions : exception_type , _ = self . date_exceptions [ date ] if exception_type == self . _EXCEPTION_TYPE_ADD : return True else : return False if ( self . start_date and self . end_date and self . start_date <= date and date <= self . end...
Test if this service period is active on a date .
31,074
def ActiveDates ( self ) : ( earliest , latest ) = self . GetDateRange ( ) if earliest is None : return [ ] dates = [ ] date_it = util . DateStringToDateObject ( earliest ) date_end = util . DateStringToDateObject ( latest ) delta = datetime . timedelta ( days = 1 ) while date_it <= date_end : date_it_string = date_it ...
Return dates this service period is active as a list of YYYYMMDD .
31,075
def Validate ( self , problems = default_problem_reporter ) : found_problem = False found_problem = ( ( not util . ValidateRequiredFieldsAreNotEmpty ( self , self . _REQUIRED_FIELD_NAMES , problems ) ) or found_problem ) found_problem = self . ValidateAgencyUrl ( problems ) or found_problem found_problem = self . Valid...
Validate attribute values and this object s internal consistency .
31,076
def ConvertCH1903 ( x , y ) : "Converts coordinates from the 1903 Swiss national grid system to WGS-84." yb = ( x - 600000.0 ) / 1e6 xb = ( y - 200000.0 ) / 1e6 lam = 2.6779094 + 4.728982 * yb + 0.791484 * yb * xb + 0.1306 * yb * xb * xb - 0.0436 * yb * yb * yb phi = 16.9023892 + 3.238372 * xb - 0.270978 * yb * yb - 0....
Converts coordinates from the 1903 Swiss national grid system to WGS - 84 .
31,077
def EncodeForCSV ( x ) : "Encodes one value for CSV." k = x . encode ( 'utf-8' ) if ',' in k or '"' in k : return '"%s"' % k . replace ( '"' , '""' ) else : return k
Encodes one value for CSV .
31,078
def WriteRow ( stream , values ) : "Writes one row of comma-separated values to stream." stream . write ( ',' . join ( [ EncodeForCSV ( val ) for val in values ] ) ) stream . write ( '\n' )
Writes one row of comma - separated values to stream .
31,079
def ImportStations ( self , station_file , adv_file ) : "Imports the rec_ort.mdv file." for id , name , x , y , uic_code in ReadCSV ( station_file , [ 'ORT_NR' , 'ORT_NAME' , 'ORT_POS_X' , 'ORT_POS_Y' , 'ORT_NR_NATIONAL' ] ) : station = Station ( ) station . id = id station . position = self . coord_converter ( float (...
Imports the rec_ort . mdv file .
31,080
def ImportRoutes ( self , s ) : "Imports the rec_lin_ber.mdv file." for line_id , name in ReadCSV ( s , [ 'LI_NR' , 'LINIEN_BEZ_DRUCK' ] ) : route = Route ( ) route . id = line_id route . name = name route . color = "FFFFFF" route . color_text = "000000" if name in TRAM_LINES : route . type = TYPE_TRAM route . color = ...
Imports the rec_lin_ber . mdv file .
31,081
def ImportPatterns ( self , s ) : "Imports the lid_verlauf.mdv file." for line , strli , direction , seq , station_id in ReadCSV ( s , [ 'LI_NR' , 'STR_LI_VAR' , 'LI_RI_NR' , 'LI_LFD_NR' , 'ORT_NR' ] ) : pattern_id = u'Pat.%s.%s.%s' % ( line , strli , direction ) pattern = self . patterns . get ( pattern_id , None ) if...
Imports the lid_verlauf . mdv file .
31,082
def ImportBoarding ( self , drop_off_file ) : "Reads the bedverb.mdv file." for trip_id , seq , code in ReadCSV ( drop_off_file , [ 'FRT_FID' , 'LI_LFD_NR' , 'BEDVERB_CODE' ] ) : key = ( trip_id , int ( seq ) - 1 ) if code == 'A' : self . pickup_type [ key ] = '1' elif code == 'E' : self . drop_off_type [ key ] = '1' e...
Reads the bedverb . mdv file .
31,083
def ImportTrafficRestrictions ( self , restrictions_file ) : "Reads the vb_regio.mdv file." ParseDate = lambda x : datetime . date ( int ( x [ : 4 ] ) , int ( x [ 4 : 6 ] ) , int ( x [ 6 : 8 ] ) ) MonthNr = lambda x : int ( x [ : 4 ] ) * 12 + int ( x [ 4 : 6 ] ) for schedule , id , bitmask , start_date , end_date in Re...
Reads the vb_regio . mdv file .
31,084
def ImportStopTimes ( self , stoptimes_file ) : "Imports the lid_fahrzeitart.mdv file." for line , strli , direction , seq , stoptime_id , drive_secs , wait_secs in ReadCSV ( stoptimes_file , [ 'LI_NR' , 'STR_LI_VAR' , 'LI_RI_NR' , 'LI_LFD_NR' , 'FGR_NR' , 'FZT_REL' , 'HZEIT' ] ) : pattern = self . patterns [ u'Pat.%s....
Imports the lid_fahrzeitart . mdv file .
31,085
def ImportTrips ( self , trips_file ) : "Imports the rec_frt.mdv file." for trip_id , trip_starttime , line , strli , direction , stoptime_id , schedule_id , daytype_id , restriction_id , dest_station_id , dest_stop_id , trip_type in ReadCSV ( trips_file , [ 'FRT_FID' , 'FRT_START' , 'LI_NR' , 'STR_LI_VAR' , 'LI_RI_NR'...
Imports the rec_frt . mdv file .
31,086
def Write ( self , outpath ) : "Writes a .zip file in Google Transit format." out = zipfile . ZipFile ( outpath , mode = "w" , compression = zipfile . ZIP_DEFLATED ) for filename , func in [ ( 'agency.txt' , self . WriteAgency ) , ( 'calendar.txt' , self . WriteCalendar ) , ( 'calendar_dates.txt' , self . WriteCalendar...
Writes a . zip file in Google Transit format .
31,087
def TransposeTable ( table ) : transposed = [ ] rows = len ( table ) cols = max ( len ( row ) for row in table ) for x in range ( cols ) : transposed . append ( [ ] ) for y in range ( rows ) : if x < len ( table [ y ] ) : transposed [ x ] . append ( table [ y ] [ x ] ) else : transposed [ x ] . append ( None ) return t...
Transpose a list of lists using None to extend all input lists to the same length .
31,088
def CheckVersion ( problems , latest_version = None ) : if not latest_version : timeout = 20 socket . setdefaulttimeout ( timeout ) request = urllib2 . Request ( LATEST_RELEASE_VERSION_URL ) try : response = urllib2 . urlopen ( request ) content = response . read ( ) m = re . search ( r'version=(\d+\.\d+\.\d+)' , conte...
Check if there is a newer version of transitfeed available .
31,089
def EncodeUnicode ( text ) : if type ( text ) == type ( u'' ) : return text . encode ( OUTPUT_ENCODING ) else : return text
Optionally encode text and return it . The result should be safe to print .
31,090
def ValidateYesNoUnknown ( value , column_name = None , problems = None ) : if IsEmpty ( value ) or IsValidYesNoUnknown ( value ) : return True else : if problems : problems . InvalidValue ( column_name , value ) return False
Validates a value 0 for uknown 1 for yes and 2 for no .
31,091
def FindUniqueId ( dic ) : name = str ( len ( dic ) ) while name in dic : name = str ( random . randint ( 1000000 , 999999999 ) ) return name
Return a string not used as a key in the dictionary dic
31,092
def DateStringToDateObject ( date_string ) : if re . match ( '^\d{8}$' , date_string ) == None : return None try : return datetime . date ( int ( date_string [ 0 : 4 ] ) , int ( date_string [ 4 : 6 ] ) , int ( date_string [ 6 : 8 ] ) ) except ValueError : return None
Return a date object for a string YYYYMMDD .
31,093
def FloatStringToFloat ( float_string , problems = None ) : match = re . match ( r"^[+-]?\d+(\.\d+)?$" , float_string ) parsed_value = float ( float_string ) if "x" in float_string : raise ValueError ( ) if not match and problems is not None : problems . InvalidFloatValue ( float_string ) return parsed_value
Convert a float as a string to a float or raise an exception
31,094
def NonNegIntStringToInt ( int_string , problems = None ) : match = re . match ( r"^(?:0|[1-9]\d*)$" , int_string ) parsed_value = int ( int_string ) if parsed_value < 0 : raise ValueError ( ) elif not match and problems is not None : problems . InvalidNonNegativeIntegerValue ( int_string ) return parsed_value
Convert an non - negative integer string to an int or raise an exception
31,095
def ApproximateDistance ( degree_lat1 , degree_lng1 , degree_lat2 , degree_lng2 ) : lat1 = math . radians ( degree_lat1 ) lng1 = math . radians ( degree_lng1 ) lat2 = math . radians ( degree_lat2 ) lng2 = math . radians ( degree_lng2 ) dlat = math . sin ( 0.5 * ( lat2 - lat1 ) ) dlng = math . sin ( 0.5 * ( lng2 - lng1 ...
Compute approximate distance between two points in meters . Assumes the Earth is a sphere .
31,096
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 )
Compute approximate distance between two stops in meters . Assumes the Earth is a sphere .
31,097
def writerow ( self , row ) : encoded_row = [ ] for s in row : if isinstance ( s , unicode ) : encoded_row . append ( s . encode ( "utf-8" ) ) else : encoded_row . append ( s ) try : self . writer . writerow ( encoded_row ) except Exception as e : print ( 'error writing %s as %s' % ( row , encoded_row ) ) raise e
Write row to the csv file . Any unicode strings in row are encoded as utf - 8 .
31,098
def next ( self ) : try : next_line = next ( self . _f ) except StopIteration : self . _FinalCheck ( ) raise self . _line_number += 1 m_eol = re . search ( r"[\x0a\x0d]*$" , next_line ) if m_eol . group ( ) == "\x0d\x0a" : self . _crlf += 1 if self . _crlf <= 5 : self . _crlf_examples . append ( self . _line_number ) e...
Return next line without end of line marker or raise StopIteration .
31,099
def read_first_available_value ( filename , field_name ) : if not os . path . exists ( filename ) : return None with open ( filename , 'rb' ) as csvfile : reader = csv . DictReader ( csvfile ) for row in reader : value = row . get ( field_name ) if value : return value return None
Reads the first assigned value of the given field in the CSV table .