id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
225,100 | google/transitfeed | transitfeed/util.py | EncodeUnicode | def EncodeUnicode(text):
"""
Optionally encode text and return it. The result should be safe to print.
"""
if type(text) == type(u''):
return text.encode(OUTPUT_ENCODING)
else:
return text | python | def EncodeUnicode(text):
"""
Optionally encode text and return it. The result should be safe to print.
"""
if type(text) == type(u''):
return text.encode(OUTPUT_ENCODING)
else:
return text | [
"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. | [
"Optionally",
"encode",
"text",
"and",
"return",
"it",
".",
"The",
"result",
"should",
"be",
"safe",
"to",
"print",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/util.py#L238-L245 |
225,101 | google/transitfeed | transitfeed/util.py | ValidateYesNoUnknown | def ValidateYesNoUnknown(value, column_name=None, problems=None):
"""Validates a value "0" for uknown, "1" for yes, and "2" for no."""
if IsEmpty(value) or IsValidYesNoUnknown(value):
return True
else:
if problems:
problems.InvalidValue(column_name, value)
return False | python | def ValidateYesNoUnknown(value, column_name=None, problems=None):
"""Validates a value "0" for uknown, "1" for yes, and "2" for no."""
if IsEmpty(value) or IsValidYesNoUnknown(value):
return True
else:
if problems:
problems.InvalidValue(column_name, value)
return False | [
"def",
"ValidateYesNoUnknown",
"(",
"value",
",",
"column_name",
"=",
"None",
",",
"problems",
"=",
"None",
")",
":",
"if",
"IsEmpty",
"(",
"value",
")",
"or",
"IsValidYesNoUnknown",
"(",
"value",
")",
":",
"return",
"True",
"else",
":",
"if",
"problems",
... | Validates a value "0" for uknown, "1" for yes, and "2" for no. | [
"Validates",
"a",
"value",
"0",
"for",
"uknown",
"1",
"for",
"yes",
"and",
"2",
"for",
"no",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/util.py#L437-L444 |
225,102 | google/transitfeed | transitfeed/util.py | FindUniqueId | def FindUniqueId(dic):
"""Return a string not used as a key in the dictionary dic"""
name = str(len(dic))
while name in dic:
# Use bigger numbers so it is obvious when an id is picked randomly.
name = str(random.randint(1000000, 999999999))
return name | python | def FindUniqueId(dic):
"""Return a string not used as a key in the dictionary dic"""
name = str(len(dic))
while name in dic:
# Use bigger numbers so it is obvious when an id is picked randomly.
name = str(random.randint(1000000, 999999999))
return name | [
"def",
"FindUniqueId",
"(",
"dic",
")",
":",
"name",
"=",
"str",
"(",
"len",
"(",
"dic",
")",
")",
"while",
"name",
"in",
"dic",
":",
"# Use bigger numbers so it is obvious when an id is picked randomly.",
"name",
"=",
"str",
"(",
"random",
".",
"randint",
"("... | Return a string not used as a key in the dictionary dic | [
"Return",
"a",
"string",
"not",
"used",
"as",
"a",
"key",
"in",
"the",
"dictionary",
"dic"
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/util.py#L449-L455 |
225,103 | google/transitfeed | transitfeed/util.py | DateStringToDateObject | def DateStringToDateObject(date_string):
"""Return a date object for a string "YYYYMMDD"."""
# If this becomes a bottleneck date objects could be cached
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 | python | def DateStringToDateObject(date_string):
"""Return a date object for a string "YYYYMMDD"."""
# If this becomes a bottleneck date objects could be cached
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 | [
"def",
"DateStringToDateObject",
"(",
"date_string",
")",
":",
"# If this becomes a bottleneck date objects could be cached",
"if",
"re",
".",
"match",
"(",
"'^\\d{8}$'",
",",
"date_string",
")",
"==",
"None",
":",
"return",
"None",
"try",
":",
"return",
"datetime",
... | Return a date object for a string "YYYYMMDD". | [
"Return",
"a",
"date",
"object",
"for",
"a",
"string",
"YYYYMMDD",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/util.py#L473-L482 |
225,104 | google/transitfeed | transitfeed/util.py | FloatStringToFloat | def FloatStringToFloat(float_string, problems=None):
"""Convert a float as a string to a float or raise an exception"""
# Will raise TypeError unless a string
match = re.match(r"^[+-]?\d+(\.\d+)?$", float_string)
# Will raise TypeError if the string can't be parsed
parsed_value = float(float_string)
if "x" in float_string:
# This is needed because Python 2.4 does not complain about float("0x20").
# But it does complain about float("0b10"), so this should be enough.
raise ValueError()
if not match and problems is not None:
# Does not match the regex, but it's a float according to Python
problems.InvalidFloatValue(float_string)
return parsed_value | python | def FloatStringToFloat(float_string, problems=None):
"""Convert a float as a string to a float or raise an exception"""
# Will raise TypeError unless a string
match = re.match(r"^[+-]?\d+(\.\d+)?$", float_string)
# Will raise TypeError if the string can't be parsed
parsed_value = float(float_string)
if "x" in float_string:
# This is needed because Python 2.4 does not complain about float("0x20").
# But it does complain about float("0b10"), so this should be enough.
raise ValueError()
if not match and problems is not None:
# Does not match the regex, but it's a float according to Python
problems.InvalidFloatValue(float_string)
return parsed_value | [
"def",
"FloatStringToFloat",
"(",
"float_string",
",",
"problems",
"=",
"None",
")",
":",
"# Will raise TypeError unless a string",
"match",
"=",
"re",
".",
"match",
"(",
"r\"^[+-]?\\d+(\\.\\d+)?$\"",
",",
"float_string",
")",
"# Will raise TypeError if the string can't be ... | Convert a float as a string to a float or raise an exception | [
"Convert",
"a",
"float",
"as",
"a",
"string",
"to",
"a",
"float",
"or",
"raise",
"an",
"exception"
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/util.py#L484-L499 |
225,105 | google/transitfeed | transitfeed/util.py | NonNegIntStringToInt | def NonNegIntStringToInt(int_string, problems=None):
"""Convert an non-negative integer string to an int or raise an exception"""
# Will raise TypeError unless a string
match = re.match(r"^(?:0|[1-9]\d*)$", int_string)
# Will raise ValueError if the string can't be parsed
parsed_value = int(int_string)
if parsed_value < 0:
raise ValueError()
elif not match and problems is not None:
# Does not match the regex, but it's an int according to Python
problems.InvalidNonNegativeIntegerValue(int_string)
return parsed_value | python | def NonNegIntStringToInt(int_string, problems=None):
"""Convert an non-negative integer string to an int or raise an exception"""
# Will raise TypeError unless a string
match = re.match(r"^(?:0|[1-9]\d*)$", int_string)
# Will raise ValueError if the string can't be parsed
parsed_value = int(int_string)
if parsed_value < 0:
raise ValueError()
elif not match and problems is not None:
# Does not match the regex, but it's an int according to Python
problems.InvalidNonNegativeIntegerValue(int_string)
return parsed_value | [
"def",
"NonNegIntStringToInt",
"(",
"int_string",
",",
"problems",
"=",
"None",
")",
":",
"# Will raise TypeError unless a string",
"match",
"=",
"re",
".",
"match",
"(",
"r\"^(?:0|[1-9]\\d*)$\"",
",",
"int_string",
")",
"# Will raise ValueError if the string can't be parse... | Convert an non-negative integer string to an int or raise an exception | [
"Convert",
"an",
"non",
"-",
"negative",
"integer",
"string",
"to",
"an",
"int",
"or",
"raise",
"an",
"exception"
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/util.py#L501-L514 |
225,106 | google/transitfeed | transitfeed/util.py | ApproximateDistance | def ApproximateDistance(degree_lat1, degree_lng1, degree_lat2, degree_lng2):
"""Compute approximate distance between two points in meters. Assumes the
Earth is a sphere."""
# TODO: change to ellipsoid approximation, such as
# http://www.codeguru.com/Cpp/Cpp/algorithms/article.php/c5115/
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))
x = dlat * dlat + dlng * dlng * math.cos(lat1) * math.cos(lat2)
return EARTH_RADIUS * (2 * math.atan2(math.sqrt(x),
math.sqrt(max(0.0, 1.0 - x)))) | python | def ApproximateDistance(degree_lat1, degree_lng1, degree_lat2, degree_lng2):
"""Compute approximate distance between two points in meters. Assumes the
Earth is a sphere."""
# TODO: change to ellipsoid approximation, such as
# http://www.codeguru.com/Cpp/Cpp/algorithms/article.php/c5115/
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))
x = dlat * dlat + dlng * dlng * math.cos(lat1) * math.cos(lat2)
return EARTH_RADIUS * (2 * math.atan2(math.sqrt(x),
math.sqrt(max(0.0, 1.0 - x)))) | [
"def",
"ApproximateDistance",
"(",
"degree_lat1",
",",
"degree_lng1",
",",
"degree_lat2",
",",
"degree_lng2",
")",
":",
"# TODO: change to ellipsoid approximation, such as",
"# http://www.codeguru.com/Cpp/Cpp/algorithms/article.php/c5115/",
"lat1",
"=",
"math",
".",
"radians",
... | Compute approximate distance between two points in meters. Assumes the
Earth is a sphere. | [
"Compute",
"approximate",
"distance",
"between",
"two",
"points",
"in",
"meters",
".",
"Assumes",
"the",
"Earth",
"is",
"a",
"sphere",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/util.py#L517-L530 |
225,107 | google/transitfeed | transitfeed/util.py | ApproximateDistanceBetweenStops | def ApproximateDistanceBetweenStops(stop1, stop2):
"""Compute approximate distance between two stops in meters. Assumes the
Earth is a sphere."""
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) | python | def ApproximateDistanceBetweenStops(stop1, stop2):
"""Compute approximate distance between two stops in meters. Assumes the
Earth is a sphere."""
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) | [
"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",
... | Compute approximate distance between two stops in meters. Assumes the
Earth is a sphere. | [
"Compute",
"approximate",
"distance",
"between",
"two",
"stops",
"in",
"meters",
".",
"Assumes",
"the",
"Earth",
"is",
"a",
"sphere",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/util.py#L532-L539 |
225,108 | google/transitfeed | transitfeed/util.py | CsvUnicodeWriter.writerow | def writerow(self, row):
"""Write row to the csv file. Any unicode strings in row are encoded as
utf-8."""
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 | python | def writerow(self, row):
"""Write row to the csv file. Any unicode strings in row are encoded as
utf-8."""
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 | [
"def",
"writerow",
"(",
"self",
",",
"row",
")",
":",
"encoded_row",
"=",
"[",
"]",
"for",
"s",
"in",
"row",
":",
"if",
"isinstance",
"(",
"s",
",",
"unicode",
")",
":",
"encoded_row",
".",
"append",
"(",
"s",
".",
"encode",
"(",
"\"utf-8\"",
")",
... | Write row to the csv file. Any unicode strings in row are encoded as
utf-8. | [
"Write",
"row",
"to",
"the",
"csv",
"file",
".",
"Any",
"unicode",
"strings",
"in",
"row",
"are",
"encoded",
"as",
"utf",
"-",
"8",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/util.py#L549-L562 |
225,109 | google/transitfeed | transitfeed/util.py | EndOfLineChecker.next | def next(self):
"""Return next line without end of line marker or raise StopIteration."""
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)
elif m_eol.group() == "\x0a":
self._lf += 1
if self._lf <= 5:
self._lf_examples.append(self._line_number)
elif m_eol.group() == "":
# Should only happen at the end of the file
try:
next(self._f)
raise RuntimeError("Unexpected row without new line sequence")
except StopIteration:
# Will be raised again when EndOfLineChecker.next() is next called
pass
else:
self._problems.InvalidLineEnd(
codecs.getencoder('string_escape')(m_eol.group())[0],
(self._name, self._line_number))
next_line_contents = next_line[0:m_eol.start()]
for seq, name in INVALID_LINE_SEPARATOR_UTF8.items():
if next_line_contents.find(seq) != -1:
self._problems.OtherProblem(
"Line contains %s" % name,
context=(self._name, self._line_number))
return next_line_contents | python | def next(self):
"""Return next line without end of line marker or raise StopIteration."""
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)
elif m_eol.group() == "\x0a":
self._lf += 1
if self._lf <= 5:
self._lf_examples.append(self._line_number)
elif m_eol.group() == "":
# Should only happen at the end of the file
try:
next(self._f)
raise RuntimeError("Unexpected row without new line sequence")
except StopIteration:
# Will be raised again when EndOfLineChecker.next() is next called
pass
else:
self._problems.InvalidLineEnd(
codecs.getencoder('string_escape')(m_eol.group())[0],
(self._name, self._line_number))
next_line_contents = next_line[0:m_eol.start()]
for seq, name in INVALID_LINE_SEPARATOR_UTF8.items():
if next_line_contents.find(seq) != -1:
self._problems.OtherProblem(
"Line contains %s" % name,
context=(self._name, self._line_number))
return next_line_contents | [
"def",
"next",
"(",
"self",
")",
":",
"try",
":",
"next_line",
"=",
"next",
"(",
"self",
".",
"_f",
")",
"except",
"StopIteration",
":",
"self",
".",
"_FinalCheck",
"(",
")",
"raise",
"self",
".",
"_line_number",
"+=",
"1",
"m_eol",
"=",
"re",
".",
... | Return next line without end of line marker or raise StopIteration. | [
"Return",
"next",
"line",
"without",
"end",
"of",
"line",
"marker",
"or",
"raise",
"StopIteration",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/util.py#L610-L646 |
225,110 | google/transitfeed | upgrade_translations.py | read_first_available_value | def read_first_available_value(filename, field_name):
"""Reads the first assigned value of the given field in the CSV table.
"""
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 | python | def read_first_available_value(filename, field_name):
"""Reads the first assigned value of the given field in the CSV table.
"""
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 | [
"def",
"read_first_available_value",
"(",
"filename",
",",
"field_name",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"return",
"None",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"csvfile",
":",
"reade... | Reads the first assigned value of the given field in the CSV table. | [
"Reads",
"the",
"first",
"assigned",
"value",
"of",
"the",
"given",
"field",
"in",
"the",
"CSV",
"table",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/upgrade_translations.py#L162-L173 |
225,111 | google/transitfeed | upgrade_translations.py | OldTranslations._find_feed_language | def _find_feed_language(self):
"""Find feed language based specified feed_info.txt or agency.txt.
"""
self.feed_language = (
read_first_available_value(
os.path.join(self.src_dir, 'feed_info.txt'), 'feed_lang') or
read_first_available_value(
os.path.join(self.src_dir, 'agency.txt'), 'agency_lang'))
if not self.feed_language:
raise Exception(
'Cannot find feed language in feed_info.txt and agency.txt')
print('\tfeed language: %s' % self.feed_language) | python | def _find_feed_language(self):
"""Find feed language based specified feed_info.txt or agency.txt.
"""
self.feed_language = (
read_first_available_value(
os.path.join(self.src_dir, 'feed_info.txt'), 'feed_lang') or
read_first_available_value(
os.path.join(self.src_dir, 'agency.txt'), 'agency_lang'))
if not self.feed_language:
raise Exception(
'Cannot find feed language in feed_info.txt and agency.txt')
print('\tfeed language: %s' % self.feed_language) | [
"def",
"_find_feed_language",
"(",
"self",
")",
":",
"self",
".",
"feed_language",
"=",
"(",
"read_first_available_value",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"src_dir",
",",
"'feed_info.txt'",
")",
",",
"'feed_lang'",
")",
"or",
"read_fir... | Find feed language based specified feed_info.txt or agency.txt. | [
"Find",
"feed",
"language",
"based",
"specified",
"feed_info",
".",
"txt",
"or",
"agency",
".",
"txt",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/upgrade_translations.py#L196-L207 |
225,112 | google/transitfeed | upgrade_translations.py | OldTranslations._read_translations | def _read_translations(self):
"""Read from the old translations.txt.
"""
print('Reading original translations')
self.translations_map = {}
n_translations = 0
with open(os.path.join(self.src_dir, 'translations.txt'),
'rb') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
self.translations_map.setdefault(
row['trans_id'], {})[row['lang']] = row['translation']
n_translations += 1
print('\ttotal original translations: %s' % n_translations) | python | def _read_translations(self):
"""Read from the old translations.txt.
"""
print('Reading original translations')
self.translations_map = {}
n_translations = 0
with open(os.path.join(self.src_dir, 'translations.txt'),
'rb') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
self.translations_map.setdefault(
row['trans_id'], {})[row['lang']] = row['translation']
n_translations += 1
print('\ttotal original translations: %s' % n_translations) | [
"def",
"_read_translations",
"(",
"self",
")",
":",
"print",
"(",
"'Reading original translations'",
")",
"self",
".",
"translations_map",
"=",
"{",
"}",
"n_translations",
"=",
"0",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"sr... | Read from the old translations.txt. | [
"Read",
"from",
"the",
"old",
"translations",
".",
"txt",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/upgrade_translations.py#L209-L222 |
225,113 | google/transitfeed | upgrade_translations.py | OldTranslations._find_context_dependent_names | def _find_context_dependent_names(self):
"""Finds texts whose translation depends on context.
Example.
Here the word "Palacio" is translated from Spanish to English in
multiple ways. Feed language is es (Spanish).
trans_id,lang,translation
stop-name-1,es,Palacio
stop-name-1,en,Palace
headsign-1,es,Palacio
headsign-1,en,To Palace
"""
n_occurences_of_original = {}
for trans_id, translations in self.translations_map.items():
try:
original_name = translations[self.feed_language]
except KeyError:
raise Exception(
'No translation in feed language for %s, available: %s' %
(trans_id, translations))
n_occurences_of_original[original_name] = (
n_occurences_of_original.get(original_name, 0) +
1)
self.context_dependent_names = set(
name
for name, occur in n_occurences_of_original.items()
if occur > 1)
print('Total context-dependent translations: %d' %
len(self.context_dependent_names)) | python | def _find_context_dependent_names(self):
"""Finds texts whose translation depends on context.
Example.
Here the word "Palacio" is translated from Spanish to English in
multiple ways. Feed language is es (Spanish).
trans_id,lang,translation
stop-name-1,es,Palacio
stop-name-1,en,Palace
headsign-1,es,Palacio
headsign-1,en,To Palace
"""
n_occurences_of_original = {}
for trans_id, translations in self.translations_map.items():
try:
original_name = translations[self.feed_language]
except KeyError:
raise Exception(
'No translation in feed language for %s, available: %s' %
(trans_id, translations))
n_occurences_of_original[original_name] = (
n_occurences_of_original.get(original_name, 0) +
1)
self.context_dependent_names = set(
name
for name, occur in n_occurences_of_original.items()
if occur > 1)
print('Total context-dependent translations: %d' %
len(self.context_dependent_names)) | [
"def",
"_find_context_dependent_names",
"(",
"self",
")",
":",
"n_occurences_of_original",
"=",
"{",
"}",
"for",
"trans_id",
",",
"translations",
"in",
"self",
".",
"translations_map",
".",
"items",
"(",
")",
":",
"try",
":",
"original_name",
"=",
"translations"... | Finds texts whose translation depends on context.
Example.
Here the word "Palacio" is translated from Spanish to English in
multiple ways. Feed language is es (Spanish).
trans_id,lang,translation
stop-name-1,es,Palacio
stop-name-1,en,Palace
headsign-1,es,Palacio
headsign-1,en,To Palace | [
"Finds",
"texts",
"whose",
"translation",
"depends",
"on",
"context",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/upgrade_translations.py#L224-L254 |
225,114 | google/transitfeed | upgrade_translations.py | TranslationsConverter.convert_translations | def convert_translations(self, dest_dir):
"""
Converts translations to the new format and stores at dest_dir.
"""
if not os.path.isdir(dest_dir):
os.makedirs(dest_dir)
total_translation_rows = 0
with open(os.path.join(dest_dir, 'translations.txt'),
'w+b') as out_file:
writer = csv.DictWriter(
out_file, fieldnames=NEW_TRANSLATIONS_FIELDS)
writer.writeheader()
for filename in sorted(os.listdir(self.src_dir)):
if not (filename.endswith('.txt') and
os.path.isfile(os.path.join(self.src_dir, filename))):
print('Skipping %s' % filename)
continue
table_name = filename[:-len('.txt')]
if table_name == 'translations':
continue
total_translation_rows += self._translate_table(
dest_dir, table_name, writer)
print('Total translation rows: %s' % total_translation_rows) | python | def convert_translations(self, dest_dir):
"""
Converts translations to the new format and stores at dest_dir.
"""
if not os.path.isdir(dest_dir):
os.makedirs(dest_dir)
total_translation_rows = 0
with open(os.path.join(dest_dir, 'translations.txt'),
'w+b') as out_file:
writer = csv.DictWriter(
out_file, fieldnames=NEW_TRANSLATIONS_FIELDS)
writer.writeheader()
for filename in sorted(os.listdir(self.src_dir)):
if not (filename.endswith('.txt') and
os.path.isfile(os.path.join(self.src_dir, filename))):
print('Skipping %s' % filename)
continue
table_name = filename[:-len('.txt')]
if table_name == 'translations':
continue
total_translation_rows += self._translate_table(
dest_dir, table_name, writer)
print('Total translation rows: %s' % total_translation_rows) | [
"def",
"convert_translations",
"(",
"self",
",",
"dest_dir",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"dest_dir",
")",
":",
"os",
".",
"makedirs",
"(",
"dest_dir",
")",
"total_translation_rows",
"=",
"0",
"with",
"open",
"(",
"os",
... | Converts translations to the new format and stores at dest_dir. | [
"Converts",
"translations",
"to",
"the",
"new",
"format",
"and",
"stores",
"at",
"dest_dir",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/upgrade_translations.py#L264-L286 |
225,115 | google/transitfeed | upgrade_translations.py | TranslationsConverter._translate_table | def _translate_table(self, dest_dir, table_name, translations_writer):
"""
Converts translations to the new format for a single table.
"""
in_filename = os.path.join(self.src_dir, '%s.txt' % table_name)
if not os.path.exists(in_filename):
raise Exception('No %s' % table_name)
out_filename = os.path.join(dest_dir, '%s.txt' % table_name)
with open(in_filename, 'rb') as in_file:
reader = csv.DictReader(in_file)
if not reader.fieldnames or not any_translatable_field(
reader.fieldnames):
print('Copying %s with no translatable columns' % table_name)
shutil.copy(in_filename, out_filename)
return 0
table_translator = TableTranslator(
table_name, reader.fieldnames, self.old_translations,
translations_writer)
with open(out_filename, 'w+b') as out_file:
writer = csv.DictWriter(out_file, fieldnames=reader.fieldnames)
writer.writeheader()
for row in reader:
writer.writerow(table_translator.translate_row(row))
table_translator.write_for_field_values()
print('\ttranslation rows: %s' %
table_translator.total_translation_rows)
return table_translator.total_translation_rows | python | def _translate_table(self, dest_dir, table_name, translations_writer):
"""
Converts translations to the new format for a single table.
"""
in_filename = os.path.join(self.src_dir, '%s.txt' % table_name)
if not os.path.exists(in_filename):
raise Exception('No %s' % table_name)
out_filename = os.path.join(dest_dir, '%s.txt' % table_name)
with open(in_filename, 'rb') as in_file:
reader = csv.DictReader(in_file)
if not reader.fieldnames or not any_translatable_field(
reader.fieldnames):
print('Copying %s with no translatable columns' % table_name)
shutil.copy(in_filename, out_filename)
return 0
table_translator = TableTranslator(
table_name, reader.fieldnames, self.old_translations,
translations_writer)
with open(out_filename, 'w+b') as out_file:
writer = csv.DictWriter(out_file, fieldnames=reader.fieldnames)
writer.writeheader()
for row in reader:
writer.writerow(table_translator.translate_row(row))
table_translator.write_for_field_values()
print('\ttranslation rows: %s' %
table_translator.total_translation_rows)
return table_translator.total_translation_rows | [
"def",
"_translate_table",
"(",
"self",
",",
"dest_dir",
",",
"table_name",
",",
"translations_writer",
")",
":",
"in_filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"src_dir",
",",
"'%s.txt'",
"%",
"table_name",
")",
"if",
"not",
"os",
... | Converts translations to the new format for a single table. | [
"Converts",
"translations",
"to",
"the",
"new",
"format",
"for",
"a",
"single",
"table",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/upgrade_translations.py#L288-L316 |
225,116 | google/transitfeed | transitfeed/loader.py | Loader._DetermineFormat | def _DetermineFormat(self):
"""Determines whether the feed is in a form that we understand, and
if so, returns True."""
if self._zip:
# If zip was passed to __init__ then path isn't used
assert not self._path
return True
if not isinstance(self._path, basestring) and hasattr(self._path, 'read'):
# A file-like object, used for testing with a StringIO file
self._zip = zipfile.ZipFile(self._path, mode='r')
return True
if not os.path.exists(self._path):
self._problems.FeedNotFound(self._path)
return False
if self._path.endswith('.zip'):
try:
self._zip = zipfile.ZipFile(self._path, mode='r')
except IOError: # self._path is a directory
pass
except zipfile.BadZipfile:
self._problems.UnknownFormat(self._path)
return False
if not self._zip and not os.path.isdir(self._path):
self._problems.UnknownFormat(self._path)
return False
return True | python | def _DetermineFormat(self):
"""Determines whether the feed is in a form that we understand, and
if so, returns True."""
if self._zip:
# If zip was passed to __init__ then path isn't used
assert not self._path
return True
if not isinstance(self._path, basestring) and hasattr(self._path, 'read'):
# A file-like object, used for testing with a StringIO file
self._zip = zipfile.ZipFile(self._path, mode='r')
return True
if not os.path.exists(self._path):
self._problems.FeedNotFound(self._path)
return False
if self._path.endswith('.zip'):
try:
self._zip = zipfile.ZipFile(self._path, mode='r')
except IOError: # self._path is a directory
pass
except zipfile.BadZipfile:
self._problems.UnknownFormat(self._path)
return False
if not self._zip and not os.path.isdir(self._path):
self._problems.UnknownFormat(self._path)
return False
return True | [
"def",
"_DetermineFormat",
"(",
"self",
")",
":",
"if",
"self",
".",
"_zip",
":",
"# If zip was passed to __init__ then path isn't used",
"assert",
"not",
"self",
".",
"_path",
"return",
"True",
"if",
"not",
"isinstance",
"(",
"self",
".",
"_path",
",",
"basestr... | Determines whether the feed is in a form that we understand, and
if so, returns True. | [
"Determines",
"whether",
"the",
"feed",
"is",
"in",
"a",
"form",
"that",
"we",
"understand",
"and",
"if",
"so",
"returns",
"True",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/loader.py#L69-L99 |
225,117 | google/transitfeed | transitfeed/loader.py | Loader._GetFileNames | def _GetFileNames(self):
"""Returns a list of file names in the feed."""
if self._zip:
return self._zip.namelist()
else:
return os.listdir(self._path) | python | def _GetFileNames(self):
"""Returns a list of file names in the feed."""
if self._zip:
return self._zip.namelist()
else:
return os.listdir(self._path) | [
"def",
"_GetFileNames",
"(",
"self",
")",
":",
"if",
"self",
".",
"_zip",
":",
"return",
"self",
".",
"_zip",
".",
"namelist",
"(",
")",
"else",
":",
"return",
"os",
".",
"listdir",
"(",
"self",
".",
"_path",
")"
] | Returns a list of file names in the feed. | [
"Returns",
"a",
"list",
"of",
"file",
"names",
"in",
"the",
"feed",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/loader.py#L101-L106 |
225,118 | google/transitfeed | transitfeed/loader.py | Loader._GetUtf8Contents | def _GetUtf8Contents(self, file_name):
"""Check for errors in file_name and return a string for csv reader."""
contents = self._FileContents(file_name)
if not contents: # Missing file
return
# Check for errors that will prevent csv.reader from working
if len(contents) >= 2 and contents[0:2] in (codecs.BOM_UTF16_BE,
codecs.BOM_UTF16_LE):
self._problems.FileFormat("appears to be encoded in utf-16", (file_name, ))
# Convert and continue, so we can find more errors
contents = codecs.getdecoder('utf-16')(contents)[0].encode('utf-8')
null_index = contents.find('\0')
if null_index != -1:
# It is easier to get some surrounding text than calculate the exact
# row_num
m = re.search(r'.{,20}\0.{,20}', contents, re.DOTALL)
self._problems.FileFormat(
"contains a null in text \"%s\" at byte %d" %
(codecs.getencoder('string_escape')(m.group()), null_index + 1),
(file_name, ))
return
# strip out any UTF-8 Byte Order Marker (otherwise it'll be
# treated as part of the first column name, causing a mis-parse)
contents = contents.lstrip(codecs.BOM_UTF8)
return contents | python | def _GetUtf8Contents(self, file_name):
"""Check for errors in file_name and return a string for csv reader."""
contents = self._FileContents(file_name)
if not contents: # Missing file
return
# Check for errors that will prevent csv.reader from working
if len(contents) >= 2 and contents[0:2] in (codecs.BOM_UTF16_BE,
codecs.BOM_UTF16_LE):
self._problems.FileFormat("appears to be encoded in utf-16", (file_name, ))
# Convert and continue, so we can find more errors
contents = codecs.getdecoder('utf-16')(contents)[0].encode('utf-8')
null_index = contents.find('\0')
if null_index != -1:
# It is easier to get some surrounding text than calculate the exact
# row_num
m = re.search(r'.{,20}\0.{,20}', contents, re.DOTALL)
self._problems.FileFormat(
"contains a null in text \"%s\" at byte %d" %
(codecs.getencoder('string_escape')(m.group()), null_index + 1),
(file_name, ))
return
# strip out any UTF-8 Byte Order Marker (otherwise it'll be
# treated as part of the first column name, causing a mis-parse)
contents = contents.lstrip(codecs.BOM_UTF8)
return contents | [
"def",
"_GetUtf8Contents",
"(",
"self",
",",
"file_name",
")",
":",
"contents",
"=",
"self",
".",
"_FileContents",
"(",
"file_name",
")",
"if",
"not",
"contents",
":",
"# Missing file",
"return",
"# Check for errors that will prevent csv.reader from working",
"if",
"l... | Check for errors in file_name and return a string for csv reader. | [
"Check",
"for",
"errors",
"in",
"file_name",
"and",
"return",
"a",
"string",
"for",
"csv",
"reader",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/loader.py#L118-L145 |
225,119 | google/transitfeed | transitfeed/loader.py | Loader._HasFile | def _HasFile(self, file_name):
"""Returns True if there's a file in the current feed with the
given file_name in the current feed."""
if self._zip:
return file_name in self._zip.namelist()
else:
file_path = os.path.join(self._path, file_name)
return os.path.exists(file_path) and os.path.isfile(file_path) | python | def _HasFile(self, file_name):
"""Returns True if there's a file in the current feed with the
given file_name in the current feed."""
if self._zip:
return file_name in self._zip.namelist()
else:
file_path = os.path.join(self._path, file_name)
return os.path.exists(file_path) and os.path.isfile(file_path) | [
"def",
"_HasFile",
"(",
"self",
",",
"file_name",
")",
":",
"if",
"self",
".",
"_zip",
":",
"return",
"file_name",
"in",
"self",
".",
"_zip",
".",
"namelist",
"(",
")",
"else",
":",
"file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
"."... | Returns True if there's a file in the current feed with the
given file_name in the current feed. | [
"Returns",
"True",
"if",
"there",
"s",
"a",
"file",
"in",
"the",
"current",
"feed",
"with",
"the",
"given",
"file_name",
"in",
"the",
"current",
"feed",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/loader.py#L375-L382 |
225,120 | google/transitfeed | transitfeed/route.py | Route.AddTrip | def AddTrip(self, schedule=None, headsign=None, service_period=None,
trip_id=None):
"""Add a trip to this route.
Args:
schedule: a Schedule object which will hold the new trip or None to use
the schedule of this route.
headsign: headsign of the trip as a string
service_period: a ServicePeriod object or None to use
schedule.GetDefaultServicePeriod()
trip_id: optional trip_id for the new trip
Returns:
a new Trip object
"""
if schedule is None:
assert self._schedule is not None
schedule = self._schedule
if trip_id is None:
trip_id = util.FindUniqueId(schedule.trips)
if service_period is None:
service_period = schedule.GetDefaultServicePeriod()
trip_class = self.GetGtfsFactory().Trip
trip_obj = trip_class(route=self, headsign=headsign,
service_period=service_period, trip_id=trip_id)
schedule.AddTripObject(trip_obj)
return trip_obj | python | def AddTrip(self, schedule=None, headsign=None, service_period=None,
trip_id=None):
"""Add a trip to this route.
Args:
schedule: a Schedule object which will hold the new trip or None to use
the schedule of this route.
headsign: headsign of the trip as a string
service_period: a ServicePeriod object or None to use
schedule.GetDefaultServicePeriod()
trip_id: optional trip_id for the new trip
Returns:
a new Trip object
"""
if schedule is None:
assert self._schedule is not None
schedule = self._schedule
if trip_id is None:
trip_id = util.FindUniqueId(schedule.trips)
if service_period is None:
service_period = schedule.GetDefaultServicePeriod()
trip_class = self.GetGtfsFactory().Trip
trip_obj = trip_class(route=self, headsign=headsign,
service_period=service_period, trip_id=trip_id)
schedule.AddTripObject(trip_obj)
return trip_obj | [
"def",
"AddTrip",
"(",
"self",
",",
"schedule",
"=",
"None",
",",
"headsign",
"=",
"None",
",",
"service_period",
"=",
"None",
",",
"trip_id",
"=",
"None",
")",
":",
"if",
"schedule",
"is",
"None",
":",
"assert",
"self",
".",
"_schedule",
"is",
"not",
... | Add a trip to this route.
Args:
schedule: a Schedule object which will hold the new trip or None to use
the schedule of this route.
headsign: headsign of the trip as a string
service_period: a ServicePeriod object or None to use
schedule.GetDefaultServicePeriod()
trip_id: optional trip_id for the new trip
Returns:
a new Trip object | [
"Add",
"a",
"trip",
"to",
"this",
"route",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/route.py#L69-L95 |
225,121 | google/transitfeed | transitfeed/route.py | Route.GetPatternIdTripDict | def GetPatternIdTripDict(self):
"""Return a dictionary that maps pattern_id to a list of Trip objects."""
d = {}
for t in self._trips:
d.setdefault(t.pattern_id, []).append(t)
return d | python | def GetPatternIdTripDict(self):
"""Return a dictionary that maps pattern_id to a list of Trip objects."""
d = {}
for t in self._trips:
d.setdefault(t.pattern_id, []).append(t)
return d | [
"def",
"GetPatternIdTripDict",
"(",
"self",
")",
":",
"d",
"=",
"{",
"}",
"for",
"t",
"in",
"self",
".",
"_trips",
":",
"d",
".",
"setdefault",
"(",
"t",
".",
"pattern_id",
",",
"[",
"]",
")",
".",
"append",
"(",
"t",
")",
"return",
"d"
] | Return a dictionary that maps pattern_id to a list of Trip objects. | [
"Return",
"a",
"dictionary",
"that",
"maps",
"pattern_id",
"to",
"a",
"list",
"of",
"Trip",
"objects",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/route.py#L113-L118 |
225,122 | google/transitfeed | transitfeed/gtfsfactory.py | GtfsFactory.GetGtfsClassByFileName | def GetGtfsClassByFileName(self, filename):
"""Returns the transitfeed class corresponding to a GTFS file.
Args:
filename: The filename whose class is to be returned
Raises:
NonStandardMapping if the specified filename has more than one
corresponding class
"""
if filename not in self._file_mapping:
return None
mapping = self._file_mapping[filename]
class_list = mapping['classes']
if len(class_list) > 1:
raise problems.NonStandardMapping(filename)
else:
return self._class_mapping[class_list[0]] | python | def GetGtfsClassByFileName(self, filename):
"""Returns the transitfeed class corresponding to a GTFS file.
Args:
filename: The filename whose class is to be returned
Raises:
NonStandardMapping if the specified filename has more than one
corresponding class
"""
if filename not in self._file_mapping:
return None
mapping = self._file_mapping[filename]
class_list = mapping['classes']
if len(class_list) > 1:
raise problems.NonStandardMapping(filename)
else:
return self._class_mapping[class_list[0]] | [
"def",
"GetGtfsClassByFileName",
"(",
"self",
",",
"filename",
")",
":",
"if",
"filename",
"not",
"in",
"self",
".",
"_file_mapping",
":",
"return",
"None",
"mapping",
"=",
"self",
".",
"_file_mapping",
"[",
"filename",
"]",
"class_list",
"=",
"mapping",
"["... | Returns the transitfeed class corresponding to a GTFS file.
Args:
filename: The filename whose class is to be returned
Raises:
NonStandardMapping if the specified filename has more than one
corresponding class | [
"Returns",
"the",
"transitfeed",
"class",
"corresponding",
"to",
"a",
"GTFS",
"file",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/gtfsfactory.py#L108-L125 |
225,123 | google/transitfeed | transitfeed/gtfsfactory.py | GtfsFactory.GetLoadingOrder | def GetLoadingOrder(self):
"""Returns a list of filenames sorted by loading order.
Only includes files that Loader's standardized loading knows how to load"""
result = {}
for filename, mapping in self._file_mapping.iteritems():
loading_order = mapping['loading_order']
if loading_order is not None:
result[loading_order] = filename
return list(result[key] for key in sorted(result)) | python | def GetLoadingOrder(self):
"""Returns a list of filenames sorted by loading order.
Only includes files that Loader's standardized loading knows how to load"""
result = {}
for filename, mapping in self._file_mapping.iteritems():
loading_order = mapping['loading_order']
if loading_order is not None:
result[loading_order] = filename
return list(result[key] for key in sorted(result)) | [
"def",
"GetLoadingOrder",
"(",
"self",
")",
":",
"result",
"=",
"{",
"}",
"for",
"filename",
",",
"mapping",
"in",
"self",
".",
"_file_mapping",
".",
"iteritems",
"(",
")",
":",
"loading_order",
"=",
"mapping",
"[",
"'loading_order'",
"]",
"if",
"loading_o... | Returns a list of filenames sorted by loading order.
Only includes files that Loader's standardized loading knows how to load | [
"Returns",
"a",
"list",
"of",
"filenames",
"sorted",
"by",
"loading",
"order",
".",
"Only",
"includes",
"files",
"that",
"Loader",
"s",
"standardized",
"loading",
"knows",
"how",
"to",
"load"
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/gtfsfactory.py#L127-L135 |
225,124 | google/transitfeed | transitfeed/gtfsfactory.py | GtfsFactory.IsFileRequired | def IsFileRequired(self, filename):
"""Returns true if a file is required by GTFS, false otherwise.
Unknown files are, by definition, not required"""
if filename not in self._file_mapping:
return False
mapping = self._file_mapping[filename]
return mapping['required'] | python | def IsFileRequired(self, filename):
"""Returns true if a file is required by GTFS, false otherwise.
Unknown files are, by definition, not required"""
if filename not in self._file_mapping:
return False
mapping = self._file_mapping[filename]
return mapping['required'] | [
"def",
"IsFileRequired",
"(",
"self",
",",
"filename",
")",
":",
"if",
"filename",
"not",
"in",
"self",
".",
"_file_mapping",
":",
"return",
"False",
"mapping",
"=",
"self",
".",
"_file_mapping",
"[",
"filename",
"]",
"return",
"mapping",
"[",
"'required'",
... | Returns true if a file is required by GTFS, false otherwise.
Unknown files are, by definition, not required | [
"Returns",
"true",
"if",
"a",
"file",
"is",
"required",
"by",
"GTFS",
"false",
"otherwise",
".",
"Unknown",
"files",
"are",
"by",
"definition",
"not",
"required"
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/gtfsfactory.py#L137-L143 |
225,125 | google/transitfeed | transitfeed/gtfsfactory.py | GtfsFactory.AddMapping | def AddMapping(self, filename, new_mapping):
"""Adds an entry to the list of known filenames.
Args:
filename: The filename whose mapping is being added.
new_mapping: A dictionary with the mapping to add. Must contain all
fields in _REQUIRED_MAPPING_FIELDS.
Raises:
DuplicateMapping if the filename already exists in the mapping
InvalidMapping if not all required fields are present
"""
for field in self._REQUIRED_MAPPING_FIELDS:
if field not in new_mapping:
raise problems.InvalidMapping(field)
if filename in self.GetKnownFilenames():
raise problems.DuplicateMapping(filename)
self._file_mapping[filename] = new_mapping | python | def AddMapping(self, filename, new_mapping):
"""Adds an entry to the list of known filenames.
Args:
filename: The filename whose mapping is being added.
new_mapping: A dictionary with the mapping to add. Must contain all
fields in _REQUIRED_MAPPING_FIELDS.
Raises:
DuplicateMapping if the filename already exists in the mapping
InvalidMapping if not all required fields are present
"""
for field in self._REQUIRED_MAPPING_FIELDS:
if field not in new_mapping:
raise problems.InvalidMapping(field)
if filename in self.GetKnownFilenames():
raise problems.DuplicateMapping(filename)
self._file_mapping[filename] = new_mapping | [
"def",
"AddMapping",
"(",
"self",
",",
"filename",
",",
"new_mapping",
")",
":",
"for",
"field",
"in",
"self",
".",
"_REQUIRED_MAPPING_FIELDS",
":",
"if",
"field",
"not",
"in",
"new_mapping",
":",
"raise",
"problems",
".",
"InvalidMapping",
"(",
"field",
")"... | Adds an entry to the list of known filenames.
Args:
filename: The filename whose mapping is being added.
new_mapping: A dictionary with the mapping to add. Must contain all
fields in _REQUIRED_MAPPING_FIELDS.
Raises:
DuplicateMapping if the filename already exists in the mapping
InvalidMapping if not all required fields are present | [
"Adds",
"an",
"entry",
"to",
"the",
"list",
"of",
"known",
"filenames",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/gtfsfactory.py#L158-L174 |
225,126 | google/transitfeed | transitfeed/gtfsfactory.py | GtfsFactory.UpdateMapping | def UpdateMapping(self, filename, mapping_update):
"""Updates an entry in the list of known filenames.
An entry is identified by its filename.
Args:
filename: The filename whose mapping is to be updated
mapping_update: A dictionary containing the fields to update and their
new values.
Raises:
InexistentMapping if the filename does not exist in the mapping
"""
if filename not in self._file_mapping:
raise problems.NonexistentMapping(filename)
mapping = self._file_mapping[filename]
mapping.update(mapping_update) | python | def UpdateMapping(self, filename, mapping_update):
"""Updates an entry in the list of known filenames.
An entry is identified by its filename.
Args:
filename: The filename whose mapping is to be updated
mapping_update: A dictionary containing the fields to update and their
new values.
Raises:
InexistentMapping if the filename does not exist in the mapping
"""
if filename not in self._file_mapping:
raise problems.NonexistentMapping(filename)
mapping = self._file_mapping[filename]
mapping.update(mapping_update) | [
"def",
"UpdateMapping",
"(",
"self",
",",
"filename",
",",
"mapping_update",
")",
":",
"if",
"filename",
"not",
"in",
"self",
".",
"_file_mapping",
":",
"raise",
"problems",
".",
"NonexistentMapping",
"(",
"filename",
")",
"mapping",
"=",
"self",
".",
"_file... | Updates an entry in the list of known filenames.
An entry is identified by its filename.
Args:
filename: The filename whose mapping is to be updated
mapping_update: A dictionary containing the fields to update and their
new values.
Raises:
InexistentMapping if the filename does not exist in the mapping | [
"Updates",
"an",
"entry",
"in",
"the",
"list",
"of",
"known",
"filenames",
".",
"An",
"entry",
"is",
"identified",
"by",
"its",
"filename",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/gtfsfactory.py#L176-L190 |
225,127 | google/transitfeed | transitfeed/gtfsfactory.py | GtfsFactory.AddClass | def AddClass(self, class_name, gtfs_class):
"""Adds an entry to the list of known classes.
Args:
class_name: A string with name through which gtfs_class is to be made
accessible.
gtfs_class: The class to be added.
Raises:
DuplicateMapping if class_name is already present in the class mapping.
"""
if class_name in self._class_mapping:
raise problems.DuplicateMapping(class_name)
self._class_mapping[class_name] = gtfs_class | python | def AddClass(self, class_name, gtfs_class):
"""Adds an entry to the list of known classes.
Args:
class_name: A string with name through which gtfs_class is to be made
accessible.
gtfs_class: The class to be added.
Raises:
DuplicateMapping if class_name is already present in the class mapping.
"""
if class_name in self._class_mapping:
raise problems.DuplicateMapping(class_name)
self._class_mapping[class_name] = gtfs_class | [
"def",
"AddClass",
"(",
"self",
",",
"class_name",
",",
"gtfs_class",
")",
":",
"if",
"class_name",
"in",
"self",
".",
"_class_mapping",
":",
"raise",
"problems",
".",
"DuplicateMapping",
"(",
"class_name",
")",
"self",
".",
"_class_mapping",
"[",
"class_name"... | Adds an entry to the list of known classes.
Args:
class_name: A string with name through which gtfs_class is to be made
accessible.
gtfs_class: The class to be added.
Raises:
DuplicateMapping if class_name is already present in the class mapping. | [
"Adds",
"an",
"entry",
"to",
"the",
"list",
"of",
"known",
"classes",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/gtfsfactory.py#L192-L204 |
225,128 | google/transitfeed | transitfeed/gtfsfactory.py | GtfsFactory.UpdateClass | def UpdateClass(self, class_name, gtfs_class):
"""Updates an entry in the list of known classes.
Args:
class_name: A string with the class name that is to be updated.
gtfs_class: The new class
Raises:
NonexistentMapping if there is no class with the specified class_name.
"""
if class_name not in self._class_mapping:
raise problems.NonexistentMapping(class_name)
self._class_mapping[class_name] = gtfs_class | python | def UpdateClass(self, class_name, gtfs_class):
"""Updates an entry in the list of known classes.
Args:
class_name: A string with the class name that is to be updated.
gtfs_class: The new class
Raises:
NonexistentMapping if there is no class with the specified class_name.
"""
if class_name not in self._class_mapping:
raise problems.NonexistentMapping(class_name)
self._class_mapping[class_name] = gtfs_class | [
"def",
"UpdateClass",
"(",
"self",
",",
"class_name",
",",
"gtfs_class",
")",
":",
"if",
"class_name",
"not",
"in",
"self",
".",
"_class_mapping",
":",
"raise",
"problems",
".",
"NonexistentMapping",
"(",
"class_name",
")",
"self",
".",
"_class_mapping",
"[",
... | Updates an entry in the list of known classes.
Args:
class_name: A string with the class name that is to be updated.
gtfs_class: The new class
Raises:
NonexistentMapping if there is no class with the specified class_name. | [
"Updates",
"an",
"entry",
"in",
"the",
"list",
"of",
"known",
"classes",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/gtfsfactory.py#L206-L217 |
225,129 | google/transitfeed | transitfeed/gtfsfactory.py | GtfsFactory.RemoveClass | def RemoveClass(self, class_name):
"""Removes an entry from the list of known classes.
Args:
class_name: A string with the class name that is to be removed.
Raises:
NonexistentMapping if there is no class with the specified class_name.
"""
if class_name not in self._class_mapping:
raise problems.NonexistentMapping(class_name)
del self._class_mapping[class_name] | python | def RemoveClass(self, class_name):
"""Removes an entry from the list of known classes.
Args:
class_name: A string with the class name that is to be removed.
Raises:
NonexistentMapping if there is no class with the specified class_name.
"""
if class_name not in self._class_mapping:
raise problems.NonexistentMapping(class_name)
del self._class_mapping[class_name] | [
"def",
"RemoveClass",
"(",
"self",
",",
"class_name",
")",
":",
"if",
"class_name",
"not",
"in",
"self",
".",
"_class_mapping",
":",
"raise",
"problems",
".",
"NonexistentMapping",
"(",
"class_name",
")",
"del",
"self",
".",
"_class_mapping",
"[",
"class_name"... | Removes an entry from the list of known classes.
Args:
class_name: A string with the class name that is to be removed.
Raises:
NonexistentMapping if there is no class with the specified class_name. | [
"Removes",
"an",
"entry",
"from",
"the",
"list",
"of",
"known",
"classes",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/gtfsfactory.py#L219-L229 |
225,130 | google/transitfeed | kmlparser.py | KmlParser.Parse | def Parse(self, filename, feed):
"""
Reads the kml file, parses it and updated the Google transit feed
object with the extracted information.
Args:
filename - kml file name
feed - an instance of Schedule class to be updated
"""
dom = minidom.parse(filename)
self.ParseDom(dom, feed) | python | def Parse(self, filename, feed):
"""
Reads the kml file, parses it and updated the Google transit feed
object with the extracted information.
Args:
filename - kml file name
feed - an instance of Schedule class to be updated
"""
dom = minidom.parse(filename)
self.ParseDom(dom, feed) | [
"def",
"Parse",
"(",
"self",
",",
"filename",
",",
"feed",
")",
":",
"dom",
"=",
"minidom",
".",
"parse",
"(",
"filename",
")",
"self",
".",
"ParseDom",
"(",
"dom",
",",
"feed",
")"
] | Reads the kml file, parses it and updated the Google transit feed
object with the extracted information.
Args:
filename - kml file name
feed - an instance of Schedule class to be updated | [
"Reads",
"the",
"kml",
"file",
"parses",
"it",
"and",
"updated",
"the",
"Google",
"transit",
"feed",
"object",
"with",
"the",
"extracted",
"information",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/kmlparser.py#L61-L71 |
225,131 | google/transitfeed | kmlparser.py | KmlParser.ParseDom | def ParseDom(self, dom, feed):
"""
Parses the given kml dom tree and updates the Google transit feed object.
Args:
dom - kml dom tree
feed - an instance of Schedule class to be updated
"""
shape_num = 0
for node in dom.getElementsByTagName('Placemark'):
p = self.ParsePlacemark(node)
if p.IsPoint():
(lon, lat) = p.coordinates[0]
m = self.stopNameRe.search(p.name)
feed.AddStop(lat, lon, m.group(1))
elif p.IsLine():
self.ConvertPlacemarkToShape(p, feed) | python | def ParseDom(self, dom, feed):
"""
Parses the given kml dom tree and updates the Google transit feed object.
Args:
dom - kml dom tree
feed - an instance of Schedule class to be updated
"""
shape_num = 0
for node in dom.getElementsByTagName('Placemark'):
p = self.ParsePlacemark(node)
if p.IsPoint():
(lon, lat) = p.coordinates[0]
m = self.stopNameRe.search(p.name)
feed.AddStop(lat, lon, m.group(1))
elif p.IsLine():
self.ConvertPlacemarkToShape(p, feed) | [
"def",
"ParseDom",
"(",
"self",
",",
"dom",
",",
"feed",
")",
":",
"shape_num",
"=",
"0",
"for",
"node",
"in",
"dom",
".",
"getElementsByTagName",
"(",
"'Placemark'",
")",
":",
"p",
"=",
"self",
".",
"ParsePlacemark",
"(",
"node",
")",
"if",
"p",
"."... | Parses the given kml dom tree and updates the Google transit feed object.
Args:
dom - kml dom tree
feed - an instance of Schedule class to be updated | [
"Parses",
"the",
"given",
"kml",
"dom",
"tree",
"and",
"updates",
"the",
"Google",
"transit",
"feed",
"object",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/kmlparser.py#L73-L89 |
225,132 | google/transitfeed | examples/google_random_queries.py | Distance | def Distance(lat0, lng0, lat1, lng1):
"""
Compute the geodesic distance in meters between two points on the
surface of the Earth. The latitude and longitude angles are in
degrees.
Approximate geodesic distance function (Haversine Formula) assuming
a perfect sphere of radius 6367 km (see "What are some algorithms
for calculating the distance between 2 points?" in the GIS Faq at
http://www.census.gov/geo/www/faq-index.html). The approximate
radius is adequate for our needs here, but a more sophisticated
geodesic function should be used if greater accuracy is required
(see "When is it NOT okay to assume the Earth is a sphere?" in the
same faq).
"""
deg2rad = math.pi / 180.0
lat0 = lat0 * deg2rad
lng0 = lng0 * deg2rad
lat1 = lat1 * deg2rad
lng1 = lng1 * deg2rad
dlng = lng1 - lng0
dlat = lat1 - lat0
a = math.sin(dlat*0.5)
b = math.sin(dlng*0.5)
a = a * a + math.cos(lat0) * math.cos(lat1) * b * b
c = 2.0 * math.atan2(math.sqrt(a), math.sqrt(1.0 - a))
return 6367000.0 * c | python | def Distance(lat0, lng0, lat1, lng1):
"""
Compute the geodesic distance in meters between two points on the
surface of the Earth. The latitude and longitude angles are in
degrees.
Approximate geodesic distance function (Haversine Formula) assuming
a perfect sphere of radius 6367 km (see "What are some algorithms
for calculating the distance between 2 points?" in the GIS Faq at
http://www.census.gov/geo/www/faq-index.html). The approximate
radius is adequate for our needs here, but a more sophisticated
geodesic function should be used if greater accuracy is required
(see "When is it NOT okay to assume the Earth is a sphere?" in the
same faq).
"""
deg2rad = math.pi / 180.0
lat0 = lat0 * deg2rad
lng0 = lng0 * deg2rad
lat1 = lat1 * deg2rad
lng1 = lng1 * deg2rad
dlng = lng1 - lng0
dlat = lat1 - lat0
a = math.sin(dlat*0.5)
b = math.sin(dlng*0.5)
a = a * a + math.cos(lat0) * math.cos(lat1) * b * b
c = 2.0 * math.atan2(math.sqrt(a), math.sqrt(1.0 - a))
return 6367000.0 * c | [
"def",
"Distance",
"(",
"lat0",
",",
"lng0",
",",
"lat1",
",",
"lng1",
")",
":",
"deg2rad",
"=",
"math",
".",
"pi",
"/",
"180.0",
"lat0",
"=",
"lat0",
"*",
"deg2rad",
"lng0",
"=",
"lng0",
"*",
"deg2rad",
"lat1",
"=",
"lat1",
"*",
"deg2rad",
"lng1",... | Compute the geodesic distance in meters between two points on the
surface of the Earth. The latitude and longitude angles are in
degrees.
Approximate geodesic distance function (Haversine Formula) assuming
a perfect sphere of radius 6367 km (see "What are some algorithms
for calculating the distance between 2 points?" in the GIS Faq at
http://www.census.gov/geo/www/faq-index.html). The approximate
radius is adequate for our needs here, but a more sophisticated
geodesic function should be used if greater accuracy is required
(see "When is it NOT okay to assume the Earth is a sphere?" in the
same faq). | [
"Compute",
"the",
"geodesic",
"distance",
"in",
"meters",
"between",
"two",
"points",
"on",
"the",
"surface",
"of",
"the",
"Earth",
".",
"The",
"latitude",
"and",
"longitude",
"angles",
"are",
"in",
"degrees",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/examples/google_random_queries.py#L40-L66 |
225,133 | google/transitfeed | examples/google_random_queries.py | AddNoiseToLatLng | def AddNoiseToLatLng(lat, lng):
"""Add up to 500m of error to each coordinate of lat, lng."""
m_per_tenth_lat = Distance(lat, lng, lat + 0.1, lng)
m_per_tenth_lng = Distance(lat, lng, lat, lng + 0.1)
lat_per_100m = 1 / m_per_tenth_lat * 10
lng_per_100m = 1 / m_per_tenth_lng * 10
return (lat + (lat_per_100m * 5 * (random.random() * 2 - 1)),
lng + (lng_per_100m * 5 * (random.random() * 2 - 1))) | python | def AddNoiseToLatLng(lat, lng):
"""Add up to 500m of error to each coordinate of lat, lng."""
m_per_tenth_lat = Distance(lat, lng, lat + 0.1, lng)
m_per_tenth_lng = Distance(lat, lng, lat, lng + 0.1)
lat_per_100m = 1 / m_per_tenth_lat * 10
lng_per_100m = 1 / m_per_tenth_lng * 10
return (lat + (lat_per_100m * 5 * (random.random() * 2 - 1)),
lng + (lng_per_100m * 5 * (random.random() * 2 - 1))) | [
"def",
"AddNoiseToLatLng",
"(",
"lat",
",",
"lng",
")",
":",
"m_per_tenth_lat",
"=",
"Distance",
"(",
"lat",
",",
"lng",
",",
"lat",
"+",
"0.1",
",",
"lng",
")",
"m_per_tenth_lng",
"=",
"Distance",
"(",
"lat",
",",
"lng",
",",
"lat",
",",
"lng",
"+",... | Add up to 500m of error to each coordinate of lat, lng. | [
"Add",
"up",
"to",
"500m",
"of",
"error",
"to",
"each",
"coordinate",
"of",
"lat",
"lng",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/examples/google_random_queries.py#L69-L76 |
225,134 | google/transitfeed | examples/google_random_queries.py | GetRandomDatetime | def GetRandomDatetime():
"""Return a datetime in the next week."""
seconds_offset = random.randint(0, 60 * 60 * 24 * 7)
dt = datetime.today() + timedelta(seconds=seconds_offset)
return dt.replace(second=0, microsecond=0) | python | def GetRandomDatetime():
"""Return a datetime in the next week."""
seconds_offset = random.randint(0, 60 * 60 * 24 * 7)
dt = datetime.today() + timedelta(seconds=seconds_offset)
return dt.replace(second=0, microsecond=0) | [
"def",
"GetRandomDatetime",
"(",
")",
":",
"seconds_offset",
"=",
"random",
".",
"randint",
"(",
"0",
",",
"60",
"*",
"60",
"*",
"24",
"*",
"7",
")",
"dt",
"=",
"datetime",
".",
"today",
"(",
")",
"+",
"timedelta",
"(",
"seconds",
"=",
"seconds_offse... | Return a datetime in the next week. | [
"Return",
"a",
"datetime",
"in",
"the",
"next",
"week",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/examples/google_random_queries.py#L87-L91 |
225,135 | google/transitfeed | examples/google_random_queries.py | LatLngsToGoogleLink | def LatLngsToGoogleLink(source, destination):
"""Return a string "<a ..." for a trip at a random time."""
dt = GetRandomDatetime()
return "<a href='%s'>from:%s to:%s on %s</a>" % (
LatLngsToGoogleUrl(source, destination, dt),
FormatLatLng(source), FormatLatLng(destination),
dt.ctime()) | python | def LatLngsToGoogleLink(source, destination):
"""Return a string "<a ..." for a trip at a random time."""
dt = GetRandomDatetime()
return "<a href='%s'>from:%s to:%s on %s</a>" % (
LatLngsToGoogleUrl(source, destination, dt),
FormatLatLng(source), FormatLatLng(destination),
dt.ctime()) | [
"def",
"LatLngsToGoogleLink",
"(",
"source",
",",
"destination",
")",
":",
"dt",
"=",
"GetRandomDatetime",
"(",
")",
"return",
"\"<a href='%s'>from:%s to:%s on %s</a>\"",
"%",
"(",
"LatLngsToGoogleUrl",
"(",
"source",
",",
"destination",
",",
"dt",
")",
",",
"Form... | Return a string "<a ..." for a trip at a random time. | [
"Return",
"a",
"string",
"<a",
"...",
"for",
"a",
"trip",
"at",
"a",
"random",
"time",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/examples/google_random_queries.py#L113-L119 |
225,136 | google/transitfeed | examples/google_random_queries.py | ParentAndBaseName | def ParentAndBaseName(path):
"""Given a path return only the parent name and file name as a string."""
dirname, basename = os.path.split(path)
dirname = dirname.rstrip(os.path.sep)
if os.path.altsep:
dirname = dirname.rstrip(os.path.altsep)
_, parentname = os.path.split(dirname)
return os.path.join(parentname, basename) | python | def ParentAndBaseName(path):
"""Given a path return only the parent name and file name as a string."""
dirname, basename = os.path.split(path)
dirname = dirname.rstrip(os.path.sep)
if os.path.altsep:
dirname = dirname.rstrip(os.path.altsep)
_, parentname = os.path.split(dirname)
return os.path.join(parentname, basename) | [
"def",
"ParentAndBaseName",
"(",
"path",
")",
":",
"dirname",
",",
"basename",
"=",
"os",
".",
"path",
".",
"split",
"(",
"path",
")",
"dirname",
"=",
"dirname",
".",
"rstrip",
"(",
"os",
".",
"path",
".",
"sep",
")",
"if",
"os",
".",
"path",
".",
... | Given a path return only the parent name and file name as a string. | [
"Given",
"a",
"path",
"return",
"only",
"the",
"parent",
"name",
"and",
"file",
"name",
"as",
"a",
"string",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/examples/google_random_queries.py#L181-L188 |
225,137 | google/transitfeed | misc/sql_loop.py | LoadFile | def LoadFile(f, table_name, conn):
"""Import lines from f as new table in db with cursor c."""
reader = csv.reader(f)
header = next(reader)
columns = []
for n in header:
n = n.replace(' ', '')
n = n.replace('-', '_')
columns.append(n)
create_columns = []
column_types = {}
for n in columns:
if n in column_types:
create_columns.append("%s %s" % (n, column_types[n]))
else:
create_columns.append("%s INTEGER" % (n))
c = conn.cursor()
try:
c.execute("CREATE TABLE %s (%s)" % (table_name, ",".join(create_columns)))
except sqlite.OperationalError:
# Likely table exists
print("table %s already exists?" % (table_name))
for create_column in create_columns:
try:
c.execute("ALTER TABLE %s ADD COLUMN %s" % (table_name, create_column))
except sqlite.OperationalError:
# Likely it already exists
print("column %s already exists in %s?" % (create_column, table_name))
placeholders = ",".join(["?"] * len(columns))
insert_values = "INSERT INTO %s (%s) VALUES (%s)" % (table_name, ",".join(columns), placeholders)
#c.execute("BEGIN TRANSACTION;")
for row in reader:
if row:
if len(row) < len(columns):
row.extend([None] * (len(columns) - len(row)))
c.execute(insert_values, row)
#c.execute("END TRANSACTION;")
conn.commit() | python | def LoadFile(f, table_name, conn):
"""Import lines from f as new table in db with cursor c."""
reader = csv.reader(f)
header = next(reader)
columns = []
for n in header:
n = n.replace(' ', '')
n = n.replace('-', '_')
columns.append(n)
create_columns = []
column_types = {}
for n in columns:
if n in column_types:
create_columns.append("%s %s" % (n, column_types[n]))
else:
create_columns.append("%s INTEGER" % (n))
c = conn.cursor()
try:
c.execute("CREATE TABLE %s (%s)" % (table_name, ",".join(create_columns)))
except sqlite.OperationalError:
# Likely table exists
print("table %s already exists?" % (table_name))
for create_column in create_columns:
try:
c.execute("ALTER TABLE %s ADD COLUMN %s" % (table_name, create_column))
except sqlite.OperationalError:
# Likely it already exists
print("column %s already exists in %s?" % (create_column, table_name))
placeholders = ",".join(["?"] * len(columns))
insert_values = "INSERT INTO %s (%s) VALUES (%s)" % (table_name, ",".join(columns), placeholders)
#c.execute("BEGIN TRANSACTION;")
for row in reader:
if row:
if len(row) < len(columns):
row.extend([None] * (len(columns) - len(row)))
c.execute(insert_values, row)
#c.execute("END TRANSACTION;")
conn.commit() | [
"def",
"LoadFile",
"(",
"f",
",",
"table_name",
",",
"conn",
")",
":",
"reader",
"=",
"csv",
".",
"reader",
"(",
"f",
")",
"header",
"=",
"next",
"(",
"reader",
")",
"columns",
"=",
"[",
"]",
"for",
"n",
"in",
"header",
":",
"n",
"=",
"n",
".",... | Import lines from f as new table in db with cursor c. | [
"Import",
"lines",
"from",
"f",
"as",
"new",
"table",
"in",
"db",
"with",
"cursor",
"c",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/misc/sql_loop.py#L81-L123 |
225,138 | google/transitfeed | shape_importer.py | PrintColumns | def PrintColumns(shapefile):
"""
Print the columns of layer 0 of the shapefile to the screen.
"""
ds = ogr.Open(shapefile)
layer = ds.GetLayer(0)
if len(layer) == 0:
raise ShapeImporterError("Layer 0 has no elements!")
feature = layer.GetFeature(0)
print("%d features" % feature.GetFieldCount())
for j in range(0, feature.GetFieldCount()):
print('--' + feature.GetFieldDefnRef(j).GetName() + \
': ' + feature.GetFieldAsString(j)) | python | def PrintColumns(shapefile):
"""
Print the columns of layer 0 of the shapefile to the screen.
"""
ds = ogr.Open(shapefile)
layer = ds.GetLayer(0)
if len(layer) == 0:
raise ShapeImporterError("Layer 0 has no elements!")
feature = layer.GetFeature(0)
print("%d features" % feature.GetFieldCount())
for j in range(0, feature.GetFieldCount()):
print('--' + feature.GetFieldDefnRef(j).GetName() + \
': ' + feature.GetFieldAsString(j)) | [
"def",
"PrintColumns",
"(",
"shapefile",
")",
":",
"ds",
"=",
"ogr",
".",
"Open",
"(",
"shapefile",
")",
"layer",
"=",
"ds",
".",
"GetLayer",
"(",
"0",
")",
"if",
"len",
"(",
"layer",
")",
"==",
"0",
":",
"raise",
"ShapeImporterError",
"(",
"\"Layer ... | Print the columns of layer 0 of the shapefile to the screen. | [
"Print",
"the",
"columns",
"of",
"layer",
"0",
"of",
"the",
"shapefile",
"to",
"the",
"screen",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/shape_importer.py#L42-L55 |
225,139 | google/transitfeed | shape_importer.py | AddShapefile | def AddShapefile(shapefile, graph, key_cols):
"""
Adds shapes found in the given shape filename to the given polyline
graph object.
"""
ds = ogr.Open(shapefile)
layer = ds.GetLayer(0)
for i in range(0, len(layer)):
feature = layer.GetFeature(i)
geometry = feature.GetGeometryRef()
if key_cols:
key_list = []
for col in key_cols:
key_list.append(str(feature.GetField(col)))
shape_id = '-'.join(key_list)
else:
shape_id = '%s-%d' % (shapefile, i)
poly = shapelib.Poly(name=shape_id)
for j in range(0, geometry.GetPointCount()):
(lat, lng) = (round(geometry.GetY(j), 15), round(geometry.GetX(j), 15))
poly.AddPoint(shapelib.Point.FromLatLng(lat, lng))
graph.AddPoly(poly)
return graph | python | def AddShapefile(shapefile, graph, key_cols):
"""
Adds shapes found in the given shape filename to the given polyline
graph object.
"""
ds = ogr.Open(shapefile)
layer = ds.GetLayer(0)
for i in range(0, len(layer)):
feature = layer.GetFeature(i)
geometry = feature.GetGeometryRef()
if key_cols:
key_list = []
for col in key_cols:
key_list.append(str(feature.GetField(col)))
shape_id = '-'.join(key_list)
else:
shape_id = '%s-%d' % (shapefile, i)
poly = shapelib.Poly(name=shape_id)
for j in range(0, geometry.GetPointCount()):
(lat, lng) = (round(geometry.GetY(j), 15), round(geometry.GetX(j), 15))
poly.AddPoint(shapelib.Point.FromLatLng(lat, lng))
graph.AddPoly(poly)
return graph | [
"def",
"AddShapefile",
"(",
"shapefile",
",",
"graph",
",",
"key_cols",
")",
":",
"ds",
"=",
"ogr",
".",
"Open",
"(",
"shapefile",
")",
"layer",
"=",
"ds",
".",
"GetLayer",
"(",
"0",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"lay... | Adds shapes found in the given shape filename to the given polyline
graph object. | [
"Adds",
"shapes",
"found",
"in",
"the",
"given",
"shape",
"filename",
"to",
"the",
"given",
"polyline",
"graph",
"object",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/shape_importer.py#L58-L85 |
225,140 | google/transitfeed | shape_importer.py | GetMatchingShape | def GetMatchingShape(pattern_poly, trip, matches, max_distance, verbosity=0):
"""
Tries to find a matching shape for the given pattern Poly object,
trip, and set of possibly matching Polys from which to choose a match.
"""
if len(matches) == 0:
print ('No matching shape found within max-distance %d for trip %s '
% (max_distance, trip.trip_id))
return None
if verbosity >= 1:
for match in matches:
print("match: size %d" % match.GetNumPoints())
scores = [(pattern_poly.GreedyPolyMatchDist(match), match)
for match in matches]
scores.sort()
if scores[0][0] > max_distance:
print ('No matching shape found within max-distance %d for trip %s '
'(min score was %f)'
% (max_distance, trip.trip_id, scores[0][0]))
return None
return scores[0][1] | python | def GetMatchingShape(pattern_poly, trip, matches, max_distance, verbosity=0):
"""
Tries to find a matching shape for the given pattern Poly object,
trip, and set of possibly matching Polys from which to choose a match.
"""
if len(matches) == 0:
print ('No matching shape found within max-distance %d for trip %s '
% (max_distance, trip.trip_id))
return None
if verbosity >= 1:
for match in matches:
print("match: size %d" % match.GetNumPoints())
scores = [(pattern_poly.GreedyPolyMatchDist(match), match)
for match in matches]
scores.sort()
if scores[0][0] > max_distance:
print ('No matching shape found within max-distance %d for trip %s '
'(min score was %f)'
% (max_distance, trip.trip_id, scores[0][0]))
return None
return scores[0][1] | [
"def",
"GetMatchingShape",
"(",
"pattern_poly",
",",
"trip",
",",
"matches",
",",
"max_distance",
",",
"verbosity",
"=",
"0",
")",
":",
"if",
"len",
"(",
"matches",
")",
"==",
"0",
":",
"print",
"(",
"'No matching shape found within max-distance %d for trip %s '",... | Tries to find a matching shape for the given pattern Poly object,
trip, and set of possibly matching Polys from which to choose a match. | [
"Tries",
"to",
"find",
"a",
"matching",
"shape",
"for",
"the",
"given",
"pattern",
"Poly",
"object",
"trip",
"and",
"set",
"of",
"possibly",
"matching",
"Polys",
"from",
"which",
"to",
"choose",
"a",
"match",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/shape_importer.py#L88-L112 |
225,141 | google/transitfeed | shape_importer.py | AddExtraShapes | def AddExtraShapes(extra_shapes_txt, graph):
"""
Add extra shapes into our input set by parsing them out of a GTFS-formatted
shapes.txt file. Useful for manually adding lines to a shape file, since it's
a pain to edit .shp files.
"""
print("Adding extra shapes from %s" % extra_shapes_txt)
try:
tmpdir = tempfile.mkdtemp()
shutil.copy(extra_shapes_txt, os.path.join(tmpdir, 'shapes.txt'))
loader = transitfeed.ShapeLoader(tmpdir)
schedule = loader.Load()
for shape in schedule.GetShapeList():
print("Adding extra shape: %s" % shape.shape_id)
graph.AddPoly(ShapeToPoly(shape))
finally:
if tmpdir:
shutil.rmtree(tmpdir) | python | def AddExtraShapes(extra_shapes_txt, graph):
"""
Add extra shapes into our input set by parsing them out of a GTFS-formatted
shapes.txt file. Useful for manually adding lines to a shape file, since it's
a pain to edit .shp files.
"""
print("Adding extra shapes from %s" % extra_shapes_txt)
try:
tmpdir = tempfile.mkdtemp()
shutil.copy(extra_shapes_txt, os.path.join(tmpdir, 'shapes.txt'))
loader = transitfeed.ShapeLoader(tmpdir)
schedule = loader.Load()
for shape in schedule.GetShapeList():
print("Adding extra shape: %s" % shape.shape_id)
graph.AddPoly(ShapeToPoly(shape))
finally:
if tmpdir:
shutil.rmtree(tmpdir) | [
"def",
"AddExtraShapes",
"(",
"extra_shapes_txt",
",",
"graph",
")",
":",
"print",
"(",
"\"Adding extra shapes from %s\"",
"%",
"extra_shapes_txt",
")",
"try",
":",
"tmpdir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"shutil",
".",
"copy",
"(",
"extra_shapes_tx... | Add extra shapes into our input set by parsing them out of a GTFS-formatted
shapes.txt file. Useful for manually adding lines to a shape file, since it's
a pain to edit .shp files. | [
"Add",
"extra",
"shapes",
"into",
"our",
"input",
"set",
"by",
"parsing",
"them",
"out",
"of",
"a",
"GTFS",
"-",
"formatted",
"shapes",
".",
"txt",
"file",
".",
"Useful",
"for",
"manually",
"adding",
"lines",
"to",
"a",
"shape",
"file",
"since",
"it",
... | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/shape_importer.py#L114-L132 |
225,142 | google/transitfeed | merge.py | ApproximateDistanceBetweenPoints | def ApproximateDistanceBetweenPoints(pa, pb):
"""Finds the distance between two points on the Earth's surface.
This is an approximate distance based on assuming that the Earth is a sphere.
The points are specified by their lattitude and longitude.
Args:
pa: the first (lat, lon) point tuple
pb: the second (lat, lon) point tuple
Returns:
The distance as a float in metres.
"""
alat, alon = pa
blat, blon = pb
sa = transitfeed.Stop(lat=alat, lng=alon)
sb = transitfeed.Stop(lat=blat, lng=blon)
return transitfeed.ApproximateDistanceBetweenStops(sa, sb) | python | def ApproximateDistanceBetweenPoints(pa, pb):
"""Finds the distance between two points on the Earth's surface.
This is an approximate distance based on assuming that the Earth is a sphere.
The points are specified by their lattitude and longitude.
Args:
pa: the first (lat, lon) point tuple
pb: the second (lat, lon) point tuple
Returns:
The distance as a float in metres.
"""
alat, alon = pa
blat, blon = pb
sa = transitfeed.Stop(lat=alat, lng=alon)
sb = transitfeed.Stop(lat=blat, lng=blon)
return transitfeed.ApproximateDistanceBetweenStops(sa, sb) | [
"def",
"ApproximateDistanceBetweenPoints",
"(",
"pa",
",",
"pb",
")",
":",
"alat",
",",
"alon",
"=",
"pa",
"blat",
",",
"blon",
"=",
"pb",
"sa",
"=",
"transitfeed",
".",
"Stop",
"(",
"lat",
"=",
"alat",
",",
"lng",
"=",
"alon",
")",
"sb",
"=",
"tra... | Finds the distance between two points on the Earth's surface.
This is an approximate distance based on assuming that the Earth is a sphere.
The points are specified by their lattitude and longitude.
Args:
pa: the first (lat, lon) point tuple
pb: the second (lat, lon) point tuple
Returns:
The distance as a float in metres. | [
"Finds",
"the",
"distance",
"between",
"two",
"points",
"on",
"the",
"Earth",
"s",
"surface",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L63-L80 |
225,143 | google/transitfeed | merge.py | LoadWithoutErrors | def LoadWithoutErrors(path, memory_db):
""""Return a Schedule object loaded from path; sys.exit for any error."""
accumulator = transitfeed.ExceptionProblemAccumulator()
loading_problem_handler = MergeProblemReporter(accumulator)
try:
schedule = transitfeed.Loader(path,
memory_db=memory_db,
problems=loading_problem_handler,
extra_validation=True).Load()
except transitfeed.ExceptionWithContext as e:
print((
"\n\nFeeds to merge must load without any errors.\n"
"While loading %s the following error was found:\n%s\n%s\n" %
(path, e.FormatContext(), transitfeed.EncodeUnicode(e.FormatProblem()))), file=sys.stderr)
sys.exit(1)
return schedule | python | def LoadWithoutErrors(path, memory_db):
""""Return a Schedule object loaded from path; sys.exit for any error."""
accumulator = transitfeed.ExceptionProblemAccumulator()
loading_problem_handler = MergeProblemReporter(accumulator)
try:
schedule = transitfeed.Loader(path,
memory_db=memory_db,
problems=loading_problem_handler,
extra_validation=True).Load()
except transitfeed.ExceptionWithContext as e:
print((
"\n\nFeeds to merge must load without any errors.\n"
"While loading %s the following error was found:\n%s\n%s\n" %
(path, e.FormatContext(), transitfeed.EncodeUnicode(e.FormatProblem()))), file=sys.stderr)
sys.exit(1)
return schedule | [
"def",
"LoadWithoutErrors",
"(",
"path",
",",
"memory_db",
")",
":",
"accumulator",
"=",
"transitfeed",
".",
"ExceptionProblemAccumulator",
"(",
")",
"loading_problem_handler",
"=",
"MergeProblemReporter",
"(",
"accumulator",
")",
"try",
":",
"schedule",
"=",
"trans... | Return a Schedule object loaded from path; sys.exit for any error. | [
"Return",
"a",
"Schedule",
"object",
"loaded",
"from",
"path",
";",
"sys",
".",
"exit",
"for",
"any",
"error",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L353-L368 |
225,144 | google/transitfeed | merge.py | HTMLProblemAccumulator._GenerateStatsTable | def _GenerateStatsTable(self, feed_merger):
"""Generate an HTML table of merge statistics.
Args:
feed_merger: The FeedMerger instance.
Returns:
The generated HTML as a string.
"""
rows = []
rows.append('<tr><th class="header"/><th class="header">Merged</th>'
'<th class="header">Copied from old feed</th>'
'<th class="header">Copied from new feed</th></tr>')
for merger in feed_merger.GetMergerList():
stats = merger.GetMergeStats()
if stats is None:
continue
merged, not_merged_a, not_merged_b = stats
rows.append('<tr><th class="header">%s</th>'
'<td class="header">%d</td>'
'<td class="header">%d</td>'
'<td class="header">%d</td></tr>' %
(merger.DATASET_NAME, merged, not_merged_a, not_merged_b))
return '<table>%s</table>' % '\n'.join(rows) | python | def _GenerateStatsTable(self, feed_merger):
"""Generate an HTML table of merge statistics.
Args:
feed_merger: The FeedMerger instance.
Returns:
The generated HTML as a string.
"""
rows = []
rows.append('<tr><th class="header"/><th class="header">Merged</th>'
'<th class="header">Copied from old feed</th>'
'<th class="header">Copied from new feed</th></tr>')
for merger in feed_merger.GetMergerList():
stats = merger.GetMergeStats()
if stats is None:
continue
merged, not_merged_a, not_merged_b = stats
rows.append('<tr><th class="header">%s</th>'
'<td class="header">%d</td>'
'<td class="header">%d</td>'
'<td class="header">%d</td></tr>' %
(merger.DATASET_NAME, merged, not_merged_a, not_merged_b))
return '<table>%s</table>' % '\n'.join(rows) | [
"def",
"_GenerateStatsTable",
"(",
"self",
",",
"feed_merger",
")",
":",
"rows",
"=",
"[",
"]",
"rows",
".",
"append",
"(",
"'<tr><th class=\"header\"/><th class=\"header\">Merged</th>'",
"'<th class=\"header\">Copied from old feed</th>'",
"'<th class=\"header\">Copied from new f... | Generate an HTML table of merge statistics.
Args:
feed_merger: The FeedMerger instance.
Returns:
The generated HTML as a string. | [
"Generate",
"an",
"HTML",
"table",
"of",
"merge",
"statistics",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L193-L216 |
225,145 | google/transitfeed | merge.py | HTMLProblemAccumulator._GenerateSection | def _GenerateSection(self, problem_type):
"""Generate a listing of the given type of problems.
Args:
problem_type: The type of problem. This is one of the problem type
constants from transitfeed.
Returns:
The generated HTML as a string.
"""
if problem_type == transitfeed.TYPE_WARNING:
dataset_problems = self._dataset_warnings
heading = 'Warnings'
else:
dataset_problems = self._dataset_errors
heading = 'Errors'
if not dataset_problems:
return ''
prefix = '<h2 class="issueHeader">%s:</h2>' % heading
dataset_sections = []
for dataset_merger, problems in dataset_problems.items():
dataset_sections.append('<h3>%s</h3><ol>%s</ol>' % (
dataset_merger.FILE_NAME, '\n'.join(problems)))
body = '\n'.join(dataset_sections)
return prefix + body | python | def _GenerateSection(self, problem_type):
"""Generate a listing of the given type of problems.
Args:
problem_type: The type of problem. This is one of the problem type
constants from transitfeed.
Returns:
The generated HTML as a string.
"""
if problem_type == transitfeed.TYPE_WARNING:
dataset_problems = self._dataset_warnings
heading = 'Warnings'
else:
dataset_problems = self._dataset_errors
heading = 'Errors'
if not dataset_problems:
return ''
prefix = '<h2 class="issueHeader">%s:</h2>' % heading
dataset_sections = []
for dataset_merger, problems in dataset_problems.items():
dataset_sections.append('<h3>%s</h3><ol>%s</ol>' % (
dataset_merger.FILE_NAME, '\n'.join(problems)))
body = '\n'.join(dataset_sections)
return prefix + body | [
"def",
"_GenerateSection",
"(",
"self",
",",
"problem_type",
")",
":",
"if",
"problem_type",
"==",
"transitfeed",
".",
"TYPE_WARNING",
":",
"dataset_problems",
"=",
"self",
".",
"_dataset_warnings",
"heading",
"=",
"'Warnings'",
"else",
":",
"dataset_problems",
"=... | Generate a listing of the given type of problems.
Args:
problem_type: The type of problem. This is one of the problem type
constants from transitfeed.
Returns:
The generated HTML as a string. | [
"Generate",
"a",
"listing",
"of",
"the",
"given",
"type",
"of",
"problems",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L218-L244 |
225,146 | google/transitfeed | merge.py | HTMLProblemAccumulator._GenerateSummary | def _GenerateSummary(self):
"""Generate a summary of the warnings and errors.
Returns:
The generated HTML as a string.
"""
items = []
if self._notices:
items.append('notices: %d' % self._notice_count)
if self._dataset_errors:
items.append('errors: %d' % self._error_count)
if self._dataset_warnings:
items.append('warnings: %d' % self._warning_count)
if items:
return '<p><span class="fail">%s</span></p>' % '<br>'.join(items)
else:
return '<p><span class="pass">feeds merged successfully</span></p>' | python | def _GenerateSummary(self):
"""Generate a summary of the warnings and errors.
Returns:
The generated HTML as a string.
"""
items = []
if self._notices:
items.append('notices: %d' % self._notice_count)
if self._dataset_errors:
items.append('errors: %d' % self._error_count)
if self._dataset_warnings:
items.append('warnings: %d' % self._warning_count)
if items:
return '<p><span class="fail">%s</span></p>' % '<br>'.join(items)
else:
return '<p><span class="pass">feeds merged successfully</span></p>' | [
"def",
"_GenerateSummary",
"(",
"self",
")",
":",
"items",
"=",
"[",
"]",
"if",
"self",
".",
"_notices",
":",
"items",
".",
"append",
"(",
"'notices: %d'",
"%",
"self",
".",
"_notice_count",
")",
"if",
"self",
".",
"_dataset_errors",
":",
"items",
".",
... | Generate a summary of the warnings and errors.
Returns:
The generated HTML as a string. | [
"Generate",
"a",
"summary",
"of",
"the",
"warnings",
"and",
"errors",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L246-L263 |
225,147 | google/transitfeed | merge.py | HTMLProblemAccumulator._GenerateNotices | def _GenerateNotices(self):
"""Generate a summary of any notices.
Returns:
The generated HTML as a string.
"""
items = []
for e in self._notices:
d = e.GetDictToFormat()
if 'url' in d.keys():
d['url'] = '<a href="%(url)s">%(url)s</a>' % d
items.append('<li class="notice">%s</li>' %
e.FormatProblem(d).replace('\n', '<br>'))
if items:
return '<h2>Notices:</h2>\n<ul>%s</ul>\n' % '\n'.join(items)
else:
return '' | python | def _GenerateNotices(self):
"""Generate a summary of any notices.
Returns:
The generated HTML as a string.
"""
items = []
for e in self._notices:
d = e.GetDictToFormat()
if 'url' in d.keys():
d['url'] = '<a href="%(url)s">%(url)s</a>' % d
items.append('<li class="notice">%s</li>' %
e.FormatProblem(d).replace('\n', '<br>'))
if items:
return '<h2>Notices:</h2>\n<ul>%s</ul>\n' % '\n'.join(items)
else:
return '' | [
"def",
"_GenerateNotices",
"(",
"self",
")",
":",
"items",
"=",
"[",
"]",
"for",
"e",
"in",
"self",
".",
"_notices",
":",
"d",
"=",
"e",
".",
"GetDictToFormat",
"(",
")",
"if",
"'url'",
"in",
"d",
".",
"keys",
"(",
")",
":",
"d",
"[",
"'url'",
... | Generate a summary of any notices.
Returns:
The generated HTML as a string. | [
"Generate",
"a",
"summary",
"of",
"any",
"notices",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L265-L281 |
225,148 | google/transitfeed | merge.py | DataSetMerger._MergeIdentical | def _MergeIdentical(self, a, b):
"""Tries to merge two values. The values are required to be identical.
Args:
a: The first value.
b: The second value.
Returns:
The trivially merged value.
Raises:
MergeError: The values were not identical.
"""
if a != b:
raise MergeError("values must be identical ('%s' vs '%s')" %
(transitfeed.EncodeUnicode(a),
transitfeed.EncodeUnicode(b)))
return b | python | def _MergeIdentical(self, a, b):
"""Tries to merge two values. The values are required to be identical.
Args:
a: The first value.
b: The second value.
Returns:
The trivially merged value.
Raises:
MergeError: The values were not identical.
"""
if a != b:
raise MergeError("values must be identical ('%s' vs '%s')" %
(transitfeed.EncodeUnicode(a),
transitfeed.EncodeUnicode(b)))
return b | [
"def",
"_MergeIdentical",
"(",
"self",
",",
"a",
",",
"b",
")",
":",
"if",
"a",
"!=",
"b",
":",
"raise",
"MergeError",
"(",
"\"values must be identical ('%s' vs '%s')\"",
"%",
"(",
"transitfeed",
".",
"EncodeUnicode",
"(",
"a",
")",
",",
"transitfeed",
".",
... | Tries to merge two values. The values are required to be identical.
Args:
a: The first value.
b: The second value.
Returns:
The trivially merged value.
Raises:
MergeError: The values were not identical. | [
"Tries",
"to",
"merge",
"two",
"values",
".",
"The",
"values",
"are",
"required",
"to",
"be",
"identical",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L394-L411 |
225,149 | google/transitfeed | merge.py | DataSetMerger._MergeIdenticalCaseInsensitive | def _MergeIdenticalCaseInsensitive(self, a, b):
"""Tries to merge two strings.
The string are required to be the same ignoring case. The second string is
always used as the merged value.
Args:
a: The first string.
b: The second string.
Returns:
The merged string. This is equal to the second string.
Raises:
MergeError: The strings were not the same ignoring case.
"""
if a.lower() != b.lower():
raise MergeError("values must be the same (case insensitive) "
"('%s' vs '%s')" % (transitfeed.EncodeUnicode(a),
transitfeed.EncodeUnicode(b)))
return b | python | def _MergeIdenticalCaseInsensitive(self, a, b):
"""Tries to merge two strings.
The string are required to be the same ignoring case. The second string is
always used as the merged value.
Args:
a: The first string.
b: The second string.
Returns:
The merged string. This is equal to the second string.
Raises:
MergeError: The strings were not the same ignoring case.
"""
if a.lower() != b.lower():
raise MergeError("values must be the same (case insensitive) "
"('%s' vs '%s')" % (transitfeed.EncodeUnicode(a),
transitfeed.EncodeUnicode(b)))
return b | [
"def",
"_MergeIdenticalCaseInsensitive",
"(",
"self",
",",
"a",
",",
"b",
")",
":",
"if",
"a",
".",
"lower",
"(",
")",
"!=",
"b",
".",
"lower",
"(",
")",
":",
"raise",
"MergeError",
"(",
"\"values must be the same (case insensitive) \"",
"\"('%s' vs '%s')\"",
... | Tries to merge two strings.
The string are required to be the same ignoring case. The second string is
always used as the merged value.
Args:
a: The first string.
b: The second string.
Returns:
The merged string. This is equal to the second string.
Raises:
MergeError: The strings were not the same ignoring case. | [
"Tries",
"to",
"merge",
"two",
"strings",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L413-L433 |
225,150 | google/transitfeed | merge.py | DataSetMerger._MergeOptional | def _MergeOptional(self, a, b):
"""Tries to merge two values which may be None.
If both values are not None, they are required to be the same and the
merge is trivial. If one of the values is None and the other is not None,
the merge results in the one which is not None. If both are None, the merge
results in None.
Args:
a: The first value.
b: The second value.
Returns:
The merged value.
Raises:
MergeError: If both values are not None and are not the same.
"""
if a and b:
if a != b:
raise MergeError("values must be identical if both specified "
"('%s' vs '%s')" % (transitfeed.EncodeUnicode(a),
transitfeed.EncodeUnicode(b)))
return a or b | python | def _MergeOptional(self, a, b):
"""Tries to merge two values which may be None.
If both values are not None, they are required to be the same and the
merge is trivial. If one of the values is None and the other is not None,
the merge results in the one which is not None. If both are None, the merge
results in None.
Args:
a: The first value.
b: The second value.
Returns:
The merged value.
Raises:
MergeError: If both values are not None and are not the same.
"""
if a and b:
if a != b:
raise MergeError("values must be identical if both specified "
"('%s' vs '%s')" % (transitfeed.EncodeUnicode(a),
transitfeed.EncodeUnicode(b)))
return a or b | [
"def",
"_MergeOptional",
"(",
"self",
",",
"a",
",",
"b",
")",
":",
"if",
"a",
"and",
"b",
":",
"if",
"a",
"!=",
"b",
":",
"raise",
"MergeError",
"(",
"\"values must be identical if both specified \"",
"\"('%s' vs '%s')\"",
"%",
"(",
"transitfeed",
".",
"Enc... | Tries to merge two values which may be None.
If both values are not None, they are required to be the same and the
merge is trivial. If one of the values is None and the other is not None,
the merge results in the one which is not None. If both are None, the merge
results in None.
Args:
a: The first value.
b: The second value.
Returns:
The merged value.
Raises:
MergeError: If both values are not None and are not the same. | [
"Tries",
"to",
"merge",
"two",
"values",
"which",
"may",
"be",
"None",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L435-L458 |
225,151 | google/transitfeed | merge.py | DataSetMerger._MergeSameAgency | def _MergeSameAgency(self, a_agency_id, b_agency_id):
"""Merge agency ids to the corresponding agency id in the merged schedule.
Args:
a_agency_id: an agency id from the old schedule
b_agency_id: an agency id from the new schedule
Returns:
The agency id of the corresponding merged agency.
Raises:
MergeError: If a_agency_id and b_agency_id do not correspond to the same
merged agency.
KeyError: Either aaid or baid is not a valid agency id.
"""
a_agency_id = (a_agency_id or
self.feed_merger.a_schedule.GetDefaultAgency().agency_id)
b_agency_id = (b_agency_id or
self.feed_merger.b_schedule.GetDefaultAgency().agency_id)
a_agency = self.feed_merger.a_schedule.GetAgency(
a_agency_id)._migrated_entity
b_agency = self.feed_merger.b_schedule.GetAgency(
b_agency_id)._migrated_entity
if a_agency != b_agency:
raise MergeError('agency must be the same')
return a_agency.agency_id | python | def _MergeSameAgency(self, a_agency_id, b_agency_id):
"""Merge agency ids to the corresponding agency id in the merged schedule.
Args:
a_agency_id: an agency id from the old schedule
b_agency_id: an agency id from the new schedule
Returns:
The agency id of the corresponding merged agency.
Raises:
MergeError: If a_agency_id and b_agency_id do not correspond to the same
merged agency.
KeyError: Either aaid or baid is not a valid agency id.
"""
a_agency_id = (a_agency_id or
self.feed_merger.a_schedule.GetDefaultAgency().agency_id)
b_agency_id = (b_agency_id or
self.feed_merger.b_schedule.GetDefaultAgency().agency_id)
a_agency = self.feed_merger.a_schedule.GetAgency(
a_agency_id)._migrated_entity
b_agency = self.feed_merger.b_schedule.GetAgency(
b_agency_id)._migrated_entity
if a_agency != b_agency:
raise MergeError('agency must be the same')
return a_agency.agency_id | [
"def",
"_MergeSameAgency",
"(",
"self",
",",
"a_agency_id",
",",
"b_agency_id",
")",
":",
"a_agency_id",
"=",
"(",
"a_agency_id",
"or",
"self",
".",
"feed_merger",
".",
"a_schedule",
".",
"GetDefaultAgency",
"(",
")",
".",
"agency_id",
")",
"b_agency_id",
"=",... | Merge agency ids to the corresponding agency id in the merged schedule.
Args:
a_agency_id: an agency id from the old schedule
b_agency_id: an agency id from the new schedule
Returns:
The agency id of the corresponding merged agency.
Raises:
MergeError: If a_agency_id and b_agency_id do not correspond to the same
merged agency.
KeyError: Either aaid or baid is not a valid agency id. | [
"Merge",
"agency",
"ids",
"to",
"the",
"corresponding",
"agency",
"id",
"in",
"the",
"merged",
"schedule",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L460-L485 |
225,152 | google/transitfeed | merge.py | DataSetMerger._SchemedMerge | def _SchemedMerge(self, scheme, a, b):
"""Tries to merge two entities according to a merge scheme.
A scheme is specified by a map where the keys are entity attributes and the
values are merge functions like Merger._MergeIdentical or
Merger._MergeOptional. The entity is first migrated to the merged schedule.
Then the attributes are individually merged as specified by the scheme.
Args:
scheme: The merge scheme, a map from entity attributes to merge
functions.
a: The entity from the old schedule.
b: The entity from the new schedule.
Returns:
The migrated and merged entity.
Raises:
MergeError: One of the attributes was not able to be merged.
"""
migrated = self._Migrate(b, self.feed_merger.b_schedule, False)
for attr, merger in scheme.items():
a_attr = getattr(a, attr, None)
b_attr = getattr(b, attr, None)
try:
merged_attr = merger(a_attr, b_attr)
except MergeError as merge_error:
raise MergeError("Attribute '%s' could not be merged: %s." % (
attr, merge_error))
setattr(migrated, attr, merged_attr)
return migrated | python | def _SchemedMerge(self, scheme, a, b):
"""Tries to merge two entities according to a merge scheme.
A scheme is specified by a map where the keys are entity attributes and the
values are merge functions like Merger._MergeIdentical or
Merger._MergeOptional. The entity is first migrated to the merged schedule.
Then the attributes are individually merged as specified by the scheme.
Args:
scheme: The merge scheme, a map from entity attributes to merge
functions.
a: The entity from the old schedule.
b: The entity from the new schedule.
Returns:
The migrated and merged entity.
Raises:
MergeError: One of the attributes was not able to be merged.
"""
migrated = self._Migrate(b, self.feed_merger.b_schedule, False)
for attr, merger in scheme.items():
a_attr = getattr(a, attr, None)
b_attr = getattr(b, attr, None)
try:
merged_attr = merger(a_attr, b_attr)
except MergeError as merge_error:
raise MergeError("Attribute '%s' could not be merged: %s." % (
attr, merge_error))
setattr(migrated, attr, merged_attr)
return migrated | [
"def",
"_SchemedMerge",
"(",
"self",
",",
"scheme",
",",
"a",
",",
"b",
")",
":",
"migrated",
"=",
"self",
".",
"_Migrate",
"(",
"b",
",",
"self",
".",
"feed_merger",
".",
"b_schedule",
",",
"False",
")",
"for",
"attr",
",",
"merger",
"in",
"scheme",... | Tries to merge two entities according to a merge scheme.
A scheme is specified by a map where the keys are entity attributes and the
values are merge functions like Merger._MergeIdentical or
Merger._MergeOptional. The entity is first migrated to the merged schedule.
Then the attributes are individually merged as specified by the scheme.
Args:
scheme: The merge scheme, a map from entity attributes to merge
functions.
a: The entity from the old schedule.
b: The entity from the new schedule.
Returns:
The migrated and merged entity.
Raises:
MergeError: One of the attributes was not able to be merged. | [
"Tries",
"to",
"merge",
"two",
"entities",
"according",
"to",
"a",
"merge",
"scheme",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L487-L517 |
225,153 | google/transitfeed | merge.py | DataSetMerger._MergeSameId | def _MergeSameId(self):
"""Tries to merge entities based on their ids.
This tries to merge only the entities from the old and new schedules which
have the same id. These are added into the merged schedule. Entities which
do not merge or do not have the same id as another entity in the other
schedule are simply migrated into the merged schedule.
This method is less flexible than _MergeDifferentId since it only tries
to merge entities which have the same id while _MergeDifferentId tries to
merge everything. However, it is faster and so should be used whenever
possible.
This method makes use of various methods like _Merge and _Migrate which
are not implemented in the abstract DataSetMerger class. These method
should be overwritten in a subclass to allow _MergeSameId to work with
different entity types.
Returns:
The number of merged entities.
"""
a_not_merged = []
b_not_merged = []
for a in self._GetIter(self.feed_merger.a_schedule):
try:
b = self._GetById(self.feed_merger.b_schedule, self._GetId(a))
except KeyError:
# there was no entity in B with the same id as a
a_not_merged.append(a)
continue
try:
self._Add(a, b, self._MergeEntities(a, b))
self._num_merged += 1
except MergeError as merge_error:
a_not_merged.append(a)
b_not_merged.append(b)
self._ReportSameIdButNotMerged(self._GetId(a), merge_error)
for b in self._GetIter(self.feed_merger.b_schedule):
try:
a = self._GetById(self.feed_merger.a_schedule, self._GetId(b))
except KeyError:
# there was no entity in A with the same id as b
b_not_merged.append(b)
# migrate the remaining entities
for a in a_not_merged:
newid = self._HasId(self.feed_merger.b_schedule, self._GetId(a))
self._Add(a, None, self._Migrate(a, self.feed_merger.a_schedule, newid))
for b in b_not_merged:
newid = self._HasId(self.feed_merger.a_schedule, self._GetId(b))
self._Add(None, b, self._Migrate(b, self.feed_merger.b_schedule, newid))
self._num_not_merged_a = len(a_not_merged)
self._num_not_merged_b = len(b_not_merged)
return self._num_merged | python | def _MergeSameId(self):
"""Tries to merge entities based on their ids.
This tries to merge only the entities from the old and new schedules which
have the same id. These are added into the merged schedule. Entities which
do not merge or do not have the same id as another entity in the other
schedule are simply migrated into the merged schedule.
This method is less flexible than _MergeDifferentId since it only tries
to merge entities which have the same id while _MergeDifferentId tries to
merge everything. However, it is faster and so should be used whenever
possible.
This method makes use of various methods like _Merge and _Migrate which
are not implemented in the abstract DataSetMerger class. These method
should be overwritten in a subclass to allow _MergeSameId to work with
different entity types.
Returns:
The number of merged entities.
"""
a_not_merged = []
b_not_merged = []
for a in self._GetIter(self.feed_merger.a_schedule):
try:
b = self._GetById(self.feed_merger.b_schedule, self._GetId(a))
except KeyError:
# there was no entity in B with the same id as a
a_not_merged.append(a)
continue
try:
self._Add(a, b, self._MergeEntities(a, b))
self._num_merged += 1
except MergeError as merge_error:
a_not_merged.append(a)
b_not_merged.append(b)
self._ReportSameIdButNotMerged(self._GetId(a), merge_error)
for b in self._GetIter(self.feed_merger.b_schedule):
try:
a = self._GetById(self.feed_merger.a_schedule, self._GetId(b))
except KeyError:
# there was no entity in A with the same id as b
b_not_merged.append(b)
# migrate the remaining entities
for a in a_not_merged:
newid = self._HasId(self.feed_merger.b_schedule, self._GetId(a))
self._Add(a, None, self._Migrate(a, self.feed_merger.a_schedule, newid))
for b in b_not_merged:
newid = self._HasId(self.feed_merger.a_schedule, self._GetId(b))
self._Add(None, b, self._Migrate(b, self.feed_merger.b_schedule, newid))
self._num_not_merged_a = len(a_not_merged)
self._num_not_merged_b = len(b_not_merged)
return self._num_merged | [
"def",
"_MergeSameId",
"(",
"self",
")",
":",
"a_not_merged",
"=",
"[",
"]",
"b_not_merged",
"=",
"[",
"]",
"for",
"a",
"in",
"self",
".",
"_GetIter",
"(",
"self",
".",
"feed_merger",
".",
"a_schedule",
")",
":",
"try",
":",
"b",
"=",
"self",
".",
... | Tries to merge entities based on their ids.
This tries to merge only the entities from the old and new schedules which
have the same id. These are added into the merged schedule. Entities which
do not merge or do not have the same id as another entity in the other
schedule are simply migrated into the merged schedule.
This method is less flexible than _MergeDifferentId since it only tries
to merge entities which have the same id while _MergeDifferentId tries to
merge everything. However, it is faster and so should be used whenever
possible.
This method makes use of various methods like _Merge and _Migrate which
are not implemented in the abstract DataSetMerger class. These method
should be overwritten in a subclass to allow _MergeSameId to work with
different entity types.
Returns:
The number of merged entities. | [
"Tries",
"to",
"merge",
"entities",
"based",
"on",
"their",
"ids",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L519-L575 |
225,154 | google/transitfeed | merge.py | DataSetMerger._MergeDifferentId | def _MergeDifferentId(self):
"""Tries to merge all possible combinations of entities.
This tries to merge every entity in the old schedule with every entity in
the new schedule. Unlike _MergeSameId, the ids do not need to match.
However, _MergeDifferentId is much slower than _MergeSameId.
This method makes use of various methods like _Merge and _Migrate which
are not implemented in the abstract DataSetMerger class. These method
should be overwritten in a subclass to allow _MergeSameId to work with
different entity types.
Returns:
The number of merged entities.
"""
# TODO: The same entity from A could merge with multiple from B.
# This should either generate an error or should be prevented from
# happening.
for a in self._GetIter(self.feed_merger.a_schedule):
for b in self._GetIter(self.feed_merger.b_schedule):
try:
self._Add(a, b, self._MergeEntities(a, b))
self._num_merged += 1
except MergeError:
continue
for a in self._GetIter(self.feed_merger.a_schedule):
if a not in self.feed_merger.a_merge_map:
self._num_not_merged_a += 1
newid = self._HasId(self.feed_merger.b_schedule, self._GetId(a))
self._Add(a, None,
self._Migrate(a, self.feed_merger.a_schedule, newid))
for b in self._GetIter(self.feed_merger.b_schedule):
if b not in self.feed_merger.b_merge_map:
self._num_not_merged_b += 1
newid = self._HasId(self.feed_merger.a_schedule, self._GetId(b))
self._Add(None, b,
self._Migrate(b, self.feed_merger.b_schedule, newid))
return self._num_merged | python | def _MergeDifferentId(self):
"""Tries to merge all possible combinations of entities.
This tries to merge every entity in the old schedule with every entity in
the new schedule. Unlike _MergeSameId, the ids do not need to match.
However, _MergeDifferentId is much slower than _MergeSameId.
This method makes use of various methods like _Merge and _Migrate which
are not implemented in the abstract DataSetMerger class. These method
should be overwritten in a subclass to allow _MergeSameId to work with
different entity types.
Returns:
The number of merged entities.
"""
# TODO: The same entity from A could merge with multiple from B.
# This should either generate an error or should be prevented from
# happening.
for a in self._GetIter(self.feed_merger.a_schedule):
for b in self._GetIter(self.feed_merger.b_schedule):
try:
self._Add(a, b, self._MergeEntities(a, b))
self._num_merged += 1
except MergeError:
continue
for a in self._GetIter(self.feed_merger.a_schedule):
if a not in self.feed_merger.a_merge_map:
self._num_not_merged_a += 1
newid = self._HasId(self.feed_merger.b_schedule, self._GetId(a))
self._Add(a, None,
self._Migrate(a, self.feed_merger.a_schedule, newid))
for b in self._GetIter(self.feed_merger.b_schedule):
if b not in self.feed_merger.b_merge_map:
self._num_not_merged_b += 1
newid = self._HasId(self.feed_merger.a_schedule, self._GetId(b))
self._Add(None, b,
self._Migrate(b, self.feed_merger.b_schedule, newid))
return self._num_merged | [
"def",
"_MergeDifferentId",
"(",
"self",
")",
":",
"# TODO: The same entity from A could merge with multiple from B.",
"# This should either generate an error or should be prevented from",
"# happening.",
"for",
"a",
"in",
"self",
".",
"_GetIter",
"(",
"self",
".",
"feed_merger",... | Tries to merge all possible combinations of entities.
This tries to merge every entity in the old schedule with every entity in
the new schedule. Unlike _MergeSameId, the ids do not need to match.
However, _MergeDifferentId is much slower than _MergeSameId.
This method makes use of various methods like _Merge and _Migrate which
are not implemented in the abstract DataSetMerger class. These method
should be overwritten in a subclass to allow _MergeSameId to work with
different entity types.
Returns:
The number of merged entities. | [
"Tries",
"to",
"merge",
"all",
"possible",
"combinations",
"of",
"entities",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L618-L657 |
225,155 | google/transitfeed | merge.py | DataSetMerger._ReportSameIdButNotMerged | def _ReportSameIdButNotMerged(self, entity_id, reason):
"""Report that two entities have the same id but could not be merged.
Args:
entity_id: The id of the entities.
reason: A string giving a reason why they could not be merged.
"""
self.feed_merger.problem_reporter.SameIdButNotMerged(self,
entity_id,
reason) | python | def _ReportSameIdButNotMerged(self, entity_id, reason):
"""Report that two entities have the same id but could not be merged.
Args:
entity_id: The id of the entities.
reason: A string giving a reason why they could not be merged.
"""
self.feed_merger.problem_reporter.SameIdButNotMerged(self,
entity_id,
reason) | [
"def",
"_ReportSameIdButNotMerged",
"(",
"self",
",",
"entity_id",
",",
"reason",
")",
":",
"self",
".",
"feed_merger",
".",
"problem_reporter",
".",
"SameIdButNotMerged",
"(",
"self",
",",
"entity_id",
",",
"reason",
")"
] | Report that two entities have the same id but could not be merged.
Args:
entity_id: The id of the entities.
reason: A string giving a reason why they could not be merged. | [
"Report",
"that",
"two",
"entities",
"have",
"the",
"same",
"id",
"but",
"could",
"not",
"be",
"merged",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L659-L668 |
225,156 | google/transitfeed | merge.py | DataSetMerger._HasId | def _HasId(self, schedule, entity_id):
"""Check if the schedule has an entity with the given id.
Args:
schedule: The transitfeed.Schedule instance to look in.
entity_id: The id of the entity.
Returns:
True if the schedule has an entity with the id or False if not.
"""
try:
self._GetById(schedule, entity_id)
has = True
except KeyError:
has = False
return has | python | def _HasId(self, schedule, entity_id):
"""Check if the schedule has an entity with the given id.
Args:
schedule: The transitfeed.Schedule instance to look in.
entity_id: The id of the entity.
Returns:
True if the schedule has an entity with the id or False if not.
"""
try:
self._GetById(schedule, entity_id)
has = True
except KeyError:
has = False
return has | [
"def",
"_HasId",
"(",
"self",
",",
"schedule",
",",
"entity_id",
")",
":",
"try",
":",
"self",
".",
"_GetById",
"(",
"schedule",
",",
"entity_id",
")",
"has",
"=",
"True",
"except",
"KeyError",
":",
"has",
"=",
"False",
"return",
"has"
] | Check if the schedule has an entity with the given id.
Args:
schedule: The transitfeed.Schedule instance to look in.
entity_id: The id of the entity.
Returns:
True if the schedule has an entity with the id or False if not. | [
"Check",
"if",
"the",
"schedule",
"has",
"an",
"entity",
"with",
"the",
"given",
"id",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L708-L723 |
225,157 | google/transitfeed | merge.py | AgencyMerger._MergeEntities | def _MergeEntities(self, a, b):
"""Merges two agencies.
To be merged, they are required to have the same id, name, url and
timezone. The remaining language attribute is taken from the new agency.
Args:
a: The first agency.
b: The second agency.
Returns:
The merged agency.
Raises:
MergeError: The agencies could not be merged.
"""
def _MergeAgencyId(a_agency_id, b_agency_id):
"""Merge two agency ids.
The only difference between this and _MergeIdentical() is that the values
None and '' are regarded as being the same.
Args:
a_agency_id: The first agency id.
b_agency_id: The second agency id.
Returns:
The merged agency id.
Raises:
MergeError: The agency ids could not be merged.
"""
a_agency_id = a_agency_id or None
b_agency_id = b_agency_id or None
return self._MergeIdentical(a_agency_id, b_agency_id)
scheme = {'agency_id': _MergeAgencyId,
'agency_name': self._MergeIdentical,
'agency_url': self._MergeIdentical,
'agency_timezone': self._MergeIdentical}
return self._SchemedMerge(scheme, a, b) | python | def _MergeEntities(self, a, b):
"""Merges two agencies.
To be merged, they are required to have the same id, name, url and
timezone. The remaining language attribute is taken from the new agency.
Args:
a: The first agency.
b: The second agency.
Returns:
The merged agency.
Raises:
MergeError: The agencies could not be merged.
"""
def _MergeAgencyId(a_agency_id, b_agency_id):
"""Merge two agency ids.
The only difference between this and _MergeIdentical() is that the values
None and '' are regarded as being the same.
Args:
a_agency_id: The first agency id.
b_agency_id: The second agency id.
Returns:
The merged agency id.
Raises:
MergeError: The agency ids could not be merged.
"""
a_agency_id = a_agency_id or None
b_agency_id = b_agency_id or None
return self._MergeIdentical(a_agency_id, b_agency_id)
scheme = {'agency_id': _MergeAgencyId,
'agency_name': self._MergeIdentical,
'agency_url': self._MergeIdentical,
'agency_timezone': self._MergeIdentical}
return self._SchemedMerge(scheme, a, b) | [
"def",
"_MergeEntities",
"(",
"self",
",",
"a",
",",
"b",
")",
":",
"def",
"_MergeAgencyId",
"(",
"a_agency_id",
",",
"b_agency_id",
")",
":",
"\"\"\"Merge two agency ids.\n\n The only difference between this and _MergeIdentical() is that the values\n None and '' are re... | Merges two agencies.
To be merged, they are required to have the same id, name, url and
timezone. The remaining language attribute is taken from the new agency.
Args:
a: The first agency.
b: The second agency.
Returns:
The merged agency.
Raises:
MergeError: The agencies could not be merged. | [
"Merges",
"two",
"agencies",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L841-L882 |
225,158 | google/transitfeed | merge.py | StopMerger._MergeEntities | def _MergeEntities(self, a, b):
"""Merges two stops.
For the stops to be merged, they must have:
- the same stop_id
- the same stop_name (case insensitive)
- the same zone_id
- locations less than largest_stop_distance apart
The other attributes can have arbitary changes. The merged attributes are
taken from the new stop.
Args:
a: The first stop.
b: The second stop.
Returns:
The merged stop.
Raises:
MergeError: The stops could not be merged.
"""
distance = transitfeed.ApproximateDistanceBetweenStops(a, b)
if distance > self.largest_stop_distance:
raise MergeError("Stops are too far apart: %.1fm "
"(largest_stop_distance is %.1fm)." %
(distance, self.largest_stop_distance))
scheme = {'stop_id': self._MergeIdentical,
'stop_name': self._MergeIdenticalCaseInsensitive,
'zone_id': self._MergeIdentical,
'location_type': self._MergeIdentical}
return self._SchemedMerge(scheme, a, b) | python | def _MergeEntities(self, a, b):
"""Merges two stops.
For the stops to be merged, they must have:
- the same stop_id
- the same stop_name (case insensitive)
- the same zone_id
- locations less than largest_stop_distance apart
The other attributes can have arbitary changes. The merged attributes are
taken from the new stop.
Args:
a: The first stop.
b: The second stop.
Returns:
The merged stop.
Raises:
MergeError: The stops could not be merged.
"""
distance = transitfeed.ApproximateDistanceBetweenStops(a, b)
if distance > self.largest_stop_distance:
raise MergeError("Stops are too far apart: %.1fm "
"(largest_stop_distance is %.1fm)." %
(distance, self.largest_stop_distance))
scheme = {'stop_id': self._MergeIdentical,
'stop_name': self._MergeIdenticalCaseInsensitive,
'zone_id': self._MergeIdentical,
'location_type': self._MergeIdentical}
return self._SchemedMerge(scheme, a, b) | [
"def",
"_MergeEntities",
"(",
"self",
",",
"a",
",",
"b",
")",
":",
"distance",
"=",
"transitfeed",
".",
"ApproximateDistanceBetweenStops",
"(",
"a",
",",
"b",
")",
"if",
"distance",
">",
"self",
".",
"largest_stop_distance",
":",
"raise",
"MergeError",
"(",... | Merges two stops.
For the stops to be merged, they must have:
- the same stop_id
- the same stop_name (case insensitive)
- the same zone_id
- locations less than largest_stop_distance apart
The other attributes can have arbitary changes. The merged attributes are
taken from the new stop.
Args:
a: The first stop.
b: The second stop.
Returns:
The merged stop.
Raises:
MergeError: The stops could not be merged. | [
"Merges",
"two",
"stops",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L932-L962 |
225,159 | google/transitfeed | merge.py | StopMerger._UpdateAndMigrateUnmerged | def _UpdateAndMigrateUnmerged(self, not_merged_stops, zone_map, merge_map,
schedule):
"""Correct references in migrated unmerged stops and add to merged_schedule.
For stops migrated from one of the input feeds to the output feed update the
parent_station and zone_id references to point to objects in the output
feed. Then add the migrated stop to the new schedule.
Args:
not_merged_stops: list of stops from one input feed that have not been
merged
zone_map: map from zone_id in the input feed to zone_id in the output feed
merge_map: map from Stop objects in the input feed to Stop objects in
the output feed
schedule: the input Schedule object
"""
# for the unmerged stops, we use an already mapped zone_id if possible
# if not, we generate a new one and add it to the map
for stop, migrated_stop in not_merged_stops:
if stop.zone_id in zone_map:
migrated_stop.zone_id = zone_map[stop.zone_id]
else:
migrated_stop.zone_id = self.feed_merger.GenerateId(stop.zone_id)
zone_map[stop.zone_id] = migrated_stop.zone_id
if stop.parent_station:
parent_original = schedule.GetStop(stop.parent_station)
migrated_stop.parent_station = merge_map[parent_original].stop_id
self.feed_merger.merged_schedule.AddStopObject(migrated_stop) | python | def _UpdateAndMigrateUnmerged(self, not_merged_stops, zone_map, merge_map,
schedule):
"""Correct references in migrated unmerged stops and add to merged_schedule.
For stops migrated from one of the input feeds to the output feed update the
parent_station and zone_id references to point to objects in the output
feed. Then add the migrated stop to the new schedule.
Args:
not_merged_stops: list of stops from one input feed that have not been
merged
zone_map: map from zone_id in the input feed to zone_id in the output feed
merge_map: map from Stop objects in the input feed to Stop objects in
the output feed
schedule: the input Schedule object
"""
# for the unmerged stops, we use an already mapped zone_id if possible
# if not, we generate a new one and add it to the map
for stop, migrated_stop in not_merged_stops:
if stop.zone_id in zone_map:
migrated_stop.zone_id = zone_map[stop.zone_id]
else:
migrated_stop.zone_id = self.feed_merger.GenerateId(stop.zone_id)
zone_map[stop.zone_id] = migrated_stop.zone_id
if stop.parent_station:
parent_original = schedule.GetStop(stop.parent_station)
migrated_stop.parent_station = merge_map[parent_original].stop_id
self.feed_merger.merged_schedule.AddStopObject(migrated_stop) | [
"def",
"_UpdateAndMigrateUnmerged",
"(",
"self",
",",
"not_merged_stops",
",",
"zone_map",
",",
"merge_map",
",",
"schedule",
")",
":",
"# for the unmerged stops, we use an already mapped zone_id if possible",
"# if not, we generate a new one and add it to the map",
"for",
"stop",
... | Correct references in migrated unmerged stops and add to merged_schedule.
For stops migrated from one of the input feeds to the output feed update the
parent_station and zone_id references to point to objects in the output
feed. Then add the migrated stop to the new schedule.
Args:
not_merged_stops: list of stops from one input feed that have not been
merged
zone_map: map from zone_id in the input feed to zone_id in the output feed
merge_map: map from Stop objects in the input feed to Stop objects in
the output feed
schedule: the input Schedule object | [
"Correct",
"references",
"in",
"migrated",
"unmerged",
"stops",
"and",
"add",
"to",
"merged_schedule",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L1014-L1041 |
225,160 | google/transitfeed | merge.py | ServicePeriodMerger.DisjoinCalendars | def DisjoinCalendars(self, cutoff):
"""Forces the old and new calendars to be disjoint about a cutoff date.
This truncates the service periods of the old schedule so that service
stops one day before the given cutoff date and truncates the new schedule
so that service only begins on the cutoff date.
Args:
cutoff: The cutoff date as a string in YYYYMMDD format. The timezone
is the same as used in the calendar.txt file.
"""
def TruncatePeriod(service_period, start, end):
"""Truncate the service period to into the range [start, end].
Args:
service_period: The service period to truncate.
start: The start date as a string in YYYYMMDD format.
end: The end date as a string in YYYYMMDD format.
"""
service_period.start_date = max(service_period.start_date, start)
service_period.end_date = min(service_period.end_date, end)
dates_to_delete = []
for k in service_period.date_exceptions:
if (k < start) or (k > end):
dates_to_delete.append(k)
for k in dates_to_delete:
del service_period.date_exceptions[k]
# find the date one day before cutoff
year = int(cutoff[:4])
month = int(cutoff[4:6])
day = int(cutoff[6:8])
cutoff_date = datetime.date(year, month, day)
one_day_delta = datetime.timedelta(days=1)
before = (cutoff_date - one_day_delta).strftime('%Y%m%d')
for a in self.feed_merger.a_schedule.GetServicePeriodList():
TruncatePeriod(a, 0, before)
for b in self.feed_merger.b_schedule.GetServicePeriodList():
TruncatePeriod(b, cutoff, '9'*8) | python | def DisjoinCalendars(self, cutoff):
"""Forces the old and new calendars to be disjoint about a cutoff date.
This truncates the service periods of the old schedule so that service
stops one day before the given cutoff date and truncates the new schedule
so that service only begins on the cutoff date.
Args:
cutoff: The cutoff date as a string in YYYYMMDD format. The timezone
is the same as used in the calendar.txt file.
"""
def TruncatePeriod(service_period, start, end):
"""Truncate the service period to into the range [start, end].
Args:
service_period: The service period to truncate.
start: The start date as a string in YYYYMMDD format.
end: The end date as a string in YYYYMMDD format.
"""
service_period.start_date = max(service_period.start_date, start)
service_period.end_date = min(service_period.end_date, end)
dates_to_delete = []
for k in service_period.date_exceptions:
if (k < start) or (k > end):
dates_to_delete.append(k)
for k in dates_to_delete:
del service_period.date_exceptions[k]
# find the date one day before cutoff
year = int(cutoff[:4])
month = int(cutoff[4:6])
day = int(cutoff[6:8])
cutoff_date = datetime.date(year, month, day)
one_day_delta = datetime.timedelta(days=1)
before = (cutoff_date - one_day_delta).strftime('%Y%m%d')
for a in self.feed_merger.a_schedule.GetServicePeriodList():
TruncatePeriod(a, 0, before)
for b in self.feed_merger.b_schedule.GetServicePeriodList():
TruncatePeriod(b, cutoff, '9'*8) | [
"def",
"DisjoinCalendars",
"(",
"self",
",",
"cutoff",
")",
":",
"def",
"TruncatePeriod",
"(",
"service_period",
",",
"start",
",",
"end",
")",
":",
"\"\"\"Truncate the service period to into the range [start, end].\n\n Args:\n service_period: The service period to tr... | Forces the old and new calendars to be disjoint about a cutoff date.
This truncates the service periods of the old schedule so that service
stops one day before the given cutoff date and truncates the new schedule
so that service only begins on the cutoff date.
Args:
cutoff: The cutoff date as a string in YYYYMMDD format. The timezone
is the same as used in the calendar.txt file. | [
"Forces",
"the",
"old",
"and",
"new",
"calendars",
"to",
"be",
"disjoint",
"about",
"a",
"cutoff",
"date",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L1166-L1206 |
225,161 | google/transitfeed | merge.py | ServicePeriodMerger.CheckDisjointCalendars | def CheckDisjointCalendars(self):
"""Check whether any old service periods intersect with any new ones.
This is a rather coarse check based on
transitfeed.SevicePeriod.GetDateRange.
Returns:
True if the calendars are disjoint or False if not.
"""
# TODO: Do an exact check here.
a_service_periods = self.feed_merger.a_schedule.GetServicePeriodList()
b_service_periods = self.feed_merger.b_schedule.GetServicePeriodList()
for a_service_period in a_service_periods:
a_start, a_end = a_service_period.GetDateRange()
for b_service_period in b_service_periods:
b_start, b_end = b_service_period.GetDateRange()
overlap_start = max(a_start, b_start)
overlap_end = min(a_end, b_end)
if overlap_end >= overlap_start:
return False
return True | python | def CheckDisjointCalendars(self):
"""Check whether any old service periods intersect with any new ones.
This is a rather coarse check based on
transitfeed.SevicePeriod.GetDateRange.
Returns:
True if the calendars are disjoint or False if not.
"""
# TODO: Do an exact check here.
a_service_periods = self.feed_merger.a_schedule.GetServicePeriodList()
b_service_periods = self.feed_merger.b_schedule.GetServicePeriodList()
for a_service_period in a_service_periods:
a_start, a_end = a_service_period.GetDateRange()
for b_service_period in b_service_periods:
b_start, b_end = b_service_period.GetDateRange()
overlap_start = max(a_start, b_start)
overlap_end = min(a_end, b_end)
if overlap_end >= overlap_start:
return False
return True | [
"def",
"CheckDisjointCalendars",
"(",
"self",
")",
":",
"# TODO: Do an exact check here.",
"a_service_periods",
"=",
"self",
".",
"feed_merger",
".",
"a_schedule",
".",
"GetServicePeriodList",
"(",
")",
"b_service_periods",
"=",
"self",
".",
"feed_merger",
".",
"b_sch... | Check whether any old service periods intersect with any new ones.
This is a rather coarse check based on
transitfeed.SevicePeriod.GetDateRange.
Returns:
True if the calendars are disjoint or False if not. | [
"Check",
"whether",
"any",
"old",
"service",
"periods",
"intersect",
"with",
"any",
"new",
"ones",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L1208-L1230 |
225,162 | google/transitfeed | merge.py | FareMerger._MergeEntities | def _MergeEntities(self, a, b):
"""Merges the fares if all the attributes are the same."""
scheme = {'price': self._MergeIdentical,
'currency_type': self._MergeIdentical,
'payment_method': self._MergeIdentical,
'transfers': self._MergeIdentical,
'transfer_duration': self._MergeIdentical}
return self._SchemedMerge(scheme, a, b) | python | def _MergeEntities(self, a, b):
"""Merges the fares if all the attributes are the same."""
scheme = {'price': self._MergeIdentical,
'currency_type': self._MergeIdentical,
'payment_method': self._MergeIdentical,
'transfers': self._MergeIdentical,
'transfer_duration': self._MergeIdentical}
return self._SchemedMerge(scheme, a, b) | [
"def",
"_MergeEntities",
"(",
"self",
",",
"a",
",",
"b",
")",
":",
"scheme",
"=",
"{",
"'price'",
":",
"self",
".",
"_MergeIdentical",
",",
"'currency_type'",
":",
"self",
".",
"_MergeIdentical",
",",
"'payment_method'",
":",
"self",
".",
"_MergeIdentical",... | Merges the fares if all the attributes are the same. | [
"Merges",
"the",
"fares",
"if",
"all",
"the",
"attributes",
"are",
"the",
"same",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L1249-L1256 |
225,163 | google/transitfeed | merge.py | ShapeMerger._MergeEntities | def _MergeEntities(self, a, b):
"""Merges the shapes by taking the new shape.
Args:
a: The first transitfeed.Shape instance.
b: The second transitfeed.Shape instance.
Returns:
The merged shape.
Raises:
MergeError: If the ids are different or if the endpoints are further
than largest_shape_distance apart.
"""
if a.shape_id != b.shape_id:
raise MergeError('shape_id must be the same')
distance = max(ApproximateDistanceBetweenPoints(a.points[0][:2],
b.points[0][:2]),
ApproximateDistanceBetweenPoints(a.points[-1][:2],
b.points[-1][:2]))
if distance > self.largest_shape_distance:
raise MergeError('The shape endpoints are too far away: %.1fm '
'(largest_shape_distance is %.1fm)' %
(distance, self.largest_shape_distance))
return self._Migrate(b, self.feed_merger.b_schedule, False) | python | def _MergeEntities(self, a, b):
"""Merges the shapes by taking the new shape.
Args:
a: The first transitfeed.Shape instance.
b: The second transitfeed.Shape instance.
Returns:
The merged shape.
Raises:
MergeError: If the ids are different or if the endpoints are further
than largest_shape_distance apart.
"""
if a.shape_id != b.shape_id:
raise MergeError('shape_id must be the same')
distance = max(ApproximateDistanceBetweenPoints(a.points[0][:2],
b.points[0][:2]),
ApproximateDistanceBetweenPoints(a.points[-1][:2],
b.points[-1][:2]))
if distance > self.largest_shape_distance:
raise MergeError('The shape endpoints are too far away: %.1fm '
'(largest_shape_distance is %.1fm)' %
(distance, self.largest_shape_distance))
return self._Migrate(b, self.feed_merger.b_schedule, False) | [
"def",
"_MergeEntities",
"(",
"self",
",",
"a",
",",
"b",
")",
":",
"if",
"a",
".",
"shape_id",
"!=",
"b",
".",
"shape_id",
":",
"raise",
"MergeError",
"(",
"'shape_id must be the same'",
")",
"distance",
"=",
"max",
"(",
"ApproximateDistanceBetweenPoints",
... | Merges the shapes by taking the new shape.
Args:
a: The first transitfeed.Shape instance.
b: The second transitfeed.Shape instance.
Returns:
The merged shape.
Raises:
MergeError: If the ids are different or if the endpoints are further
than largest_shape_distance apart. | [
"Merges",
"the",
"shapes",
"by",
"taking",
"the",
"new",
"shape",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L1361-L1387 |
225,164 | google/transitfeed | merge.py | FareRuleMerger.MergeDataSets | def MergeDataSets(self):
"""Merge the fare rule datasets.
The fare rules are first migrated. Merging is done by removing any
duplicate rules.
Returns:
True since fare rules can always be merged.
"""
rules = set()
for (schedule, merge_map, zone_map) in ([self.feed_merger.a_schedule,
self.feed_merger.a_merge_map,
self.feed_merger.a_zone_map],
[self.feed_merger.b_schedule,
self.feed_merger.b_merge_map,
self.feed_merger.b_zone_map]):
for fare in schedule.GetFareAttributeList():
for fare_rule in fare.GetFareRuleList():
fare_id = merge_map[
schedule.GetFareAttribute(fare_rule.fare_id)].fare_id
route_id = (fare_rule.route_id and
merge_map[schedule.GetRoute(fare_rule.route_id)].route_id)
origin_id = (fare_rule.origin_id and
zone_map[fare_rule.origin_id])
destination_id = (fare_rule.destination_id and
zone_map[fare_rule.destination_id])
contains_id = (fare_rule.contains_id and
zone_map[fare_rule.contains_id])
rules.add((fare_id, route_id, origin_id, destination_id,
contains_id))
for fare_rule_tuple in rules:
migrated_fare_rule = transitfeed.FareRule(*fare_rule_tuple)
self.feed_merger.merged_schedule.AddFareRuleObject(migrated_fare_rule)
if rules:
self.feed_merger.problem_reporter.FareRulesBroken(self)
print('Fare Rules: union has %d fare rules' % len(rules))
return True | python | def MergeDataSets(self):
"""Merge the fare rule datasets.
The fare rules are first migrated. Merging is done by removing any
duplicate rules.
Returns:
True since fare rules can always be merged.
"""
rules = set()
for (schedule, merge_map, zone_map) in ([self.feed_merger.a_schedule,
self.feed_merger.a_merge_map,
self.feed_merger.a_zone_map],
[self.feed_merger.b_schedule,
self.feed_merger.b_merge_map,
self.feed_merger.b_zone_map]):
for fare in schedule.GetFareAttributeList():
for fare_rule in fare.GetFareRuleList():
fare_id = merge_map[
schedule.GetFareAttribute(fare_rule.fare_id)].fare_id
route_id = (fare_rule.route_id and
merge_map[schedule.GetRoute(fare_rule.route_id)].route_id)
origin_id = (fare_rule.origin_id and
zone_map[fare_rule.origin_id])
destination_id = (fare_rule.destination_id and
zone_map[fare_rule.destination_id])
contains_id = (fare_rule.contains_id and
zone_map[fare_rule.contains_id])
rules.add((fare_id, route_id, origin_id, destination_id,
contains_id))
for fare_rule_tuple in rules:
migrated_fare_rule = transitfeed.FareRule(*fare_rule_tuple)
self.feed_merger.merged_schedule.AddFareRuleObject(migrated_fare_rule)
if rules:
self.feed_merger.problem_reporter.FareRulesBroken(self)
print('Fare Rules: union has %d fare rules' % len(rules))
return True | [
"def",
"MergeDataSets",
"(",
"self",
")",
":",
"rules",
"=",
"set",
"(",
")",
"for",
"(",
"schedule",
",",
"merge_map",
",",
"zone_map",
")",
"in",
"(",
"[",
"self",
".",
"feed_merger",
".",
"a_schedule",
",",
"self",
".",
"feed_merger",
".",
"a_merge_... | Merge the fare rule datasets.
The fare rules are first migrated. Merging is done by removing any
duplicate rules.
Returns:
True since fare rules can always be merged. | [
"Merge",
"the",
"fare",
"rule",
"datasets",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L1510-L1547 |
225,165 | google/transitfeed | merge.py | FeedMerger._FindLargestIdPostfixNumber | def _FindLargestIdPostfixNumber(self, schedule):
"""Finds the largest integer used as the ending of an id in the schedule.
Args:
schedule: The schedule to check.
Returns:
The maximum integer used as an ending for an id.
"""
postfix_number_re = re.compile('(\d+)$')
def ExtractPostfixNumber(entity_id):
"""Try to extract an integer from the end of entity_id.
If entity_id is None or if there is no integer ending the id, zero is
returned.
Args:
entity_id: An id string or None.
Returns:
An integer ending the entity_id or zero.
"""
if entity_id is None:
return 0
match = postfix_number_re.search(entity_id)
if match is not None:
return int(match.group(1))
else:
return 0
id_data_sets = {'agency_id': schedule.GetAgencyList(),
'stop_id': schedule.GetStopList(),
'route_id': schedule.GetRouteList(),
'trip_id': schedule.GetTripList(),
'service_id': schedule.GetServicePeriodList(),
'fare_id': schedule.GetFareAttributeList(),
'shape_id': schedule.GetShapeList()}
max_postfix_number = 0
for id_name, entity_list in id_data_sets.items():
for entity in entity_list:
entity_id = getattr(entity, id_name)
postfix_number = ExtractPostfixNumber(entity_id)
max_postfix_number = max(max_postfix_number, postfix_number)
return max_postfix_number | python | def _FindLargestIdPostfixNumber(self, schedule):
"""Finds the largest integer used as the ending of an id in the schedule.
Args:
schedule: The schedule to check.
Returns:
The maximum integer used as an ending for an id.
"""
postfix_number_re = re.compile('(\d+)$')
def ExtractPostfixNumber(entity_id):
"""Try to extract an integer from the end of entity_id.
If entity_id is None or if there is no integer ending the id, zero is
returned.
Args:
entity_id: An id string or None.
Returns:
An integer ending the entity_id or zero.
"""
if entity_id is None:
return 0
match = postfix_number_re.search(entity_id)
if match is not None:
return int(match.group(1))
else:
return 0
id_data_sets = {'agency_id': schedule.GetAgencyList(),
'stop_id': schedule.GetStopList(),
'route_id': schedule.GetRouteList(),
'trip_id': schedule.GetTripList(),
'service_id': schedule.GetServicePeriodList(),
'fare_id': schedule.GetFareAttributeList(),
'shape_id': schedule.GetShapeList()}
max_postfix_number = 0
for id_name, entity_list in id_data_sets.items():
for entity in entity_list:
entity_id = getattr(entity, id_name)
postfix_number = ExtractPostfixNumber(entity_id)
max_postfix_number = max(max_postfix_number, postfix_number)
return max_postfix_number | [
"def",
"_FindLargestIdPostfixNumber",
"(",
"self",
",",
"schedule",
")",
":",
"postfix_number_re",
"=",
"re",
".",
"compile",
"(",
"'(\\d+)$'",
")",
"def",
"ExtractPostfixNumber",
"(",
"entity_id",
")",
":",
"\"\"\"Try to extract an integer from the end of entity_id.\n\n ... | Finds the largest integer used as the ending of an id in the schedule.
Args:
schedule: The schedule to check.
Returns:
The maximum integer used as an ending for an id. | [
"Finds",
"the",
"largest",
"integer",
"used",
"as",
"the",
"ending",
"of",
"an",
"id",
"in",
"the",
"schedule",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L1597-L1642 |
225,166 | google/transitfeed | merge.py | FeedMerger.GenerateId | def GenerateId(self, entity_id=None):
"""Generate a unique id based on the given id.
This is done by appending a counter which is then incremented. The
counter is initialised at the maximum number used as an ending for
any id in the old and new schedules.
Args:
entity_id: The base id string. This is allowed to be None.
Returns:
The generated id.
"""
self._idnum += 1
if entity_id:
return '%s_merged_%d' % (entity_id, self._idnum)
else:
return 'merged_%d' % self._idnum | python | def GenerateId(self, entity_id=None):
"""Generate a unique id based on the given id.
This is done by appending a counter which is then incremented. The
counter is initialised at the maximum number used as an ending for
any id in the old and new schedules.
Args:
entity_id: The base id string. This is allowed to be None.
Returns:
The generated id.
"""
self._idnum += 1
if entity_id:
return '%s_merged_%d' % (entity_id, self._idnum)
else:
return 'merged_%d' % self._idnum | [
"def",
"GenerateId",
"(",
"self",
",",
"entity_id",
"=",
"None",
")",
":",
"self",
".",
"_idnum",
"+=",
"1",
"if",
"entity_id",
":",
"return",
"'%s_merged_%d'",
"%",
"(",
"entity_id",
",",
"self",
".",
"_idnum",
")",
"else",
":",
"return",
"'merged_%d'",... | Generate a unique id based on the given id.
This is done by appending a counter which is then incremented. The
counter is initialised at the maximum number used as an ending for
any id in the old and new schedules.
Args:
entity_id: The base id string. This is allowed to be None.
Returns:
The generated id. | [
"Generate",
"a",
"unique",
"id",
"based",
"on",
"the",
"given",
"id",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L1661-L1678 |
225,167 | google/transitfeed | merge.py | FeedMerger.Register | def Register(self, a, b, migrated_entity):
"""Registers a merge mapping.
If a and b are both not None, this means that entities a and b were merged
to produce migrated_entity. If one of a or b are not None, then it means
it was not merged but simply migrated.
The effect of a call to register is to update a_merge_map and b_merge_map
according to the merge. Also the private attributes _migrated_entity of a
and b are set to migrated_entity.
Args:
a: The entity from the old feed or None.
b: The entity from the new feed or None.
migrated_entity: The migrated entity.
"""
# There are a few places where code needs to find the corresponding
# migrated entity of an object without knowing in which original schedule
# the entity started. With a_merge_map and b_merge_map both have to be
# checked. Use of the _migrated_entity attribute allows the migrated entity
# to be directly found without the schedule. The merge maps also require
# that all objects be hashable. GenericGTFSObject is at the moment, but
# this is a bug. See comment in transitfeed.GenericGTFSObject.
if a is not None:
self.a_merge_map[a] = migrated_entity
a._migrated_entity = migrated_entity
if b is not None:
self.b_merge_map[b] = migrated_entity
b._migrated_entity = migrated_entity | python | def Register(self, a, b, migrated_entity):
"""Registers a merge mapping.
If a and b are both not None, this means that entities a and b were merged
to produce migrated_entity. If one of a or b are not None, then it means
it was not merged but simply migrated.
The effect of a call to register is to update a_merge_map and b_merge_map
according to the merge. Also the private attributes _migrated_entity of a
and b are set to migrated_entity.
Args:
a: The entity from the old feed or None.
b: The entity from the new feed or None.
migrated_entity: The migrated entity.
"""
# There are a few places where code needs to find the corresponding
# migrated entity of an object without knowing in which original schedule
# the entity started. With a_merge_map and b_merge_map both have to be
# checked. Use of the _migrated_entity attribute allows the migrated entity
# to be directly found without the schedule. The merge maps also require
# that all objects be hashable. GenericGTFSObject is at the moment, but
# this is a bug. See comment in transitfeed.GenericGTFSObject.
if a is not None:
self.a_merge_map[a] = migrated_entity
a._migrated_entity = migrated_entity
if b is not None:
self.b_merge_map[b] = migrated_entity
b._migrated_entity = migrated_entity | [
"def",
"Register",
"(",
"self",
",",
"a",
",",
"b",
",",
"migrated_entity",
")",
":",
"# There are a few places where code needs to find the corresponding",
"# migrated entity of an object without knowing in which original schedule",
"# the entity started. With a_merge_map and b_merge_ma... | Registers a merge mapping.
If a and b are both not None, this means that entities a and b were merged
to produce migrated_entity. If one of a or b are not None, then it means
it was not merged but simply migrated.
The effect of a call to register is to update a_merge_map and b_merge_map
according to the merge. Also the private attributes _migrated_entity of a
and b are set to migrated_entity.
Args:
a: The entity from the old feed or None.
b: The entity from the new feed or None.
migrated_entity: The migrated entity. | [
"Registers",
"a",
"merge",
"mapping",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L1680-L1708 |
225,168 | google/transitfeed | merge.py | FeedMerger.AddDefaultMergers | def AddDefaultMergers(self):
"""Adds the default DataSetMergers defined in this module."""
self.AddMerger(AgencyMerger(self))
self.AddMerger(StopMerger(self))
self.AddMerger(RouteMerger(self))
self.AddMerger(ServicePeriodMerger(self))
self.AddMerger(FareMerger(self))
self.AddMerger(ShapeMerger(self))
self.AddMerger(TripMerger(self))
self.AddMerger(FareRuleMerger(self)) | python | def AddDefaultMergers(self):
"""Adds the default DataSetMergers defined in this module."""
self.AddMerger(AgencyMerger(self))
self.AddMerger(StopMerger(self))
self.AddMerger(RouteMerger(self))
self.AddMerger(ServicePeriodMerger(self))
self.AddMerger(FareMerger(self))
self.AddMerger(ShapeMerger(self))
self.AddMerger(TripMerger(self))
self.AddMerger(FareRuleMerger(self)) | [
"def",
"AddDefaultMergers",
"(",
"self",
")",
":",
"self",
".",
"AddMerger",
"(",
"AgencyMerger",
"(",
"self",
")",
")",
"self",
".",
"AddMerger",
"(",
"StopMerger",
"(",
"self",
")",
")",
"self",
".",
"AddMerger",
"(",
"RouteMerger",
"(",
"self",
")",
... | Adds the default DataSetMergers defined in this module. | [
"Adds",
"the",
"default",
"DataSetMergers",
"defined",
"in",
"this",
"module",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L1718-L1727 |
225,169 | google/transitfeed | merge.py | FeedMerger.GetMerger | def GetMerger(self, cls):
"""Looks for an added DataSetMerger derived from the given class.
Args:
cls: A class derived from DataSetMerger.
Returns:
The matching DataSetMerger instance.
Raises:
LookupError: No matching DataSetMerger has been added.
"""
for merger in self._mergers:
if isinstance(merger, cls):
return merger
raise LookupError('No matching DataSetMerger found') | python | def GetMerger(self, cls):
"""Looks for an added DataSetMerger derived from the given class.
Args:
cls: A class derived from DataSetMerger.
Returns:
The matching DataSetMerger instance.
Raises:
LookupError: No matching DataSetMerger has been added.
"""
for merger in self._mergers:
if isinstance(merger, cls):
return merger
raise LookupError('No matching DataSetMerger found') | [
"def",
"GetMerger",
"(",
"self",
",",
"cls",
")",
":",
"for",
"merger",
"in",
"self",
".",
"_mergers",
":",
"if",
"isinstance",
"(",
"merger",
",",
"cls",
")",
":",
"return",
"merger",
"raise",
"LookupError",
"(",
"'No matching DataSetMerger found'",
")"
] | Looks for an added DataSetMerger derived from the given class.
Args:
cls: A class derived from DataSetMerger.
Returns:
The matching DataSetMerger instance.
Raises:
LookupError: No matching DataSetMerger has been added. | [
"Looks",
"for",
"an",
"added",
"DataSetMerger",
"derived",
"from",
"the",
"given",
"class",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L1729-L1744 |
225,170 | google/transitfeed | unusual_trip_filter.py | UnusualTripFilter.filter_line | def filter_line(self, route):
"""Mark unusual trips for the given route."""
if self._route_type is not None and self._route_type != route.route_type:
self.info('Skipping route %s due to different route_type value (%s)' %
(route['route_id'], route['route_type']))
return
self.info('Filtering infrequent trips for route %s.' % route.route_id)
trip_count = len(route.trips)
for pattern_id, pattern in route.GetPatternIdTripDict().items():
ratio = float(1.0 * len(pattern) / trip_count)
if not self._force:
if (ratio < self._threshold):
self.info("\t%d trips on route %s with headsign '%s' recognized "
"as unusual (ratio %f)" %
(len(pattern),
route['route_short_name'],
pattern[0]['trip_headsign'],
ratio))
for trip in pattern:
trip.trip_type = 1 # special
self.info("\t\tsetting trip_type of trip %s as special" %
trip.trip_id)
else:
self.info("\t%d trips on route %s with headsign '%s' recognized "
"as %s (ratio %f)" %
(len(pattern),
route['route_short_name'],
pattern[0]['trip_headsign'],
('regular', 'unusual')[ratio < self._threshold],
ratio))
for trip in pattern:
trip.trip_type = ('0','1')[ratio < self._threshold]
self.info("\t\tsetting trip_type of trip %s as %s" %
(trip.trip_id,
('regular', 'unusual')[ratio < self._threshold])) | python | def filter_line(self, route):
"""Mark unusual trips for the given route."""
if self._route_type is not None and self._route_type != route.route_type:
self.info('Skipping route %s due to different route_type value (%s)' %
(route['route_id'], route['route_type']))
return
self.info('Filtering infrequent trips for route %s.' % route.route_id)
trip_count = len(route.trips)
for pattern_id, pattern in route.GetPatternIdTripDict().items():
ratio = float(1.0 * len(pattern) / trip_count)
if not self._force:
if (ratio < self._threshold):
self.info("\t%d trips on route %s with headsign '%s' recognized "
"as unusual (ratio %f)" %
(len(pattern),
route['route_short_name'],
pattern[0]['trip_headsign'],
ratio))
for trip in pattern:
trip.trip_type = 1 # special
self.info("\t\tsetting trip_type of trip %s as special" %
trip.trip_id)
else:
self.info("\t%d trips on route %s with headsign '%s' recognized "
"as %s (ratio %f)" %
(len(pattern),
route['route_short_name'],
pattern[0]['trip_headsign'],
('regular', 'unusual')[ratio < self._threshold],
ratio))
for trip in pattern:
trip.trip_type = ('0','1')[ratio < self._threshold]
self.info("\t\tsetting trip_type of trip %s as %s" %
(trip.trip_id,
('regular', 'unusual')[ratio < self._threshold])) | [
"def",
"filter_line",
"(",
"self",
",",
"route",
")",
":",
"if",
"self",
".",
"_route_type",
"is",
"not",
"None",
"and",
"self",
".",
"_route_type",
"!=",
"route",
".",
"route_type",
":",
"self",
".",
"info",
"(",
"'Skipping route %s due to different route_typ... | Mark unusual trips for the given route. | [
"Mark",
"unusual",
"trips",
"for",
"the",
"given",
"route",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/unusual_trip_filter.py#L56-L90 |
225,171 | google/transitfeed | unusual_trip_filter.py | UnusualTripFilter.filter | def filter(self, dataset):
"""Mark unusual trips for all the routes in the dataset."""
self.info('Going to filter infrequent routes in the dataset')
for route in dataset.routes.values():
self.filter_line(route) | python | def filter(self, dataset):
"""Mark unusual trips for all the routes in the dataset."""
self.info('Going to filter infrequent routes in the dataset')
for route in dataset.routes.values():
self.filter_line(route) | [
"def",
"filter",
"(",
"self",
",",
"dataset",
")",
":",
"self",
".",
"info",
"(",
"'Going to filter infrequent routes in the dataset'",
")",
"for",
"route",
"in",
"dataset",
".",
"routes",
".",
"values",
"(",
")",
":",
"self",
".",
"filter_line",
"(",
"route... | Mark unusual trips for all the routes in the dataset. | [
"Mark",
"unusual",
"trips",
"for",
"all",
"the",
"routes",
"in",
"the",
"dataset",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/unusual_trip_filter.py#L92-L96 |
225,172 | google/transitfeed | schedule_viewer.py | StopToTuple | def StopToTuple(stop):
"""Return tuple as expected by javascript function addStopMarkerFromList"""
return (stop.stop_id, stop.stop_name, float(stop.stop_lat),
float(stop.stop_lon), stop.location_type) | python | def StopToTuple(stop):
"""Return tuple as expected by javascript function addStopMarkerFromList"""
return (stop.stop_id, stop.stop_name, float(stop.stop_lat),
float(stop.stop_lon), stop.location_type) | [
"def",
"StopToTuple",
"(",
"stop",
")",
":",
"return",
"(",
"stop",
".",
"stop_id",
",",
"stop",
".",
"stop_name",
",",
"float",
"(",
"stop",
".",
"stop_lat",
")",
",",
"float",
"(",
"stop",
".",
"stop_lon",
")",
",",
"stop",
".",
"location_type",
")... | Return tuple as expected by javascript function addStopMarkerFromList | [
"Return",
"tuple",
"as",
"expected",
"by",
"javascript",
"function",
"addStopMarkerFromList"
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/schedule_viewer.py#L89-L92 |
225,173 | google/transitfeed | schedule_viewer.py | FindDefaultFileDir | def FindDefaultFileDir():
"""Return the path of the directory containing the static files. By default
the directory is called 'files'. The location depends on where setup.py put
it."""
base = FindPy2ExeBase()
if base:
return os.path.join(base, 'schedule_viewer_files')
else:
# For all other distributions 'files' is in the gtfsscheduleviewer
# directory.
base = os.path.dirname(gtfsscheduleviewer.__file__) # Strip __init__.py
return os.path.join(base, 'files') | python | def FindDefaultFileDir():
"""Return the path of the directory containing the static files. By default
the directory is called 'files'. The location depends on where setup.py put
it."""
base = FindPy2ExeBase()
if base:
return os.path.join(base, 'schedule_viewer_files')
else:
# For all other distributions 'files' is in the gtfsscheduleviewer
# directory.
base = os.path.dirname(gtfsscheduleviewer.__file__) # Strip __init__.py
return os.path.join(base, 'files') | [
"def",
"FindDefaultFileDir",
"(",
")",
":",
"base",
"=",
"FindPy2ExeBase",
"(",
")",
"if",
"base",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"base",
",",
"'schedule_viewer_files'",
")",
"else",
":",
"# For all other distributions 'files' is in the gtfssc... | Return the path of the directory containing the static files. By default
the directory is called 'files'. The location depends on where setup.py put
it. | [
"Return",
"the",
"path",
"of",
"the",
"directory",
"containing",
"the",
"static",
"files",
".",
"By",
"default",
"the",
"directory",
"is",
"called",
"files",
".",
"The",
"location",
"depends",
"on",
"where",
"setup",
".",
"py",
"put",
"it",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/schedule_viewer.py#L461-L472 |
225,174 | google/transitfeed | schedule_viewer.py | ScheduleRequestHandler.handle_json_GET_routepatterns | def handle_json_GET_routepatterns(self, params):
"""Given a route_id generate a list of patterns of the route. For each
pattern include some basic information and a few sample trips."""
schedule = self.server.schedule
route = schedule.GetRoute(params.get('route', None))
if not route:
self.send_error(404)
return
time = int(params.get('time', 0))
date = params.get('date', "")
sample_size = 3 # For each pattern return the start time for this many trips
pattern_id_trip_dict = route.GetPatternIdTripDict()
patterns = []
for pattern_id, trips in pattern_id_trip_dict.items():
time_stops = trips[0].GetTimeStops()
if not time_stops:
continue
has_non_zero_trip_type = False;
# Iterating over a copy so we can remove from trips inside the loop
trips_with_service = []
for trip in trips:
service_id = trip.service_id
service_period = schedule.GetServicePeriod(service_id)
if date and not service_period.IsActiveOn(date):
continue
trips_with_service.append(trip)
if trip['trip_type'] and trip['trip_type'] != '0':
has_non_zero_trip_type = True
# We're only interested in the trips that do run on the specified date
trips = trips_with_service
name = u'%s to %s, %d stops' % (time_stops[0][2].stop_name, time_stops[-1][2].stop_name, len(time_stops))
transitfeed.SortListOfTripByTime(trips)
num_trips = len(trips)
if num_trips <= sample_size:
start_sample_index = 0
num_after_sample = 0
else:
# Will return sample_size trips that start after the 'time' param.
# Linear search because I couldn't find a built-in way to do a binary
# search with a custom key.
start_sample_index = len(trips)
for i, trip in enumerate(trips):
if trip.GetStartTime() >= time:
start_sample_index = i
break
num_after_sample = num_trips - (start_sample_index + sample_size)
if num_after_sample < 0:
# Less than sample_size trips start after 'time' so return all the
# last sample_size trips.
num_after_sample = 0
start_sample_index = num_trips - sample_size
sample = []
for t in trips[start_sample_index:start_sample_index + sample_size]:
sample.append( (t.GetStartTime(), t.trip_id) )
patterns.append((name, pattern_id, start_sample_index, sample,
num_after_sample, (0,1)[has_non_zero_trip_type]))
patterns.sort()
return patterns | python | def handle_json_GET_routepatterns(self, params):
"""Given a route_id generate a list of patterns of the route. For each
pattern include some basic information and a few sample trips."""
schedule = self.server.schedule
route = schedule.GetRoute(params.get('route', None))
if not route:
self.send_error(404)
return
time = int(params.get('time', 0))
date = params.get('date', "")
sample_size = 3 # For each pattern return the start time for this many trips
pattern_id_trip_dict = route.GetPatternIdTripDict()
patterns = []
for pattern_id, trips in pattern_id_trip_dict.items():
time_stops = trips[0].GetTimeStops()
if not time_stops:
continue
has_non_zero_trip_type = False;
# Iterating over a copy so we can remove from trips inside the loop
trips_with_service = []
for trip in trips:
service_id = trip.service_id
service_period = schedule.GetServicePeriod(service_id)
if date and not service_period.IsActiveOn(date):
continue
trips_with_service.append(trip)
if trip['trip_type'] and trip['trip_type'] != '0':
has_non_zero_trip_type = True
# We're only interested in the trips that do run on the specified date
trips = trips_with_service
name = u'%s to %s, %d stops' % (time_stops[0][2].stop_name, time_stops[-1][2].stop_name, len(time_stops))
transitfeed.SortListOfTripByTime(trips)
num_trips = len(trips)
if num_trips <= sample_size:
start_sample_index = 0
num_after_sample = 0
else:
# Will return sample_size trips that start after the 'time' param.
# Linear search because I couldn't find a built-in way to do a binary
# search with a custom key.
start_sample_index = len(trips)
for i, trip in enumerate(trips):
if trip.GetStartTime() >= time:
start_sample_index = i
break
num_after_sample = num_trips - (start_sample_index + sample_size)
if num_after_sample < 0:
# Less than sample_size trips start after 'time' so return all the
# last sample_size trips.
num_after_sample = 0
start_sample_index = num_trips - sample_size
sample = []
for t in trips[start_sample_index:start_sample_index + sample_size]:
sample.append( (t.GetStartTime(), t.trip_id) )
patterns.append((name, pattern_id, start_sample_index, sample,
num_after_sample, (0,1)[has_non_zero_trip_type]))
patterns.sort()
return patterns | [
"def",
"handle_json_GET_routepatterns",
"(",
"self",
",",
"params",
")",
":",
"schedule",
"=",
"self",
".",
"server",
".",
"schedule",
"route",
"=",
"schedule",
".",
"GetRoute",
"(",
"params",
".",
"get",
"(",
"'route'",
",",
"None",
")",
")",
"if",
"not... | Given a route_id generate a list of patterns of the route. For each
pattern include some basic information and a few sample trips. | [
"Given",
"a",
"route_id",
"generate",
"a",
"list",
"of",
"patterns",
"of",
"the",
"route",
".",
"For",
"each",
"pattern",
"include",
"some",
"basic",
"information",
"and",
"a",
"few",
"sample",
"trips",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/schedule_viewer.py#L187-L257 |
225,175 | google/transitfeed | schedule_viewer.py | ScheduleRequestHandler.handle_json_wrapper_GET | def handle_json_wrapper_GET(self, handler, parsed_params):
"""Call handler and output the return value in JSON."""
schedule = self.server.schedule
result = handler(parsed_params)
content = ResultEncoder().encode(result)
self.send_response(200)
self.send_header('Content-Type', 'text/plain')
self.send_header('Content-Length', str(len(content)))
self.end_headers()
self.wfile.write(content) | python | def handle_json_wrapper_GET(self, handler, parsed_params):
"""Call handler and output the return value in JSON."""
schedule = self.server.schedule
result = handler(parsed_params)
content = ResultEncoder().encode(result)
self.send_response(200)
self.send_header('Content-Type', 'text/plain')
self.send_header('Content-Length', str(len(content)))
self.end_headers()
self.wfile.write(content) | [
"def",
"handle_json_wrapper_GET",
"(",
"self",
",",
"handler",
",",
"parsed_params",
")",
":",
"schedule",
"=",
"self",
".",
"server",
".",
"schedule",
"result",
"=",
"handler",
"(",
"parsed_params",
")",
"content",
"=",
"ResultEncoder",
"(",
")",
".",
"enco... | Call handler and output the return value in JSON. | [
"Call",
"handler",
"and",
"output",
"the",
"return",
"value",
"in",
"JSON",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/schedule_viewer.py#L259-L268 |
225,176 | google/transitfeed | schedule_viewer.py | ScheduleRequestHandler.handle_json_GET_routes | def handle_json_GET_routes(self, params):
"""Return a list of all routes."""
schedule = self.server.schedule
result = []
for r in schedule.GetRouteList():
result.append( (r.route_id, r.route_short_name, r.route_long_name) )
result.sort(key = lambda x: x[1:3])
return result | python | def handle_json_GET_routes(self, params):
"""Return a list of all routes."""
schedule = self.server.schedule
result = []
for r in schedule.GetRouteList():
result.append( (r.route_id, r.route_short_name, r.route_long_name) )
result.sort(key = lambda x: x[1:3])
return result | [
"def",
"handle_json_GET_routes",
"(",
"self",
",",
"params",
")",
":",
"schedule",
"=",
"self",
".",
"server",
".",
"schedule",
"result",
"=",
"[",
"]",
"for",
"r",
"in",
"schedule",
".",
"GetRouteList",
"(",
")",
":",
"result",
".",
"append",
"(",
"("... | Return a list of all routes. | [
"Return",
"a",
"list",
"of",
"all",
"routes",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/schedule_viewer.py#L270-L277 |
225,177 | google/transitfeed | schedule_viewer.py | ScheduleRequestHandler.handle_json_GET_triprows | def handle_json_GET_triprows(self, params):
"""Return a list of rows from the feed file that are related to this
trip."""
schedule = self.server.schedule
try:
trip = schedule.GetTrip(params.get('trip', None))
except KeyError:
# if a non-existent trip is searched for, the return nothing
return
route = schedule.GetRoute(trip.route_id)
trip_row = dict(trip.iteritems())
route_row = dict(route.iteritems())
return [['trips.txt', trip_row], ['routes.txt', route_row]] | python | def handle_json_GET_triprows(self, params):
"""Return a list of rows from the feed file that are related to this
trip."""
schedule = self.server.schedule
try:
trip = schedule.GetTrip(params.get('trip', None))
except KeyError:
# if a non-existent trip is searched for, the return nothing
return
route = schedule.GetRoute(trip.route_id)
trip_row = dict(trip.iteritems())
route_row = dict(route.iteritems())
return [['trips.txt', trip_row], ['routes.txt', route_row]] | [
"def",
"handle_json_GET_triprows",
"(",
"self",
",",
"params",
")",
":",
"schedule",
"=",
"self",
".",
"server",
".",
"schedule",
"try",
":",
"trip",
"=",
"schedule",
".",
"GetTrip",
"(",
"params",
".",
"get",
"(",
"'trip'",
",",
"None",
")",
")",
"exc... | Return a list of rows from the feed file that are related to this
trip. | [
"Return",
"a",
"list",
"of",
"rows",
"from",
"the",
"feed",
"file",
"that",
"are",
"related",
"to",
"this",
"trip",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/schedule_viewer.py#L284-L296 |
225,178 | google/transitfeed | schedule_viewer.py | ScheduleRequestHandler.handle_json_GET_neareststops | def handle_json_GET_neareststops(self, params):
"""Return a list of the nearest 'limit' stops to 'lat', 'lon'"""
schedule = self.server.schedule
lat = float(params.get('lat'))
lon = float(params.get('lon'))
limit = int(params.get('limit'))
stops = schedule.GetNearestStops(lat=lat, lon=lon, n=limit)
return [StopToTuple(s) for s in stops] | python | def handle_json_GET_neareststops(self, params):
"""Return a list of the nearest 'limit' stops to 'lat', 'lon'"""
schedule = self.server.schedule
lat = float(params.get('lat'))
lon = float(params.get('lon'))
limit = int(params.get('limit'))
stops = schedule.GetNearestStops(lat=lat, lon=lon, n=limit)
return [StopToTuple(s) for s in stops] | [
"def",
"handle_json_GET_neareststops",
"(",
"self",
",",
"params",
")",
":",
"schedule",
"=",
"self",
".",
"server",
".",
"schedule",
"lat",
"=",
"float",
"(",
"params",
".",
"get",
"(",
"'lat'",
")",
")",
"lon",
"=",
"float",
"(",
"params",
".",
"get"... | Return a list of the nearest 'limit' stops to 'lat', 'lon | [
"Return",
"a",
"list",
"of",
"the",
"nearest",
"limit",
"stops",
"to",
"lat",
"lon"
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/schedule_viewer.py#L337-L344 |
225,179 | google/transitfeed | schedule_viewer.py | ScheduleRequestHandler.handle_json_GET_boundboxstops | def handle_json_GET_boundboxstops(self, params):
"""Return a list of up to 'limit' stops within bounding box with 'n','e'
and 's','w' in the NE and SW corners. Does not handle boxes crossing
longitude line 180."""
schedule = self.server.schedule
n = float(params.get('n'))
e = float(params.get('e'))
s = float(params.get('s'))
w = float(params.get('w'))
limit = int(params.get('limit'))
stops = schedule.GetStopsInBoundingBox(north=n, east=e, south=s, west=w, n=limit)
return [StopToTuple(s) for s in stops] | python | def handle_json_GET_boundboxstops(self, params):
"""Return a list of up to 'limit' stops within bounding box with 'n','e'
and 's','w' in the NE and SW corners. Does not handle boxes crossing
longitude line 180."""
schedule = self.server.schedule
n = float(params.get('n'))
e = float(params.get('e'))
s = float(params.get('s'))
w = float(params.get('w'))
limit = int(params.get('limit'))
stops = schedule.GetStopsInBoundingBox(north=n, east=e, south=s, west=w, n=limit)
return [StopToTuple(s) for s in stops] | [
"def",
"handle_json_GET_boundboxstops",
"(",
"self",
",",
"params",
")",
":",
"schedule",
"=",
"self",
".",
"server",
".",
"schedule",
"n",
"=",
"float",
"(",
"params",
".",
"get",
"(",
"'n'",
")",
")",
"e",
"=",
"float",
"(",
"params",
".",
"get",
"... | Return a list of up to 'limit' stops within bounding box with 'n','e'
and 's','w' in the NE and SW corners. Does not handle boxes crossing
longitude line 180. | [
"Return",
"a",
"list",
"of",
"up",
"to",
"limit",
"stops",
"within",
"bounding",
"box",
"with",
"n",
"e",
"and",
"s",
"w",
"in",
"the",
"NE",
"and",
"SW",
"corners",
".",
"Does",
"not",
"handle",
"boxes",
"crossing",
"longitude",
"line",
"180",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/schedule_viewer.py#L346-L357 |
225,180 | google/transitfeed | schedule_viewer.py | ScheduleRequestHandler.handle_json_GET_stoptrips | def handle_json_GET_stoptrips(self, params):
"""Given a stop_id and time in seconds since midnight return the next
trips to visit the stop."""
schedule = self.server.schedule
stop = schedule.GetStop(params.get('stop', None))
time = int(params.get('time', 0))
date = params.get('date', "")
time_trips = stop.GetStopTimeTrips(schedule)
time_trips.sort() # OPT: use bisect.insort to make this O(N*ln(N)) -> O(N)
# Keep the first 5 after param 'time'.
# Need make a tuple to find correct bisect point
time_trips = time_trips[bisect.bisect_left(time_trips, (time, 0)):]
time_trips = time_trips[:5]
# TODO: combine times for a route to show next 2 departure times
result = []
for time, (trip, index), tp in time_trips:
service_id = trip.service_id
service_period = schedule.GetServicePeriod(service_id)
if date and not service_period.IsActiveOn(date):
continue
headsign = None
# Find the most recent headsign from the StopTime objects
for stoptime in trip.GetStopTimes()[index::-1]:
if stoptime.stop_headsign:
headsign = stoptime.stop_headsign
break
# If stop_headsign isn't found, look for a trip_headsign
if not headsign:
headsign = trip.trip_headsign
route = schedule.GetRoute(trip.route_id)
trip_name = ''
if route.route_short_name:
trip_name += route.route_short_name
if route.route_long_name:
if len(trip_name):
trip_name += " - "
trip_name += route.route_long_name
if headsign:
trip_name += " (Direction: %s)" % headsign
result.append((time, (trip.trip_id, trip_name, trip.service_id), tp))
return result | python | def handle_json_GET_stoptrips(self, params):
"""Given a stop_id and time in seconds since midnight return the next
trips to visit the stop."""
schedule = self.server.schedule
stop = schedule.GetStop(params.get('stop', None))
time = int(params.get('time', 0))
date = params.get('date', "")
time_trips = stop.GetStopTimeTrips(schedule)
time_trips.sort() # OPT: use bisect.insort to make this O(N*ln(N)) -> O(N)
# Keep the first 5 after param 'time'.
# Need make a tuple to find correct bisect point
time_trips = time_trips[bisect.bisect_left(time_trips, (time, 0)):]
time_trips = time_trips[:5]
# TODO: combine times for a route to show next 2 departure times
result = []
for time, (trip, index), tp in time_trips:
service_id = trip.service_id
service_period = schedule.GetServicePeriod(service_id)
if date and not service_period.IsActiveOn(date):
continue
headsign = None
# Find the most recent headsign from the StopTime objects
for stoptime in trip.GetStopTimes()[index::-1]:
if stoptime.stop_headsign:
headsign = stoptime.stop_headsign
break
# If stop_headsign isn't found, look for a trip_headsign
if not headsign:
headsign = trip.trip_headsign
route = schedule.GetRoute(trip.route_id)
trip_name = ''
if route.route_short_name:
trip_name += route.route_short_name
if route.route_long_name:
if len(trip_name):
trip_name += " - "
trip_name += route.route_long_name
if headsign:
trip_name += " (Direction: %s)" % headsign
result.append((time, (trip.trip_id, trip_name, trip.service_id), tp))
return result | [
"def",
"handle_json_GET_stoptrips",
"(",
"self",
",",
"params",
")",
":",
"schedule",
"=",
"self",
".",
"server",
".",
"schedule",
"stop",
"=",
"schedule",
".",
"GetStop",
"(",
"params",
".",
"get",
"(",
"'stop'",
",",
"None",
")",
")",
"time",
"=",
"i... | Given a stop_id and time in seconds since midnight return the next
trips to visit the stop. | [
"Given",
"a",
"stop_id",
"and",
"time",
"in",
"seconds",
"since",
"midnight",
"return",
"the",
"next",
"trips",
"to",
"visit",
"the",
"stop",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/schedule_viewer.py#L368-L410 |
225,181 | google/transitfeed | misc/traceplus.py | MakeExpandedTrace | def MakeExpandedTrace(frame_records):
"""Return a list of text lines for the given list of frame records."""
dump = []
for (frame_obj, filename, line_num, fun_name, context_lines,
context_index) in frame_records:
dump.append('File "%s", line %d, in %s\n' % (filename, line_num,
fun_name))
if context_lines:
for (i, line) in enumerate(context_lines):
if i == context_index:
dump.append(' --> %s' % line)
else:
dump.append(' %s' % line)
for local_name, local_val in frame_obj.f_locals.items():
try:
local_type_name = type(local_val).__name__
except Exception as e:
local_type_name = ' Exception in type({}).__name__: {}'.format(local_name, e)
try:
truncated_val = repr(local_val)[0:500]
except Exception as e:
dump.append(' Exception in repr({}): {}\n'.format(local_name, e))
else:
if len(truncated_val) >= 500:
truncated_val = '%s...' % truncated_val[0:499]
dump.append(' {} = {} ({})\n'.format(local_name, truncated_val, local_type_name))
dump.append('\n')
return dump | python | def MakeExpandedTrace(frame_records):
"""Return a list of text lines for the given list of frame records."""
dump = []
for (frame_obj, filename, line_num, fun_name, context_lines,
context_index) in frame_records:
dump.append('File "%s", line %d, in %s\n' % (filename, line_num,
fun_name))
if context_lines:
for (i, line) in enumerate(context_lines):
if i == context_index:
dump.append(' --> %s' % line)
else:
dump.append(' %s' % line)
for local_name, local_val in frame_obj.f_locals.items():
try:
local_type_name = type(local_val).__name__
except Exception as e:
local_type_name = ' Exception in type({}).__name__: {}'.format(local_name, e)
try:
truncated_val = repr(local_val)[0:500]
except Exception as e:
dump.append(' Exception in repr({}): {}\n'.format(local_name, e))
else:
if len(truncated_val) >= 500:
truncated_val = '%s...' % truncated_val[0:499]
dump.append(' {} = {} ({})\n'.format(local_name, truncated_val, local_type_name))
dump.append('\n')
return dump | [
"def",
"MakeExpandedTrace",
"(",
"frame_records",
")",
":",
"dump",
"=",
"[",
"]",
"for",
"(",
"frame_obj",
",",
"filename",
",",
"line_num",
",",
"fun_name",
",",
"context_lines",
",",
"context_index",
")",
"in",
"frame_records",
":",
"dump",
".",
"append",... | Return a list of text lines for the given list of frame records. | [
"Return",
"a",
"list",
"of",
"text",
"lines",
"for",
"the",
"given",
"list",
"of",
"frame",
"records",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/misc/traceplus.py#L24-L51 |
225,182 | google/transitfeed | transitfeed/shapepoint.py | ShapePoint.ParseAttributes | def ParseAttributes(self, problems):
"""Parse all attributes, calling problems as needed.
Return True if all of the values are valid.
"""
if util.IsEmpty(self.shape_id):
problems.MissingValue('shape_id')
return
try:
if not isinstance(self.shape_pt_sequence, int):
self.shape_pt_sequence = \
util.NonNegIntStringToInt(self.shape_pt_sequence, problems)
elif self.shape_pt_sequence < 0:
problems.InvalidValue('shape_pt_sequence', self.shape_pt_sequence,
'Value should be a number (0 or higher)')
except (TypeError, ValueError):
problems.InvalidValue('shape_pt_sequence', self.shape_pt_sequence,
'Value should be a number (0 or higher)')
return
try:
if not isinstance(self.shape_pt_lat, (int, float)):
self.shape_pt_lat = util.FloatStringToFloat(self.shape_pt_lat, problems)
if abs(self.shape_pt_lat) > 90.0:
problems.InvalidValue('shape_pt_lat', self.shape_pt_lat)
return
except (TypeError, ValueError):
problems.InvalidValue('shape_pt_lat', self.shape_pt_lat)
return
try:
if not isinstance(self.shape_pt_lon, (int, float)):
self.shape_pt_lon = util.FloatStringToFloat(self.shape_pt_lon, problems)
if abs(self.shape_pt_lon) > 180.0:
problems.InvalidValue('shape_pt_lon', self.shape_pt_lon)
return
except (TypeError, ValueError):
problems.InvalidValue('shape_pt_lon', self.shape_pt_lon)
return
if abs(self.shape_pt_lat) < 1.0 and abs(self.shape_pt_lon) < 1.0:
problems.InvalidValue('shape_pt_lat', self.shape_pt_lat,
'Point location too close to 0, 0, which means '
'that it\'s probably an incorrect location.',
type=problems_module.TYPE_WARNING)
return
if self.shape_dist_traveled == '':
self.shape_dist_traveled = None
if (self.shape_dist_traveled is not None and
not isinstance(self.shape_dist_traveled, (int, float))):
try:
self.shape_dist_traveled = \
util.FloatStringToFloat(self.shape_dist_traveled, problems)
except (TypeError, ValueError):
problems.InvalidValue('shape_dist_traveled', self.shape_dist_traveled,
'This value should be a positive number.')
return
if self.shape_dist_traveled is not None and self.shape_dist_traveled < 0:
problems.InvalidValue('shape_dist_traveled', self.shape_dist_traveled,
'This value should be a positive number.')
return
return True | python | def ParseAttributes(self, problems):
"""Parse all attributes, calling problems as needed.
Return True if all of the values are valid.
"""
if util.IsEmpty(self.shape_id):
problems.MissingValue('shape_id')
return
try:
if not isinstance(self.shape_pt_sequence, int):
self.shape_pt_sequence = \
util.NonNegIntStringToInt(self.shape_pt_sequence, problems)
elif self.shape_pt_sequence < 0:
problems.InvalidValue('shape_pt_sequence', self.shape_pt_sequence,
'Value should be a number (0 or higher)')
except (TypeError, ValueError):
problems.InvalidValue('shape_pt_sequence', self.shape_pt_sequence,
'Value should be a number (0 or higher)')
return
try:
if not isinstance(self.shape_pt_lat, (int, float)):
self.shape_pt_lat = util.FloatStringToFloat(self.shape_pt_lat, problems)
if abs(self.shape_pt_lat) > 90.0:
problems.InvalidValue('shape_pt_lat', self.shape_pt_lat)
return
except (TypeError, ValueError):
problems.InvalidValue('shape_pt_lat', self.shape_pt_lat)
return
try:
if not isinstance(self.shape_pt_lon, (int, float)):
self.shape_pt_lon = util.FloatStringToFloat(self.shape_pt_lon, problems)
if abs(self.shape_pt_lon) > 180.0:
problems.InvalidValue('shape_pt_lon', self.shape_pt_lon)
return
except (TypeError, ValueError):
problems.InvalidValue('shape_pt_lon', self.shape_pt_lon)
return
if abs(self.shape_pt_lat) < 1.0 and abs(self.shape_pt_lon) < 1.0:
problems.InvalidValue('shape_pt_lat', self.shape_pt_lat,
'Point location too close to 0, 0, which means '
'that it\'s probably an incorrect location.',
type=problems_module.TYPE_WARNING)
return
if self.shape_dist_traveled == '':
self.shape_dist_traveled = None
if (self.shape_dist_traveled is not None and
not isinstance(self.shape_dist_traveled, (int, float))):
try:
self.shape_dist_traveled = \
util.FloatStringToFloat(self.shape_dist_traveled, problems)
except (TypeError, ValueError):
problems.InvalidValue('shape_dist_traveled', self.shape_dist_traveled,
'This value should be a positive number.')
return
if self.shape_dist_traveled is not None and self.shape_dist_traveled < 0:
problems.InvalidValue('shape_dist_traveled', self.shape_dist_traveled,
'This value should be a positive number.')
return
return True | [
"def",
"ParseAttributes",
"(",
"self",
",",
"problems",
")",
":",
"if",
"util",
".",
"IsEmpty",
"(",
"self",
".",
"shape_id",
")",
":",
"problems",
".",
"MissingValue",
"(",
"'shape_id'",
")",
"return",
"try",
":",
"if",
"not",
"isinstance",
"(",
"self",... | Parse all attributes, calling problems as needed.
Return True if all of the values are valid. | [
"Parse",
"all",
"attributes",
"calling",
"problems",
"as",
"needed",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/shapepoint.py#L59-L125 |
225,183 | google/transitfeed | transitfeed/problems.py | ProblemReporter.SetFileContext | def SetFileContext(self, file_name, row_num, row, headers):
"""Save the current context to be output with any errors.
Args:
file_name: string
row_num: int
row: list of strings
headers: list of column headers, its order corresponding to row's
"""
self._context = (file_name, row_num, row, headers) | python | def SetFileContext(self, file_name, row_num, row, headers):
"""Save the current context to be output with any errors.
Args:
file_name: string
row_num: int
row: list of strings
headers: list of column headers, its order corresponding to row's
"""
self._context = (file_name, row_num, row, headers) | [
"def",
"SetFileContext",
"(",
"self",
",",
"file_name",
",",
"row_num",
",",
"row",
",",
"headers",
")",
":",
"self",
".",
"_context",
"=",
"(",
"file_name",
",",
"row_num",
",",
"row",
",",
"headers",
")"
] | Save the current context to be output with any errors.
Args:
file_name: string
row_num: int
row: list of strings
headers: list of column headers, its order corresponding to row's | [
"Save",
"the",
"current",
"context",
"to",
"be",
"output",
"with",
"any",
"errors",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/problems.py#L53-L62 |
225,184 | google/transitfeed | transitfeed/problems.py | ProblemReporter.InvalidLineEnd | def InvalidLineEnd(self, bad_line_end, context=None, type=TYPE_WARNING):
"""bad_line_end is a human readable string."""
e = InvalidLineEnd(bad_line_end=bad_line_end, context=context,
context2=self._context, type=type)
self.AddToAccumulator(e) | python | def InvalidLineEnd(self, bad_line_end, context=None, type=TYPE_WARNING):
"""bad_line_end is a human readable string."""
e = InvalidLineEnd(bad_line_end=bad_line_end, context=context,
context2=self._context, type=type)
self.AddToAccumulator(e) | [
"def",
"InvalidLineEnd",
"(",
"self",
",",
"bad_line_end",
",",
"context",
"=",
"None",
",",
"type",
"=",
"TYPE_WARNING",
")",
":",
"e",
"=",
"InvalidLineEnd",
"(",
"bad_line_end",
"=",
"bad_line_end",
",",
"context",
"=",
"context",
",",
"context2",
"=",
... | bad_line_end is a human readable string. | [
"bad_line_end",
"is",
"a",
"human",
"readable",
"string",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/problems.py#L268-L272 |
225,185 | google/transitfeed | transitfeed/problems.py | ExceptionWithContext.GetDictToFormat | def GetDictToFormat(self):
"""Return a copy of self as a dict, suitable for passing to FormatProblem"""
d = {}
for k, v in self.__dict__.items():
# TODO: Better handling of unicode/utf-8 within Schedule objects.
# Concatinating a unicode and utf-8 str object causes an exception such
# as "UnicodeDecodeError: 'ascii' codec can't decode byte ..." as python
# tries to convert the str to a unicode. To avoid that happening within
# the problem reporter convert all unicode attributes to utf-8.
# Currently valid utf-8 fields are converted to unicode in _ReadCsvDict.
# Perhaps all fields should be left as utf-8.
d[k] = util.EncodeUnicode(v)
return d | python | def GetDictToFormat(self):
"""Return a copy of self as a dict, suitable for passing to FormatProblem"""
d = {}
for k, v in self.__dict__.items():
# TODO: Better handling of unicode/utf-8 within Schedule objects.
# Concatinating a unicode and utf-8 str object causes an exception such
# as "UnicodeDecodeError: 'ascii' codec can't decode byte ..." as python
# tries to convert the str to a unicode. To avoid that happening within
# the problem reporter convert all unicode attributes to utf-8.
# Currently valid utf-8 fields are converted to unicode in _ReadCsvDict.
# Perhaps all fields should be left as utf-8.
d[k] = util.EncodeUnicode(v)
return d | [
"def",
"GetDictToFormat",
"(",
"self",
")",
":",
"d",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"self",
".",
"__dict__",
".",
"items",
"(",
")",
":",
"# TODO: Better handling of unicode/utf-8 within Schedule objects.",
"# Concatinating a unicode and utf-8 str object ... | Return a copy of self as a dict, suitable for passing to FormatProblem | [
"Return",
"a",
"copy",
"of",
"self",
"as",
"a",
"dict",
"suitable",
"for",
"passing",
"to",
"FormatProblem"
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/problems.py#L445-L457 |
225,186 | google/transitfeed | transitfeed/problems.py | ExceptionWithContext.FormatProblem | def FormatProblem(self, d=None):
"""Return a text string describing the problem.
Args:
d: map returned by GetDictToFormat with with formatting added
"""
if not d:
d = self.GetDictToFormat()
output_error_text = self.__class__.ERROR_TEXT % d
if ('reason' in d) and d['reason']:
return '%s\n%s' % (output_error_text, d['reason'])
else:
return output_error_text | python | def FormatProblem(self, d=None):
"""Return a text string describing the problem.
Args:
d: map returned by GetDictToFormat with with formatting added
"""
if not d:
d = self.GetDictToFormat()
output_error_text = self.__class__.ERROR_TEXT % d
if ('reason' in d) and d['reason']:
return '%s\n%s' % (output_error_text, d['reason'])
else:
return output_error_text | [
"def",
"FormatProblem",
"(",
"self",
",",
"d",
"=",
"None",
")",
":",
"if",
"not",
"d",
":",
"d",
"=",
"self",
".",
"GetDictToFormat",
"(",
")",
"output_error_text",
"=",
"self",
".",
"__class__",
".",
"ERROR_TEXT",
"%",
"d",
"if",
"(",
"'reason'",
"... | Return a text string describing the problem.
Args:
d: map returned by GetDictToFormat with with formatting added | [
"Return",
"a",
"text",
"string",
"describing",
"the",
"problem",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/problems.py#L459-L472 |
225,187 | google/transitfeed | transitfeed/problems.py | ExceptionWithContext.FormatContext | def FormatContext(self):
"""Return a text string describing the context"""
text = ''
if hasattr(self, 'feed_name'):
text += "In feed '%s': " % self.feed_name
if hasattr(self, 'file_name'):
text += self.file_name
if hasattr(self, 'row_num'):
text += ":%i" % self.row_num
if hasattr(self, 'column_name'):
text += " column %s" % self.column_name
return text | python | def FormatContext(self):
"""Return a text string describing the context"""
text = ''
if hasattr(self, 'feed_name'):
text += "In feed '%s': " % self.feed_name
if hasattr(self, 'file_name'):
text += self.file_name
if hasattr(self, 'row_num'):
text += ":%i" % self.row_num
if hasattr(self, 'column_name'):
text += " column %s" % self.column_name
return text | [
"def",
"FormatContext",
"(",
"self",
")",
":",
"text",
"=",
"''",
"if",
"hasattr",
"(",
"self",
",",
"'feed_name'",
")",
":",
"text",
"+=",
"\"In feed '%s': \"",
"%",
"self",
".",
"feed_name",
"if",
"hasattr",
"(",
"self",
",",
"'file_name'",
")",
":",
... | Return a text string describing the context | [
"Return",
"a",
"text",
"string",
"describing",
"the",
"context"
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/problems.py#L474-L485 |
225,188 | google/transitfeed | transitfeed/problems.py | ExceptionWithContext.GetOrderKey | def GetOrderKey(self):
"""Return a tuple that can be used to sort problems into a consistent order.
Returns:
A list of values.
"""
context_attributes = ['_type']
context_attributes.extend(ExceptionWithContext.CONTEXT_PARTS)
context_attributes.extend(self._GetExtraOrderAttributes())
tokens = []
for context_attribute in context_attributes:
tokens.append(getattr(self, context_attribute, None))
return tokens | python | def GetOrderKey(self):
"""Return a tuple that can be used to sort problems into a consistent order.
Returns:
A list of values.
"""
context_attributes = ['_type']
context_attributes.extend(ExceptionWithContext.CONTEXT_PARTS)
context_attributes.extend(self._GetExtraOrderAttributes())
tokens = []
for context_attribute in context_attributes:
tokens.append(getattr(self, context_attribute, None))
return tokens | [
"def",
"GetOrderKey",
"(",
"self",
")",
":",
"context_attributes",
"=",
"[",
"'_type'",
"]",
"context_attributes",
".",
"extend",
"(",
"ExceptionWithContext",
".",
"CONTEXT_PARTS",
")",
"context_attributes",
".",
"extend",
"(",
"self",
".",
"_GetExtraOrderAttributes... | Return a tuple that can be used to sort problems into a consistent order.
Returns:
A list of values. | [
"Return",
"a",
"tuple",
"that",
"can",
"be",
"used",
"to",
"sort",
"problems",
"into",
"a",
"consistent",
"order",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/problems.py#L506-L519 |
225,189 | google/transitfeed | visualize_pathways.py | gtfs_to_graphviz | def gtfs_to_graphviz(gtfs, stop_ids=None):
"""Reads GTFS data and returns GraphViz DOT file content as string.
"""
graph = GraphViz()
location_ids = choose_location_ids(gtfs, stop_ids)
locations = [gtfs.get_location(i) for i in location_ids]
for location in locations:
if not location.parent_id:
graph.add_cluster(GraphCluster(
location.gtfs_id,
location_label(location, max_length=-1),
location_color(location.location_type)))
for location in locations:
if location.parent_id and requires_platform_cluster(location):
graph.get_cluster(location.parent_id).add_cluster(GraphCluster(
location.gtfs_id,
location_label(location),
location_color(location.location_type)))
for location in locations:
if not location.parent_id or requires_platform_cluster(location):
continue
node = GraphNode(
location.gtfs_id,
location_label(location, max_length=25),
location_color(location.location_type),
location_shape(location.location_type))
cluster = graph.get_cluster(location.station().gtfs_id)
if location.location_type == LocationType.boarding_area:
cluster = cluster.get_cluster(location.parent_id)
cluster.nodes.append(node)
for pathway in gtfs.pathways:
if pathway.from_id in location_ids and pathway.to_id in location_ids:
graph.edges.append(GraphEdge(
pathway.from_id, pathway.to_id,
'both' if pathway.is_bidirectional else 'forward',
pathway_label(pathway)))
return graph | python | def gtfs_to_graphviz(gtfs, stop_ids=None):
"""Reads GTFS data and returns GraphViz DOT file content as string.
"""
graph = GraphViz()
location_ids = choose_location_ids(gtfs, stop_ids)
locations = [gtfs.get_location(i) for i in location_ids]
for location in locations:
if not location.parent_id:
graph.add_cluster(GraphCluster(
location.gtfs_id,
location_label(location, max_length=-1),
location_color(location.location_type)))
for location in locations:
if location.parent_id and requires_platform_cluster(location):
graph.get_cluster(location.parent_id).add_cluster(GraphCluster(
location.gtfs_id,
location_label(location),
location_color(location.location_type)))
for location in locations:
if not location.parent_id or requires_platform_cluster(location):
continue
node = GraphNode(
location.gtfs_id,
location_label(location, max_length=25),
location_color(location.location_type),
location_shape(location.location_type))
cluster = graph.get_cluster(location.station().gtfs_id)
if location.location_type == LocationType.boarding_area:
cluster = cluster.get_cluster(location.parent_id)
cluster.nodes.append(node)
for pathway in gtfs.pathways:
if pathway.from_id in location_ids and pathway.to_id in location_ids:
graph.edges.append(GraphEdge(
pathway.from_id, pathway.to_id,
'both' if pathway.is_bidirectional else 'forward',
pathway_label(pathway)))
return graph | [
"def",
"gtfs_to_graphviz",
"(",
"gtfs",
",",
"stop_ids",
"=",
"None",
")",
":",
"graph",
"=",
"GraphViz",
"(",
")",
"location_ids",
"=",
"choose_location_ids",
"(",
"gtfs",
",",
"stop_ids",
")",
"locations",
"=",
"[",
"gtfs",
".",
"get_location",
"(",
"i",... | Reads GTFS data and returns GraphViz DOT file content as string. | [
"Reads",
"GTFS",
"data",
"and",
"returns",
"GraphViz",
"DOT",
"file",
"content",
"as",
"string",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/visualize_pathways.py#L424-L466 |
225,190 | google/transitfeed | transitfeed/gtfsfactoryuser.py | GtfsFactoryUser.GetGtfsFactory | def GetGtfsFactory(self):
"""Return the object's GTFS Factory.
Returns:
The GTFS Factory that was set for this object. If none was explicitly
set, it first sets the object's factory to transitfeed's GtfsFactory
and returns it"""
if self._gtfs_factory is None:
#TODO(anog): We really need to create a dependency graph and clean things
# up, as the comment in __init__.py says.
# Not having GenericGTFSObject as a leaf (with no other
# imports) creates all sorts of circular import problems.
# This is why the import is here and not at the top level.
# When this runs, gtfsfactory should have already been loaded
# by other modules, avoiding the circular imports.
from . import gtfsfactory
self._gtfs_factory = gtfsfactory.GetGtfsFactory()
return self._gtfs_factory | python | def GetGtfsFactory(self):
"""Return the object's GTFS Factory.
Returns:
The GTFS Factory that was set for this object. If none was explicitly
set, it first sets the object's factory to transitfeed's GtfsFactory
and returns it"""
if self._gtfs_factory is None:
#TODO(anog): We really need to create a dependency graph and clean things
# up, as the comment in __init__.py says.
# Not having GenericGTFSObject as a leaf (with no other
# imports) creates all sorts of circular import problems.
# This is why the import is here and not at the top level.
# When this runs, gtfsfactory should have already been loaded
# by other modules, avoiding the circular imports.
from . import gtfsfactory
self._gtfs_factory = gtfsfactory.GetGtfsFactory()
return self._gtfs_factory | [
"def",
"GetGtfsFactory",
"(",
"self",
")",
":",
"if",
"self",
".",
"_gtfs_factory",
"is",
"None",
":",
"#TODO(anog): We really need to create a dependency graph and clean things",
"# up, as the comment in __init__.py says.",
"# Not having GenericGTFSObject as a le... | Return the object's GTFS Factory.
Returns:
The GTFS Factory that was set for this object. If none was explicitly
set, it first sets the object's factory to transitfeed's GtfsFactory
and returns it | [
"Return",
"the",
"object",
"s",
"GTFS",
"Factory",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/gtfsfactoryuser.py#L26-L44 |
225,191 | google/transitfeed | transitfeed/gtfsobjectbase.py | GtfsObjectBase.keys | def keys(self):
"""Return iterable of columns used by this object."""
columns = set()
for name in vars(self):
if (not name) or name[0] == "_":
continue
columns.add(name)
return columns | python | def keys(self):
"""Return iterable of columns used by this object."""
columns = set()
for name in vars(self):
if (not name) or name[0] == "_":
continue
columns.add(name)
return columns | [
"def",
"keys",
"(",
"self",
")",
":",
"columns",
"=",
"set",
"(",
")",
"for",
"name",
"in",
"vars",
"(",
"self",
")",
":",
"if",
"(",
"not",
"name",
")",
"or",
"name",
"[",
"0",
"]",
"==",
"\"_\"",
":",
"continue",
"columns",
".",
"add",
"(",
... | Return iterable of columns used by this object. | [
"Return",
"iterable",
"of",
"columns",
"used",
"by",
"this",
"object",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/gtfsobjectbase.py#L108-L115 |
225,192 | google/transitfeed | transitfeed/shape.py | Shape.AddShapePointObjectUnsorted | def AddShapePointObjectUnsorted(self, shapepoint, problems):
"""Insert a point into a correct position by sequence. """
if (len(self.sequence) == 0 or
shapepoint.shape_pt_sequence >= self.sequence[-1]):
index = len(self.sequence)
elif shapepoint.shape_pt_sequence <= self.sequence[0]:
index = 0
else:
index = bisect.bisect(self.sequence, shapepoint.shape_pt_sequence)
if shapepoint.shape_pt_sequence in self.sequence:
problems.InvalidValue('shape_pt_sequence', shapepoint.shape_pt_sequence,
'The sequence number %d occurs more than once in '
'shape %s.' %
(shapepoint.shape_pt_sequence, self.shape_id))
if shapepoint.shape_dist_traveled is not None and len(self.sequence) > 0:
if (index != len(self.sequence) and
shapepoint.shape_dist_traveled > self.distance[index]):
problems.InvalidValue('shape_dist_traveled',
shapepoint.shape_dist_traveled,
'Each subsequent point in a shape should have '
'a distance value that shouldn\'t be larger '
'than the next ones. In this case, the next '
'distance was %f.' % self.distance[index])
if (index > 0 and
shapepoint.shape_dist_traveled < self.distance[index - 1]):
problems.InvalidValue('shape_dist_traveled',
shapepoint.shape_dist_traveled,
'Each subsequent point in a shape should have '
'a distance value that\'s at least as large as '
'the previous ones. In this case, the previous '
'distance was %f.' % self.distance[index - 1])
if shapepoint.shape_dist_traveled > self.max_distance:
self.max_distance = shapepoint.shape_dist_traveled
self.sequence.insert(index, shapepoint.shape_pt_sequence)
self.distance.insert(index, shapepoint.shape_dist_traveled)
self.points.insert(index, (shapepoint.shape_pt_lat,
shapepoint.shape_pt_lon,
shapepoint.shape_dist_traveled)) | python | def AddShapePointObjectUnsorted(self, shapepoint, problems):
"""Insert a point into a correct position by sequence. """
if (len(self.sequence) == 0 or
shapepoint.shape_pt_sequence >= self.sequence[-1]):
index = len(self.sequence)
elif shapepoint.shape_pt_sequence <= self.sequence[0]:
index = 0
else:
index = bisect.bisect(self.sequence, shapepoint.shape_pt_sequence)
if shapepoint.shape_pt_sequence in self.sequence:
problems.InvalidValue('shape_pt_sequence', shapepoint.shape_pt_sequence,
'The sequence number %d occurs more than once in '
'shape %s.' %
(shapepoint.shape_pt_sequence, self.shape_id))
if shapepoint.shape_dist_traveled is not None and len(self.sequence) > 0:
if (index != len(self.sequence) and
shapepoint.shape_dist_traveled > self.distance[index]):
problems.InvalidValue('shape_dist_traveled',
shapepoint.shape_dist_traveled,
'Each subsequent point in a shape should have '
'a distance value that shouldn\'t be larger '
'than the next ones. In this case, the next '
'distance was %f.' % self.distance[index])
if (index > 0 and
shapepoint.shape_dist_traveled < self.distance[index - 1]):
problems.InvalidValue('shape_dist_traveled',
shapepoint.shape_dist_traveled,
'Each subsequent point in a shape should have '
'a distance value that\'s at least as large as '
'the previous ones. In this case, the previous '
'distance was %f.' % self.distance[index - 1])
if shapepoint.shape_dist_traveled > self.max_distance:
self.max_distance = shapepoint.shape_dist_traveled
self.sequence.insert(index, shapepoint.shape_pt_sequence)
self.distance.insert(index, shapepoint.shape_dist_traveled)
self.points.insert(index, (shapepoint.shape_pt_lat,
shapepoint.shape_pt_lon,
shapepoint.shape_dist_traveled)) | [
"def",
"AddShapePointObjectUnsorted",
"(",
"self",
",",
"shapepoint",
",",
"problems",
")",
":",
"if",
"(",
"len",
"(",
"self",
".",
"sequence",
")",
"==",
"0",
"or",
"shapepoint",
".",
"shape_pt_sequence",
">=",
"self",
".",
"sequence",
"[",
"-",
"1",
"... | Insert a point into a correct position by sequence. | [
"Insert",
"a",
"point",
"into",
"a",
"correct",
"position",
"by",
"sequence",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/shape.py#L54-L96 |
225,193 | google/transitfeed | transitfeed/shape.py | Shape.GetPointWithDistanceTraveled | def GetPointWithDistanceTraveled(self, shape_dist_traveled):
"""Returns a point on the shape polyline with the input shape_dist_traveled.
Args:
shape_dist_traveled: The input shape_dist_traveled.
Returns:
The shape point as a tuple (lat, lng, shape_dist_traveled), where lat and
lng is the location of the shape point, and shape_dist_traveled is an
increasing metric representing the distance traveled along the shape.
Returns None if there is data error in shape.
"""
if not self.distance:
return None
if shape_dist_traveled <= self.distance[0]:
return self.points[0]
if shape_dist_traveled >= self.distance[-1]:
return self.points[-1]
index = bisect.bisect(self.distance, shape_dist_traveled)
(lat0, lng0, dist0) = self.points[index - 1]
(lat1, lng1, dist1) = self.points[index]
# Interpolate if shape_dist_traveled does not equal to any of the point
# in shape segment.
# (lat0, lng0) (lat, lng) (lat1, lng1)
# -----|--------------------|---------------------|------
# dist0 shape_dist_traveled dist1
# \------- ca --------/ \-------- bc -------/
# \----------------- ba ------------------/
ca = shape_dist_traveled - dist0
bc = dist1 - shape_dist_traveled
ba = bc + ca
if ba == 0:
# This only happens when there's data error in shapes and should have been
# catched before. Check to avoid crash.
return None
# This won't work crossing longitude 180 and is only an approximation which
# works well for short distance.
lat = (lat1 * ca + lat0 * bc) / ba
lng = (lng1 * ca + lng0 * bc) / ba
return (lat, lng, shape_dist_traveled) | python | def GetPointWithDistanceTraveled(self, shape_dist_traveled):
"""Returns a point on the shape polyline with the input shape_dist_traveled.
Args:
shape_dist_traveled: The input shape_dist_traveled.
Returns:
The shape point as a tuple (lat, lng, shape_dist_traveled), where lat and
lng is the location of the shape point, and shape_dist_traveled is an
increasing metric representing the distance traveled along the shape.
Returns None if there is data error in shape.
"""
if not self.distance:
return None
if shape_dist_traveled <= self.distance[0]:
return self.points[0]
if shape_dist_traveled >= self.distance[-1]:
return self.points[-1]
index = bisect.bisect(self.distance, shape_dist_traveled)
(lat0, lng0, dist0) = self.points[index - 1]
(lat1, lng1, dist1) = self.points[index]
# Interpolate if shape_dist_traveled does not equal to any of the point
# in shape segment.
# (lat0, lng0) (lat, lng) (lat1, lng1)
# -----|--------------------|---------------------|------
# dist0 shape_dist_traveled dist1
# \------- ca --------/ \-------- bc -------/
# \----------------- ba ------------------/
ca = shape_dist_traveled - dist0
bc = dist1 - shape_dist_traveled
ba = bc + ca
if ba == 0:
# This only happens when there's data error in shapes and should have been
# catched before. Check to avoid crash.
return None
# This won't work crossing longitude 180 and is only an approximation which
# works well for short distance.
lat = (lat1 * ca + lat0 * bc) / ba
lng = (lng1 * ca + lng0 * bc) / ba
return (lat, lng, shape_dist_traveled) | [
"def",
"GetPointWithDistanceTraveled",
"(",
"self",
",",
"shape_dist_traveled",
")",
":",
"if",
"not",
"self",
".",
"distance",
":",
"return",
"None",
"if",
"shape_dist_traveled",
"<=",
"self",
".",
"distance",
"[",
"0",
"]",
":",
"return",
"self",
".",
"poi... | Returns a point on the shape polyline with the input shape_dist_traveled.
Args:
shape_dist_traveled: The input shape_dist_traveled.
Returns:
The shape point as a tuple (lat, lng, shape_dist_traveled), where lat and
lng is the location of the shape point, and shape_dist_traveled is an
increasing metric representing the distance traveled along the shape.
Returns None if there is data error in shape. | [
"Returns",
"a",
"point",
"on",
"the",
"shape",
"polyline",
"with",
"the",
"input",
"shape_dist_traveled",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/shape.py#L129-L170 |
225,194 | google/transitfeed | transitfeed/trip.py | Trip.AddStopTime | def AddStopTime(self, stop, problems=None, schedule=None, **kwargs):
"""Add a stop to this trip. Stops must be added in the order visited.
Args:
stop: A Stop object
kwargs: remaining keyword args passed to StopTime.__init__
Returns:
None
"""
if problems is None:
# TODO: delete this branch when StopTime.__init__ doesn't need a
# ProblemReporter
problems = problems_module.default_problem_reporter
stoptime = self.GetGtfsFactory().StopTime(
problems=problems, stop=stop, **kwargs)
self.AddStopTimeObject(stoptime, schedule) | python | def AddStopTime(self, stop, problems=None, schedule=None, **kwargs):
"""Add a stop to this trip. Stops must be added in the order visited.
Args:
stop: A Stop object
kwargs: remaining keyword args passed to StopTime.__init__
Returns:
None
"""
if problems is None:
# TODO: delete this branch when StopTime.__init__ doesn't need a
# ProblemReporter
problems = problems_module.default_problem_reporter
stoptime = self.GetGtfsFactory().StopTime(
problems=problems, stop=stop, **kwargs)
self.AddStopTimeObject(stoptime, schedule) | [
"def",
"AddStopTime",
"(",
"self",
",",
"stop",
",",
"problems",
"=",
"None",
",",
"schedule",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"problems",
"is",
"None",
":",
"# TODO: delete this branch when StopTime.__init__ doesn't need a",
"# ProblemReport... | Add a stop to this trip. Stops must be added in the order visited.
Args:
stop: A Stop object
kwargs: remaining keyword args passed to StopTime.__init__
Returns:
None | [
"Add",
"a",
"stop",
"to",
"this",
"trip",
".",
"Stops",
"must",
"be",
"added",
"in",
"the",
"order",
"visited",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/trip.py#L59-L75 |
225,195 | google/transitfeed | transitfeed/trip.py | Trip._AddStopTimeObjectUnordered | def _AddStopTimeObjectUnordered(self, stoptime, schedule):
"""Add StopTime object to this trip.
The trip isn't checked for duplicate sequence numbers so it must be
validated later."""
stop_time_class = self.GetGtfsFactory().StopTime
cursor = schedule._connection.cursor()
insert_query = "INSERT INTO stop_times (%s) VALUES (%s);" % (
','.join(stop_time_class._SQL_FIELD_NAMES),
','.join(['?'] * len(stop_time_class._SQL_FIELD_NAMES)))
cursor = schedule._connection.cursor()
cursor.execute(
insert_query, stoptime.GetSqlValuesTuple(self.trip_id)) | python | def _AddStopTimeObjectUnordered(self, stoptime, schedule):
"""Add StopTime object to this trip.
The trip isn't checked for duplicate sequence numbers so it must be
validated later."""
stop_time_class = self.GetGtfsFactory().StopTime
cursor = schedule._connection.cursor()
insert_query = "INSERT INTO stop_times (%s) VALUES (%s);" % (
','.join(stop_time_class._SQL_FIELD_NAMES),
','.join(['?'] * len(stop_time_class._SQL_FIELD_NAMES)))
cursor = schedule._connection.cursor()
cursor.execute(
insert_query, stoptime.GetSqlValuesTuple(self.trip_id)) | [
"def",
"_AddStopTimeObjectUnordered",
"(",
"self",
",",
"stoptime",
",",
"schedule",
")",
":",
"stop_time_class",
"=",
"self",
".",
"GetGtfsFactory",
"(",
")",
".",
"StopTime",
"cursor",
"=",
"schedule",
".",
"_connection",
".",
"cursor",
"(",
")",
"insert_que... | Add StopTime object to this trip.
The trip isn't checked for duplicate sequence numbers so it must be
validated later. | [
"Add",
"StopTime",
"object",
"to",
"this",
"trip",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/trip.py#L77-L89 |
225,196 | google/transitfeed | transitfeed/trip.py | Trip.ReplaceStopTimeObject | def ReplaceStopTimeObject(self, stoptime, schedule=None):
"""Replace a StopTime object from this trip with the given one.
Keys the StopTime object to be replaced by trip_id, stop_sequence
and stop_id as 'stoptime', with the object 'stoptime'.
"""
if schedule is None:
schedule = self._schedule
new_secs = stoptime.GetTimeSecs()
cursor = schedule._connection.cursor()
cursor.execute("DELETE FROM stop_times WHERE trip_id=? and "
"stop_sequence=? and stop_id=?",
(self.trip_id, stoptime.stop_sequence, stoptime.stop_id))
if cursor.rowcount == 0:
raise problems_module.Error('Attempted replacement of StopTime object which does not exist')
self._AddStopTimeObjectUnordered(stoptime, schedule) | python | def ReplaceStopTimeObject(self, stoptime, schedule=None):
"""Replace a StopTime object from this trip with the given one.
Keys the StopTime object to be replaced by trip_id, stop_sequence
and stop_id as 'stoptime', with the object 'stoptime'.
"""
if schedule is None:
schedule = self._schedule
new_secs = stoptime.GetTimeSecs()
cursor = schedule._connection.cursor()
cursor.execute("DELETE FROM stop_times WHERE trip_id=? and "
"stop_sequence=? and stop_id=?",
(self.trip_id, stoptime.stop_sequence, stoptime.stop_id))
if cursor.rowcount == 0:
raise problems_module.Error('Attempted replacement of StopTime object which does not exist')
self._AddStopTimeObjectUnordered(stoptime, schedule) | [
"def",
"ReplaceStopTimeObject",
"(",
"self",
",",
"stoptime",
",",
"schedule",
"=",
"None",
")",
":",
"if",
"schedule",
"is",
"None",
":",
"schedule",
"=",
"self",
".",
"_schedule",
"new_secs",
"=",
"stoptime",
".",
"GetTimeSecs",
"(",
")",
"cursor",
"=",
... | Replace a StopTime object from this trip with the given one.
Keys the StopTime object to be replaced by trip_id, stop_sequence
and stop_id as 'stoptime', with the object 'stoptime'. | [
"Replace",
"a",
"StopTime",
"object",
"from",
"this",
"trip",
"with",
"the",
"given",
"one",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/trip.py#L91-L108 |
225,197 | google/transitfeed | transitfeed/trip.py | Trip.AddStopTimeObject | def AddStopTimeObject(self, stoptime, schedule=None, problems=None):
"""Add a StopTime object to the end of this trip.
Args:
stoptime: A StopTime object. Should not be reused in multiple trips.
schedule: Schedule object containing this trip which must be
passed to Trip.__init__ or here
problems: ProblemReporter object for validating the StopTime in its new
home
Returns:
None
"""
if schedule is None:
schedule = self._schedule
if schedule is None:
warnings.warn("No longer supported. _schedule attribute is used to get "
"stop_times table", DeprecationWarning)
if problems is None:
problems = schedule.problem_reporter
new_secs = stoptime.GetTimeSecs()
cursor = schedule._connection.cursor()
cursor.execute("SELECT max(stop_sequence), max(arrival_secs), "
"max(departure_secs) FROM stop_times WHERE trip_id=?",
(self.trip_id,))
row = cursor.fetchone()
if row[0] is None:
# This is the first stop_time of the trip
stoptime.stop_sequence = 1
if new_secs == None:
problems.OtherProblem(
'No time for first StopTime of trip_id "%s"' % (self.trip_id,))
else:
stoptime.stop_sequence = row[0] + 1
prev_secs = max(row[1], row[2])
if new_secs != None and new_secs < prev_secs:
problems.OtherProblem(
'out of order stop time for stop_id=%s trip_id=%s %s < %s' %
(util.EncodeUnicode(stoptime.stop_id),
util.EncodeUnicode(self.trip_id),
util.FormatSecondsSinceMidnight(new_secs),
util.FormatSecondsSinceMidnight(prev_secs)))
self._AddStopTimeObjectUnordered(stoptime, schedule) | python | def AddStopTimeObject(self, stoptime, schedule=None, problems=None):
"""Add a StopTime object to the end of this trip.
Args:
stoptime: A StopTime object. Should not be reused in multiple trips.
schedule: Schedule object containing this trip which must be
passed to Trip.__init__ or here
problems: ProblemReporter object for validating the StopTime in its new
home
Returns:
None
"""
if schedule is None:
schedule = self._schedule
if schedule is None:
warnings.warn("No longer supported. _schedule attribute is used to get "
"stop_times table", DeprecationWarning)
if problems is None:
problems = schedule.problem_reporter
new_secs = stoptime.GetTimeSecs()
cursor = schedule._connection.cursor()
cursor.execute("SELECT max(stop_sequence), max(arrival_secs), "
"max(departure_secs) FROM stop_times WHERE trip_id=?",
(self.trip_id,))
row = cursor.fetchone()
if row[0] is None:
# This is the first stop_time of the trip
stoptime.stop_sequence = 1
if new_secs == None:
problems.OtherProblem(
'No time for first StopTime of trip_id "%s"' % (self.trip_id,))
else:
stoptime.stop_sequence = row[0] + 1
prev_secs = max(row[1], row[2])
if new_secs != None and new_secs < prev_secs:
problems.OtherProblem(
'out of order stop time for stop_id=%s trip_id=%s %s < %s' %
(util.EncodeUnicode(stoptime.stop_id),
util.EncodeUnicode(self.trip_id),
util.FormatSecondsSinceMidnight(new_secs),
util.FormatSecondsSinceMidnight(prev_secs)))
self._AddStopTimeObjectUnordered(stoptime, schedule) | [
"def",
"AddStopTimeObject",
"(",
"self",
",",
"stoptime",
",",
"schedule",
"=",
"None",
",",
"problems",
"=",
"None",
")",
":",
"if",
"schedule",
"is",
"None",
":",
"schedule",
"=",
"self",
".",
"_schedule",
"if",
"schedule",
"is",
"None",
":",
"warnings... | Add a StopTime object to the end of this trip.
Args:
stoptime: A StopTime object. Should not be reused in multiple trips.
schedule: Schedule object containing this trip which must be
passed to Trip.__init__ or here
problems: ProblemReporter object for validating the StopTime in its new
home
Returns:
None | [
"Add",
"a",
"StopTime",
"object",
"to",
"the",
"end",
"of",
"this",
"trip",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/trip.py#L110-L153 |
225,198 | google/transitfeed | transitfeed/trip.py | Trip.GetCountStopTimes | def GetCountStopTimes(self):
"""Return the number of stops made by this trip."""
cursor = self._schedule._connection.cursor()
cursor.execute(
'SELECT count(*) FROM stop_times WHERE trip_id=?', (self.trip_id,))
return cursor.fetchone()[0] | python | def GetCountStopTimes(self):
"""Return the number of stops made by this trip."""
cursor = self._schedule._connection.cursor()
cursor.execute(
'SELECT count(*) FROM stop_times WHERE trip_id=?', (self.trip_id,))
return cursor.fetchone()[0] | [
"def",
"GetCountStopTimes",
"(",
"self",
")",
":",
"cursor",
"=",
"self",
".",
"_schedule",
".",
"_connection",
".",
"cursor",
"(",
")",
"cursor",
".",
"execute",
"(",
"'SELECT count(*) FROM stop_times WHERE trip_id=?'",
",",
"(",
"self",
".",
"trip_id",
",",
... | Return the number of stops made by this trip. | [
"Return",
"the",
"number",
"of",
"stops",
"made",
"by",
"this",
"trip",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/trip.py#L163-L168 |
225,199 | google/transitfeed | transitfeed/trip.py | Trip.ClearStopTimes | def ClearStopTimes(self):
"""Remove all stop times from this trip.
StopTime objects previously returned by GetStopTimes are unchanged but are
no longer associated with this trip.
"""
cursor = self._schedule._connection.cursor()
cursor.execute('DELETE FROM stop_times WHERE trip_id=?', (self.trip_id,)) | python | def ClearStopTimes(self):
"""Remove all stop times from this trip.
StopTime objects previously returned by GetStopTimes are unchanged but are
no longer associated with this trip.
"""
cursor = self._schedule._connection.cursor()
cursor.execute('DELETE FROM stop_times WHERE trip_id=?', (self.trip_id,)) | [
"def",
"ClearStopTimes",
"(",
"self",
")",
":",
"cursor",
"=",
"self",
".",
"_schedule",
".",
"_connection",
".",
"cursor",
"(",
")",
"cursor",
".",
"execute",
"(",
"'DELETE FROM stop_times WHERE trip_id=?'",
",",
"(",
"self",
".",
"trip_id",
",",
")",
")"
] | Remove all stop times from this trip.
StopTime objects previously returned by GetStopTimes are unchanged but are
no longer associated with this trip. | [
"Remove",
"all",
"stop",
"times",
"from",
"this",
"trip",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/trip.py#L218-L225 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.