repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
rmed/pyemtmad | pyemtmad/api/geo.py | GeoApi.get_info_line | def get_info_line(self, **kwargs):
"""Obtain basic information on a bus line on a given date.
Args:
day (int): Day of the month in format DD.
The number is automatically padded if it only has one digit.
month (int): Month number in format MM.
The number is automatically padded if it only has one digit.
year (int): Year number in format YYYY.
lines (list[int] | int): Lines to query, may be empty to get
all the lines.
lang (str): Language code (*es* or *en*).
Returns:
Status boolean and parsed response (list[Line]), or message string
in case of error.
"""
# Endpoint parameters
select_date = '%02d/%02d/%d' % (
kwargs.get('day', '01'),
kwargs.get('month', '01'),
kwargs.get('year', '1970')
)
params = {
'fecha': select_date,
'line': util.ints_to_string(kwargs.get('lines', [])),
'cultureInfo': util.language_code(kwargs.get('lang'))
}
# Request
result = self.make_request('geo', 'get_info_line', **params)
# Funny endpoint, no status code
if not util.check_result(result, 'Line'):
return False, 'UNKNOWN ERROR'
# Parse
values = util.response_list(result, 'Line')
return True, [emtype.Line(**a) for a in values] | python | def get_info_line(self, **kwargs):
"""Obtain basic information on a bus line on a given date.
Args:
day (int): Day of the month in format DD.
The number is automatically padded if it only has one digit.
month (int): Month number in format MM.
The number is automatically padded if it only has one digit.
year (int): Year number in format YYYY.
lines (list[int] | int): Lines to query, may be empty to get
all the lines.
lang (str): Language code (*es* or *en*).
Returns:
Status boolean and parsed response (list[Line]), or message string
in case of error.
"""
# Endpoint parameters
select_date = '%02d/%02d/%d' % (
kwargs.get('day', '01'),
kwargs.get('month', '01'),
kwargs.get('year', '1970')
)
params = {
'fecha': select_date,
'line': util.ints_to_string(kwargs.get('lines', [])),
'cultureInfo': util.language_code(kwargs.get('lang'))
}
# Request
result = self.make_request('geo', 'get_info_line', **params)
# Funny endpoint, no status code
if not util.check_result(result, 'Line'):
return False, 'UNKNOWN ERROR'
# Parse
values = util.response_list(result, 'Line')
return True, [emtype.Line(**a) for a in values] | [
"def",
"get_info_line",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# Endpoint parameters",
"select_date",
"=",
"'%02d/%02d/%d'",
"%",
"(",
"kwargs",
".",
"get",
"(",
"'day'",
",",
"'01'",
")",
",",
"kwargs",
".",
"get",
"(",
"'month'",
",",
"'01'",... | Obtain basic information on a bus line on a given date.
Args:
day (int): Day of the month in format DD.
The number is automatically padded if it only has one digit.
month (int): Month number in format MM.
The number is automatically padded if it only has one digit.
year (int): Year number in format YYYY.
lines (list[int] | int): Lines to query, may be empty to get
all the lines.
lang (str): Language code (*es* or *en*).
Returns:
Status boolean and parsed response (list[Line]), or message string
in case of error. | [
"Obtain",
"basic",
"information",
"on",
"a",
"bus",
"line",
"on",
"a",
"given",
"date",
"."
] | train | https://github.com/rmed/pyemtmad/blob/c21c42d0c7b50035dfed29540d7e64ab67833728/pyemtmad/api/geo.py#L92-L131 |
rmed/pyemtmad | pyemtmad/api/geo.py | GeoApi.get_poi | def get_poi(self, **kwargs):
"""Obtain a list of POI in the given radius.
Args:
latitude (double): Latitude in decimal degrees.
longitude (double): Longitude in decimal degrees.
types (list[int] | int): POI IDs (or empty list to get all).
radius (int): Radius (in meters) of the search.
lang (str): Language code (*es* or *en*).
Returns:
Status boolean and parsed response (list[Poi]), or message string
in case of error.
"""
# Endpoint parameters
params = {
'coordinateX': kwargs.get('longitude'),
'coordinateY': kwargs.get('latitude'),
'tipos': util.ints_to_string(kwargs.get('types')),
'Radius': kwargs.get('radius'),
'cultureInfo': util.language_code(kwargs.get('lang'))
}
# Request
result = self.make_request('geo', 'get_poi', **params)
# Funny endpoint, no status code
if not util.check_result(result, 'poiList'):
return False, 'UNKNOWN ERROR'
# Parse
values = util.response_list(result, 'poiList')
return True, [emtype.Poi(**a) for a in values] | python | def get_poi(self, **kwargs):
"""Obtain a list of POI in the given radius.
Args:
latitude (double): Latitude in decimal degrees.
longitude (double): Longitude in decimal degrees.
types (list[int] | int): POI IDs (or empty list to get all).
radius (int): Radius (in meters) of the search.
lang (str): Language code (*es* or *en*).
Returns:
Status boolean and parsed response (list[Poi]), or message string
in case of error.
"""
# Endpoint parameters
params = {
'coordinateX': kwargs.get('longitude'),
'coordinateY': kwargs.get('latitude'),
'tipos': util.ints_to_string(kwargs.get('types')),
'Radius': kwargs.get('radius'),
'cultureInfo': util.language_code(kwargs.get('lang'))
}
# Request
result = self.make_request('geo', 'get_poi', **params)
# Funny endpoint, no status code
if not util.check_result(result, 'poiList'):
return False, 'UNKNOWN ERROR'
# Parse
values = util.response_list(result, 'poiList')
return True, [emtype.Poi(**a) for a in values] | [
"def",
"get_poi",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# Endpoint parameters",
"params",
"=",
"{",
"'coordinateX'",
":",
"kwargs",
".",
"get",
"(",
"'longitude'",
")",
",",
"'coordinateY'",
":",
"kwargs",
".",
"get",
"(",
"'latitude'",
")",
"... | Obtain a list of POI in the given radius.
Args:
latitude (double): Latitude in decimal degrees.
longitude (double): Longitude in decimal degrees.
types (list[int] | int): POI IDs (or empty list to get all).
radius (int): Radius (in meters) of the search.
lang (str): Language code (*es* or *en*).
Returns:
Status boolean and parsed response (list[Poi]), or message string
in case of error. | [
"Obtain",
"a",
"list",
"of",
"POI",
"in",
"the",
"given",
"radius",
"."
] | train | https://github.com/rmed/pyemtmad/blob/c21c42d0c7b50035dfed29540d7e64ab67833728/pyemtmad/api/geo.py#L174-L206 |
rmed/pyemtmad | pyemtmad/api/geo.py | GeoApi.get_poi_types | def get_poi_types(self, **kwargs):
"""Obtain POI types.
Args:
lang (str): Language code (*es* or *en*).
Returns:
Status boolean and parsed response (list[PoiType]), or message string
in case of error.
"""
# Endpoint parameters
params = {
'cultureInfo': util.language_code(kwargs.get('lang'))
}
# Request
result = self.make_request('geo', 'get_poi_types', **params)
# Parse
values = result.get('types', [])
return True, [emtype.PoiType(**a) for a in values] | python | def get_poi_types(self, **kwargs):
"""Obtain POI types.
Args:
lang (str): Language code (*es* or *en*).
Returns:
Status boolean and parsed response (list[PoiType]), or message string
in case of error.
"""
# Endpoint parameters
params = {
'cultureInfo': util.language_code(kwargs.get('lang'))
}
# Request
result = self.make_request('geo', 'get_poi_types', **params)
# Parse
values = result.get('types', [])
return True, [emtype.PoiType(**a) for a in values] | [
"def",
"get_poi_types",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# Endpoint parameters",
"params",
"=",
"{",
"'cultureInfo'",
":",
"util",
".",
"language_code",
"(",
"kwargs",
".",
"get",
"(",
"'lang'",
")",
")",
"}",
"# Request",
"result",
"=",
... | Obtain POI types.
Args:
lang (str): Language code (*es* or *en*).
Returns:
Status boolean and parsed response (list[PoiType]), or message string
in case of error. | [
"Obtain",
"POI",
"types",
"."
] | train | https://github.com/rmed/pyemtmad/blob/c21c42d0c7b50035dfed29540d7e64ab67833728/pyemtmad/api/geo.py#L208-L228 |
rmed/pyemtmad | pyemtmad/api/geo.py | GeoApi.get_route_lines_route | def get_route_lines_route(self, **kwargs):
"""Obtain itinerary for one or more lines in the given date.
Args:
day (int): Day of the month in format DD.
The number is automatically padded if it only has one digit.
month (int): Month number in format MM.
The number is automatically padded if it only has one digit.
year (int): Year number in format YYYY.
lines (list[int] | int): Lines to query, may be empty to get
all the lines.
Returns:
Status boolean and parsed response (list[RouteLinesItem]), or message
string in case of error.
"""
# Endpoint parameters
select_date = '%02d/%02d/%d' % (
kwargs.get('day', '01'),
kwargs.get('month', '01'),
kwargs.get('year', '1970')
)
params = {
'SelectDate': select_date,
'Lines': util.ints_to_string(kwargs.get('lines', []))
}
# Request
result = self.make_request('geo', 'get_route_lines_route', **params)
if not util.check_result(result):
return False, result.get('resultDescription', 'UNKNOWN ERROR')
# Parse
values = util.response_list(result, 'resultValues')
return True, [emtype.RouteLinesItem(**a) for a in values] | python | def get_route_lines_route(self, **kwargs):
"""Obtain itinerary for one or more lines in the given date.
Args:
day (int): Day of the month in format DD.
The number is automatically padded if it only has one digit.
month (int): Month number in format MM.
The number is automatically padded if it only has one digit.
year (int): Year number in format YYYY.
lines (list[int] | int): Lines to query, may be empty to get
all the lines.
Returns:
Status boolean and parsed response (list[RouteLinesItem]), or message
string in case of error.
"""
# Endpoint parameters
select_date = '%02d/%02d/%d' % (
kwargs.get('day', '01'),
kwargs.get('month', '01'),
kwargs.get('year', '1970')
)
params = {
'SelectDate': select_date,
'Lines': util.ints_to_string(kwargs.get('lines', []))
}
# Request
result = self.make_request('geo', 'get_route_lines_route', **params)
if not util.check_result(result):
return False, result.get('resultDescription', 'UNKNOWN ERROR')
# Parse
values = util.response_list(result, 'resultValues')
return True, [emtype.RouteLinesItem(**a) for a in values] | [
"def",
"get_route_lines_route",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# Endpoint parameters",
"select_date",
"=",
"'%02d/%02d/%d'",
"%",
"(",
"kwargs",
".",
"get",
"(",
"'day'",
",",
"'01'",
")",
",",
"kwargs",
".",
"get",
"(",
"'month'",
",",
... | Obtain itinerary for one or more lines in the given date.
Args:
day (int): Day of the month in format DD.
The number is automatically padded if it only has one digit.
month (int): Month number in format MM.
The number is automatically padded if it only has one digit.
year (int): Year number in format YYYY.
lines (list[int] | int): Lines to query, may be empty to get
all the lines.
Returns:
Status boolean and parsed response (list[RouteLinesItem]), or message
string in case of error. | [
"Obtain",
"itinerary",
"for",
"one",
"or",
"more",
"lines",
"in",
"the",
"given",
"date",
"."
] | train | https://github.com/rmed/pyemtmad/blob/c21c42d0c7b50035dfed29540d7e64ab67833728/pyemtmad/api/geo.py#L230-L266 |
rmed/pyemtmad | pyemtmad/api/geo.py | GeoApi.get_stops_line | def get_stops_line(self, **kwargs):
"""Obtain information on the stops of the given lines.
Arguments:
lines (list[int] | int): Lines to query, may be empty to get
all the lines.
direction (str): Optional, either *forward* or *backward*.
lang (str): Language code (*es* or *en*).
Returns:
Status boolean and parsed response (list[Stop]), or message string
in case of error.
"""
# Endpoint parameters
params = {
'line': util.ints_to_string(kwargs.get('lines', [])),
'direction': util.direction_code(kwargs.get('direction', '')),
'cultureInfo': util.language_code(kwargs.get('lang'))
}
# Request
result = self.make_request('geo', 'get_stops_line', **params)
# Funny endpoint, no status code
# Only interested in 'stop'
if not util.check_result(result, 'stop'):
return False, 'UNKNOWN ERROR'
# Parse
values = util.response_list(result, 'stop')
return True, [emtype.Stop(**a) for a in values] | python | def get_stops_line(self, **kwargs):
"""Obtain information on the stops of the given lines.
Arguments:
lines (list[int] | int): Lines to query, may be empty to get
all the lines.
direction (str): Optional, either *forward* or *backward*.
lang (str): Language code (*es* or *en*).
Returns:
Status boolean and parsed response (list[Stop]), or message string
in case of error.
"""
# Endpoint parameters
params = {
'line': util.ints_to_string(kwargs.get('lines', [])),
'direction': util.direction_code(kwargs.get('direction', '')),
'cultureInfo': util.language_code(kwargs.get('lang'))
}
# Request
result = self.make_request('geo', 'get_stops_line', **params)
# Funny endpoint, no status code
# Only interested in 'stop'
if not util.check_result(result, 'stop'):
return False, 'UNKNOWN ERROR'
# Parse
values = util.response_list(result, 'stop')
return True, [emtype.Stop(**a) for a in values] | [
"def",
"get_stops_line",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# Endpoint parameters",
"params",
"=",
"{",
"'line'",
":",
"util",
".",
"ints_to_string",
"(",
"kwargs",
".",
"get",
"(",
"'lines'",
",",
"[",
"]",
")",
")",
",",
"'direction'",
... | Obtain information on the stops of the given lines.
Arguments:
lines (list[int] | int): Lines to query, may be empty to get
all the lines.
direction (str): Optional, either *forward* or *backward*.
lang (str): Language code (*es* or *en*).
Returns:
Status boolean and parsed response (list[Stop]), or message string
in case of error. | [
"Obtain",
"information",
"on",
"the",
"stops",
"of",
"the",
"given",
"lines",
"."
] | train | https://github.com/rmed/pyemtmad/blob/c21c42d0c7b50035dfed29540d7e64ab67833728/pyemtmad/api/geo.py#L331-L361 |
rmed/pyemtmad | pyemtmad/api/geo.py | GeoApi.get_street | def get_street(self, **kwargs):
"""Obtain a list of nodes related to a location within a given radius.
Not sure of its use, but...
Args:
street_name (str): Name of the street to search.
street_number (int): Street number to search.
radius (int): Radius (in meters) of the search.
stops (int): Number of the stop to search.
lang (str): Language code (*es* or *en*).
Returns:
Status boolean and parsed response (list[Site]), or message string
in case of error.
"""
# Endpoint parameters
params = {
'description': kwargs.get('street_name'),
'streetNumber': kwargs.get('street_number'),
'Radius': kwargs.get('radius'),
'Stops': kwargs.get('stops'),
'cultureInfo': util.language_code(kwargs.get('lang'))
}
# Request
result = self.make_request('geo', 'get_street', **params)
# Funny endpoint, no status code
if not util.check_result(result, 'site'):
return False, 'UNKNOWN ERROR'
# Parse
values = util.response_list(result, 'site')
return True, [emtype.Site(**a) for a in values] | python | def get_street(self, **kwargs):
"""Obtain a list of nodes related to a location within a given radius.
Not sure of its use, but...
Args:
street_name (str): Name of the street to search.
street_number (int): Street number to search.
radius (int): Radius (in meters) of the search.
stops (int): Number of the stop to search.
lang (str): Language code (*es* or *en*).
Returns:
Status boolean and parsed response (list[Site]), or message string
in case of error.
"""
# Endpoint parameters
params = {
'description': kwargs.get('street_name'),
'streetNumber': kwargs.get('street_number'),
'Radius': kwargs.get('radius'),
'Stops': kwargs.get('stops'),
'cultureInfo': util.language_code(kwargs.get('lang'))
}
# Request
result = self.make_request('geo', 'get_street', **params)
# Funny endpoint, no status code
if not util.check_result(result, 'site'):
return False, 'UNKNOWN ERROR'
# Parse
values = util.response_list(result, 'site')
return True, [emtype.Site(**a) for a in values] | [
"def",
"get_street",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# Endpoint parameters",
"params",
"=",
"{",
"'description'",
":",
"kwargs",
".",
"get",
"(",
"'street_name'",
")",
",",
"'streetNumber'",
":",
"kwargs",
".",
"get",
"(",
"'street_number'",... | Obtain a list of nodes related to a location within a given radius.
Not sure of its use, but...
Args:
street_name (str): Name of the street to search.
street_number (int): Street number to search.
radius (int): Radius (in meters) of the search.
stops (int): Number of the stop to search.
lang (str): Language code (*es* or *en*).
Returns:
Status boolean and parsed response (list[Site]), or message string
in case of error. | [
"Obtain",
"a",
"list",
"of",
"nodes",
"related",
"to",
"a",
"location",
"within",
"a",
"given",
"radius",
"."
] | train | https://github.com/rmed/pyemtmad/blob/c21c42d0c7b50035dfed29540d7e64ab67833728/pyemtmad/api/geo.py#L363-L397 |
rmed/pyemtmad | pyemtmad/api/geo.py | GeoApi.get_street_from_xy | def get_street_from_xy(self, **kwargs):
"""Obtain a list of streets around the specified point.
Args:
latitude (double): Latitude in decimal degrees.
longitude (double): Longitude in decimal degrees.
radius (int): Radius (in meters) of the search.
lang (str): Language code (*es* or *en*).
Returns:
Status boolean and parsed response (list[Street]), or message string
in case of error.
"""
# Endpoint parameters
params = {
'coordinateX': kwargs.get('longitude'),
'coordinateY': kwargs.get('latitude'),
'Radius': kwargs.get('radius'),
'cultureInfo': util.language_code(kwargs.get('lang'))
}
# Request
result = self.make_request('geo', 'get_street_from_xy', **params)
# Funny endpoint, no status code
if not util.check_result(result, 'site'):
return False, 'UNKNOWN ERROR'
# Parse
values = util.response_list(result, 'site')
return True, [emtype.Street(**a) for a in values] | python | def get_street_from_xy(self, **kwargs):
"""Obtain a list of streets around the specified point.
Args:
latitude (double): Latitude in decimal degrees.
longitude (double): Longitude in decimal degrees.
radius (int): Radius (in meters) of the search.
lang (str): Language code (*es* or *en*).
Returns:
Status boolean and parsed response (list[Street]), or message string
in case of error.
"""
# Endpoint parameters
params = {
'coordinateX': kwargs.get('longitude'),
'coordinateY': kwargs.get('latitude'),
'Radius': kwargs.get('radius'),
'cultureInfo': util.language_code(kwargs.get('lang'))
}
# Request
result = self.make_request('geo', 'get_street_from_xy', **params)
# Funny endpoint, no status code
if not util.check_result(result, 'site'):
return False, 'UNKNOWN ERROR'
# Parse
values = util.response_list(result, 'site')
return True, [emtype.Street(**a) for a in values] | [
"def",
"get_street_from_xy",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# Endpoint parameters",
"params",
"=",
"{",
"'coordinateX'",
":",
"kwargs",
".",
"get",
"(",
"'longitude'",
")",
",",
"'coordinateY'",
":",
"kwargs",
".",
"get",
"(",
"'latitude'",... | Obtain a list of streets around the specified point.
Args:
latitude (double): Latitude in decimal degrees.
longitude (double): Longitude in decimal degrees.
radius (int): Radius (in meters) of the search.
lang (str): Language code (*es* or *en*).
Returns:
Status boolean and parsed response (list[Street]), or message string
in case of error. | [
"Obtain",
"a",
"list",
"of",
"streets",
"around",
"the",
"specified",
"point",
"."
] | train | https://github.com/rmed/pyemtmad/blob/c21c42d0c7b50035dfed29540d7e64ab67833728/pyemtmad/api/geo.py#L399-L429 |
inveniosoftware/invenio-openaire | invenio_openaire/tasks.py | harvest_fundref | def harvest_fundref(source=None):
"""Harvest funders from FundRef and store as authority records."""
loader = LocalFundRefLoader(source=source) if source \
else RemoteFundRefLoader()
for funder_json in loader.iter_funders():
register_funder.delay(funder_json) | python | def harvest_fundref(source=None):
"""Harvest funders from FundRef and store as authority records."""
loader = LocalFundRefLoader(source=source) if source \
else RemoteFundRefLoader()
for funder_json in loader.iter_funders():
register_funder.delay(funder_json) | [
"def",
"harvest_fundref",
"(",
"source",
"=",
"None",
")",
":",
"loader",
"=",
"LocalFundRefLoader",
"(",
"source",
"=",
"source",
")",
"if",
"source",
"else",
"RemoteFundRefLoader",
"(",
")",
"for",
"funder_json",
"in",
"loader",
".",
"iter_funders",
"(",
"... | Harvest funders from FundRef and store as authority records. | [
"Harvest",
"funders",
"from",
"FundRef",
"and",
"store",
"as",
"authority",
"records",
"."
] | train | https://github.com/inveniosoftware/invenio-openaire/blob/71860effff6abe7f658d3a11894e064202ef1c36/invenio_openaire/tasks.py#L45-L50 |
inveniosoftware/invenio-openaire | invenio_openaire/tasks.py | harvest_openaire_projects | def harvest_openaire_projects(source=None, setspec=None):
"""Harvest grants from OpenAIRE and store as authority records."""
loader = LocalOAIRELoader(source=source) if source \
else RemoteOAIRELoader(setspec=setspec)
for grant_json in loader.iter_grants():
register_grant.delay(grant_json) | python | def harvest_openaire_projects(source=None, setspec=None):
"""Harvest grants from OpenAIRE and store as authority records."""
loader = LocalOAIRELoader(source=source) if source \
else RemoteOAIRELoader(setspec=setspec)
for grant_json in loader.iter_grants():
register_grant.delay(grant_json) | [
"def",
"harvest_openaire_projects",
"(",
"source",
"=",
"None",
",",
"setspec",
"=",
"None",
")",
":",
"loader",
"=",
"LocalOAIRELoader",
"(",
"source",
"=",
"source",
")",
"if",
"source",
"else",
"RemoteOAIRELoader",
"(",
"setspec",
"=",
"setspec",
")",
"fo... | Harvest grants from OpenAIRE and store as authority records. | [
"Harvest",
"grants",
"from",
"OpenAIRE",
"and",
"store",
"as",
"authority",
"records",
"."
] | train | https://github.com/inveniosoftware/invenio-openaire/blob/71860effff6abe7f658d3a11894e064202ef1c36/invenio_openaire/tasks.py#L54-L59 |
inveniosoftware/invenio-openaire | invenio_openaire/tasks.py | harvest_all_openaire_projects | def harvest_all_openaire_projects():
"""Reharvest all grants from OpenAIRE.
Harvest all OpenAIRE grants in a chain to prevent OpenAIRE
overloading from multiple parallel harvesting.
"""
setspecs = current_app.config['OPENAIRE_GRANTS_SPECS']
chain(harvest_openaire_projects.s(setspec=setspec)
for setspec in setspecs).apply_async() | python | def harvest_all_openaire_projects():
"""Reharvest all grants from OpenAIRE.
Harvest all OpenAIRE grants in a chain to prevent OpenAIRE
overloading from multiple parallel harvesting.
"""
setspecs = current_app.config['OPENAIRE_GRANTS_SPECS']
chain(harvest_openaire_projects.s(setspec=setspec)
for setspec in setspecs).apply_async() | [
"def",
"harvest_all_openaire_projects",
"(",
")",
":",
"setspecs",
"=",
"current_app",
".",
"config",
"[",
"'OPENAIRE_GRANTS_SPECS'",
"]",
"chain",
"(",
"harvest_openaire_projects",
".",
"s",
"(",
"setspec",
"=",
"setspec",
")",
"for",
"setspec",
"in",
"setspecs",... | Reharvest all grants from OpenAIRE.
Harvest all OpenAIRE grants in a chain to prevent OpenAIRE
overloading from multiple parallel harvesting. | [
"Reharvest",
"all",
"grants",
"from",
"OpenAIRE",
"."
] | train | https://github.com/inveniosoftware/invenio-openaire/blob/71860effff6abe7f658d3a11894e064202ef1c36/invenio_openaire/tasks.py#L63-L71 |
inveniosoftware/invenio-openaire | invenio_openaire/tasks.py | create_or_update_record | def create_or_update_record(data, pid_type, id_key, minter):
"""Register a funder or grant."""
resolver = Resolver(
pid_type=pid_type, object_type='rec', getter=Record.get_record)
try:
pid, record = resolver.resolve(data[id_key])
data_c = deepcopy(data)
del data_c['remote_modified']
record_c = deepcopy(record)
del record_c['remote_modified']
# All grants on OpenAIRE are modified periodically even if nothing
# has changed. We need to check for actual differences in the metadata
if data_c != record_c:
record.update(data)
record.commit()
record_id = record.id
db.session.commit()
RecordIndexer().index_by_id(str(record_id))
except PIDDoesNotExistError:
record = Record.create(data)
record_id = record.id
minter(record.id, data)
db.session.commit()
RecordIndexer().index_by_id(str(record_id)) | python | def create_or_update_record(data, pid_type, id_key, minter):
"""Register a funder or grant."""
resolver = Resolver(
pid_type=pid_type, object_type='rec', getter=Record.get_record)
try:
pid, record = resolver.resolve(data[id_key])
data_c = deepcopy(data)
del data_c['remote_modified']
record_c = deepcopy(record)
del record_c['remote_modified']
# All grants on OpenAIRE are modified periodically even if nothing
# has changed. We need to check for actual differences in the metadata
if data_c != record_c:
record.update(data)
record.commit()
record_id = record.id
db.session.commit()
RecordIndexer().index_by_id(str(record_id))
except PIDDoesNotExistError:
record = Record.create(data)
record_id = record.id
minter(record.id, data)
db.session.commit()
RecordIndexer().index_by_id(str(record_id)) | [
"def",
"create_or_update_record",
"(",
"data",
",",
"pid_type",
",",
"id_key",
",",
"minter",
")",
":",
"resolver",
"=",
"Resolver",
"(",
"pid_type",
"=",
"pid_type",
",",
"object_type",
"=",
"'rec'",
",",
"getter",
"=",
"Record",
".",
"get_record",
")",
"... | Register a funder or grant. | [
"Register",
"a",
"funder",
"or",
"grant",
"."
] | train | https://github.com/inveniosoftware/invenio-openaire/blob/71860effff6abe7f658d3a11894e064202ef1c36/invenio_openaire/tasks.py#L86-L110 |
72squared/redpipe | redpipe/futures.py | IS | def IS(instance, other): # noqa
"""
Support the `future is other` use-case.
Can't override the language so we built a function.
Will work on non-future objects too.
:param instance: future or any python object
:param other: object to compare.
:return:
"""
try:
instance = instance._redpipe_future_result # noqa
except AttributeError:
pass
try:
other = other._redpipe_future_result
except AttributeError:
pass
return instance is other | python | def IS(instance, other): # noqa
"""
Support the `future is other` use-case.
Can't override the language so we built a function.
Will work on non-future objects too.
:param instance: future or any python object
:param other: object to compare.
:return:
"""
try:
instance = instance._redpipe_future_result # noqa
except AttributeError:
pass
try:
other = other._redpipe_future_result
except AttributeError:
pass
return instance is other | [
"def",
"IS",
"(",
"instance",
",",
"other",
")",
":",
"# noqa",
"try",
":",
"instance",
"=",
"instance",
".",
"_redpipe_future_result",
"# noqa",
"except",
"AttributeError",
":",
"pass",
"try",
":",
"other",
"=",
"other",
".",
"_redpipe_future_result",
"except... | Support the `future is other` use-case.
Can't override the language so we built a function.
Will work on non-future objects too.
:param instance: future or any python object
:param other: object to compare.
:return: | [
"Support",
"the",
"future",
"is",
"other",
"use",
"-",
"case",
".",
"Can",
"t",
"override",
"the",
"language",
"so",
"we",
"built",
"a",
"function",
".",
"Will",
"work",
"on",
"non",
"-",
"future",
"objects",
"too",
"."
] | train | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/futures.py#L106-L126 |
72squared/redpipe | redpipe/futures.py | ISINSTANCE | def ISINSTANCE(instance, A_tuple): # noqa
"""
Allows you to do isinstance checks on futures.
Really, I discourage this because duck-typing is usually better.
But this can provide you with a way to use isinstance with futures.
Works with other objects too.
:param instance:
:param A_tuple:
:return:
"""
try:
instance = instance._redpipe_future_result
except AttributeError:
pass
return isinstance(instance, A_tuple) | python | def ISINSTANCE(instance, A_tuple): # noqa
"""
Allows you to do isinstance checks on futures.
Really, I discourage this because duck-typing is usually better.
But this can provide you with a way to use isinstance with futures.
Works with other objects too.
:param instance:
:param A_tuple:
:return:
"""
try:
instance = instance._redpipe_future_result
except AttributeError:
pass
return isinstance(instance, A_tuple) | [
"def",
"ISINSTANCE",
"(",
"instance",
",",
"A_tuple",
")",
":",
"# noqa",
"try",
":",
"instance",
"=",
"instance",
".",
"_redpipe_future_result",
"except",
"AttributeError",
":",
"pass",
"return",
"isinstance",
"(",
"instance",
",",
"A_tuple",
")"
] | Allows you to do isinstance checks on futures.
Really, I discourage this because duck-typing is usually better.
But this can provide you with a way to use isinstance with futures.
Works with other objects too.
:param instance:
:param A_tuple:
:return: | [
"Allows",
"you",
"to",
"do",
"isinstance",
"checks",
"on",
"futures",
".",
"Really",
"I",
"discourage",
"this",
"because",
"duck",
"-",
"typing",
"is",
"usually",
"better",
".",
"But",
"this",
"can",
"provide",
"you",
"with",
"a",
"way",
"to",
"use",
"is... | train | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/futures.py#L129-L145 |
72squared/redpipe | redpipe/futures.py | _json_default_encoder | def _json_default_encoder(func):
"""
Monkey-Patch the core json encoder library.
This isn't as bad as it sounds.
We override the default method so that if an object
falls through and can't be encoded normally, we see if it is
a Future object and return the result to be encoded.
I set a special attribute on the Future object so I can tell
that's what it is, and can grab the result.
If that doesn't work, I fall back to the earlier behavior.
The nice thing about patching the library this way is that it
won't inerfere with existing code and it can itself be wrapped
by other methods.
So it's very extensible.
:param func: the JSONEncoder.default method.
:return: an object that can be json serialized.
"""
@wraps(func)
def inner(self, o):
try:
return o._redpipe_future_result # noqa
except AttributeError:
pass
return func(self, o)
return inner | python | def _json_default_encoder(func):
"""
Monkey-Patch the core json encoder library.
This isn't as bad as it sounds.
We override the default method so that if an object
falls through and can't be encoded normally, we see if it is
a Future object and return the result to be encoded.
I set a special attribute on the Future object so I can tell
that's what it is, and can grab the result.
If that doesn't work, I fall back to the earlier behavior.
The nice thing about patching the library this way is that it
won't inerfere with existing code and it can itself be wrapped
by other methods.
So it's very extensible.
:param func: the JSONEncoder.default method.
:return: an object that can be json serialized.
"""
@wraps(func)
def inner(self, o):
try:
return o._redpipe_future_result # noqa
except AttributeError:
pass
return func(self, o)
return inner | [
"def",
"_json_default_encoder",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"inner",
"(",
"self",
",",
"o",
")",
":",
"try",
":",
"return",
"o",
".",
"_redpipe_future_result",
"# noqa",
"except",
"AttributeError",
":",
"pass",
"return",
... | Monkey-Patch the core json encoder library.
This isn't as bad as it sounds.
We override the default method so that if an object
falls through and can't be encoded normally, we see if it is
a Future object and return the result to be encoded.
I set a special attribute on the Future object so I can tell
that's what it is, and can grab the result.
If that doesn't work, I fall back to the earlier behavior.
The nice thing about patching the library this way is that it
won't inerfere with existing code and it can itself be wrapped
by other methods.
So it's very extensible.
:param func: the JSONEncoder.default method.
:return: an object that can be json serialized. | [
"Monkey",
"-",
"Patch",
"the",
"core",
"json",
"encoder",
"library",
".",
"This",
"isn",
"t",
"as",
"bad",
"as",
"it",
"sounds",
".",
"We",
"override",
"the",
"default",
"method",
"so",
"that",
"if",
"an",
"object",
"falls",
"through",
"and",
"can",
"t... | train | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/futures.py#L625-L654 |
twisted/mantissa | xmantissa/suspension.py | suspendJustTabProviders | def suspendJustTabProviders(installation):
"""
Replace INavigableElements with facades that indicate their suspension.
"""
if installation.suspended:
raise RuntimeError("Installation already suspended")
powerups = list(installation.allPowerups)
for p in powerups:
if INavigableElement.providedBy(p):
p.store.powerDown(p, INavigableElement)
sne = SuspendedNavigableElement(store=p.store, originalNE=p)
p.store.powerUp(sne, INavigableElement)
p.store.powerUp(sne, ISuspender)
installation.suspended = True | python | def suspendJustTabProviders(installation):
"""
Replace INavigableElements with facades that indicate their suspension.
"""
if installation.suspended:
raise RuntimeError("Installation already suspended")
powerups = list(installation.allPowerups)
for p in powerups:
if INavigableElement.providedBy(p):
p.store.powerDown(p, INavigableElement)
sne = SuspendedNavigableElement(store=p.store, originalNE=p)
p.store.powerUp(sne, INavigableElement)
p.store.powerUp(sne, ISuspender)
installation.suspended = True | [
"def",
"suspendJustTabProviders",
"(",
"installation",
")",
":",
"if",
"installation",
".",
"suspended",
":",
"raise",
"RuntimeError",
"(",
"\"Installation already suspended\"",
")",
"powerups",
"=",
"list",
"(",
"installation",
".",
"allPowerups",
")",
"for",
"p",
... | Replace INavigableElements with facades that indicate their suspension. | [
"Replace",
"INavigableElements",
"with",
"facades",
"that",
"indicate",
"their",
"suspension",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/suspension.py#L46-L59 |
twisted/mantissa | xmantissa/suspension.py | unsuspendTabProviders | def unsuspendTabProviders(installation):
"""
Remove suspension facades and replace them with their originals.
"""
if not installation.suspended:
raise RuntimeError("Installation not suspended")
powerups = list(installation.allPowerups)
allSNEs = list(powerups[0].store.powerupsFor(ISuspender))
for p in powerups:
for sne in allSNEs:
if sne.originalNE is p:
p.store.powerDown(sne, INavigableElement)
p.store.powerDown(sne, ISuspender)
p.store.powerUp(p, INavigableElement)
sne.deleteFromStore()
installation.suspended = False | python | def unsuspendTabProviders(installation):
"""
Remove suspension facades and replace them with their originals.
"""
if not installation.suspended:
raise RuntimeError("Installation not suspended")
powerups = list(installation.allPowerups)
allSNEs = list(powerups[0].store.powerupsFor(ISuspender))
for p in powerups:
for sne in allSNEs:
if sne.originalNE is p:
p.store.powerDown(sne, INavigableElement)
p.store.powerDown(sne, ISuspender)
p.store.powerUp(p, INavigableElement)
sne.deleteFromStore()
installation.suspended = False | [
"def",
"unsuspendTabProviders",
"(",
"installation",
")",
":",
"if",
"not",
"installation",
".",
"suspended",
":",
"raise",
"RuntimeError",
"(",
"\"Installation not suspended\"",
")",
"powerups",
"=",
"list",
"(",
"installation",
".",
"allPowerups",
")",
"allSNEs",
... | Remove suspension facades and replace them with their originals. | [
"Remove",
"suspension",
"facades",
"and",
"replace",
"them",
"with",
"their",
"originals",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/suspension.py#L61-L76 |
datacratic/pymldb | pymldb/data.py | BatFrame.rows | def rows(self):
"""Returns a numpy array of the rows name"""
bf = self.copy()
result = bf.query.executeQuery(format="soa")
return result["_rowName"] | python | def rows(self):
"""Returns a numpy array of the rows name"""
bf = self.copy()
result = bf.query.executeQuery(format="soa")
return result["_rowName"] | [
"def",
"rows",
"(",
"self",
")",
":",
"bf",
"=",
"self",
".",
"copy",
"(",
")",
"result",
"=",
"bf",
".",
"query",
".",
"executeQuery",
"(",
"format",
"=",
"\"soa\"",
")",
"return",
"result",
"[",
"\"_rowName\"",
"]"
] | Returns a numpy array of the rows name | [
"Returns",
"a",
"numpy",
"array",
"of",
"the",
"rows",
"name"
] | train | https://github.com/datacratic/pymldb/blob/e41f3c37138e9fd4a82ef3db685899cdafa4125e/pymldb/data.py#L65-L69 |
datacratic/pymldb | pymldb/data.py | BatFrame.shape | def shape(self):
"""
Returns (rowCount, valueCount)
"""
bf = self.copy()
content = requests.get(bf.dataset_url).json()
rowCount = content['status']['rowCount']
valueCount = content['status']['valueCount']
return (rowCount, valueCount) | python | def shape(self):
"""
Returns (rowCount, valueCount)
"""
bf = self.copy()
content = requests.get(bf.dataset_url).json()
rowCount = content['status']['rowCount']
valueCount = content['status']['valueCount']
return (rowCount, valueCount) | [
"def",
"shape",
"(",
"self",
")",
":",
"bf",
"=",
"self",
".",
"copy",
"(",
")",
"content",
"=",
"requests",
".",
"get",
"(",
"bf",
".",
"dataset_url",
")",
".",
"json",
"(",
")",
"rowCount",
"=",
"content",
"[",
"'status'",
"]",
"[",
"'rowCount'",... | Returns (rowCount, valueCount) | [
"Returns",
"(",
"rowCount",
"valueCount",
")"
] | train | https://github.com/datacratic/pymldb/blob/e41f3c37138e9fd4a82ef3db685899cdafa4125e/pymldb/data.py#L120-L129 |
datacratic/pymldb | pymldb/data.py | Column._comparison | def _comparison(self, value, operator):
"""
Parameters
----------
value: Column object or base type
The value against which to compare the column. It can either be
another column or a base type value (e.g. int)
Returns
-------
self.query
Notes
-----
Returning self.query will allow the next object to use this column
ops and concatenate something else
"""
if isinstance(value, Column):
self.query.addWHERE("(({}){}({}))".format(
self.execution_name,
operator,
value.execution_name))
elif isinstance(value, str):
self.query.addWHERE("(({}){}\'{}\')".format(
self.execution_name,
operator,
value))
else:
self.query.addWHERE("(({}){}({}))".format(
self.execution_name,
operator,
value))
copy = self.copy()
copy.query.removeSELECT("{}".format(copy.execution_name))
return copy.query | python | def _comparison(self, value, operator):
"""
Parameters
----------
value: Column object or base type
The value against which to compare the column. It can either be
another column or a base type value (e.g. int)
Returns
-------
self.query
Notes
-----
Returning self.query will allow the next object to use this column
ops and concatenate something else
"""
if isinstance(value, Column):
self.query.addWHERE("(({}){}({}))".format(
self.execution_name,
operator,
value.execution_name))
elif isinstance(value, str):
self.query.addWHERE("(({}){}\'{}\')".format(
self.execution_name,
operator,
value))
else:
self.query.addWHERE("(({}){}({}))".format(
self.execution_name,
operator,
value))
copy = self.copy()
copy.query.removeSELECT("{}".format(copy.execution_name))
return copy.query | [
"def",
"_comparison",
"(",
"self",
",",
"value",
",",
"operator",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"Column",
")",
":",
"self",
".",
"query",
".",
"addWHERE",
"(",
"\"(({}){}({}))\"",
".",
"format",
"(",
"self",
".",
"execution_name",
",",... | Parameters
----------
value: Column object or base type
The value against which to compare the column. It can either be
another column or a base type value (e.g. int)
Returns
-------
self.query
Notes
-----
Returning self.query will allow the next object to use this column
ops and concatenate something else | [
"Parameters",
"----------",
"value",
":",
"Column",
"object",
"or",
"base",
"type",
"The",
"value",
"against",
"which",
"to",
"compare",
"the",
"column",
".",
"It",
"can",
"either",
"be",
"another",
"column",
"or",
"a",
"base",
"type",
"value",
"(",
"e",
... | train | https://github.com/datacratic/pymldb/blob/e41f3c37138e9fd4a82ef3db685899cdafa4125e/pymldb/data.py#L199-L234 |
datacratic/pymldb | pymldb/data.py | Column._binary_arithemtic | def _binary_arithemtic(self, left, binary, right):
"""
Parameters
----------
operand: Column object, integer or float
Value on which to apply operator to this column
binary: char
binary arithmetic operator (-, +, *, /, ^, %)
Returns
-------
self
Notes
-----
Returning self will allow the next object to use this column ops and
concatenate something else
"""
if isinstance(right, (int, float)):
right = right
elif isinstance(right, Column):
right = right.execution_name
else:
raise AttributeError(
"{} can only be used ".format(binary)
+ "with integer, float or column")
if isinstance(left, (int, float)):
left = left
elif isinstance(left, Column):
left = left.execution_name
else:
raise AttributeError(
"{} can only be used ".format(binary)
+ "with integer, float or column")
copy = self.copy()
copy.query.removeSELECT("{}".format(copy.execution_name))
if binary == '^': # POWER needs a different treatment
copy.execution_name = "pow({},{})".format(left, right)
else:
copy.execution_name = "{}{}{}".format(left, binary, right)
copy.query.addSELECT(copy.execution_name)
return copy | python | def _binary_arithemtic(self, left, binary, right):
"""
Parameters
----------
operand: Column object, integer or float
Value on which to apply operator to this column
binary: char
binary arithmetic operator (-, +, *, /, ^, %)
Returns
-------
self
Notes
-----
Returning self will allow the next object to use this column ops and
concatenate something else
"""
if isinstance(right, (int, float)):
right = right
elif isinstance(right, Column):
right = right.execution_name
else:
raise AttributeError(
"{} can only be used ".format(binary)
+ "with integer, float or column")
if isinstance(left, (int, float)):
left = left
elif isinstance(left, Column):
left = left.execution_name
else:
raise AttributeError(
"{} can only be used ".format(binary)
+ "with integer, float or column")
copy = self.copy()
copy.query.removeSELECT("{}".format(copy.execution_name))
if binary == '^': # POWER needs a different treatment
copy.execution_name = "pow({},{})".format(left, right)
else:
copy.execution_name = "{}{}{}".format(left, binary, right)
copy.query.addSELECT(copy.execution_name)
return copy | [
"def",
"_binary_arithemtic",
"(",
"self",
",",
"left",
",",
"binary",
",",
"right",
")",
":",
"if",
"isinstance",
"(",
"right",
",",
"(",
"int",
",",
"float",
")",
")",
":",
"right",
"=",
"right",
"elif",
"isinstance",
"(",
"right",
",",
"Column",
")... | Parameters
----------
operand: Column object, integer or float
Value on which to apply operator to this column
binary: char
binary arithmetic operator (-, +, *, /, ^, %)
Returns
-------
self
Notes
-----
Returning self will allow the next object to use this column ops and
concatenate something else | [
"Parameters",
"----------",
"operand",
":",
"Column",
"object",
"integer",
"or",
"float",
"Value",
"on",
"which",
"to",
"apply",
"operator",
"to",
"this",
"column",
"binary",
":",
"char",
"binary",
"arithmetic",
"operator",
"(",
"-",
"+",
"*",
"/",
"^",
"%... | train | https://github.com/datacratic/pymldb/blob/e41f3c37138e9fd4a82ef3db685899cdafa4125e/pymldb/data.py#L257-L301 |
datacratic/pymldb | pymldb/data.py | Column._unary_arithmetic | def _unary_arithmetic(self, unary):
"""
Parameters
----------
unary: char
Unary arithmetic operator (-, +) to be applied to this column
Returns
-------
self
Notes
-----
Returning self will allow the next object to use this column ops and
concatenate something else
"""
copy = self.copy()
copy.query.removeSELECT("{}".format(copy.execution_name))
copy.execution_name = "{}({})".format(unary, self.execution_name)
copy.query.addSELECT(copy.execution_name)
return copy | python | def _unary_arithmetic(self, unary):
"""
Parameters
----------
unary: char
Unary arithmetic operator (-, +) to be applied to this column
Returns
-------
self
Notes
-----
Returning self will allow the next object to use this column ops and
concatenate something else
"""
copy = self.copy()
copy.query.removeSELECT("{}".format(copy.execution_name))
copy.execution_name = "{}({})".format(unary, self.execution_name)
copy.query.addSELECT(copy.execution_name)
return copy | [
"def",
"_unary_arithmetic",
"(",
"self",
",",
"unary",
")",
":",
"copy",
"=",
"self",
".",
"copy",
"(",
")",
"copy",
".",
"query",
".",
"removeSELECT",
"(",
"\"{}\"",
".",
"format",
"(",
"copy",
".",
"execution_name",
")",
")",
"copy",
".",
"execution_... | Parameters
----------
unary: char
Unary arithmetic operator (-, +) to be applied to this column
Returns
-------
self
Notes
-----
Returning self will allow the next object to use this column ops and
concatenate something else | [
"Parameters",
"----------",
"unary",
":",
"char",
"Unary",
"arithmetic",
"operator",
"(",
"-",
"+",
")",
"to",
"be",
"applied",
"to",
"this",
"column"
] | train | https://github.com/datacratic/pymldb/blob/e41f3c37138e9fd4a82ef3db685899cdafa4125e/pymldb/data.py#L416-L437 |
datacratic/pymldb | pymldb/data.py | Column.head | def head(self, n=5):
"""Returns first n rows"""
col = self.copy()
col.query.setLIMIT(n)
return col.toPandas() | python | def head(self, n=5):
"""Returns first n rows"""
col = self.copy()
col.query.setLIMIT(n)
return col.toPandas() | [
"def",
"head",
"(",
"self",
",",
"n",
"=",
"5",
")",
":",
"col",
"=",
"self",
".",
"copy",
"(",
")",
"col",
".",
"query",
".",
"setLIMIT",
"(",
"n",
")",
"return",
"col",
".",
"toPandas",
"(",
")"
] | Returns first n rows | [
"Returns",
"first",
"n",
"rows"
] | train | https://github.com/datacratic/pymldb/blob/e41f3c37138e9fd4a82ef3db685899cdafa4125e/pymldb/data.py#L512-L516 |
miku/gluish | gluish/format.py | write_tsv | def write_tsv(output_stream, *tup, **kwargs):
"""
Write argument list in `tup` out as a tab-separeated row to the stream.
"""
encoding = kwargs.get('encoding') or 'utf-8'
value = '\t'.join([s for s in tup]) + '\n'
output_stream.write(value.encode(encoding)) | python | def write_tsv(output_stream, *tup, **kwargs):
"""
Write argument list in `tup` out as a tab-separeated row to the stream.
"""
encoding = kwargs.get('encoding') or 'utf-8'
value = '\t'.join([s for s in tup]) + '\n'
output_stream.write(value.encode(encoding)) | [
"def",
"write_tsv",
"(",
"output_stream",
",",
"*",
"tup",
",",
"*",
"*",
"kwargs",
")",
":",
"encoding",
"=",
"kwargs",
".",
"get",
"(",
"'encoding'",
")",
"or",
"'utf-8'",
"value",
"=",
"'\\t'",
".",
"join",
"(",
"[",
"s",
"for",
"s",
"in",
"tup"... | Write argument list in `tup` out as a tab-separeated row to the stream. | [
"Write",
"argument",
"list",
"in",
"tup",
"out",
"as",
"a",
"tab",
"-",
"separeated",
"row",
"to",
"the",
"stream",
"."
] | train | https://github.com/miku/gluish/blob/56d3ac4f41a944e31ecac0aa3b6d1dc2ce705e29/gluish/format.py#L56-L62 |
miku/gluish | gluish/format.py | iter_tsv | def iter_tsv(input_stream, cols=None, encoding='utf-8'):
"""
If a tuple is given in cols, use the elements as names to construct
a namedtuple.
Columns can be marked as ignored by using ``X`` or ``0`` as column name.
Example (ignore the first four columns of a five column TSV):
::
def run(self):
with self.input().open() as handle:
for row in handle.iter_tsv(cols=('X', 'X', 'X', 'X', 'iln')):
print(row.iln)
"""
if cols:
cols = [c if not c in ('x', 'X', 0, None) else random_string(length=5)
for c in cols]
Record = collections.namedtuple('Record', cols)
for line in input_stream:
yield Record._make(line.decode(encoding).rstrip('\n').split('\t'))
else:
for line in input_stream:
yield tuple(line.decode(encoding).rstrip('\n').split('\t')) | python | def iter_tsv(input_stream, cols=None, encoding='utf-8'):
"""
If a tuple is given in cols, use the elements as names to construct
a namedtuple.
Columns can be marked as ignored by using ``X`` or ``0`` as column name.
Example (ignore the first four columns of a five column TSV):
::
def run(self):
with self.input().open() as handle:
for row in handle.iter_tsv(cols=('X', 'X', 'X', 'X', 'iln')):
print(row.iln)
"""
if cols:
cols = [c if not c in ('x', 'X', 0, None) else random_string(length=5)
for c in cols]
Record = collections.namedtuple('Record', cols)
for line in input_stream:
yield Record._make(line.decode(encoding).rstrip('\n').split('\t'))
else:
for line in input_stream:
yield tuple(line.decode(encoding).rstrip('\n').split('\t')) | [
"def",
"iter_tsv",
"(",
"input_stream",
",",
"cols",
"=",
"None",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"if",
"cols",
":",
"cols",
"=",
"[",
"c",
"if",
"not",
"c",
"in",
"(",
"'x'",
",",
"'X'",
",",
"0",
",",
"None",
")",
"else",
"random_str... | If a tuple is given in cols, use the elements as names to construct
a namedtuple.
Columns can be marked as ignored by using ``X`` or ``0`` as column name.
Example (ignore the first four columns of a five column TSV):
::
def run(self):
with self.input().open() as handle:
for row in handle.iter_tsv(cols=('X', 'X', 'X', 'X', 'iln')):
print(row.iln) | [
"If",
"a",
"tuple",
"is",
"given",
"in",
"cols",
"use",
"the",
"elements",
"as",
"names",
"to",
"construct",
"a",
"namedtuple",
"."
] | train | https://github.com/miku/gluish/blob/56d3ac4f41a944e31ecac0aa3b6d1dc2ce705e29/gluish/format.py#L65-L89 |
mozilla-releng/signtool | signtool/signtool.py | is_authenticode_signed | def is_authenticode_signed(filename):
"""Returns True if the file is signed with authenticode"""
with open(filename, 'rb') as fp:
fp.seek(0)
magic = fp.read(2)
if magic != b'MZ':
return False
# First grab the pointer to the coff_header, which is at offset 60
fp.seek(60)
coff_header_offset = struct.unpack('<L', fp.read(4))[0]
# Check the COFF magic
fp.seek(coff_header_offset)
magic = fp.read(4)
if magic != b'PE\x00\x00':
return False
# Get the PE type
fp.seek(coff_header_offset + 0x18)
pe_type = struct.unpack('<h', fp.read(2))[0]
if pe_type == 0x10b:
# PE32 file (32-bit apps)
number_of_data_dirs_offset = coff_header_offset + 0x74
elif pe_type == 0x20b:
# PE32+ files (64-bit apps)
# PE32+ files have slightly larger fields in the header
number_of_data_dirs_offset = coff_header_offset + 0x74 + 16
else:
return False
fp.seek(number_of_data_dirs_offset)
num_data_dirs = struct.unpack('<L', fp.read(4))[0]
if num_data_dirs < 5:
# Probably shouldn't happen, but just in case
return False
cert_table_offset = number_of_data_dirs_offset + 4*8 + 4
fp.seek(cert_table_offset)
addr, size = struct.unpack('<LL', fp.read(8))
if not addr or not size:
return False
# Check that addr is inside the file
fp.seek(addr)
if fp.tell() != addr:
return False
cert = fp.read(size)
if len(cert) != size:
return False
return True | python | def is_authenticode_signed(filename):
"""Returns True if the file is signed with authenticode"""
with open(filename, 'rb') as fp:
fp.seek(0)
magic = fp.read(2)
if magic != b'MZ':
return False
# First grab the pointer to the coff_header, which is at offset 60
fp.seek(60)
coff_header_offset = struct.unpack('<L', fp.read(4))[0]
# Check the COFF magic
fp.seek(coff_header_offset)
magic = fp.read(4)
if magic != b'PE\x00\x00':
return False
# Get the PE type
fp.seek(coff_header_offset + 0x18)
pe_type = struct.unpack('<h', fp.read(2))[0]
if pe_type == 0x10b:
# PE32 file (32-bit apps)
number_of_data_dirs_offset = coff_header_offset + 0x74
elif pe_type == 0x20b:
# PE32+ files (64-bit apps)
# PE32+ files have slightly larger fields in the header
number_of_data_dirs_offset = coff_header_offset + 0x74 + 16
else:
return False
fp.seek(number_of_data_dirs_offset)
num_data_dirs = struct.unpack('<L', fp.read(4))[0]
if num_data_dirs < 5:
# Probably shouldn't happen, but just in case
return False
cert_table_offset = number_of_data_dirs_offset + 4*8 + 4
fp.seek(cert_table_offset)
addr, size = struct.unpack('<LL', fp.read(8))
if not addr or not size:
return False
# Check that addr is inside the file
fp.seek(addr)
if fp.tell() != addr:
return False
cert = fp.read(size)
if len(cert) != size:
return False
return True | [
"def",
"is_authenticode_signed",
"(",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"fp",
":",
"fp",
".",
"seek",
"(",
"0",
")",
"magic",
"=",
"fp",
".",
"read",
"(",
"2",
")",
"if",
"magic",
"!=",
"b'MZ'",
":",
"... | Returns True if the file is signed with authenticode | [
"Returns",
"True",
"if",
"the",
"file",
"is",
"signed",
"with",
"authenticode"
] | train | https://github.com/mozilla-releng/signtool/blob/0a778778a181cb9cab424b29fa104b70345f53c2/signtool/signtool.py#L37-L88 |
mozilla-releng/signtool | signtool/signtool.py | parse_cmdln_opts | def parse_cmdln_opts(parser, cmdln_args):
"""Rather than have this all clutter main(), let's split this out.
Clean arch decision: rather than parsing sys.argv directly, pass
sys.argv[1:] to this function (or any iterable for testing.)
"""
parser.set_defaults(
hosts=[],
cert=None,
log_level=logging.INFO,
output_dir=None,
output_file=None,
formats=[],
includes=[],
excludes=[],
nsscmd=None,
tokenfile=None,
noncefile=None,
cachedir=None,
)
parser.add_option(
"-H", "--host", dest="hosts", action="append", help="format[:format]:hostname[:port]")
parser.add_option("-c", "--server-cert", dest="cert")
parser.add_option("-t", "--token-file", dest="tokenfile",
help="file where token is stored")
parser.add_option("-n", "--nonce-file", dest="noncefile",
help="file where nonce is stored")
parser.add_option("-d", "--output-dir", dest="output_dir",
help="output directory; if not set then files are "
"replaced with signed copies")
parser.add_option("-o", "--output-file", dest="output_file",
help="output file; if not set then files are replaced with signed "
"copies. This can only be used when signing a single file")
parser.add_option("-f", "--formats", dest="formats", action="append",
help="signing formats (one or more of %s)" % ", ".join(ALLOWED_FORMATS))
parser.add_option("-q", "--quiet", dest="log_level", action="store_const",
const=logging.WARN)
parser.add_option(
"-v", "--verbose", dest="log_level", action="store_const",
const=logging.DEBUG)
parser.add_option("-i", "--include", dest="includes", action="append",
help="add to include patterns")
parser.add_option("-x", "--exclude", dest="excludes", action="append",
help="add to exclude patterns")
parser.add_option("--nsscmd", dest="nsscmd",
help="command to re-sign nss libraries, if required")
parser.add_option("--cachedir", dest="cachedir",
help="local cache directory")
# TODO: Concurrency?
# TODO: Different certs per server?
options, args = parser.parse_args(cmdln_args)
if not options.hosts:
parser.error("at least one host is required")
if not options.cert:
parser.error("certificate is required")
if not os.path.exists(options.cert):
parser.error("certificate not found")
if not options.tokenfile:
parser.error("token file is required")
if not options.noncefile:
parser.error("nonce file is required")
# Covert nsscmd to win32 path if required
if sys.platform == 'win32' and options.nsscmd:
nsscmd = options.nsscmd.strip()
if nsscmd.startswith("/"):
drive = nsscmd[1]
options.nsscmd = "%s:%s" % (drive, nsscmd[2:])
# Handle format
formats = []
for fmt in options.formats:
if "," in fmt:
for fmt in fmt.split(","):
if fmt not in ALLOWED_FORMATS:
parser.error("invalid format: %s" % fmt)
formats.append(fmt)
elif fmt not in ALLOWED_FORMATS:
parser.error("invalid format: %s" % fmt)
else:
formats.append(fmt)
# bug 1382882, 1164456
# Widevine and GPG signing must happen last because they will be invalid if
# done prior to any format that modifies the file in-place.
for fmt in ("widevine", "widevine_blessed", "gpg"):
if fmt in formats:
formats.remove(fmt)
formats.append(fmt)
if options.output_file and (len(args) > 1 or os.path.isdir(args[0])):
parser.error(
"-o / --output-file can only be used when signing a single file")
if options.output_dir:
if os.path.exists(options.output_dir):
if not os.path.isdir(options.output_dir):
parser.error(
"output_dir (%s) must be a directory", options.output_dir)
else:
os.makedirs(options.output_dir)
if not options.includes:
# Do everything!
options.includes.append("*")
if not formats:
parser.error("no formats specified")
options.formats = formats
format_urls = defaultdict(list)
for h in options.hosts:
# The last two parts of a host is the actual hostname:port. Any parts
# before that are formats - there could be 0..n formats so this is
# tricky to split.
parts = h.split(":")
h = parts[-2:]
fmts = parts[:-2]
# If no formats are specified, the host is assumed to support all of them.
if not fmts:
fmts = formats
for f in fmts:
format_urls[f].append("https://%s" % ":".join(h))
options.format_urls = format_urls
missing_fmt_hosts = set(formats) - set(format_urls.keys())
if missing_fmt_hosts:
parser.error("no hosts capable of signing formats: %s" % " ".join(missing_fmt_hosts))
return options, args | python | def parse_cmdln_opts(parser, cmdln_args):
"""Rather than have this all clutter main(), let's split this out.
Clean arch decision: rather than parsing sys.argv directly, pass
sys.argv[1:] to this function (or any iterable for testing.)
"""
parser.set_defaults(
hosts=[],
cert=None,
log_level=logging.INFO,
output_dir=None,
output_file=None,
formats=[],
includes=[],
excludes=[],
nsscmd=None,
tokenfile=None,
noncefile=None,
cachedir=None,
)
parser.add_option(
"-H", "--host", dest="hosts", action="append", help="format[:format]:hostname[:port]")
parser.add_option("-c", "--server-cert", dest="cert")
parser.add_option("-t", "--token-file", dest="tokenfile",
help="file where token is stored")
parser.add_option("-n", "--nonce-file", dest="noncefile",
help="file where nonce is stored")
parser.add_option("-d", "--output-dir", dest="output_dir",
help="output directory; if not set then files are "
"replaced with signed copies")
parser.add_option("-o", "--output-file", dest="output_file",
help="output file; if not set then files are replaced with signed "
"copies. This can only be used when signing a single file")
parser.add_option("-f", "--formats", dest="formats", action="append",
help="signing formats (one or more of %s)" % ", ".join(ALLOWED_FORMATS))
parser.add_option("-q", "--quiet", dest="log_level", action="store_const",
const=logging.WARN)
parser.add_option(
"-v", "--verbose", dest="log_level", action="store_const",
const=logging.DEBUG)
parser.add_option("-i", "--include", dest="includes", action="append",
help="add to include patterns")
parser.add_option("-x", "--exclude", dest="excludes", action="append",
help="add to exclude patterns")
parser.add_option("--nsscmd", dest="nsscmd",
help="command to re-sign nss libraries, if required")
parser.add_option("--cachedir", dest="cachedir",
help="local cache directory")
# TODO: Concurrency?
# TODO: Different certs per server?
options, args = parser.parse_args(cmdln_args)
if not options.hosts:
parser.error("at least one host is required")
if not options.cert:
parser.error("certificate is required")
if not os.path.exists(options.cert):
parser.error("certificate not found")
if not options.tokenfile:
parser.error("token file is required")
if not options.noncefile:
parser.error("nonce file is required")
# Covert nsscmd to win32 path if required
if sys.platform == 'win32' and options.nsscmd:
nsscmd = options.nsscmd.strip()
if nsscmd.startswith("/"):
drive = nsscmd[1]
options.nsscmd = "%s:%s" % (drive, nsscmd[2:])
# Handle format
formats = []
for fmt in options.formats:
if "," in fmt:
for fmt in fmt.split(","):
if fmt not in ALLOWED_FORMATS:
parser.error("invalid format: %s" % fmt)
formats.append(fmt)
elif fmt not in ALLOWED_FORMATS:
parser.error("invalid format: %s" % fmt)
else:
formats.append(fmt)
# bug 1382882, 1164456
# Widevine and GPG signing must happen last because they will be invalid if
# done prior to any format that modifies the file in-place.
for fmt in ("widevine", "widevine_blessed", "gpg"):
if fmt in formats:
formats.remove(fmt)
formats.append(fmt)
if options.output_file and (len(args) > 1 or os.path.isdir(args[0])):
parser.error(
"-o / --output-file can only be used when signing a single file")
if options.output_dir:
if os.path.exists(options.output_dir):
if not os.path.isdir(options.output_dir):
parser.error(
"output_dir (%s) must be a directory", options.output_dir)
else:
os.makedirs(options.output_dir)
if not options.includes:
# Do everything!
options.includes.append("*")
if not formats:
parser.error("no formats specified")
options.formats = formats
format_urls = defaultdict(list)
for h in options.hosts:
# The last two parts of a host is the actual hostname:port. Any parts
# before that are formats - there could be 0..n formats so this is
# tricky to split.
parts = h.split(":")
h = parts[-2:]
fmts = parts[:-2]
# If no formats are specified, the host is assumed to support all of them.
if not fmts:
fmts = formats
for f in fmts:
format_urls[f].append("https://%s" % ":".join(h))
options.format_urls = format_urls
missing_fmt_hosts = set(formats) - set(format_urls.keys())
if missing_fmt_hosts:
parser.error("no hosts capable of signing formats: %s" % " ".join(missing_fmt_hosts))
return options, args | [
"def",
"parse_cmdln_opts",
"(",
"parser",
",",
"cmdln_args",
")",
":",
"parser",
".",
"set_defaults",
"(",
"hosts",
"=",
"[",
"]",
",",
"cert",
"=",
"None",
",",
"log_level",
"=",
"logging",
".",
"INFO",
",",
"output_dir",
"=",
"None",
",",
"output_file"... | Rather than have this all clutter main(), let's split this out.
Clean arch decision: rather than parsing sys.argv directly, pass
sys.argv[1:] to this function (or any iterable for testing.) | [
"Rather",
"than",
"have",
"this",
"all",
"clutter",
"main",
"()",
"let",
"s",
"split",
"this",
"out",
".",
"Clean",
"arch",
"decision",
":",
"rather",
"than",
"parsing",
"sys",
".",
"argv",
"directly",
"pass",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
... | train | https://github.com/mozilla-releng/signtool/blob/0a778778a181cb9cab424b29fa104b70345f53c2/signtool/signtool.py#L92-L229 |
KeplerGO/K2fov | K2fov/fields.py | _getCampaignDict | def _getCampaignDict():
"""Returns a dictionary specifying the details of all campaigns."""
global _campaign_dict_cache
if _campaign_dict_cache is None:
# All pointing parameters and dates are stored in a JSON file
fn = os.path.join(PACKAGEDIR, "data", "k2-campaign-parameters.json")
_campaign_dict_cache = json.load(open(fn))
return _campaign_dict_cache | python | def _getCampaignDict():
"""Returns a dictionary specifying the details of all campaigns."""
global _campaign_dict_cache
if _campaign_dict_cache is None:
# All pointing parameters and dates are stored in a JSON file
fn = os.path.join(PACKAGEDIR, "data", "k2-campaign-parameters.json")
_campaign_dict_cache = json.load(open(fn))
return _campaign_dict_cache | [
"def",
"_getCampaignDict",
"(",
")",
":",
"global",
"_campaign_dict_cache",
"if",
"_campaign_dict_cache",
"is",
"None",
":",
"# All pointing parameters and dates are stored in a JSON file",
"fn",
"=",
"os",
".",
"path",
".",
"join",
"(",
"PACKAGEDIR",
",",
"\"data\"",
... | Returns a dictionary specifying the details of all campaigns. | [
"Returns",
"a",
"dictionary",
"specifying",
"the",
"details",
"of",
"all",
"campaigns",
"."
] | train | https://github.com/KeplerGO/K2fov/blob/fb122b35687340e0357cba9e0dd47b3be0760693/K2fov/fields.py#L15-L22 |
KeplerGO/K2fov | K2fov/fields.py | getFieldInfo | def getFieldInfo(fieldnum):
"""Returns a dictionary containing the metadata of a K2 Campaign field.
Raises a ValueError if the field number is unknown.
Parameters
----------
fieldnum : int
Campaign field number (e.g. 0, 1, 2, ...)
Returns
-------
field : dict
The dictionary contains the keys
'ra', 'dec', 'roll' (floats in decimal degrees),
'start', 'stop', (strings in YYYY-MM-DD format)
and 'comments' (free text).
"""
try:
info = _getCampaignDict()["c{0}".format(fieldnum)]
# Print warning messages if necessary
if "preliminary" in info and info["preliminary"] == "True":
logger.warning("Warning: the position of field {0} is preliminary. "
"Do not use this position for your final "
"target selection!".format(fieldnum))
return info
except KeyError:
raise ValueError("Field {0} not set in this version "
"of the code".format(fieldnum)) | python | def getFieldInfo(fieldnum):
"""Returns a dictionary containing the metadata of a K2 Campaign field.
Raises a ValueError if the field number is unknown.
Parameters
----------
fieldnum : int
Campaign field number (e.g. 0, 1, 2, ...)
Returns
-------
field : dict
The dictionary contains the keys
'ra', 'dec', 'roll' (floats in decimal degrees),
'start', 'stop', (strings in YYYY-MM-DD format)
and 'comments' (free text).
"""
try:
info = _getCampaignDict()["c{0}".format(fieldnum)]
# Print warning messages if necessary
if "preliminary" in info and info["preliminary"] == "True":
logger.warning("Warning: the position of field {0} is preliminary. "
"Do not use this position for your final "
"target selection!".format(fieldnum))
return info
except KeyError:
raise ValueError("Field {0} not set in this version "
"of the code".format(fieldnum)) | [
"def",
"getFieldInfo",
"(",
"fieldnum",
")",
":",
"try",
":",
"info",
"=",
"_getCampaignDict",
"(",
")",
"[",
"\"c{0}\"",
".",
"format",
"(",
"fieldnum",
")",
"]",
"# Print warning messages if necessary",
"if",
"\"preliminary\"",
"in",
"info",
"and",
"info",
"... | Returns a dictionary containing the metadata of a K2 Campaign field.
Raises a ValueError if the field number is unknown.
Parameters
----------
fieldnum : int
Campaign field number (e.g. 0, 1, 2, ...)
Returns
-------
field : dict
The dictionary contains the keys
'ra', 'dec', 'roll' (floats in decimal degrees),
'start', 'stop', (strings in YYYY-MM-DD format)
and 'comments' (free text). | [
"Returns",
"a",
"dictionary",
"containing",
"the",
"metadata",
"of",
"a",
"K2",
"Campaign",
"field",
"."
] | train | https://github.com/KeplerGO/K2fov/blob/fb122b35687340e0357cba9e0dd47b3be0760693/K2fov/fields.py#L36-L64 |
KeplerGO/K2fov | K2fov/fields.py | getKeplerFov | def getKeplerFov(fieldnum):
"""Returns a `fov.KeplerFov` object for a given campaign.
Parameters
----------
fieldnum : int
K2 Campaign number.
Returns
-------
fovobj : `fov.KeplerFov` object
Details the footprint of the requested K2 campaign.
"""
info = getFieldInfo(fieldnum)
ra, dec, scRoll = info["ra"], info["dec"], info["roll"]
# convert from SC roll to FOV coordinates
# do not use the fovRoll coords anywhere else
# they are internal to this script only
fovRoll = fov.getFovAngleFromSpacecraftRoll(scRoll)
# KeplerFov takes a listen of broken CCD channels as optional argument;
# these channels will be ignored during plotting and on-silicon determination.
# Modules 3 and 7 broke prior to the start of K2:
brokenChannels = [5, 6, 7, 8, 17, 18, 19, 20]
# Module 4 failed during Campaign 10
if fieldnum > 10:
brokenChannels.extend([9, 10, 11, 12])
# Hack: the Kepler field is defined as "Campaign 1000"
# and (initially) had no broken channels
if fieldnum == 1000:
brokenChannels = []
return fov.KeplerFov(ra, dec, fovRoll, brokenChannels=brokenChannels) | python | def getKeplerFov(fieldnum):
"""Returns a `fov.KeplerFov` object for a given campaign.
Parameters
----------
fieldnum : int
K2 Campaign number.
Returns
-------
fovobj : `fov.KeplerFov` object
Details the footprint of the requested K2 campaign.
"""
info = getFieldInfo(fieldnum)
ra, dec, scRoll = info["ra"], info["dec"], info["roll"]
# convert from SC roll to FOV coordinates
# do not use the fovRoll coords anywhere else
# they are internal to this script only
fovRoll = fov.getFovAngleFromSpacecraftRoll(scRoll)
# KeplerFov takes a listen of broken CCD channels as optional argument;
# these channels will be ignored during plotting and on-silicon determination.
# Modules 3 and 7 broke prior to the start of K2:
brokenChannels = [5, 6, 7, 8, 17, 18, 19, 20]
# Module 4 failed during Campaign 10
if fieldnum > 10:
brokenChannels.extend([9, 10, 11, 12])
# Hack: the Kepler field is defined as "Campaign 1000"
# and (initially) had no broken channels
if fieldnum == 1000:
brokenChannels = []
return fov.KeplerFov(ra, dec, fovRoll, brokenChannels=brokenChannels) | [
"def",
"getKeplerFov",
"(",
"fieldnum",
")",
":",
"info",
"=",
"getFieldInfo",
"(",
"fieldnum",
")",
"ra",
",",
"dec",
",",
"scRoll",
"=",
"info",
"[",
"\"ra\"",
"]",
",",
"info",
"[",
"\"dec\"",
"]",
",",
"info",
"[",
"\"roll\"",
"]",
"# convert from ... | Returns a `fov.KeplerFov` object for a given campaign.
Parameters
----------
fieldnum : int
K2 Campaign number.
Returns
-------
fovobj : `fov.KeplerFov` object
Details the footprint of the requested K2 campaign. | [
"Returns",
"a",
"fov",
".",
"KeplerFov",
"object",
"for",
"a",
"given",
"campaign",
"."
] | train | https://github.com/KeplerGO/K2fov/blob/fb122b35687340e0357cba9e0dd47b3be0760693/K2fov/fields.py#L67-L98 |
inveniosoftware/invenio-openaire | invenio_openaire/indexer.py | indexer_receiver | def indexer_receiver(sender, json=None, record=None, index=None,
**dummy_kwargs):
"""Connect to before_record_index signal to transform record for ES."""
if index and index.startswith('grants-'):
# Generate suggest field
suggestions = [
json.get('code'),
json.get('acronym'),
json.get('title')
]
json['suggest'] = {
'input': [s for s in suggestions if s],
'output': json['title'],
'context': {
'funder': [json['funder']['doi']]
},
'payload': {
'id': json['internal_id'],
'legacy_id': (json['code'] if json.get('program') == 'FP7'
else json['internal_id']),
'code': json['code'],
'title': json['title'],
'acronym': json.get('acronym'),
'program': json.get('program'),
},
}
elif index and index.startswith('funders-'):
# Generate suggest field
suggestions = json.get('acronyms', []) + [json.get('name')]
json['suggest'] = {
'input': [s for s in suggestions if s],
'output': json['name'],
'payload': {
'id': json['doi']
},
} | python | def indexer_receiver(sender, json=None, record=None, index=None,
**dummy_kwargs):
"""Connect to before_record_index signal to transform record for ES."""
if index and index.startswith('grants-'):
# Generate suggest field
suggestions = [
json.get('code'),
json.get('acronym'),
json.get('title')
]
json['suggest'] = {
'input': [s for s in suggestions if s],
'output': json['title'],
'context': {
'funder': [json['funder']['doi']]
},
'payload': {
'id': json['internal_id'],
'legacy_id': (json['code'] if json.get('program') == 'FP7'
else json['internal_id']),
'code': json['code'],
'title': json['title'],
'acronym': json.get('acronym'),
'program': json.get('program'),
},
}
elif index and index.startswith('funders-'):
# Generate suggest field
suggestions = json.get('acronyms', []) + [json.get('name')]
json['suggest'] = {
'input': [s for s in suggestions if s],
'output': json['name'],
'payload': {
'id': json['doi']
},
} | [
"def",
"indexer_receiver",
"(",
"sender",
",",
"json",
"=",
"None",
",",
"record",
"=",
"None",
",",
"index",
"=",
"None",
",",
"*",
"*",
"dummy_kwargs",
")",
":",
"if",
"index",
"and",
"index",
".",
"startswith",
"(",
"'grants-'",
")",
":",
"# Generat... | Connect to before_record_index signal to transform record for ES. | [
"Connect",
"to",
"before_record_index",
"signal",
"to",
"transform",
"record",
"for",
"ES",
"."
] | train | https://github.com/inveniosoftware/invenio-openaire/blob/71860effff6abe7f658d3a11894e064202ef1c36/invenio_openaire/indexer.py#L30-L65 |
rmed/pyemtmad | pyemtmad/api/bus.py | BusApi.get_calendar | def get_calendar(self, **kwargs):
"""Obtain EMT calendar for a range of dates.
Args:
start_day (int): Starting day of the month in format DD.
The number is automatically padded if it only has one digit.
start_month (int): Starting month number in format MM.
The number is automatically padded if it only has one digit.
start_year (int): Starting year number in format YYYY.
end_day (int): Ending day of the month in format DD.
The number is automatically padded if it only has one digit.
end_month (int): Ending month number in format MM.
The number is automatically padded if it only has one digit.
end_year (int): Ending year number in format YYYY.
Returns:
Status boolean and parsed response (list[CalendarItem]), or message
string in case of error.
"""
# Endpoint parameters
start_date = util.date_string(
kwargs.get('start_day', '01'),
kwargs.get('start_month', '01'),
kwargs.get('start_year', '1970')
)
end_date = util.date_string(
kwargs.get('end_day', '01'),
kwargs.get('end_month', '01'),
kwargs.get('end_year', '1970')
)
params = {'SelectDateBegin': start_date, 'SelectDateEnd': end_date}
# Request
result = self.make_request('bus', 'get_calendar', **params)
if not util.check_result(result):
return False, result.get('resultDescription', 'UNKNOWN ERROR')
# Parse
values = util.response_list(result, 'resultValues')
return True, [emtype.CalendarItem(**a) for a in values] | python | def get_calendar(self, **kwargs):
"""Obtain EMT calendar for a range of dates.
Args:
start_day (int): Starting day of the month in format DD.
The number is automatically padded if it only has one digit.
start_month (int): Starting month number in format MM.
The number is automatically padded if it only has one digit.
start_year (int): Starting year number in format YYYY.
end_day (int): Ending day of the month in format DD.
The number is automatically padded if it only has one digit.
end_month (int): Ending month number in format MM.
The number is automatically padded if it only has one digit.
end_year (int): Ending year number in format YYYY.
Returns:
Status boolean and parsed response (list[CalendarItem]), or message
string in case of error.
"""
# Endpoint parameters
start_date = util.date_string(
kwargs.get('start_day', '01'),
kwargs.get('start_month', '01'),
kwargs.get('start_year', '1970')
)
end_date = util.date_string(
kwargs.get('end_day', '01'),
kwargs.get('end_month', '01'),
kwargs.get('end_year', '1970')
)
params = {'SelectDateBegin': start_date, 'SelectDateEnd': end_date}
# Request
result = self.make_request('bus', 'get_calendar', **params)
if not util.check_result(result):
return False, result.get('resultDescription', 'UNKNOWN ERROR')
# Parse
values = util.response_list(result, 'resultValues')
return True, [emtype.CalendarItem(**a) for a in values] | [
"def",
"get_calendar",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# Endpoint parameters",
"start_date",
"=",
"util",
".",
"date_string",
"(",
"kwargs",
".",
"get",
"(",
"'start_day'",
",",
"'01'",
")",
",",
"kwargs",
".",
"get",
"(",
"'start_month'",... | Obtain EMT calendar for a range of dates.
Args:
start_day (int): Starting day of the month in format DD.
The number is automatically padded if it only has one digit.
start_month (int): Starting month number in format MM.
The number is automatically padded if it only has one digit.
start_year (int): Starting year number in format YYYY.
end_day (int): Ending day of the month in format DD.
The number is automatically padded if it only has one digit.
end_month (int): Ending month number in format MM.
The number is automatically padded if it only has one digit.
end_year (int): Ending year number in format YYYY.
Returns:
Status boolean and parsed response (list[CalendarItem]), or message
string in case of error. | [
"Obtain",
"EMT",
"calendar",
"for",
"a",
"range",
"of",
"dates",
"."
] | train | https://github.com/rmed/pyemtmad/blob/c21c42d0c7b50035dfed29540d7e64ab67833728/pyemtmad/api/bus.py#L39-L81 |
rmed/pyemtmad | pyemtmad/api/bus.py | BusApi.get_nodes_lines | def get_nodes_lines(self, **kwargs):
"""Obtain stop IDs, coordinates and line information.
Args:
nodes (list[int] | int): nodes to query, may be empty to get
all nodes.
Returns:
Status boolean and parsed response (list[NodeLinesItem]), or message
string in case of error.
"""
# Endpoint parameters
params = {'Nodes': util.ints_to_string(kwargs.get('nodes', []))}
# Request
result = self.make_request('bus', 'get_nodes_lines', **params)
if not util.check_result(result):
return False, result.get('resultDescription', 'UNKNOWN ERROR')
# Parse
values = util.response_list(result, 'resultValues')
return True, [emtype.NodeLinesItem(**a) for a in values] | python | def get_nodes_lines(self, **kwargs):
"""Obtain stop IDs, coordinates and line information.
Args:
nodes (list[int] | int): nodes to query, may be empty to get
all nodes.
Returns:
Status boolean and parsed response (list[NodeLinesItem]), or message
string in case of error.
"""
# Endpoint parameters
params = {'Nodes': util.ints_to_string(kwargs.get('nodes', []))}
# Request
result = self.make_request('bus', 'get_nodes_lines', **params)
if not util.check_result(result):
return False, result.get('resultDescription', 'UNKNOWN ERROR')
# Parse
values = util.response_list(result, 'resultValues')
return True, [emtype.NodeLinesItem(**a) for a in values] | [
"def",
"get_nodes_lines",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# Endpoint parameters",
"params",
"=",
"{",
"'Nodes'",
":",
"util",
".",
"ints_to_string",
"(",
"kwargs",
".",
"get",
"(",
"'nodes'",
",",
"[",
"]",
")",
")",
"}",
"# Request",
... | Obtain stop IDs, coordinates and line information.
Args:
nodes (list[int] | int): nodes to query, may be empty to get
all nodes.
Returns:
Status boolean and parsed response (list[NodeLinesItem]), or message
string in case of error. | [
"Obtain",
"stop",
"IDs",
"coordinates",
"and",
"line",
"information",
"."
] | train | https://github.com/rmed/pyemtmad/blob/c21c42d0c7b50035dfed29540d7e64ab67833728/pyemtmad/api/bus.py#L144-L166 |
twisted/mantissa | xmantissa/website.py | MantissaLivePage.beforeRender | def beforeRender(self, ctx):
"""
Before rendering, retrieve the hostname from the request being
responded to and generate an URL which will serve as the root for
all JavaScript modules to be loaded.
"""
request = IRequest(ctx)
root = self.webSite.rootURL(request)
self._moduleRoot = root.child('__jsmodule__') | python | def beforeRender(self, ctx):
"""
Before rendering, retrieve the hostname from the request being
responded to and generate an URL which will serve as the root for
all JavaScript modules to be loaded.
"""
request = IRequest(ctx)
root = self.webSite.rootURL(request)
self._moduleRoot = root.child('__jsmodule__') | [
"def",
"beforeRender",
"(",
"self",
",",
"ctx",
")",
":",
"request",
"=",
"IRequest",
"(",
"ctx",
")",
"root",
"=",
"self",
".",
"webSite",
".",
"rootURL",
"(",
"request",
")",
"self",
".",
"_moduleRoot",
"=",
"root",
".",
"child",
"(",
"'__jsmodule__'... | Before rendering, retrieve the hostname from the request being
responded to and generate an URL which will serve as the root for
all JavaScript modules to be loaded. | [
"Before",
"rendering",
"retrieve",
"the",
"hostname",
"from",
"the",
"request",
"being",
"responded",
"to",
"and",
"generate",
"an",
"URL",
"which",
"will",
"serve",
"as",
"the",
"root",
"for",
"all",
"JavaScript",
"modules",
"to",
"be",
"loaded",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/website.py#L88-L96 |
twisted/mantissa | xmantissa/website.py | MantissaLivePage.getJSModuleURL | def getJSModuleURL(self, moduleName):
"""
Retrieve an L{URL} object which references the given module name.
This makes a 'best effort' guess as to an fully qualified HTTPS URL
based on the hostname provided during rendering and the configuration
of the site. This is to avoid unnecessary duplicate retrieval of the
same scripts from two different URLs by the browser.
If such configuration does not exist, however, it will simply return an
absolute path URL with no hostname or port.
@raise NotImplementedError: if rendering has not begun yet and
therefore beforeRender has not provided us with a usable hostname.
"""
if self._moduleRoot is None:
raise NotImplementedError(
"JS module URLs cannot be requested before rendering.")
moduleHash = self.hashCache.getModule(moduleName).hashValue
return self._moduleRoot.child(moduleHash).child(moduleName) | python | def getJSModuleURL(self, moduleName):
"""
Retrieve an L{URL} object which references the given module name.
This makes a 'best effort' guess as to an fully qualified HTTPS URL
based on the hostname provided during rendering and the configuration
of the site. This is to avoid unnecessary duplicate retrieval of the
same scripts from two different URLs by the browser.
If such configuration does not exist, however, it will simply return an
absolute path URL with no hostname or port.
@raise NotImplementedError: if rendering has not begun yet and
therefore beforeRender has not provided us with a usable hostname.
"""
if self._moduleRoot is None:
raise NotImplementedError(
"JS module URLs cannot be requested before rendering.")
moduleHash = self.hashCache.getModule(moduleName).hashValue
return self._moduleRoot.child(moduleHash).child(moduleName) | [
"def",
"getJSModuleURL",
"(",
"self",
",",
"moduleName",
")",
":",
"if",
"self",
".",
"_moduleRoot",
"is",
"None",
":",
"raise",
"NotImplementedError",
"(",
"\"JS module URLs cannot be requested before rendering.\"",
")",
"moduleHash",
"=",
"self",
".",
"hashCache",
... | Retrieve an L{URL} object which references the given module name.
This makes a 'best effort' guess as to an fully qualified HTTPS URL
based on the hostname provided during rendering and the configuration
of the site. This is to avoid unnecessary duplicate retrieval of the
same scripts from two different URLs by the browser.
If such configuration does not exist, however, it will simply return an
absolute path URL with no hostname or port.
@raise NotImplementedError: if rendering has not begun yet and
therefore beforeRender has not provided us with a usable hostname. | [
"Retrieve",
"an",
"L",
"{",
"URL",
"}",
"object",
"which",
"references",
"the",
"given",
"module",
"name",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/website.py#L99-L118 |
twisted/mantissa | xmantissa/website.py | PrefixURLMixin.produceResource | def produceResource(self, request, segments, webViewer):
"""
Return a C{(resource, subsegments)} tuple or None, depending on whether
I wish to return an L{IResource} provider for the given set of segments
or not.
"""
def thunk():
cr = getattr(self, 'createResource', None)
if cr is not None:
return cr()
else:
return self.createResourceWith(webViewer)
return self._produceIt(segments, thunk) | python | def produceResource(self, request, segments, webViewer):
"""
Return a C{(resource, subsegments)} tuple or None, depending on whether
I wish to return an L{IResource} provider for the given set of segments
or not.
"""
def thunk():
cr = getattr(self, 'createResource', None)
if cr is not None:
return cr()
else:
return self.createResourceWith(webViewer)
return self._produceIt(segments, thunk) | [
"def",
"produceResource",
"(",
"self",
",",
"request",
",",
"segments",
",",
"webViewer",
")",
":",
"def",
"thunk",
"(",
")",
":",
"cr",
"=",
"getattr",
"(",
"self",
",",
"'createResource'",
",",
"None",
")",
"if",
"cr",
"is",
"not",
"None",
":",
"re... | Return a C{(resource, subsegments)} tuple or None, depending on whether
I wish to return an L{IResource} provider for the given set of segments
or not. | [
"Return",
"a",
"C",
"{",
"(",
"resource",
"subsegments",
")",
"}",
"tuple",
"or",
"None",
"depending",
"on",
"whether",
"I",
"wish",
"to",
"return",
"an",
"L",
"{",
"IResource",
"}",
"provider",
"for",
"the",
"given",
"set",
"of",
"segments",
"or",
"no... | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/website.py#L169-L181 |
twisted/mantissa | xmantissa/website.py | PrefixURLMixin._produceIt | def _produceIt(self, segments, thunk):
"""
Underlying implmeentation of L{PrefixURLMixin.produceResource} and
L{PrefixURLMixin.sessionlessProduceResource}.
@param segments: the URL segments to dispatch.
@param thunk: a 0-argument callable which returns an L{IResource}
provider, or None.
@return: a 2-tuple of C{(resource, remainingSegments)}, or L{None}.
"""
if not self.prefixURL:
needle = ()
else:
needle = tuple(self.prefixURL.split('/'))
S = len(needle)
if segments[:S] == needle:
if segments == JUST_SLASH:
# I *HATE* THE WEB
subsegments = segments
else:
subsegments = segments[S:]
res = thunk()
# Even though the URL matched up, sometimes we might still
# decide to not handle this request (eg, some prerequisite
# for our function is not met by the store). Allow None
# to be returned by createResource to indicate this case.
if res is not None:
return res, subsegments | python | def _produceIt(self, segments, thunk):
"""
Underlying implmeentation of L{PrefixURLMixin.produceResource} and
L{PrefixURLMixin.sessionlessProduceResource}.
@param segments: the URL segments to dispatch.
@param thunk: a 0-argument callable which returns an L{IResource}
provider, or None.
@return: a 2-tuple of C{(resource, remainingSegments)}, or L{None}.
"""
if not self.prefixURL:
needle = ()
else:
needle = tuple(self.prefixURL.split('/'))
S = len(needle)
if segments[:S] == needle:
if segments == JUST_SLASH:
# I *HATE* THE WEB
subsegments = segments
else:
subsegments = segments[S:]
res = thunk()
# Even though the URL matched up, sometimes we might still
# decide to not handle this request (eg, some prerequisite
# for our function is not met by the store). Allow None
# to be returned by createResource to indicate this case.
if res is not None:
return res, subsegments | [
"def",
"_produceIt",
"(",
"self",
",",
"segments",
",",
"thunk",
")",
":",
"if",
"not",
"self",
".",
"prefixURL",
":",
"needle",
"=",
"(",
")",
"else",
":",
"needle",
"=",
"tuple",
"(",
"self",
".",
"prefixURL",
".",
"split",
"(",
"'/'",
")",
")",
... | Underlying implmeentation of L{PrefixURLMixin.produceResource} and
L{PrefixURLMixin.sessionlessProduceResource}.
@param segments: the URL segments to dispatch.
@param thunk: a 0-argument callable which returns an L{IResource}
provider, or None.
@return: a 2-tuple of C{(resource, remainingSegments)}, or L{None}. | [
"Underlying",
"implmeentation",
"of",
"L",
"{",
"PrefixURLMixin",
".",
"produceResource",
"}",
"and",
"L",
"{",
"PrefixURLMixin",
".",
"sessionlessProduceResource",
"}",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/website.py#L194-L223 |
twisted/mantissa | xmantissa/website.py | StaticSite.installSite | def installSite(self):
"""
Not using the dependency system for this class because it's only
installed via the command line, and multiple instances can be
installed.
"""
for iface, priority in self.__getPowerupInterfaces__([]):
self.store.powerUp(self, iface, priority) | python | def installSite(self):
"""
Not using the dependency system for this class because it's only
installed via the command line, and multiple instances can be
installed.
"""
for iface, priority in self.__getPowerupInterfaces__([]):
self.store.powerUp(self, iface, priority) | [
"def",
"installSite",
"(",
"self",
")",
":",
"for",
"iface",
",",
"priority",
"in",
"self",
".",
"__getPowerupInterfaces__",
"(",
"[",
"]",
")",
":",
"self",
".",
"store",
".",
"powerUp",
"(",
"self",
",",
"iface",
",",
"priority",
")"
] | Not using the dependency system for this class because it's only
installed via the command line, and multiple instances can be
installed. | [
"Not",
"using",
"the",
"dependency",
"system",
"for",
"this",
"class",
"because",
"it",
"s",
"only",
"installed",
"via",
"the",
"command",
"line",
"and",
"multiple",
"instances",
"can",
"be",
"installed",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/website.py#L288-L295 |
twisted/mantissa | xmantissa/website.py | StylesheetFactory.makeStylesheetResource | def makeStylesheetResource(self, path, registry):
"""
Return a resource for the css at the given path with its urls rewritten
based on self.rootURL.
"""
return StylesheetRewritingResourceWrapper(
File(path), self.installedOfferingNames, self.rootURL) | python | def makeStylesheetResource(self, path, registry):
"""
Return a resource for the css at the given path with its urls rewritten
based on self.rootURL.
"""
return StylesheetRewritingResourceWrapper(
File(path), self.installedOfferingNames, self.rootURL) | [
"def",
"makeStylesheetResource",
"(",
"self",
",",
"path",
",",
"registry",
")",
":",
"return",
"StylesheetRewritingResourceWrapper",
"(",
"File",
"(",
"path",
")",
",",
"self",
".",
"installedOfferingNames",
",",
"self",
".",
"rootURL",
")"
] | Return a resource for the css at the given path with its urls rewritten
based on self.rootURL. | [
"Return",
"a",
"resource",
"for",
"the",
"css",
"at",
"the",
"given",
"path",
"with",
"its",
"urls",
"rewritten",
"based",
"on",
"self",
".",
"rootURL",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/website.py#L379-L385 |
twisted/mantissa | xmantissa/website.py | StylesheetRewritingResourceWrapper.renderHTTP | def renderHTTP(self, context):
"""
Render C{self.resource} through a L{StylesheetRewritingRequestWrapper}.
"""
request = IRequest(context)
request = StylesheetRewritingRequestWrapper(
request, self.installedOfferingNames, self.rootURL)
context.remember(request, IRequest)
return self.resource.renderHTTP(context) | python | def renderHTTP(self, context):
"""
Render C{self.resource} through a L{StylesheetRewritingRequestWrapper}.
"""
request = IRequest(context)
request = StylesheetRewritingRequestWrapper(
request, self.installedOfferingNames, self.rootURL)
context.remember(request, IRequest)
return self.resource.renderHTTP(context) | [
"def",
"renderHTTP",
"(",
"self",
",",
"context",
")",
":",
"request",
"=",
"IRequest",
"(",
"context",
")",
"request",
"=",
"StylesheetRewritingRequestWrapper",
"(",
"request",
",",
"self",
".",
"installedOfferingNames",
",",
"self",
".",
"rootURL",
")",
"con... | Render C{self.resource} through a L{StylesheetRewritingRequestWrapper}. | [
"Render",
"C",
"{",
"self",
".",
"resource",
"}",
"through",
"a",
"L",
"{",
"StylesheetRewritingRequestWrapper",
"}",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/website.py#L404-L412 |
twisted/mantissa | xmantissa/website.py | StylesheetRewritingRequestWrapper._replace | def _replace(self, url):
"""
Change URLs with absolute paths so they are rooted at the correct
location.
"""
segments = url.split('/')
if segments[0] == '':
root = self.rootURL(self.request)
if segments[1] == 'Mantissa':
root = root.child('static').child('mantissa-base')
segments = segments[2:]
elif segments[1] in self.installedOfferingNames:
root = root.child('static').child(segments[1])
segments = segments[2:]
for seg in segments:
root = root.child(seg)
return str(root)
return url | python | def _replace(self, url):
"""
Change URLs with absolute paths so they are rooted at the correct
location.
"""
segments = url.split('/')
if segments[0] == '':
root = self.rootURL(self.request)
if segments[1] == 'Mantissa':
root = root.child('static').child('mantissa-base')
segments = segments[2:]
elif segments[1] in self.installedOfferingNames:
root = root.child('static').child(segments[1])
segments = segments[2:]
for seg in segments:
root = root.child(seg)
return str(root)
return url | [
"def",
"_replace",
"(",
"self",
",",
"url",
")",
":",
"segments",
"=",
"url",
".",
"split",
"(",
"'/'",
")",
"if",
"segments",
"[",
"0",
"]",
"==",
"''",
":",
"root",
"=",
"self",
".",
"rootURL",
"(",
"self",
".",
"request",
")",
"if",
"segments"... | Change URLs with absolute paths so they are rooted at the correct
location. | [
"Change",
"URLs",
"with",
"absolute",
"paths",
"so",
"they",
"are",
"rooted",
"at",
"the",
"correct",
"location",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/website.py#L451-L468 |
twisted/mantissa | xmantissa/website.py | StylesheetRewritingRequestWrapper.finish | def finish(self):
"""
Parse the buffered response body, rewrite its URLs, write the result to
the wrapped request, and finish the wrapped request.
"""
stylesheet = ''.join(self._buffer)
parser = CSSParser()
css = parser.parseString(stylesheet)
replaceUrls(css, self._replace)
self.request.write(css.cssText)
return self.request.finish() | python | def finish(self):
"""
Parse the buffered response body, rewrite its URLs, write the result to
the wrapped request, and finish the wrapped request.
"""
stylesheet = ''.join(self._buffer)
parser = CSSParser()
css = parser.parseString(stylesheet)
replaceUrls(css, self._replace)
self.request.write(css.cssText)
return self.request.finish() | [
"def",
"finish",
"(",
"self",
")",
":",
"stylesheet",
"=",
"''",
".",
"join",
"(",
"self",
".",
"_buffer",
")",
"parser",
"=",
"CSSParser",
"(",
")",
"css",
"=",
"parser",
".",
"parseString",
"(",
"stylesheet",
")",
"replaceUrls",
"(",
"css",
",",
"s... | Parse the buffered response body, rewrite its URLs, write the result to
the wrapped request, and finish the wrapped request. | [
"Parse",
"the",
"buffered",
"response",
"body",
"rewrite",
"its",
"URLs",
"write",
"the",
"result",
"to",
"the",
"wrapped",
"request",
"and",
"finish",
"the",
"wrapped",
"request",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/website.py#L471-L481 |
twisted/mantissa | xmantissa/website.py | WebSite.cleartextRoot | def cleartextRoot(self, hostname=None):
"""
Return a string representing the HTTP URL which is at the root of this
site.
@param hostname: An optional unicode string which, if specified, will
be used as the hostname in the resulting URL, regardless of the
C{hostname} attribute of this item.
"""
warnings.warn(
"Use ISiteURLGenerator.rootURL instead of WebSite.cleartextRoot.",
category=DeprecationWarning,
stacklevel=2)
if self.store.parent is not None:
generator = ISiteURLGenerator(self.store.parent)
else:
generator = ISiteURLGenerator(self.store)
return generator.cleartextRoot(hostname) | python | def cleartextRoot(self, hostname=None):
"""
Return a string representing the HTTP URL which is at the root of this
site.
@param hostname: An optional unicode string which, if specified, will
be used as the hostname in the resulting URL, regardless of the
C{hostname} attribute of this item.
"""
warnings.warn(
"Use ISiteURLGenerator.rootURL instead of WebSite.cleartextRoot.",
category=DeprecationWarning,
stacklevel=2)
if self.store.parent is not None:
generator = ISiteURLGenerator(self.store.parent)
else:
generator = ISiteURLGenerator(self.store)
return generator.cleartextRoot(hostname) | [
"def",
"cleartextRoot",
"(",
"self",
",",
"hostname",
"=",
"None",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Use ISiteURLGenerator.rootURL instead of WebSite.cleartextRoot.\"",
",",
"category",
"=",
"DeprecationWarning",
",",
"stacklevel",
"=",
"2",
")",
"if",
"sel... | Return a string representing the HTTP URL which is at the root of this
site.
@param hostname: An optional unicode string which, if specified, will
be used as the hostname in the resulting URL, regardless of the
C{hostname} attribute of this item. | [
"Return",
"a",
"string",
"representing",
"the",
"HTTP",
"URL",
"which",
"is",
"at",
"the",
"root",
"of",
"this",
"site",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/website.py#L498-L515 |
twisted/mantissa | xmantissa/website.py | WebSite.rootURL | def rootURL(self, request):
"""
Simple utility function to provide a root URL for this website which is
appropriate to use in links generated in response to the given request.
@type request: L{twisted.web.http.Request}
@param request: The request which is being responded to.
@rtype: L{URL}
@return: The location at which the root of the resource hierarchy for
this website is available.
"""
warnings.warn(
"Use ISiteURLGenerator.rootURL instead of WebSite.rootURL.",
category=DeprecationWarning,
stacklevel=2)
if self.store.parent is not None:
generator = ISiteURLGenerator(self.store.parent)
else:
generator = ISiteURLGenerator(self.store)
return generator.rootURL(request) | python | def rootURL(self, request):
"""
Simple utility function to provide a root URL for this website which is
appropriate to use in links generated in response to the given request.
@type request: L{twisted.web.http.Request}
@param request: The request which is being responded to.
@rtype: L{URL}
@return: The location at which the root of the resource hierarchy for
this website is available.
"""
warnings.warn(
"Use ISiteURLGenerator.rootURL instead of WebSite.rootURL.",
category=DeprecationWarning,
stacklevel=2)
if self.store.parent is not None:
generator = ISiteURLGenerator(self.store.parent)
else:
generator = ISiteURLGenerator(self.store)
return generator.rootURL(request) | [
"def",
"rootURL",
"(",
"self",
",",
"request",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Use ISiteURLGenerator.rootURL instead of WebSite.rootURL.\"",
",",
"category",
"=",
"DeprecationWarning",
",",
"stacklevel",
"=",
"2",
")",
"if",
"self",
".",
"store",
".",
... | Simple utility function to provide a root URL for this website which is
appropriate to use in links generated in response to the given request.
@type request: L{twisted.web.http.Request}
@param request: The request which is being responded to.
@rtype: L{URL}
@return: The location at which the root of the resource hierarchy for
this website is available. | [
"Simple",
"utility",
"function",
"to",
"provide",
"a",
"root",
"URL",
"for",
"this",
"website",
"which",
"is",
"appropriate",
"to",
"use",
"in",
"links",
"generated",
"in",
"response",
"to",
"the",
"given",
"request",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/website.py#L562-L582 |
twisted/mantissa | xmantissa/website.py | WebSite.rootChild_resetPassword | def rootChild_resetPassword(self, req, webViewer):
"""
Redirect authenticated users to their settings page (hopefully they
have one) when they try to reset their password.
This is the wrong way for this functionality to be implemented. See
#2524.
"""
from xmantissa.ixmantissa import IWebTranslator, IPreferenceAggregator
return URL.fromString(
IWebTranslator(self.store).linkTo(
IPreferenceAggregator(self.store).storeID)) | python | def rootChild_resetPassword(self, req, webViewer):
"""
Redirect authenticated users to their settings page (hopefully they
have one) when they try to reset their password.
This is the wrong way for this functionality to be implemented. See
#2524.
"""
from xmantissa.ixmantissa import IWebTranslator, IPreferenceAggregator
return URL.fromString(
IWebTranslator(self.store).linkTo(
IPreferenceAggregator(self.store).storeID)) | [
"def",
"rootChild_resetPassword",
"(",
"self",
",",
"req",
",",
"webViewer",
")",
":",
"from",
"xmantissa",
".",
"ixmantissa",
"import",
"IWebTranslator",
",",
"IPreferenceAggregator",
"return",
"URL",
".",
"fromString",
"(",
"IWebTranslator",
"(",
"self",
".",
... | Redirect authenticated users to their settings page (hopefully they
have one) when they try to reset their password.
This is the wrong way for this functionality to be implemented. See
#2524. | [
"Redirect",
"authenticated",
"users",
"to",
"their",
"settings",
"page",
"(",
"hopefully",
"they",
"have",
"one",
")",
"when",
"they",
"try",
"to",
"reset",
"their",
"password",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/website.py#L585-L596 |
twisted/mantissa | xmantissa/website.py | APIKey.getKeyForAPI | def getKeyForAPI(cls, siteStore, apiName):
"""
Get the API key for the named API, if one exists.
@param siteStore: The site store.
@type siteStore: L{axiom.store.Store}
@param apiName: The name of the API.
@type apiName: C{unicode} (L{APIKey} constant)
@rtype: L{APIKey} or C{NoneType}
"""
return siteStore.findUnique(
cls, cls.apiName == apiName, default=None) | python | def getKeyForAPI(cls, siteStore, apiName):
"""
Get the API key for the named API, if one exists.
@param siteStore: The site store.
@type siteStore: L{axiom.store.Store}
@param apiName: The name of the API.
@type apiName: C{unicode} (L{APIKey} constant)
@rtype: L{APIKey} or C{NoneType}
"""
return siteStore.findUnique(
cls, cls.apiName == apiName, default=None) | [
"def",
"getKeyForAPI",
"(",
"cls",
",",
"siteStore",
",",
"apiName",
")",
":",
"return",
"siteStore",
".",
"findUnique",
"(",
"cls",
",",
"cls",
".",
"apiName",
"==",
"apiName",
",",
"default",
"=",
"None",
")"
] | Get the API key for the named API, if one exists.
@param siteStore: The site store.
@type siteStore: L{axiom.store.Store}
@param apiName: The name of the API.
@type apiName: C{unicode} (L{APIKey} constant)
@rtype: L{APIKey} or C{NoneType} | [
"Get",
"the",
"API",
"key",
"for",
"the",
"named",
"API",
"if",
"one",
"exists",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/website.py#L646-L659 |
twisted/mantissa | xmantissa/website.py | APIKey.setKeyForAPI | def setKeyForAPI(cls, siteStore, apiName, apiKey):
"""
Set the API key for the named API, overwriting any existing key.
@param siteStore: The site store to install the key in.
@type siteStore: L{axiom.store.Store}
@param apiName: The name of the API.
@type apiName: C{unicode} (L{APIKey} constant)
@param apiKey: The key for accessing the API.
@type apiKey: C{unicode}
@rtype: L{APIKey}
"""
existingKey = cls.getKeyForAPI(siteStore, apiName)
if existingKey is None:
return cls(store=siteStore, apiName=apiName, apiKey=apiKey)
existingKey.apiKey = apiKey
return existingKey | python | def setKeyForAPI(cls, siteStore, apiName, apiKey):
"""
Set the API key for the named API, overwriting any existing key.
@param siteStore: The site store to install the key in.
@type siteStore: L{axiom.store.Store}
@param apiName: The name of the API.
@type apiName: C{unicode} (L{APIKey} constant)
@param apiKey: The key for accessing the API.
@type apiKey: C{unicode}
@rtype: L{APIKey}
"""
existingKey = cls.getKeyForAPI(siteStore, apiName)
if existingKey is None:
return cls(store=siteStore, apiName=apiName, apiKey=apiKey)
existingKey.apiKey = apiKey
return existingKey | [
"def",
"setKeyForAPI",
"(",
"cls",
",",
"siteStore",
",",
"apiName",
",",
"apiKey",
")",
":",
"existingKey",
"=",
"cls",
".",
"getKeyForAPI",
"(",
"siteStore",
",",
"apiName",
")",
"if",
"existingKey",
"is",
"None",
":",
"return",
"cls",
"(",
"store",
"=... | Set the API key for the named API, overwriting any existing key.
@param siteStore: The site store to install the key in.
@type siteStore: L{axiom.store.Store}
@param apiName: The name of the API.
@type apiName: C{unicode} (L{APIKey} constant)
@param apiKey: The key for accessing the API.
@type apiKey: C{unicode}
@rtype: L{APIKey} | [
"Set",
"the",
"API",
"key",
"for",
"the",
"named",
"API",
"overwriting",
"any",
"existing",
"key",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/website.py#L663-L682 |
twisted/mantissa | xmantissa/web.py | SiteConfiguration.rootURL | def rootURL(self, request):
"""
Return the URL for the root of this website which is appropriate to use
in links generated in response to the given request.
@type request: L{twisted.web.http.Request}
@param request: The request which is being responded to.
@rtype: L{URL}
@return: The location at which the root of the resource hierarchy for
this website is available.
"""
host = request.getHeader('host') or self.hostname
if ':' in host:
host = host.split(':', 1)[0]
for domain in [self.hostname] + getDomainNames(self.store):
if (host == domain or
host.startswith('www.') and host[len('www.'):] == domain):
return URL(scheme='', netloc='', pathsegs=[''])
if request.isSecure():
return self.encryptedRoot(self.hostname)
else:
return self.cleartextRoot(self.hostname) | python | def rootURL(self, request):
"""
Return the URL for the root of this website which is appropriate to use
in links generated in response to the given request.
@type request: L{twisted.web.http.Request}
@param request: The request which is being responded to.
@rtype: L{URL}
@return: The location at which the root of the resource hierarchy for
this website is available.
"""
host = request.getHeader('host') or self.hostname
if ':' in host:
host = host.split(':', 1)[0]
for domain in [self.hostname] + getDomainNames(self.store):
if (host == domain or
host.startswith('www.') and host[len('www.'):] == domain):
return URL(scheme='', netloc='', pathsegs=[''])
if request.isSecure():
return self.encryptedRoot(self.hostname)
else:
return self.cleartextRoot(self.hostname) | [
"def",
"rootURL",
"(",
"self",
",",
"request",
")",
":",
"host",
"=",
"request",
".",
"getHeader",
"(",
"'host'",
")",
"or",
"self",
".",
"hostname",
"if",
"':'",
"in",
"host",
":",
"host",
"=",
"host",
".",
"split",
"(",
"':'",
",",
"1",
")",
"[... | Return the URL for the root of this website which is appropriate to use
in links generated in response to the given request.
@type request: L{twisted.web.http.Request}
@param request: The request which is being responded to.
@rtype: L{URL}
@return: The location at which the root of the resource hierarchy for
this website is available. | [
"Return",
"the",
"URL",
"for",
"the",
"root",
"of",
"this",
"website",
"which",
"is",
"appropriate",
"to",
"use",
"in",
"links",
"generated",
"in",
"response",
"to",
"the",
"given",
"request",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/web.py#L138-L160 |
twisted/mantissa | xmantissa/web.py | SiteConfiguration.getFactory | def getFactory(self):
"""
Create an L{AxiomSite} which supports authenticated and anonymous
access.
"""
checkers = [self.loginSystem, AllowAnonymousAccess()]
guardedRoot = PersistentSessionWrapper(
self.store,
Portal(self.loginSystem, checkers),
domains=[self.hostname])
unguardedRoot = UnguardedWrapper(self.store, guardedRoot)
securingRoot = SecuringWrapper(self, unguardedRoot)
logPath = None
if self.httpLog is not None:
logPath = self.httpLog.path
return AxiomSite(self.store, securingRoot, logPath=logPath) | python | def getFactory(self):
"""
Create an L{AxiomSite} which supports authenticated and anonymous
access.
"""
checkers = [self.loginSystem, AllowAnonymousAccess()]
guardedRoot = PersistentSessionWrapper(
self.store,
Portal(self.loginSystem, checkers),
domains=[self.hostname])
unguardedRoot = UnguardedWrapper(self.store, guardedRoot)
securingRoot = SecuringWrapper(self, unguardedRoot)
logPath = None
if self.httpLog is not None:
logPath = self.httpLog.path
return AxiomSite(self.store, securingRoot, logPath=logPath) | [
"def",
"getFactory",
"(",
"self",
")",
":",
"checkers",
"=",
"[",
"self",
".",
"loginSystem",
",",
"AllowAnonymousAccess",
"(",
")",
"]",
"guardedRoot",
"=",
"PersistentSessionWrapper",
"(",
"self",
".",
"store",
",",
"Portal",
"(",
"self",
".",
"loginSystem... | Create an L{AxiomSite} which supports authenticated and anonymous
access. | [
"Create",
"an",
"L",
"{",
"AxiomSite",
"}",
"which",
"supports",
"authenticated",
"and",
"anonymous",
"access",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/web.py#L163-L178 |
twisted/mantissa | xmantissa/web.py | UnguardedWrapper.child_static | def child_static(self, context):
"""
Serve a container page for static content for Mantissa and other
offerings.
"""
offeringTech = IOfferingTechnician(self.siteStore)
installedOfferings = offeringTech.getInstalledOfferings()
offeringsWithContent = dict([
(offering.name, offering.staticContentPath)
for offering
in installedOfferings.itervalues()
if offering.staticContentPath])
# If you wanted to do CSS rewriting for all CSS files served beneath
# /static/, you could do it by passing a processor for ".css" here.
# eg:
#
# website = IResource(self.store)
# factory = StylesheetFactory(
# offeringsWithContent.keys(), website.rootURL)
# StaticContent(offeringsWithContent, {
# ".css": factory.makeStylesheetResource})
return StaticContent(offeringsWithContent, {}) | python | def child_static(self, context):
"""
Serve a container page for static content for Mantissa and other
offerings.
"""
offeringTech = IOfferingTechnician(self.siteStore)
installedOfferings = offeringTech.getInstalledOfferings()
offeringsWithContent = dict([
(offering.name, offering.staticContentPath)
for offering
in installedOfferings.itervalues()
if offering.staticContentPath])
# If you wanted to do CSS rewriting for all CSS files served beneath
# /static/, you could do it by passing a processor for ".css" here.
# eg:
#
# website = IResource(self.store)
# factory = StylesheetFactory(
# offeringsWithContent.keys(), website.rootURL)
# StaticContent(offeringsWithContent, {
# ".css": factory.makeStylesheetResource})
return StaticContent(offeringsWithContent, {}) | [
"def",
"child_static",
"(",
"self",
",",
"context",
")",
":",
"offeringTech",
"=",
"IOfferingTechnician",
"(",
"self",
".",
"siteStore",
")",
"installedOfferings",
"=",
"offeringTech",
".",
"getInstalledOfferings",
"(",
")",
"offeringsWithContent",
"=",
"dict",
"(... | Serve a container page for static content for Mantissa and other
offerings. | [
"Serve",
"a",
"container",
"page",
"for",
"static",
"content",
"for",
"Mantissa",
"and",
"other",
"offerings",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/web.py#L235-L257 |
twisted/mantissa | xmantissa/web.py | UnguardedWrapper.locateChild | def locateChild(self, context, segments):
"""
Return a statically defined child or a child defined by a sessionless
site root plugin or an avatar from guard.
"""
shortcut = getattr(self, 'child_' + segments[0], None)
if shortcut:
res = shortcut(context)
if res is not None:
return res, segments[1:]
req = IRequest(context)
for plg in self.siteStore.powerupsFor(ISessionlessSiteRootPlugin):
spr = getattr(plg, 'sessionlessProduceResource', None)
if spr is not None:
childAndSegments = spr(req, segments)
else:
childAndSegments = plg.resourceFactory(segments)
if childAndSegments is not None:
return childAndSegments
return self.guardedRoot.locateChild(context, segments) | python | def locateChild(self, context, segments):
"""
Return a statically defined child or a child defined by a sessionless
site root plugin or an avatar from guard.
"""
shortcut = getattr(self, 'child_' + segments[0], None)
if shortcut:
res = shortcut(context)
if res is not None:
return res, segments[1:]
req = IRequest(context)
for plg in self.siteStore.powerupsFor(ISessionlessSiteRootPlugin):
spr = getattr(plg, 'sessionlessProduceResource', None)
if spr is not None:
childAndSegments = spr(req, segments)
else:
childAndSegments = plg.resourceFactory(segments)
if childAndSegments is not None:
return childAndSegments
return self.guardedRoot.locateChild(context, segments) | [
"def",
"locateChild",
"(",
"self",
",",
"context",
",",
"segments",
")",
":",
"shortcut",
"=",
"getattr",
"(",
"self",
",",
"'child_'",
"+",
"segments",
"[",
"0",
"]",
",",
"None",
")",
"if",
"shortcut",
":",
"res",
"=",
"shortcut",
"(",
"context",
"... | Return a statically defined child or a child defined by a sessionless
site root plugin or an avatar from guard. | [
"Return",
"a",
"statically",
"defined",
"child",
"or",
"a",
"child",
"defined",
"by",
"a",
"sessionless",
"site",
"root",
"plugin",
"or",
"an",
"avatar",
"from",
"guard",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/web.py#L260-L281 |
twisted/mantissa | xmantissa/web.py | SecuringWrapper.locateChild | def locateChild(self, context, segments):
"""
Unwrap the wrapped resource if HTTPS is already being used, otherwise
wrap it in a helper which will preserve the wrapping all the way down
to the final resource.
"""
request = IRequest(context)
if request.isSecure():
return self.wrappedResource, segments
return _SecureWrapper(self.urlGenerator, self.wrappedResource), segments | python | def locateChild(self, context, segments):
"""
Unwrap the wrapped resource if HTTPS is already being used, otherwise
wrap it in a helper which will preserve the wrapping all the way down
to the final resource.
"""
request = IRequest(context)
if request.isSecure():
return self.wrappedResource, segments
return _SecureWrapper(self.urlGenerator, self.wrappedResource), segments | [
"def",
"locateChild",
"(",
"self",
",",
"context",
",",
"segments",
")",
":",
"request",
"=",
"IRequest",
"(",
"context",
")",
"if",
"request",
".",
"isSecure",
"(",
")",
":",
"return",
"self",
".",
"wrappedResource",
",",
"segments",
"return",
"_SecureWra... | Unwrap the wrapped resource if HTTPS is already being used, otherwise
wrap it in a helper which will preserve the wrapping all the way down
to the final resource. | [
"Unwrap",
"the",
"wrapped",
"resource",
"if",
"HTTPS",
"is",
"already",
"being",
"used",
"otherwise",
"wrap",
"it",
"in",
"a",
"helper",
"which",
"will",
"preserve",
"the",
"wrapping",
"all",
"the",
"way",
"down",
"to",
"the",
"final",
"resource",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/web.py#L302-L311 |
twisted/mantissa | xmantissa/web.py | SecuringWrapper.renderHTTP | def renderHTTP(self, context):
"""
Render the wrapped resource if HTTPS is already being used, otherwise
invoke a helper which may generate a redirect.
"""
request = IRequest(context)
if request.isSecure():
renderer = self.wrappedResource
else:
renderer = _SecureWrapper(self.urlGenerator, self.wrappedResource)
return renderer.renderHTTP(context) | python | def renderHTTP(self, context):
"""
Render the wrapped resource if HTTPS is already being used, otherwise
invoke a helper which may generate a redirect.
"""
request = IRequest(context)
if request.isSecure():
renderer = self.wrappedResource
else:
renderer = _SecureWrapper(self.urlGenerator, self.wrappedResource)
return renderer.renderHTTP(context) | [
"def",
"renderHTTP",
"(",
"self",
",",
"context",
")",
":",
"request",
"=",
"IRequest",
"(",
"context",
")",
"if",
"request",
".",
"isSecure",
"(",
")",
":",
"renderer",
"=",
"self",
".",
"wrappedResource",
"else",
":",
"renderer",
"=",
"_SecureWrapper",
... | Render the wrapped resource if HTTPS is already being used, otherwise
invoke a helper which may generate a redirect. | [
"Render",
"the",
"wrapped",
"resource",
"if",
"HTTPS",
"is",
"already",
"being",
"used",
"otherwise",
"invoke",
"a",
"helper",
"which",
"may",
"generate",
"a",
"redirect",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/web.py#L314-L324 |
twisted/mantissa | xmantissa/web.py | _SecureWrapper.locateChild | def locateChild(self, context, segments):
"""
Delegate child lookup to the wrapped resource but wrap whatever results
in another instance of this wrapper.
"""
childDeferred = maybeDeferred(
self.wrappedResource.locateChild, context, segments)
def childLocated((resource, segments)):
if (resource, segments) == NotFound:
return NotFound
return _SecureWrapper(self.urlGenerator, resource), segments
childDeferred.addCallback(childLocated)
return childDeferred | python | def locateChild(self, context, segments):
"""
Delegate child lookup to the wrapped resource but wrap whatever results
in another instance of this wrapper.
"""
childDeferred = maybeDeferred(
self.wrappedResource.locateChild, context, segments)
def childLocated((resource, segments)):
if (resource, segments) == NotFound:
return NotFound
return _SecureWrapper(self.urlGenerator, resource), segments
childDeferred.addCallback(childLocated)
return childDeferred | [
"def",
"locateChild",
"(",
"self",
",",
"context",
",",
"segments",
")",
":",
"childDeferred",
"=",
"maybeDeferred",
"(",
"self",
".",
"wrappedResource",
".",
"locateChild",
",",
"context",
",",
"segments",
")",
"def",
"childLocated",
"(",
"(",
"resource",
"... | Delegate child lookup to the wrapped resource but wrap whatever results
in another instance of this wrapper. | [
"Delegate",
"child",
"lookup",
"to",
"the",
"wrapped",
"resource",
"but",
"wrap",
"whatever",
"results",
"in",
"another",
"instance",
"of",
"this",
"wrapper",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/web.py#L345-L357 |
twisted/mantissa | xmantissa/web.py | _SecureWrapper.renderHTTP | def renderHTTP(self, context):
"""
Check to see if the wrapped resource wants to be rendered over HTTPS
and generate a redirect if this is so, if HTTPS is available, and if
the request is not already over HTTPS.
"""
if getattr(self.wrappedResource, 'needsSecure', False):
request = IRequest(context)
url = self.urlGenerator.encryptedRoot()
if url is not None:
for seg in request.prepath:
url = url.child(seg)
return url
return self.wrappedResource.renderHTTP(context) | python | def renderHTTP(self, context):
"""
Check to see if the wrapped resource wants to be rendered over HTTPS
and generate a redirect if this is so, if HTTPS is available, and if
the request is not already over HTTPS.
"""
if getattr(self.wrappedResource, 'needsSecure', False):
request = IRequest(context)
url = self.urlGenerator.encryptedRoot()
if url is not None:
for seg in request.prepath:
url = url.child(seg)
return url
return self.wrappedResource.renderHTTP(context) | [
"def",
"renderHTTP",
"(",
"self",
",",
"context",
")",
":",
"if",
"getattr",
"(",
"self",
".",
"wrappedResource",
",",
"'needsSecure'",
",",
"False",
")",
":",
"request",
"=",
"IRequest",
"(",
"context",
")",
"url",
"=",
"self",
".",
"urlGenerator",
".",... | Check to see if the wrapped resource wants to be rendered over HTTPS
and generate a redirect if this is so, if HTTPS is available, and if
the request is not already over HTTPS. | [
"Check",
"to",
"see",
"if",
"the",
"wrapped",
"resource",
"wants",
"to",
"be",
"rendered",
"over",
"HTTPS",
"and",
"generate",
"a",
"redirect",
"if",
"this",
"is",
"so",
"if",
"HTTPS",
"is",
"available",
"and",
"if",
"the",
"request",
"is",
"not",
"alrea... | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/web.py#L360-L373 |
twisted/mantissa | xmantissa/web.py | StaticContent.locateChild | def locateChild(self, context, segments):
"""
Find the offering with the name matching the first segment and return a
L{File} for its I{staticContentPath}.
"""
name = segments[0]
try:
staticContent = self.staticPaths[name]
except KeyError:
return NotFound
else:
resource = File(staticContent.path)
resource.processors = self.processors
return resource, segments[1:]
return NotFound | python | def locateChild(self, context, segments):
"""
Find the offering with the name matching the first segment and return a
L{File} for its I{staticContentPath}.
"""
name = segments[0]
try:
staticContent = self.staticPaths[name]
except KeyError:
return NotFound
else:
resource = File(staticContent.path)
resource.processors = self.processors
return resource, segments[1:]
return NotFound | [
"def",
"locateChild",
"(",
"self",
",",
"context",
",",
"segments",
")",
":",
"name",
"=",
"segments",
"[",
"0",
"]",
"try",
":",
"staticContent",
"=",
"self",
".",
"staticPaths",
"[",
"name",
"]",
"except",
"KeyError",
":",
"return",
"NotFound",
"else",... | Find the offering with the name matching the first segment and return a
L{File} for its I{staticContentPath}. | [
"Find",
"the",
"offering",
"with",
"the",
"name",
"matching",
"the",
"first",
"segment",
"and",
"return",
"a",
"L",
"{",
"File",
"}",
"for",
"its",
"I",
"{",
"staticContentPath",
"}",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/web.py#L394-L408 |
vladcalin/gemstone | gemstone/client/remote_service.py | RemoteService.handle_single_request | def handle_single_request(self, request_object):
"""
Handles a single request object and returns the raw response
:param request_object:
"""
if not isinstance(request_object, (MethodCall, Notification)):
raise TypeError("Invalid type for request_object")
method_name = request_object.method_name
params = request_object.params
req_id = request_object.id
request_body = self.build_request_body(method_name, params, id=req_id)
http_request = self.build_http_request_obj(request_body)
try:
response = urllib.request.urlopen(http_request)
except urllib.request.HTTPError as e:
raise CalledServiceError(e)
if not req_id:
return
response_body = json.loads(response.read().decode())
return response_body | python | def handle_single_request(self, request_object):
"""
Handles a single request object and returns the raw response
:param request_object:
"""
if not isinstance(request_object, (MethodCall, Notification)):
raise TypeError("Invalid type for request_object")
method_name = request_object.method_name
params = request_object.params
req_id = request_object.id
request_body = self.build_request_body(method_name, params, id=req_id)
http_request = self.build_http_request_obj(request_body)
try:
response = urllib.request.urlopen(http_request)
except urllib.request.HTTPError as e:
raise CalledServiceError(e)
if not req_id:
return
response_body = json.loads(response.read().decode())
return response_body | [
"def",
"handle_single_request",
"(",
"self",
",",
"request_object",
")",
":",
"if",
"not",
"isinstance",
"(",
"request_object",
",",
"(",
"MethodCall",
",",
"Notification",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"Invalid type for request_object\"",
")",
"meth... | Handles a single request object and returns the raw response
:param request_object: | [
"Handles",
"a",
"single",
"request",
"object",
"and",
"returns",
"the",
"raw",
"response"
] | train | https://github.com/vladcalin/gemstone/blob/325a49d17621b9d45ffd2b5eca6f0de284de8ba4/gemstone/client/remote_service.py#L30-L55 |
vladcalin/gemstone | gemstone/client/remote_service.py | RemoteService.call_method | def call_method(self, method_name_or_object, params=None):
"""
Calls the ``method_name`` method from the given service and returns a
:py:class:`gemstone.client.structs.Result` instance.
:param method_name_or_object: The name of te called method or a ``MethodCall`` instance
:param params: A list of dict representing the parameters for the request
:return: a :py:class:`gemstone.client.structs.Result` instance.
"""
if isinstance(method_name_or_object, MethodCall):
req_obj = method_name_or_object
else:
req_obj = MethodCall(method_name_or_object, params)
raw_response = self.handle_single_request(req_obj)
response_obj = Result(result=raw_response["result"], error=raw_response['error'],
id=raw_response["id"], method_call=req_obj)
return response_obj | python | def call_method(self, method_name_or_object, params=None):
"""
Calls the ``method_name`` method from the given service and returns a
:py:class:`gemstone.client.structs.Result` instance.
:param method_name_or_object: The name of te called method or a ``MethodCall`` instance
:param params: A list of dict representing the parameters for the request
:return: a :py:class:`gemstone.client.structs.Result` instance.
"""
if isinstance(method_name_or_object, MethodCall):
req_obj = method_name_or_object
else:
req_obj = MethodCall(method_name_or_object, params)
raw_response = self.handle_single_request(req_obj)
response_obj = Result(result=raw_response["result"], error=raw_response['error'],
id=raw_response["id"], method_call=req_obj)
return response_obj | [
"def",
"call_method",
"(",
"self",
",",
"method_name_or_object",
",",
"params",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"method_name_or_object",
",",
"MethodCall",
")",
":",
"req_obj",
"=",
"method_name_or_object",
"else",
":",
"req_obj",
"=",
"MethodCal... | Calls the ``method_name`` method from the given service and returns a
:py:class:`gemstone.client.structs.Result` instance.
:param method_name_or_object: The name of te called method or a ``MethodCall`` instance
:param params: A list of dict representing the parameters for the request
:return: a :py:class:`gemstone.client.structs.Result` instance. | [
"Calls",
"the",
"method_name",
"method",
"from",
"the",
"given",
"service",
"and",
"returns",
"a",
":",
"py",
":",
"class",
":",
"gemstone",
".",
"client",
".",
"structs",
".",
"Result",
"instance",
"."
] | train | https://github.com/vladcalin/gemstone/blob/325a49d17621b9d45ffd2b5eca6f0de284de8ba4/gemstone/client/remote_service.py#L76-L92 |
vladcalin/gemstone | gemstone/client/remote_service.py | RemoteService.call_method_async | def call_method_async(self, method_name_or_object, params=None):
"""
Calls the ``method_name`` method from the given service asynchronously
and returns a :py:class:`gemstone.client.structs.AsyncMethodCall` instance.
:param method_name_or_object: The name of te called method or a ``MethodCall`` instance
:param params: A list of dict representing the parameters for the request
:return: a :py:class:`gemstone.client.structs.AsyncMethodCall` instance.
"""
thread_pool = self._get_thread_pool()
if isinstance(method_name_or_object, MethodCall):
req_obj = method_name_or_object
else:
req_obj = MethodCall(method_name_or_object, params)
async_result_mp = thread_pool.apply_async(self.handle_single_request, args=(req_obj,))
return AsyncMethodCall(req_obj=req_obj, async_resp_object=async_result_mp) | python | def call_method_async(self, method_name_or_object, params=None):
"""
Calls the ``method_name`` method from the given service asynchronously
and returns a :py:class:`gemstone.client.structs.AsyncMethodCall` instance.
:param method_name_or_object: The name of te called method or a ``MethodCall`` instance
:param params: A list of dict representing the parameters for the request
:return: a :py:class:`gemstone.client.structs.AsyncMethodCall` instance.
"""
thread_pool = self._get_thread_pool()
if isinstance(method_name_or_object, MethodCall):
req_obj = method_name_or_object
else:
req_obj = MethodCall(method_name_or_object, params)
async_result_mp = thread_pool.apply_async(self.handle_single_request, args=(req_obj,))
return AsyncMethodCall(req_obj=req_obj, async_resp_object=async_result_mp) | [
"def",
"call_method_async",
"(",
"self",
",",
"method_name_or_object",
",",
"params",
"=",
"None",
")",
":",
"thread_pool",
"=",
"self",
".",
"_get_thread_pool",
"(",
")",
"if",
"isinstance",
"(",
"method_name_or_object",
",",
"MethodCall",
")",
":",
"req_obj",
... | Calls the ``method_name`` method from the given service asynchronously
and returns a :py:class:`gemstone.client.structs.AsyncMethodCall` instance.
:param method_name_or_object: The name of te called method or a ``MethodCall`` instance
:param params: A list of dict representing the parameters for the request
:return: a :py:class:`gemstone.client.structs.AsyncMethodCall` instance. | [
"Calls",
"the",
"method_name",
"method",
"from",
"the",
"given",
"service",
"asynchronously",
"and",
"returns",
"a",
":",
"py",
":",
"class",
":",
"gemstone",
".",
"client",
".",
"structs",
".",
"AsyncMethodCall",
"instance",
"."
] | train | https://github.com/vladcalin/gemstone/blob/325a49d17621b9d45ffd2b5eca6f0de284de8ba4/gemstone/client/remote_service.py#L94-L111 |
vladcalin/gemstone | gemstone/client/remote_service.py | RemoteService.notify | def notify(self, method_name_or_object, params=None):
"""
Sends a notification to the service by calling the ``method_name``
method with the ``params`` parameters. Does not wait for a response, even
if the response triggers an error.
:param method_name_or_object: the name of the method to be called or a ``Notification``
instance
:param params: a list of dict representing the parameters for the call
:return: None
"""
if isinstance(method_name_or_object, Notification):
req_obj = method_name_or_object
else:
req_obj = Notification(method_name_or_object, params)
self.handle_single_request(req_obj) | python | def notify(self, method_name_or_object, params=None):
"""
Sends a notification to the service by calling the ``method_name``
method with the ``params`` parameters. Does not wait for a response, even
if the response triggers an error.
:param method_name_or_object: the name of the method to be called or a ``Notification``
instance
:param params: a list of dict representing the parameters for the call
:return: None
"""
if isinstance(method_name_or_object, Notification):
req_obj = method_name_or_object
else:
req_obj = Notification(method_name_or_object, params)
self.handle_single_request(req_obj) | [
"def",
"notify",
"(",
"self",
",",
"method_name_or_object",
",",
"params",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"method_name_or_object",
",",
"Notification",
")",
":",
"req_obj",
"=",
"method_name_or_object",
"else",
":",
"req_obj",
"=",
"Notification... | Sends a notification to the service by calling the ``method_name``
method with the ``params`` parameters. Does not wait for a response, even
if the response triggers an error.
:param method_name_or_object: the name of the method to be called or a ``Notification``
instance
:param params: a list of dict representing the parameters for the call
:return: None | [
"Sends",
"a",
"notification",
"to",
"the",
"service",
"by",
"calling",
"the",
"method_name",
"method",
"with",
"the",
"params",
"parameters",
".",
"Does",
"not",
"wait",
"for",
"a",
"response",
"even",
"if",
"the",
"response",
"triggers",
"an",
"error",
"."
... | train | https://github.com/vladcalin/gemstone/blob/325a49d17621b9d45ffd2b5eca6f0de284de8ba4/gemstone/client/remote_service.py#L113-L128 |
vladcalin/gemstone | gemstone/core/handlers.py | TornadoJsonRpcHandler.handle_single_request | def handle_single_request(self, request_object):
"""
Handles a single request object and returns the correct result as follows:
- A valid response object if it is a regular request (with ID)
- ``None`` if it was a notification (if None is returned, a response object with
"received" body was already sent to the client.
:param request_object: A :py:class:`gemstone.core.structs.JsonRpcRequest` object
representing a Request object
:return: A :py:class:`gemstone.core.structs.JsonRpcResponse` object representing a
Response object or None if no response is expected (it was a notification)
"""
# don't handle responses?
if isinstance(request_object, JsonRpcResponse):
return request_object
error = None
result = None
id_ = request_object.id
# validate method name
if request_object.method not in self.methods:
resp = GenericResponse.METHOD_NOT_FOUND
resp.id = id_
return resp
# check for private access
method = self.methods[request_object.method]
if isinstance(request_object.params, (list, tuple)):
self.call_method_from_all_plugins("on_method_call", request_object)
else:
self.call_method_from_all_plugins("on_method_call", request_object)
if self._method_is_private(method):
if not self.get_current_user():
resp = GenericResponse.ACCESS_DENIED
resp.id = id_
return resp
method = self.prepare_method_call(method, request_object.params)
# before request hook
_method_duration = time.time()
try:
result = yield self.call_method(method)
except Exception as e:
# catch all exceptions generated by method
# and handle in a special manner only the TypeError
if isinstance(e, TypeError):
# TODO: find a proper way to check that the function got the wrong
# parameters (with **kwargs)
if "got an unexpected keyword argument" in e.args[0]:
resp = GenericResponse.INVALID_PARAMS
resp.id = id_
return resp
# TODO: find a proper way to check that the function got the wrong
# parameters (with *args)
elif "takes" in e.args[0] and "positional argument" in e.args[0] and "were given" in \
e.args[0]:
resp = GenericResponse.INVALID_PARAMS
resp.id = id_
return resp
elif "missing" in e.args[0] and "required positional argument" in e.args[0]:
resp = GenericResponse.INVALID_PARAMS
resp.id = id_
return resp
# generic handling for any exception (even TypeError) that
# is not generated because of bad parameters
self.call_method_from_all_plugins("on_internal_error", e)
err = GenericResponse.INTERNAL_ERROR
err.id = id_
err.error["data"] = {
"class": type(e).__name__,
"info": str(e)
}
return err
to_return_resp = JsonRpcResponse(result=result, error=error, id=id_)
return to_return_resp | python | def handle_single_request(self, request_object):
"""
Handles a single request object and returns the correct result as follows:
- A valid response object if it is a regular request (with ID)
- ``None`` if it was a notification (if None is returned, a response object with
"received" body was already sent to the client.
:param request_object: A :py:class:`gemstone.core.structs.JsonRpcRequest` object
representing a Request object
:return: A :py:class:`gemstone.core.structs.JsonRpcResponse` object representing a
Response object or None if no response is expected (it was a notification)
"""
# don't handle responses?
if isinstance(request_object, JsonRpcResponse):
return request_object
error = None
result = None
id_ = request_object.id
# validate method name
if request_object.method not in self.methods:
resp = GenericResponse.METHOD_NOT_FOUND
resp.id = id_
return resp
# check for private access
method = self.methods[request_object.method]
if isinstance(request_object.params, (list, tuple)):
self.call_method_from_all_plugins("on_method_call", request_object)
else:
self.call_method_from_all_plugins("on_method_call", request_object)
if self._method_is_private(method):
if not self.get_current_user():
resp = GenericResponse.ACCESS_DENIED
resp.id = id_
return resp
method = self.prepare_method_call(method, request_object.params)
# before request hook
_method_duration = time.time()
try:
result = yield self.call_method(method)
except Exception as e:
# catch all exceptions generated by method
# and handle in a special manner only the TypeError
if isinstance(e, TypeError):
# TODO: find a proper way to check that the function got the wrong
# parameters (with **kwargs)
if "got an unexpected keyword argument" in e.args[0]:
resp = GenericResponse.INVALID_PARAMS
resp.id = id_
return resp
# TODO: find a proper way to check that the function got the wrong
# parameters (with *args)
elif "takes" in e.args[0] and "positional argument" in e.args[0] and "were given" in \
e.args[0]:
resp = GenericResponse.INVALID_PARAMS
resp.id = id_
return resp
elif "missing" in e.args[0] and "required positional argument" in e.args[0]:
resp = GenericResponse.INVALID_PARAMS
resp.id = id_
return resp
# generic handling for any exception (even TypeError) that
# is not generated because of bad parameters
self.call_method_from_all_plugins("on_internal_error", e)
err = GenericResponse.INTERNAL_ERROR
err.id = id_
err.error["data"] = {
"class": type(e).__name__,
"info": str(e)
}
return err
to_return_resp = JsonRpcResponse(result=result, error=error, id=id_)
return to_return_resp | [
"def",
"handle_single_request",
"(",
"self",
",",
"request_object",
")",
":",
"# don't handle responses?",
"if",
"isinstance",
"(",
"request_object",
",",
"JsonRpcResponse",
")",
":",
"return",
"request_object",
"error",
"=",
"None",
"result",
"=",
"None",
"id_",
... | Handles a single request object and returns the correct result as follows:
- A valid response object if it is a regular request (with ID)
- ``None`` if it was a notification (if None is returned, a response object with
"received" body was already sent to the client.
:param request_object: A :py:class:`gemstone.core.structs.JsonRpcRequest` object
representing a Request object
:return: A :py:class:`gemstone.core.structs.JsonRpcResponse` object representing a
Response object or None if no response is expected (it was a notification) | [
"Handles",
"a",
"single",
"request",
"object",
"and",
"returns",
"the",
"correct",
"result",
"as",
"follows",
":"
] | train | https://github.com/vladcalin/gemstone/blob/325a49d17621b9d45ffd2b5eca6f0de284de8ba4/gemstone/core/handlers.py#L119-L204 |
vladcalin/gemstone | gemstone/core/handlers.py | TornadoJsonRpcHandler.write_single_response | def write_single_response(self, response_obj):
"""
Writes a json rpc response ``{"result": result, "error": error, "id": id}``.
If the ``id`` is ``None``, the response will not contain an ``id`` field.
The response is sent to the client as an ``application/json`` response. Only one call per
response is allowed
:param response_obj: A Json rpc response object
:return:
"""
if not isinstance(response_obj, JsonRpcResponse):
raise ValueError(
"Expected JsonRpcResponse, but got {} instead".format(type(response_obj).__name__))
if not self.response_is_sent:
self.set_status(200)
self.set_header("Content-Type", "application/json")
self.finish(response_obj.to_string())
self.response_is_sent = True | python | def write_single_response(self, response_obj):
"""
Writes a json rpc response ``{"result": result, "error": error, "id": id}``.
If the ``id`` is ``None``, the response will not contain an ``id`` field.
The response is sent to the client as an ``application/json`` response. Only one call per
response is allowed
:param response_obj: A Json rpc response object
:return:
"""
if not isinstance(response_obj, JsonRpcResponse):
raise ValueError(
"Expected JsonRpcResponse, but got {} instead".format(type(response_obj).__name__))
if not self.response_is_sent:
self.set_status(200)
self.set_header("Content-Type", "application/json")
self.finish(response_obj.to_string())
self.response_is_sent = True | [
"def",
"write_single_response",
"(",
"self",
",",
"response_obj",
")",
":",
"if",
"not",
"isinstance",
"(",
"response_obj",
",",
"JsonRpcResponse",
")",
":",
"raise",
"ValueError",
"(",
"\"Expected JsonRpcResponse, but got {} instead\"",
".",
"format",
"(",
"type",
... | Writes a json rpc response ``{"result": result, "error": error, "id": id}``.
If the ``id`` is ``None``, the response will not contain an ``id`` field.
The response is sent to the client as an ``application/json`` response. Only one call per
response is allowed
:param response_obj: A Json rpc response object
:return: | [
"Writes",
"a",
"json",
"rpc",
"response",
"{",
"result",
":",
"result",
"error",
":",
"error",
"id",
":",
"id",
"}",
".",
"If",
"the",
"id",
"is",
"None",
"the",
"response",
"will",
"not",
"contain",
"an",
"id",
"field",
".",
"The",
"response",
"is",... | train | https://github.com/vladcalin/gemstone/blob/325a49d17621b9d45ffd2b5eca6f0de284de8ba4/gemstone/core/handlers.py#L206-L224 |
vladcalin/gemstone | gemstone/core/handlers.py | TornadoJsonRpcHandler.prepare_method_call | def prepare_method_call(self, method, args):
"""
Wraps a method so that method() will call ``method(*args)`` or ``method(**args)``,
depending of args type
:param method: a callable object (method)
:param args: dict or list with the parameters for the function
:return: a 'patched' callable
"""
if self._method_requires_handler_ref(method):
if isinstance(args, list):
args = [self] + args
elif isinstance(args, dict):
args["handler"] = self
if isinstance(args, list):
to_call = partial(method, *args)
elif isinstance(args, dict):
to_call = partial(method, **args)
else:
raise TypeError(
"args must be list or dict but got {} instead".format(type(args).__name__))
return to_call | python | def prepare_method_call(self, method, args):
"""
Wraps a method so that method() will call ``method(*args)`` or ``method(**args)``,
depending of args type
:param method: a callable object (method)
:param args: dict or list with the parameters for the function
:return: a 'patched' callable
"""
if self._method_requires_handler_ref(method):
if isinstance(args, list):
args = [self] + args
elif isinstance(args, dict):
args["handler"] = self
if isinstance(args, list):
to_call = partial(method, *args)
elif isinstance(args, dict):
to_call = partial(method, **args)
else:
raise TypeError(
"args must be list or dict but got {} instead".format(type(args).__name__))
return to_call | [
"def",
"prepare_method_call",
"(",
"self",
",",
"method",
",",
"args",
")",
":",
"if",
"self",
".",
"_method_requires_handler_ref",
"(",
"method",
")",
":",
"if",
"isinstance",
"(",
"args",
",",
"list",
")",
":",
"args",
"=",
"[",
"self",
"]",
"+",
"ar... | Wraps a method so that method() will call ``method(*args)`` or ``method(**args)``,
depending of args type
:param method: a callable object (method)
:param args: dict or list with the parameters for the function
:return: a 'patched' callable | [
"Wraps",
"a",
"method",
"so",
"that",
"method",
"()",
"will",
"call",
"method",
"(",
"*",
"args",
")",
"or",
"method",
"(",
"**",
"args",
")",
"depending",
"of",
"args",
"type"
] | train | https://github.com/vladcalin/gemstone/blob/325a49d17621b9d45ffd2b5eca6f0de284de8ba4/gemstone/core/handlers.py#L246-L268 |
vladcalin/gemstone | gemstone/core/handlers.py | TornadoJsonRpcHandler.call_method | def call_method(self, method):
"""
Calls a blocking method in an executor, in order to preserve the non-blocking behaviour
If ``method`` is a coroutine, yields from it and returns, no need to execute in
in an executor.
:param method: The method or coroutine to be called (with no arguments).
:return: the result of the method call
"""
if self._method_is_async_generator(method):
result = yield method()
else:
result = yield self.executor.submit(method)
return result | python | def call_method(self, method):
"""
Calls a blocking method in an executor, in order to preserve the non-blocking behaviour
If ``method`` is a coroutine, yields from it and returns, no need to execute in
in an executor.
:param method: The method or coroutine to be called (with no arguments).
:return: the result of the method call
"""
if self._method_is_async_generator(method):
result = yield method()
else:
result = yield self.executor.submit(method)
return result | [
"def",
"call_method",
"(",
"self",
",",
"method",
")",
":",
"if",
"self",
".",
"_method_is_async_generator",
"(",
"method",
")",
":",
"result",
"=",
"yield",
"method",
"(",
")",
"else",
":",
"result",
"=",
"yield",
"self",
".",
"executor",
".",
"submit",... | Calls a blocking method in an executor, in order to preserve the non-blocking behaviour
If ``method`` is a coroutine, yields from it and returns, no need to execute in
in an executor.
:param method: The method or coroutine to be called (with no arguments).
:return: the result of the method call | [
"Calls",
"a",
"blocking",
"method",
"in",
"an",
"executor",
"in",
"order",
"to",
"preserve",
"the",
"non",
"-",
"blocking",
"behaviour"
] | train | https://github.com/vladcalin/gemstone/blob/325a49d17621b9d45ffd2b5eca6f0de284de8ba4/gemstone/core/handlers.py#L271-L285 |
vladcalin/gemstone | gemstone/core/handlers.py | TornadoJsonRpcHandler._method_is_async_generator | def _method_is_async_generator(self, method):
"""
Given a simple callable or a callable wrapped in funtools.partial, determines
if it was wrapped with the :py:func:`gemstone.async_method` decorator.
:param method:
:return:
"""
if hasattr(method, "func"):
func = method.func
else:
func = method
return getattr(func, "_is_coroutine", False) | python | def _method_is_async_generator(self, method):
"""
Given a simple callable or a callable wrapped in funtools.partial, determines
if it was wrapped with the :py:func:`gemstone.async_method` decorator.
:param method:
:return:
"""
if hasattr(method, "func"):
func = method.func
else:
func = method
return getattr(func, "_is_coroutine", False) | [
"def",
"_method_is_async_generator",
"(",
"self",
",",
"method",
")",
":",
"if",
"hasattr",
"(",
"method",
",",
"\"func\"",
")",
":",
"func",
"=",
"method",
".",
"func",
"else",
":",
"func",
"=",
"method",
"return",
"getattr",
"(",
"func",
",",
"\"_is_co... | Given a simple callable or a callable wrapped in funtools.partial, determines
if it was wrapped with the :py:func:`gemstone.async_method` decorator.
:param method:
:return: | [
"Given",
"a",
"simple",
"callable",
"or",
"a",
"callable",
"wrapped",
"in",
"funtools",
".",
"partial",
"determines",
"if",
"it",
"was",
"wrapped",
"with",
"the",
":",
"py",
":",
"func",
":",
"gemstone",
".",
"async_method",
"decorator",
".",
":",
"param",... | train | https://github.com/vladcalin/gemstone/blob/325a49d17621b9d45ffd2b5eca6f0de284de8ba4/gemstone/core/handlers.py#L296-L309 |
mozilla-releng/signtool | signtool/util/paths.py | cygpath | def cygpath(filename):
"""Convert a cygwin path into a windows style path"""
if sys.platform == 'cygwin':
proc = Popen(['cygpath', '-am', filename], stdout=PIPE)
return proc.communicate()[0].strip()
else:
return filename | python | def cygpath(filename):
"""Convert a cygwin path into a windows style path"""
if sys.platform == 'cygwin':
proc = Popen(['cygpath', '-am', filename], stdout=PIPE)
return proc.communicate()[0].strip()
else:
return filename | [
"def",
"cygpath",
"(",
"filename",
")",
":",
"if",
"sys",
".",
"platform",
"==",
"'cygwin'",
":",
"proc",
"=",
"Popen",
"(",
"[",
"'cygpath'",
",",
"'-am'",
",",
"filename",
"]",
",",
"stdout",
"=",
"PIPE",
")",
"return",
"proc",
".",
"communicate",
... | Convert a cygwin path into a windows style path | [
"Convert",
"a",
"cygwin",
"path",
"into",
"a",
"windows",
"style",
"path"
] | train | https://github.com/mozilla-releng/signtool/blob/0a778778a181cb9cab424b29fa104b70345f53c2/signtool/util/paths.py#L11-L17 |
mozilla-releng/signtool | signtool/util/paths.py | convertPath | def convertPath(srcpath, dstdir):
"""Given `srcpath`, return a corresponding path within `dstdir`"""
bits = srcpath.split("/")
bits.pop(0)
# Strip out leading 'unsigned' from paths like unsigned/update/win32/...
if bits[0] == 'unsigned':
bits.pop(0)
return os.path.join(dstdir, *bits) | python | def convertPath(srcpath, dstdir):
"""Given `srcpath`, return a corresponding path within `dstdir`"""
bits = srcpath.split("/")
bits.pop(0)
# Strip out leading 'unsigned' from paths like unsigned/update/win32/...
if bits[0] == 'unsigned':
bits.pop(0)
return os.path.join(dstdir, *bits) | [
"def",
"convertPath",
"(",
"srcpath",
",",
"dstdir",
")",
":",
"bits",
"=",
"srcpath",
".",
"split",
"(",
"\"/\"",
")",
"bits",
".",
"pop",
"(",
"0",
")",
"# Strip out leading 'unsigned' from paths like unsigned/update/win32/...",
"if",
"bits",
"[",
"0",
"]",
... | Given `srcpath`, return a corresponding path within `dstdir` | [
"Given",
"srcpath",
"return",
"a",
"corresponding",
"path",
"within",
"dstdir"
] | train | https://github.com/mozilla-releng/signtool/blob/0a778778a181cb9cab424b29fa104b70345f53c2/signtool/util/paths.py#L20-L27 |
mozilla-releng/signtool | signtool/util/paths.py | finddirs | def finddirs(root):
"""Return a list of all the directories under `root`"""
retval = []
for root, dirs, files in os.walk(root):
for d in dirs:
retval.append(os.path.join(root, d))
return retval | python | def finddirs(root):
"""Return a list of all the directories under `root`"""
retval = []
for root, dirs, files in os.walk(root):
for d in dirs:
retval.append(os.path.join(root, d))
return retval | [
"def",
"finddirs",
"(",
"root",
")",
":",
"retval",
"=",
"[",
"]",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"root",
")",
":",
"for",
"d",
"in",
"dirs",
":",
"retval",
".",
"append",
"(",
"os",
".",
"path",
".",
... | Return a list of all the directories under `root` | [
"Return",
"a",
"list",
"of",
"all",
"the",
"directories",
"under",
"root"
] | train | https://github.com/mozilla-releng/signtool/blob/0a778778a181cb9cab424b29fa104b70345f53c2/signtool/util/paths.py#L52-L58 |
twisted/mantissa | xmantissa/webtheme.py | _realGetLoader | def _realGetLoader(n, default=_marker):
"""
Search all themes for a template named C{n}, returning a loader
for it if found. If not found and a default is passed, the default
will be returned. Otherwise C{RuntimeError} will be raised.
This function is deprecated in favor of using a L{ThemedElement}
for your view code, or calling
ITemplateNameResolver(userStore).getDocFactory.
"""
for t in getAllThemes():
fact = t.getDocFactory(n, None)
if fact is not None:
return fact
if default is _marker:
raise RuntimeError("No loader for %r anywhere" % (n,))
return default | python | def _realGetLoader(n, default=_marker):
"""
Search all themes for a template named C{n}, returning a loader
for it if found. If not found and a default is passed, the default
will be returned. Otherwise C{RuntimeError} will be raised.
This function is deprecated in favor of using a L{ThemedElement}
for your view code, or calling
ITemplateNameResolver(userStore).getDocFactory.
"""
for t in getAllThemes():
fact = t.getDocFactory(n, None)
if fact is not None:
return fact
if default is _marker:
raise RuntimeError("No loader for %r anywhere" % (n,))
return default | [
"def",
"_realGetLoader",
"(",
"n",
",",
"default",
"=",
"_marker",
")",
":",
"for",
"t",
"in",
"getAllThemes",
"(",
")",
":",
"fact",
"=",
"t",
".",
"getDocFactory",
"(",
"n",
",",
"None",
")",
"if",
"fact",
"is",
"not",
"None",
":",
"return",
"fac... | Search all themes for a template named C{n}, returning a loader
for it if found. If not found and a default is passed, the default
will be returned. Otherwise C{RuntimeError} will be raised.
This function is deprecated in favor of using a L{ThemedElement}
for your view code, or calling
ITemplateNameResolver(userStore).getDocFactory. | [
"Search",
"all",
"themes",
"for",
"a",
"template",
"named",
"C",
"{",
"n",
"}",
"returning",
"a",
"loader",
"for",
"it",
"if",
"found",
".",
"If",
"not",
"found",
"and",
"a",
"default",
"is",
"passed",
"the",
"default",
"will",
"be",
"returned",
".",
... | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/webtheme.py#L131-L147 |
twisted/mantissa | xmantissa/webtheme.py | ThemeCache._realGetAllThemes | def _realGetAllThemes(self):
"""
Collect themes from all available offerings.
"""
l = []
for offering in getOfferings():
l.extend(offering.themes)
l.sort(key=lambda o: o.priority)
l.reverse()
return l | python | def _realGetAllThemes(self):
"""
Collect themes from all available offerings.
"""
l = []
for offering in getOfferings():
l.extend(offering.themes)
l.sort(key=lambda o: o.priority)
l.reverse()
return l | [
"def",
"_realGetAllThemes",
"(",
"self",
")",
":",
"l",
"=",
"[",
"]",
"for",
"offering",
"in",
"getOfferings",
"(",
")",
":",
"l",
".",
"extend",
"(",
"offering",
".",
"themes",
")",
"l",
".",
"sort",
"(",
"key",
"=",
"lambda",
"o",
":",
"o",
".... | Collect themes from all available offerings. | [
"Collect",
"themes",
"from",
"all",
"available",
"offerings",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/webtheme.py#L44-L53 |
twisted/mantissa | xmantissa/webtheme.py | ThemeCache.getAllThemes | def getAllThemes(self):
"""
Collect themes from all available offerings, or (if called
multiple times) return the previously collected list.
"""
if self._getAllThemesCache is None:
self._getAllThemesCache = self._realGetAllThemes()
return self._getAllThemesCache | python | def getAllThemes(self):
"""
Collect themes from all available offerings, or (if called
multiple times) return the previously collected list.
"""
if self._getAllThemesCache is None:
self._getAllThemesCache = self._realGetAllThemes()
return self._getAllThemesCache | [
"def",
"getAllThemes",
"(",
"self",
")",
":",
"if",
"self",
".",
"_getAllThemesCache",
"is",
"None",
":",
"self",
".",
"_getAllThemesCache",
"=",
"self",
".",
"_realGetAllThemes",
"(",
")",
"return",
"self",
".",
"_getAllThemesCache"
] | Collect themes from all available offerings, or (if called
multiple times) return the previously collected list. | [
"Collect",
"themes",
"from",
"all",
"available",
"offerings",
"or",
"(",
"if",
"called",
"multiple",
"times",
")",
"return",
"the",
"previously",
"collected",
"list",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/webtheme.py#L56-L63 |
twisted/mantissa | xmantissa/webtheme.py | ThemeCache._realGetInstalledThemes | def _realGetInstalledThemes(self, store):
"""
Collect themes from all offerings installed on this store.
"""
l = []
for offering in getInstalledOfferings(store).itervalues():
l.extend(offering.themes)
l.sort(key=lambda o: o.priority)
l.reverse()
return l | python | def _realGetInstalledThemes(self, store):
"""
Collect themes from all offerings installed on this store.
"""
l = []
for offering in getInstalledOfferings(store).itervalues():
l.extend(offering.themes)
l.sort(key=lambda o: o.priority)
l.reverse()
return l | [
"def",
"_realGetInstalledThemes",
"(",
"self",
",",
"store",
")",
":",
"l",
"=",
"[",
"]",
"for",
"offering",
"in",
"getInstalledOfferings",
"(",
"store",
")",
".",
"itervalues",
"(",
")",
":",
"l",
".",
"extend",
"(",
"offering",
".",
"themes",
")",
"... | Collect themes from all offerings installed on this store. | [
"Collect",
"themes",
"from",
"all",
"offerings",
"installed",
"on",
"this",
"store",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/webtheme.py#L66-L75 |
twisted/mantissa | xmantissa/webtheme.py | ThemeCache.getInstalledThemes | def getInstalledThemes(self, store):
"""
Collect themes from all offerings installed on this store, or (if called
multiple times) return the previously collected list.
"""
if not store in self._getInstalledThemesCache:
self._getInstalledThemesCache[store] = (self.
_realGetInstalledThemes(store))
return self._getInstalledThemesCache[store] | python | def getInstalledThemes(self, store):
"""
Collect themes from all offerings installed on this store, or (if called
multiple times) return the previously collected list.
"""
if not store in self._getInstalledThemesCache:
self._getInstalledThemesCache[store] = (self.
_realGetInstalledThemes(store))
return self._getInstalledThemesCache[store] | [
"def",
"getInstalledThemes",
"(",
"self",
",",
"store",
")",
":",
"if",
"not",
"store",
"in",
"self",
".",
"_getInstalledThemesCache",
":",
"self",
".",
"_getInstalledThemesCache",
"[",
"store",
"]",
"=",
"(",
"self",
".",
"_realGetInstalledThemes",
"(",
"stor... | Collect themes from all offerings installed on this store, or (if called
multiple times) return the previously collected list. | [
"Collect",
"themes",
"from",
"all",
"offerings",
"installed",
"on",
"this",
"store",
"or",
"(",
"if",
"called",
"multiple",
"times",
")",
"return",
"the",
"previously",
"collected",
"list",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/webtheme.py#L78-L86 |
twisted/mantissa | xmantissa/webtheme.py | SiteTemplateResolver.getDocFactory | def getDocFactory(self, name, default=None):
"""
Locate a L{nevow.inevow.IDocFactory} object with the given name from
the themes installed on the site store and return it.
"""
loader = None
for theme in getInstalledThemes(self.siteStore):
loader = theme.getDocFactory(name)
if loader is not None:
return loader
return default | python | def getDocFactory(self, name, default=None):
"""
Locate a L{nevow.inevow.IDocFactory} object with the given name from
the themes installed on the site store and return it.
"""
loader = None
for theme in getInstalledThemes(self.siteStore):
loader = theme.getDocFactory(name)
if loader is not None:
return loader
return default | [
"def",
"getDocFactory",
"(",
"self",
",",
"name",
",",
"default",
"=",
"None",
")",
":",
"loader",
"=",
"None",
"for",
"theme",
"in",
"getInstalledThemes",
"(",
"self",
".",
"siteStore",
")",
":",
"loader",
"=",
"theme",
".",
"getDocFactory",
"(",
"name"... | Locate a L{nevow.inevow.IDocFactory} object with the given name from
the themes installed on the site store and return it. | [
"Locate",
"a",
"L",
"{",
"nevow",
".",
"inevow",
".",
"IDocFactory",
"}",
"object",
"with",
"the",
"given",
"name",
"from",
"the",
"themes",
"installed",
"on",
"the",
"site",
"store",
"and",
"return",
"it",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/webtheme.py#L115-L125 |
twisted/mantissa | xmantissa/webtheme.py | XHTMLDirectoryTheme.head | def head(self, request, website):
"""
Provide content to include in the head of the document. If you only
need to provide a stylesheet, see L{stylesheetLocation}. Otherwise,
override this.
@type request: L{inevow.IRequest} provider
@param request: The request object for which this is a response.
@param website: The site-wide L{xmantissa.website.WebSite} instance.
Primarily of interest for its C{rootURL} method.
@return: Anything providing or adaptable to L{nevow.inevow.IRenderer},
or C{None} to include nothing.
"""
stylesheet = self.stylesheetLocation
if stylesheet is not None:
root = website.rootURL(request)
for segment in stylesheet:
root = root.child(segment)
return tags.link(rel='stylesheet', type='text/css', href=root) | python | def head(self, request, website):
"""
Provide content to include in the head of the document. If you only
need to provide a stylesheet, see L{stylesheetLocation}. Otherwise,
override this.
@type request: L{inevow.IRequest} provider
@param request: The request object for which this is a response.
@param website: The site-wide L{xmantissa.website.WebSite} instance.
Primarily of interest for its C{rootURL} method.
@return: Anything providing or adaptable to L{nevow.inevow.IRenderer},
or C{None} to include nothing.
"""
stylesheet = self.stylesheetLocation
if stylesheet is not None:
root = website.rootURL(request)
for segment in stylesheet:
root = root.child(segment)
return tags.link(rel='stylesheet', type='text/css', href=root) | [
"def",
"head",
"(",
"self",
",",
"request",
",",
"website",
")",
":",
"stylesheet",
"=",
"self",
".",
"stylesheetLocation",
"if",
"stylesheet",
"is",
"not",
"None",
":",
"root",
"=",
"website",
".",
"rootURL",
"(",
"request",
")",
"for",
"segment",
"in",... | Provide content to include in the head of the document. If you only
need to provide a stylesheet, see L{stylesheetLocation}. Otherwise,
override this.
@type request: L{inevow.IRequest} provider
@param request: The request object for which this is a response.
@param website: The site-wide L{xmantissa.website.WebSite} instance.
Primarily of interest for its C{rootURL} method.
@return: Anything providing or adaptable to L{nevow.inevow.IRenderer},
or C{None} to include nothing. | [
"Provide",
"content",
"to",
"include",
"in",
"the",
"head",
"of",
"the",
"document",
".",
"If",
"you",
"only",
"need",
"to",
"provide",
"a",
"stylesheet",
"see",
"L",
"{",
"stylesheetLocation",
"}",
".",
"Otherwise",
"override",
"this",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/webtheme.py#L221-L241 |
twisted/mantissa | xmantissa/webtheme.py | XHTMLDirectoryTheme.getDocFactory | def getDocFactory(self, fragmentName, default=None):
"""
For a given fragment, return a loaded Nevow template.
@param fragmentName: the name of the template (can include relative
paths).
@param default: a default loader; only used if provided and the
given fragment name cannot be resolved.
@return: A loaded Nevow template.
@type return: L{nevow.loaders.xmlfile}
"""
if fragmentName in self.cachedLoaders:
return self.cachedLoaders[fragmentName]
segments = fragmentName.split('/')
segments[-1] += '.html'
file = self.directory
for segment in segments:
file = file.child(segment)
if file.exists():
loader = xmlfile(file.path)
self.cachedLoaders[fragmentName] = loader
return loader
return default | python | def getDocFactory(self, fragmentName, default=None):
"""
For a given fragment, return a loaded Nevow template.
@param fragmentName: the name of the template (can include relative
paths).
@param default: a default loader; only used if provided and the
given fragment name cannot be resolved.
@return: A loaded Nevow template.
@type return: L{nevow.loaders.xmlfile}
"""
if fragmentName in self.cachedLoaders:
return self.cachedLoaders[fragmentName]
segments = fragmentName.split('/')
segments[-1] += '.html'
file = self.directory
for segment in segments:
file = file.child(segment)
if file.exists():
loader = xmlfile(file.path)
self.cachedLoaders[fragmentName] = loader
return loader
return default | [
"def",
"getDocFactory",
"(",
"self",
",",
"fragmentName",
",",
"default",
"=",
"None",
")",
":",
"if",
"fragmentName",
"in",
"self",
".",
"cachedLoaders",
":",
"return",
"self",
".",
"cachedLoaders",
"[",
"fragmentName",
"]",
"segments",
"=",
"fragmentName",
... | For a given fragment, return a loaded Nevow template.
@param fragmentName: the name of the template (can include relative
paths).
@param default: a default loader; only used if provided and the
given fragment name cannot be resolved.
@return: A loaded Nevow template.
@type return: L{nevow.loaders.xmlfile} | [
"For",
"a",
"given",
"fragment",
"return",
"a",
"loaded",
"Nevow",
"template",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/webtheme.py#L245-L269 |
twisted/mantissa | xmantissa/webtheme.py | _ThemedMixin.rend | def rend(self, context, data):
"""
Automatically retrieve my C{docFactory} based on C{self.fragmentName}
before invoking L{athena.LiveElement.rend}.
"""
if self.docFactory is None:
self.docFactory = self.getDocFactory(self.fragmentName)
return super(_ThemedMixin, self).rend(context, data) | python | def rend(self, context, data):
"""
Automatically retrieve my C{docFactory} based on C{self.fragmentName}
before invoking L{athena.LiveElement.rend}.
"""
if self.docFactory is None:
self.docFactory = self.getDocFactory(self.fragmentName)
return super(_ThemedMixin, self).rend(context, data) | [
"def",
"rend",
"(",
"self",
",",
"context",
",",
"data",
")",
":",
"if",
"self",
".",
"docFactory",
"is",
"None",
":",
"self",
".",
"docFactory",
"=",
"self",
".",
"getDocFactory",
"(",
"self",
".",
"fragmentName",
")",
"return",
"super",
"(",
"_Themed... | Automatically retrieve my C{docFactory} based on C{self.fragmentName}
before invoking L{athena.LiveElement.rend}. | [
"Automatically",
"retrieve",
"my",
"C",
"{",
"docFactory",
"}",
"based",
"on",
"C",
"{",
"self",
".",
"fragmentName",
"}",
"before",
"invoking",
"L",
"{",
"athena",
".",
"LiveElement",
".",
"rend",
"}",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/webtheme.py#L352-L359 |
murphy214/berrl | build/lib/berrl/pipehtml.py | make_zoom_block | def make_zoom_block(min,max,count,colorkeyfields,bounds,filter_file_dictionary):
if min == '' and max == '' and not bounds == True:
return ''
if colorkeyfields == False and bounds == False:
block = '''
map.on('zoomend', function(e) {
if ( (map.getZoom() >= %s)&&(map.getZoom() <= %s) ){
if (map.hasLayer(dataLayer) != true) {
add%s()
}
}
else { map.removeLayer( dataLayer ) }
})''' % (str(min),str(max),str(count))
elif bounds == True:
if min == '' and max == '':
min,max = [0,20]
if filter_file_dictionary == False:
block = '''
map.on('dragend',function(e) {
var outerbounds = [[map.getBounds()._southWest.lng,map.getBounds()._northEast.lat],[map.getBounds()._northEast.lng,map.getBounds()._southWest.lat]]
var outerbounds = L.bounds(outerbounds[0],outerbounds[1]);
dataLayer.eachLayer(function(layer) {
if (((outerbounds.contains(layer.feature.properties['bounds']) == true)||(outerbounds.intersects(layer.feature.properties['bounds']) == true))&&((map.getZoom() >= %s)&&(map.getZoom() <= %s))) {
layer.addTo(map)
console.log('added')
}
else {
if ( dataLayer.hasLayer(layer) == true ) {
map.removeLayer(layer)
}
}
})
});''' % (str(min),str(max))
else:
block = make_zoom_block_filter(min,max,filter_file_dictionary)
# section below is for if colorkey fields are implemented, currently not supported
# however this code below can be a good start maybe
"""
else:
block = '''
map.on('zoomend', function(e) {
if ( (map.getZoom() >= %s)&&(map.getZoom() <= %s) ){
if (map.hasLayer(dataLayer) != true) {
map.addLayer(dataLayer)
}
}
else { map.removeLayer( dataLayer ) }
})
map.on('click',function(e) {
var skillsSelect = document.getElementById("mapStyle");
var selectedText2 = skillsSelect.options[skillsSelect.selectedIndex].text;
var selectedText2 = 'COLORKEY_' + selectedText2;
if ( (map.getZoom() >= %s)&&(map.getZoom() <= %s)&&(selectedText2 != selectedText)){
// map.addLayer(dataLayer)
dataLayer.eachLayer(function (layer) {
var style = {color: layer.feature.properties[selectedText2], weight: 6, opacity: 1}
layer.setStyle(style)
});
}
else {
}
var selectedText = selectedText2;
console.log(selectedText)
})''' % (str(min),str(max),str(min),str(max))
"""
return block | python | def make_zoom_block(min,max,count,colorkeyfields,bounds,filter_file_dictionary):
if min == '' and max == '' and not bounds == True:
return ''
if colorkeyfields == False and bounds == False:
block = '''
map.on('zoomend', function(e) {
if ( (map.getZoom() >= %s)&&(map.getZoom() <= %s) ){
if (map.hasLayer(dataLayer) != true) {
add%s()
}
}
else { map.removeLayer( dataLayer ) }
})''' % (str(min),str(max),str(count))
elif bounds == True:
if min == '' and max == '':
min,max = [0,20]
if filter_file_dictionary == False:
block = '''
map.on('dragend',function(e) {
var outerbounds = [[map.getBounds()._southWest.lng,map.getBounds()._northEast.lat],[map.getBounds()._northEast.lng,map.getBounds()._southWest.lat]]
var outerbounds = L.bounds(outerbounds[0],outerbounds[1]);
dataLayer.eachLayer(function(layer) {
if (((outerbounds.contains(layer.feature.properties['bounds']) == true)||(outerbounds.intersects(layer.feature.properties['bounds']) == true))&&((map.getZoom() >= %s)&&(map.getZoom() <= %s))) {
layer.addTo(map)
console.log('added')
}
else {
if ( dataLayer.hasLayer(layer) == true ) {
map.removeLayer(layer)
}
}
})
});''' % (str(min),str(max))
else:
block = make_zoom_block_filter(min,max,filter_file_dictionary)
# section below is for if colorkey fields are implemented, currently not supported
# however this code below can be a good start maybe
"""
else:
block = '''
map.on('zoomend', function(e) {
if ( (map.getZoom() >= %s)&&(map.getZoom() <= %s) ){
if (map.hasLayer(dataLayer) != true) {
map.addLayer(dataLayer)
}
}
else { map.removeLayer( dataLayer ) }
})
map.on('click',function(e) {
var skillsSelect = document.getElementById("mapStyle");
var selectedText2 = skillsSelect.options[skillsSelect.selectedIndex].text;
var selectedText2 = 'COLORKEY_' + selectedText2;
if ( (map.getZoom() >= %s)&&(map.getZoom() <= %s)&&(selectedText2 != selectedText)){
// map.addLayer(dataLayer)
dataLayer.eachLayer(function (layer) {
var style = {color: layer.feature.properties[selectedText2], weight: 6, opacity: 1}
layer.setStyle(style)
});
}
else {
}
var selectedText = selectedText2;
console.log(selectedText)
})''' % (str(min),str(max),str(min),str(max))
"""
return block | [
"def",
"make_zoom_block",
"(",
"min",
",",
"max",
",",
"count",
",",
"colorkeyfields",
",",
"bounds",
",",
"filter_file_dictionary",
")",
":",
"if",
"min",
"==",
"''",
"and",
"max",
"==",
"''",
"and",
"not",
"bounds",
"==",
"True",
":",
"return",
"''",
... | else:
block = '''
map.on('zoomend', function(e) {
if ( (map.getZoom() >= %s)&&(map.getZoom() <= %s) ){
if (map.hasLayer(dataLayer) != true) {
map.addLayer(dataLayer)
}
}
else { map.removeLayer( dataLayer ) }
})
map.on('click',function(e) {
var skillsSelect = document.getElementById("mapStyle");
var selectedText2 = skillsSelect.options[skillsSelect.selectedIndex].text;
var selectedText2 = 'COLORKEY_' + selectedText2;
if ( (map.getZoom() >= %s)&&(map.getZoom() <= %s)&&(selectedText2 != selectedText)){
// map.addLayer(dataLayer)
dataLayer.eachLayer(function (layer) {
var style = {color: layer.feature.properties[selectedText2], weight: 6, opacity: 1}
layer.setStyle(style)
});
}
else {
}
var selectedText = selectedText2;
console.log(selectedText)
})''' % (str(min),str(max),str(min),str(max)) | [
"else",
":",
"block",
"=",
"map",
".",
"on",
"(",
"zoomend",
"function",
"(",
"e",
")",
"{",
"if",
"(",
"(",
"map",
".",
"getZoom",
"()",
">",
"=",
"%s",
")",
"&&",
"(",
"map",
".",
"getZoom",
"()",
"<",
"=",
"%s",
")",
")",
"{",
"if",
"(",... | train | https://github.com/murphy214/berrl/blob/ce4d060cc7db74c32facc538fa1d7030f1a27467/build/lib/berrl/pipehtml.py#L375-L449 |
murphy214/berrl | build/lib/berrl/pipehtml.py | making_blockstr | def making_blockstr(varblock,count,colorline,element,zoomblock,filename,sidebarstring,colorkeyfields):
# starting wrapper that comes before html table code
'''
if not colorkeyfields == False:
start = """\n\tfunction addDataToMap%s(data, map) {\t\tvar skillsSelect = document.getElementById("mapStyle");\n\t\tvar selectedText = skillsSelect.options[skillsSelect.selectedIndex].text;\n\t\tvar selectedText = 'COLORKEY_' + selectedText\n\t\tvar dataLayer = L.geoJson(data, {\n\t\t\tonEachFeature: function(feature, layer) {""" % (count)
else:
'''
start = """\n\tfunction addDataToMap%s(data, map) {\n\t\tvar dataLayer = L.geoJson(data, {\n\t\t\tonEachFeature: function(feature, layer) {""" % (count)
# ending wrapper that comes after html table code
if count == 1 and colorkeyfields == False:
end = """
layer.bindPopup(popupText, {autoPan:false, maxHeight:500, maxWidth:350} ); }
});
dataLayer.addTo(map);
console.log(map.fitBounds(dataLayer.getBounds()))};\n\t};"""
else:
end = """
layer.bindPopup(popupText, {autoPan:false, maxHeight:500, maxWidth:350} ); }
});
dataLayer.addTo(map);
\n\t};\n\t}"""
'''
else:
end="""
layer.bindPopup(popupText, {autoPan:false, maxHeight:500, maxWidth:350} ); };
});
dataLayer.addTo(map);\nconsole.log(map.fitBounds(dataLayer.getBounds()));\n\t\tsetTimeout(function() {\n\t\t\t\tdataLayer.clearLayers();\n\t\t},%s);\n\t}\n}\nsetInterval(add%s,%s)""" % (time,count,time)
'''
# iterates through each varblock and returns the entire bindings javascript block
total = ''
# logic for appending check_dropdown line to zoomblock
if not zoomblock == '' and not colorkeyfields == False:
pass
# logic for replacing the datalayer add to line with the zoom text block
if not zoomblock == '':
end = end.replace('dataLayer.addTo(map);',zoomblock)
for row in varblock:
total += row
if element == 'Point':
return start + total + colorline + sidebarstring + end
else:
return start + total + '\n' + colorline + sidebarstring + end | python | def making_blockstr(varblock,count,colorline,element,zoomblock,filename,sidebarstring,colorkeyfields):
# starting wrapper that comes before html table code
'''
if not colorkeyfields == False:
start = """\n\tfunction addDataToMap%s(data, map) {\t\tvar skillsSelect = document.getElementById("mapStyle");\n\t\tvar selectedText = skillsSelect.options[skillsSelect.selectedIndex].text;\n\t\tvar selectedText = 'COLORKEY_' + selectedText\n\t\tvar dataLayer = L.geoJson(data, {\n\t\t\tonEachFeature: function(feature, layer) {""" % (count)
else:
'''
start = """\n\tfunction addDataToMap%s(data, map) {\n\t\tvar dataLayer = L.geoJson(data, {\n\t\t\tonEachFeature: function(feature, layer) {""" % (count)
# ending wrapper that comes after html table code
if count == 1 and colorkeyfields == False:
end = """
layer.bindPopup(popupText, {autoPan:false, maxHeight:500, maxWidth:350} ); }
});
dataLayer.addTo(map);
console.log(map.fitBounds(dataLayer.getBounds()))};\n\t};"""
else:
end = """
layer.bindPopup(popupText, {autoPan:false, maxHeight:500, maxWidth:350} ); }
});
dataLayer.addTo(map);
\n\t};\n\t}"""
'''
else:
end="""
layer.bindPopup(popupText, {autoPan:false, maxHeight:500, maxWidth:350} ); };
});
dataLayer.addTo(map);\nconsole.log(map.fitBounds(dataLayer.getBounds()));\n\t\tsetTimeout(function() {\n\t\t\t\tdataLayer.clearLayers();\n\t\t},%s);\n\t}\n}\nsetInterval(add%s,%s)""" % (time,count,time)
'''
# iterates through each varblock and returns the entire bindings javascript block
total = ''
# logic for appending check_dropdown line to zoomblock
if not zoomblock == '' and not colorkeyfields == False:
pass
# logic for replacing the datalayer add to line with the zoom text block
if not zoomblock == '':
end = end.replace('dataLayer.addTo(map);',zoomblock)
for row in varblock:
total += row
if element == 'Point':
return start + total + colorline + sidebarstring + end
else:
return start + total + '\n' + colorline + sidebarstring + end | [
"def",
"making_blockstr",
"(",
"varblock",
",",
"count",
",",
"colorline",
",",
"element",
",",
"zoomblock",
",",
"filename",
",",
"sidebarstring",
",",
"colorkeyfields",
")",
":",
"# starting wrapper that comes before html table code",
"start",
"=",
"\"\"\"\\n\\tfuncti... | if not colorkeyfields == False:
start = """\n\tfunction addDataToMap%s(data, map) {\t\tvar skillsSelect = document.getElementById("mapStyle");\n\t\tvar selectedText = skillsSelect.options[skillsSelect.selectedIndex].text;\n\t\tvar selectedText = 'COLORKEY_' + selectedText\n\t\tvar dataLayer = L.geoJson(data, {\n\t\t\tonEachFeature: function(feature, layer) {""" % (count)
else: | [
"if",
"not",
"colorkeyfields",
"==",
"False",
":",
"start",
"=",
"\\",
"n",
"\\",
"tfunction",
"addDataToMap%s",
"(",
"data",
"map",
")",
"{",
"\\",
"t",
"\\",
"tvar",
"skillsSelect",
"=",
"document",
".",
"getElementById",
"(",
"mapStyle",
")",
";",
"\\... | train | https://github.com/murphy214/berrl/blob/ce4d060cc7db74c32facc538fa1d7030f1a27467/build/lib/berrl/pipehtml.py#L639-L688 |
murphy214/berrl | build/lib/berrl/pipehtml.py | make_bindings_type | def make_bindings_type(filenames,color_input,colorkey,file_dictionary,sidebar,bounds):
# instantiating string the main string block for the javascript block of html code
string = ''
'''
# logic for instantiating variable colorkey input
if not colorkeyfields == False:
colorkey = 'selectedText'
'''
# iterating through each geojson filename
count = 0
for row in filenames:
color_input = ''
colorkeyfields = False
count += 1
filename = row
zoomrange = ['','']
# reading in geojson file into memory
with open(filename) as data_file:
data = json.load(data_file)
#pprint(data)
# getting the featuretype which will later dictate what javascript splices are needed
data = data['features']
data = data[0]
featuretype = data['geometry']
featuretype = featuretype['type']
data = data['properties']
# logic for overwriting colorkey fields if it exists for the filename
# in the file dictionary
try:
colorkeyfields = file_dictionary[filename][str('colorkeyfields')]
except KeyError:
colorkeyfields = False
except TypeError:
colorkeyfields = False
if not colorkeyfields == False:
if len(colorkeyfields) == 1:
colorkey = colorkeyfields[0]
colorkeyfields = False
try:
zoomrange = file_dictionary[filename][str('zooms')]
except KeyError:
zoomrange = ['','']
except TypeError:
zoomrange = ['','']
# code for if the file_dictionary input isn't false
#(i.e. getting the color inputs out of dictionary variable)
if file_dictionary==False and colorkey == False:
# logic for getting the colorline for different feature types
# the point feature requires a different line of code
if featuretype == 'Point':
colorline = get_colorline_marker(color_input)
else:
colorline = get_colorline_marker2(color_input)
# setting minzoom and maxzoom to be sent into js parsing
minzoom,maxzoom = zoomrange
# getting filter file dictionary if filter_dictonary exists
if not file_dictionary == False:
filter_file_dictionary = file_dictionary[filename]
else:
filter_file_dictionary = False
# checking to see if a chart_dictionary exists
try:
chart_dictionary = filter_file_dictionary['chart_dictionary']
except KeyError:
chart_dictionary = False
except TypeError:
chart_dictionary = False
# sending min and max zoom into the function that makes the zoom block
zoomblock = make_zoom_block(minzoom,maxzoom,count,colorkeyfields,bounds,filter_file_dictionary)
# logic for if a color key is given
# HINT look here for rgb raw color integration in a color line
if not colorkey == '':
if row == filenames[0]:
if colorkey == 'selectedText':
colorkey = """feature.properties[%s]""" % colorkey
else:
colorkey = """feature.properties['%s']""" % colorkey
if featuretype == 'Point':
colorline = get_colorline_marker(str(colorkey))
else:
colorline = get_colorline_marker2(str(colorkey))
# this may be able to be deleted
# test later
# im not sure what the fuck its here for
if file_dictionary == False and colorkey == '':
if featuretype == 'Point':
colorline = get_colorline_marker(color_input)
else:
colorline = get_colorline_marker2(color_input)
if colorkey == '' and colorkeyfields == False:
if featuretype == 'Point':
colorline = get_colorline_marker(color_input)
else:
colorline = get_colorline_marker2(color_input)
# iterating through each header
headers = []
for row in data:
headers.append(str(row))
# logic for getting sidebar string that will be added in make_blockstr()
if sidebar == True:
sidebarstring = make_sidebar_string(headers,chart_dictionary)
else:
sidebarstring = ''
# section of javascript code dedicated to the adding the data layer
if count == 1:
blocky = """
function add%s() {
\n\tfunction addDataToMap%s(data, map) {
\t\tvar dataLayer = L.geoJson(data);
\t\tvar map = L.mapbox.map('map', 'mapbox.streets',{
\t\t\tzoom: 5
\t\t\t}).fitBounds(dataLayer.getBounds());
\t\tdataLayer.addTo(map)
\t}\n""" % (count,count)
else:
blocky = """
function add%s() {
\n\tfunction addDataToMap%s(data, map) {
\t\tvar dataLayer = L.geoJson(data);
\t\tdataLayer.addTo(map)
\t}\n""" % (count,count)
# making the string section that locally links the geojson file to the html document
'''
if not time == '':
preloc='\tfunction add%s() {\n' % (str(count))
loc = """\t$.getJSON('http://localhost:8000/%s',function(data) { addDataToMap%s(data,map); });""" % (filename,count)
loc = preloc + loc
else:
'''
loc = """\t$.getJSON('http://localhost:8000/%s',function(data) { addDataToMap%s(data,map); });""" % (filename,count)
# creating block to be added to the total or constituent string block
if featuretype == 'Point':
bindings = make_bindings(headers,count,colorline,featuretype,zoomblock,filename,sidebarstring,colorkeyfields)+'\n'
stringblock = blocky + loc + bindings
else:
bindings = make_bindings(headers,count,colorline,featuretype,zoomblock,filename,sidebarstring,colorkeyfields)+'\n'
stringblock = blocky + loc + bindings
# adding the stringblock (one geojson file javascript block) to the total string block
string += stringblock
# adding async function to end of string block
string = string + async_function_call(count)
return string | python | def make_bindings_type(filenames,color_input,colorkey,file_dictionary,sidebar,bounds):
# instantiating string the main string block for the javascript block of html code
string = ''
'''
# logic for instantiating variable colorkey input
if not colorkeyfields == False:
colorkey = 'selectedText'
'''
# iterating through each geojson filename
count = 0
for row in filenames:
color_input = ''
colorkeyfields = False
count += 1
filename = row
zoomrange = ['','']
# reading in geojson file into memory
with open(filename) as data_file:
data = json.load(data_file)
#pprint(data)
# getting the featuretype which will later dictate what javascript splices are needed
data = data['features']
data = data[0]
featuretype = data['geometry']
featuretype = featuretype['type']
data = data['properties']
# logic for overwriting colorkey fields if it exists for the filename
# in the file dictionary
try:
colorkeyfields = file_dictionary[filename][str('colorkeyfields')]
except KeyError:
colorkeyfields = False
except TypeError:
colorkeyfields = False
if not colorkeyfields == False:
if len(colorkeyfields) == 1:
colorkey = colorkeyfields[0]
colorkeyfields = False
try:
zoomrange = file_dictionary[filename][str('zooms')]
except KeyError:
zoomrange = ['','']
except TypeError:
zoomrange = ['','']
# code for if the file_dictionary input isn't false
#(i.e. getting the color inputs out of dictionary variable)
if file_dictionary==False and colorkey == False:
# logic for getting the colorline for different feature types
# the point feature requires a different line of code
if featuretype == 'Point':
colorline = get_colorline_marker(color_input)
else:
colorline = get_colorline_marker2(color_input)
# setting minzoom and maxzoom to be sent into js parsing
minzoom,maxzoom = zoomrange
# getting filter file dictionary if filter_dictonary exists
if not file_dictionary == False:
filter_file_dictionary = file_dictionary[filename]
else:
filter_file_dictionary = False
# checking to see if a chart_dictionary exists
try:
chart_dictionary = filter_file_dictionary['chart_dictionary']
except KeyError:
chart_dictionary = False
except TypeError:
chart_dictionary = False
# sending min and max zoom into the function that makes the zoom block
zoomblock = make_zoom_block(minzoom,maxzoom,count,colorkeyfields,bounds,filter_file_dictionary)
# logic for if a color key is given
# HINT look here for rgb raw color integration in a color line
if not colorkey == '':
if row == filenames[0]:
if colorkey == 'selectedText':
colorkey = """feature.properties[%s]""" % colorkey
else:
colorkey = """feature.properties['%s']""" % colorkey
if featuretype == 'Point':
colorline = get_colorline_marker(str(colorkey))
else:
colorline = get_colorline_marker2(str(colorkey))
# this may be able to be deleted
# test later
# im not sure what the fuck its here for
if file_dictionary == False and colorkey == '':
if featuretype == 'Point':
colorline = get_colorline_marker(color_input)
else:
colorline = get_colorline_marker2(color_input)
if colorkey == '' and colorkeyfields == False:
if featuretype == 'Point':
colorline = get_colorline_marker(color_input)
else:
colorline = get_colorline_marker2(color_input)
# iterating through each header
headers = []
for row in data:
headers.append(str(row))
# logic for getting sidebar string that will be added in make_blockstr()
if sidebar == True:
sidebarstring = make_sidebar_string(headers,chart_dictionary)
else:
sidebarstring = ''
# section of javascript code dedicated to the adding the data layer
if count == 1:
blocky = """
function add%s() {
\n\tfunction addDataToMap%s(data, map) {
\t\tvar dataLayer = L.geoJson(data);
\t\tvar map = L.mapbox.map('map', 'mapbox.streets',{
\t\t\tzoom: 5
\t\t\t}).fitBounds(dataLayer.getBounds());
\t\tdataLayer.addTo(map)
\t}\n""" % (count,count)
else:
blocky = """
function add%s() {
\n\tfunction addDataToMap%s(data, map) {
\t\tvar dataLayer = L.geoJson(data);
\t\tdataLayer.addTo(map)
\t}\n""" % (count,count)
# making the string section that locally links the geojson file to the html document
'''
if not time == '':
preloc='\tfunction add%s() {\n' % (str(count))
loc = """\t$.getJSON('http://localhost:8000/%s',function(data) { addDataToMap%s(data,map); });""" % (filename,count)
loc = preloc + loc
else:
'''
loc = """\t$.getJSON('http://localhost:8000/%s',function(data) { addDataToMap%s(data,map); });""" % (filename,count)
# creating block to be added to the total or constituent string block
if featuretype == 'Point':
bindings = make_bindings(headers,count,colorline,featuretype,zoomblock,filename,sidebarstring,colorkeyfields)+'\n'
stringblock = blocky + loc + bindings
else:
bindings = make_bindings(headers,count,colorline,featuretype,zoomblock,filename,sidebarstring,colorkeyfields)+'\n'
stringblock = blocky + loc + bindings
# adding the stringblock (one geojson file javascript block) to the total string block
string += stringblock
# adding async function to end of string block
string = string + async_function_call(count)
return string | [
"def",
"make_bindings_type",
"(",
"filenames",
",",
"color_input",
",",
"colorkey",
",",
"file_dictionary",
",",
"sidebar",
",",
"bounds",
")",
":",
"# instantiating string the main string block for the javascript block of html code",
"string",
"=",
"''",
"# iterating through... | # logic for instantiating variable colorkey input
if not colorkeyfields == False:
colorkey = 'selectedText' | [
"#",
"logic",
"for",
"instantiating",
"variable",
"colorkey",
"input",
"if",
"not",
"colorkeyfields",
"==",
"False",
":",
"colorkey",
"=",
"selectedText"
] | train | https://github.com/murphy214/berrl/blob/ce4d060cc7db74c32facc538fa1d7030f1a27467/build/lib/berrl/pipehtml.py#L716-L884 |
mozilla-releng/signtool | signtool/util/archives.py | unpackexe | def unpackexe(exefile, destdir):
"""Unpack the given exefile into destdir, using 7z"""
nullfd = open(os.devnull, "w")
exefile = cygpath(os.path.abspath(exefile))
try:
check_call([SEVENZIP, 'x', exefile], cwd=destdir,
stdout=nullfd, preexec_fn=_noumask)
except Exception:
log.exception("Error unpacking exe %s to %s", exefile, destdir)
raise
nullfd.close() | python | def unpackexe(exefile, destdir):
"""Unpack the given exefile into destdir, using 7z"""
nullfd = open(os.devnull, "w")
exefile = cygpath(os.path.abspath(exefile))
try:
check_call([SEVENZIP, 'x', exefile], cwd=destdir,
stdout=nullfd, preexec_fn=_noumask)
except Exception:
log.exception("Error unpacking exe %s to %s", exefile, destdir)
raise
nullfd.close() | [
"def",
"unpackexe",
"(",
"exefile",
",",
"destdir",
")",
":",
"nullfd",
"=",
"open",
"(",
"os",
".",
"devnull",
",",
"\"w\"",
")",
"exefile",
"=",
"cygpath",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"exefile",
")",
")",
"try",
":",
"check_call",
... | Unpack the given exefile into destdir, using 7z | [
"Unpack",
"the",
"given",
"exefile",
"into",
"destdir",
"using",
"7z"
] | train | https://github.com/mozilla-releng/signtool/blob/0a778778a181cb9cab424b29fa104b70345f53c2/signtool/util/archives.py#L23-L33 |
mozilla-releng/signtool | signtool/util/archives.py | packexe | def packexe(exefile, srcdir):
"""Pack the files in srcdir into exefile using 7z.
Requires that stub files are available in checkouts/stubs"""
exefile = cygpath(os.path.abspath(exefile))
appbundle = exefile + ".app.7z"
# Make sure that appbundle doesn't already exist
# We don't want to risk appending to an existing file
if os.path.exists(appbundle):
raise OSError("%s already exists" % appbundle)
files = os.listdir(srcdir)
SEVENZIP_ARGS = ['-r', '-t7z', '-mx', '-m0=BCJ2', '-m1=LZMA:d27',
'-m2=LZMA:d19:mf=bt2', '-m3=LZMA:d19:mf=bt2', '-mb0:1', '-mb0s1:2',
'-mb0s2:3', '-m1fb=128', '-m1lc=4']
# First, compress with 7z
stdout = tempfile.TemporaryFile()
try:
check_call([SEVENZIP, 'a'] + SEVENZIP_ARGS + [appbundle] + files,
cwd=srcdir, stdout=stdout, preexec_fn=_noumask)
except Exception:
stdout.seek(0)
data = stdout.read()
log.error(data)
log.exception("Error packing exe %s from %s", exefile, srcdir)
raise
stdout.close()
# Then prepend our stubs onto the compressed 7z data
o = open(exefile, "wb")
parts = [
'checkouts/stubs/7z/7zSD.sfx.compressed',
'checkouts/stubs/tagfile/app.tag',
appbundle
]
for part in parts:
i = open(part)
while True:
block = i.read(4096)
if not block:
break
o.write(block)
i.close()
o.close()
os.unlink(appbundle) | python | def packexe(exefile, srcdir):
"""Pack the files in srcdir into exefile using 7z.
Requires that stub files are available in checkouts/stubs"""
exefile = cygpath(os.path.abspath(exefile))
appbundle = exefile + ".app.7z"
# Make sure that appbundle doesn't already exist
# We don't want to risk appending to an existing file
if os.path.exists(appbundle):
raise OSError("%s already exists" % appbundle)
files = os.listdir(srcdir)
SEVENZIP_ARGS = ['-r', '-t7z', '-mx', '-m0=BCJ2', '-m1=LZMA:d27',
'-m2=LZMA:d19:mf=bt2', '-m3=LZMA:d19:mf=bt2', '-mb0:1', '-mb0s1:2',
'-mb0s2:3', '-m1fb=128', '-m1lc=4']
# First, compress with 7z
stdout = tempfile.TemporaryFile()
try:
check_call([SEVENZIP, 'a'] + SEVENZIP_ARGS + [appbundle] + files,
cwd=srcdir, stdout=stdout, preexec_fn=_noumask)
except Exception:
stdout.seek(0)
data = stdout.read()
log.error(data)
log.exception("Error packing exe %s from %s", exefile, srcdir)
raise
stdout.close()
# Then prepend our stubs onto the compressed 7z data
o = open(exefile, "wb")
parts = [
'checkouts/stubs/7z/7zSD.sfx.compressed',
'checkouts/stubs/tagfile/app.tag',
appbundle
]
for part in parts:
i = open(part)
while True:
block = i.read(4096)
if not block:
break
o.write(block)
i.close()
o.close()
os.unlink(appbundle) | [
"def",
"packexe",
"(",
"exefile",
",",
"srcdir",
")",
":",
"exefile",
"=",
"cygpath",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"exefile",
")",
")",
"appbundle",
"=",
"exefile",
"+",
"\".app.7z\"",
"# Make sure that appbundle doesn't already exist",
"# We don... | Pack the files in srcdir into exefile using 7z.
Requires that stub files are available in checkouts/stubs | [
"Pack",
"the",
"files",
"in",
"srcdir",
"into",
"exefile",
"using",
"7z",
"."
] | train | https://github.com/mozilla-releng/signtool/blob/0a778778a181cb9cab424b29fa104b70345f53c2/signtool/util/archives.py#L36-L83 |
mozilla-releng/signtool | signtool/util/archives.py | bunzip2 | def bunzip2(filename):
"""Uncompress `filename` in place"""
log.debug("Uncompressing %s", filename)
tmpfile = "%s.tmp" % filename
os.rename(filename, tmpfile)
b = bz2.BZ2File(tmpfile)
f = open(filename, "wb")
while True:
block = b.read(512 * 1024)
if not block:
break
f.write(block)
f.close()
b.close()
shutil.copystat(tmpfile, filename)
shutil.copymode(tmpfile, filename)
os.unlink(tmpfile) | python | def bunzip2(filename):
"""Uncompress `filename` in place"""
log.debug("Uncompressing %s", filename)
tmpfile = "%s.tmp" % filename
os.rename(filename, tmpfile)
b = bz2.BZ2File(tmpfile)
f = open(filename, "wb")
while True:
block = b.read(512 * 1024)
if not block:
break
f.write(block)
f.close()
b.close()
shutil.copystat(tmpfile, filename)
shutil.copymode(tmpfile, filename)
os.unlink(tmpfile) | [
"def",
"bunzip2",
"(",
"filename",
")",
":",
"log",
".",
"debug",
"(",
"\"Uncompressing %s\"",
",",
"filename",
")",
"tmpfile",
"=",
"\"%s.tmp\"",
"%",
"filename",
"os",
".",
"rename",
"(",
"filename",
",",
"tmpfile",
")",
"b",
"=",
"bz2",
".",
"BZ2File"... | Uncompress `filename` in place | [
"Uncompress",
"filename",
"in",
"place"
] | train | https://github.com/mozilla-releng/signtool/blob/0a778778a181cb9cab424b29fa104b70345f53c2/signtool/util/archives.py#L86-L102 |
mozilla-releng/signtool | signtool/util/archives.py | unpackmar | def unpackmar(marfile, destdir):
"""Unpack marfile into destdir"""
marfile = cygpath(os.path.abspath(marfile))
nullfd = open(os.devnull, "w")
try:
check_call([MAR, '-x', marfile], cwd=destdir,
stdout=nullfd, preexec_fn=_noumask)
except Exception:
log.exception("Error unpacking mar file %s to %s", marfile, destdir)
raise
nullfd.close() | python | def unpackmar(marfile, destdir):
"""Unpack marfile into destdir"""
marfile = cygpath(os.path.abspath(marfile))
nullfd = open(os.devnull, "w")
try:
check_call([MAR, '-x', marfile], cwd=destdir,
stdout=nullfd, preexec_fn=_noumask)
except Exception:
log.exception("Error unpacking mar file %s to %s", marfile, destdir)
raise
nullfd.close() | [
"def",
"unpackmar",
"(",
"marfile",
",",
"destdir",
")",
":",
"marfile",
"=",
"cygpath",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"marfile",
")",
")",
"nullfd",
"=",
"open",
"(",
"os",
".",
"devnull",
",",
"\"w\"",
")",
"try",
":",
"check_call",
... | Unpack marfile into destdir | [
"Unpack",
"marfile",
"into",
"destdir"
] | train | https://github.com/mozilla-releng/signtool/blob/0a778778a181cb9cab424b29fa104b70345f53c2/signtool/util/archives.py#L124-L134 |
mozilla-releng/signtool | signtool/util/archives.py | packmar | def packmar(marfile, srcdir):
"""Create marfile from the contents of srcdir"""
nullfd = open(os.devnull, "w")
files = [f[len(srcdir) + 1:] for f in findfiles(srcdir)]
marfile = cygpath(os.path.abspath(marfile))
try:
check_call(
[MAR, '-c', marfile] + files, cwd=srcdir, preexec_fn=_noumask)
except Exception:
log.exception("Error packing mar file %s from %s", marfile, srcdir)
raise
nullfd.close() | python | def packmar(marfile, srcdir):
"""Create marfile from the contents of srcdir"""
nullfd = open(os.devnull, "w")
files = [f[len(srcdir) + 1:] for f in findfiles(srcdir)]
marfile = cygpath(os.path.abspath(marfile))
try:
check_call(
[MAR, '-c', marfile] + files, cwd=srcdir, preexec_fn=_noumask)
except Exception:
log.exception("Error packing mar file %s from %s", marfile, srcdir)
raise
nullfd.close() | [
"def",
"packmar",
"(",
"marfile",
",",
"srcdir",
")",
":",
"nullfd",
"=",
"open",
"(",
"os",
".",
"devnull",
",",
"\"w\"",
")",
"files",
"=",
"[",
"f",
"[",
"len",
"(",
"srcdir",
")",
"+",
"1",
":",
"]",
"for",
"f",
"in",
"findfiles",
"(",
"src... | Create marfile from the contents of srcdir | [
"Create",
"marfile",
"from",
"the",
"contents",
"of",
"srcdir"
] | train | https://github.com/mozilla-releng/signtool/blob/0a778778a181cb9cab424b29fa104b70345f53c2/signtool/util/archives.py#L137-L148 |
mozilla-releng/signtool | signtool/util/archives.py | unpacktar | def unpacktar(tarfile, destdir):
""" Unpack given tarball into the specified dir """
nullfd = open(os.devnull, "w")
tarfile = cygpath(os.path.abspath(tarfile))
log.debug("unpack tar %s into %s", tarfile, destdir)
try:
check_call([TAR, '-xzf', tarfile], cwd=destdir,
stdout=nullfd, preexec_fn=_noumask)
except Exception:
log.exception("Error unpacking tar file %s to %s", tarfile, destdir)
raise
nullfd.close() | python | def unpacktar(tarfile, destdir):
""" Unpack given tarball into the specified dir """
nullfd = open(os.devnull, "w")
tarfile = cygpath(os.path.abspath(tarfile))
log.debug("unpack tar %s into %s", tarfile, destdir)
try:
check_call([TAR, '-xzf', tarfile], cwd=destdir,
stdout=nullfd, preexec_fn=_noumask)
except Exception:
log.exception("Error unpacking tar file %s to %s", tarfile, destdir)
raise
nullfd.close() | [
"def",
"unpacktar",
"(",
"tarfile",
",",
"destdir",
")",
":",
"nullfd",
"=",
"open",
"(",
"os",
".",
"devnull",
",",
"\"w\"",
")",
"tarfile",
"=",
"cygpath",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"tarfile",
")",
")",
"log",
".",
"debug",
"("... | Unpack given tarball into the specified dir | [
"Unpack",
"given",
"tarball",
"into",
"the",
"specified",
"dir"
] | train | https://github.com/mozilla-releng/signtool/blob/0a778778a181cb9cab424b29fa104b70345f53c2/signtool/util/archives.py#L151-L162 |
mozilla-releng/signtool | signtool/util/archives.py | tar_dir | def tar_dir(tarfile, srcdir):
""" Pack a tar file using all the files in the given srcdir """
files = os.listdir(srcdir)
packtar(tarfile, files, srcdir) | python | def tar_dir(tarfile, srcdir):
""" Pack a tar file using all the files in the given srcdir """
files = os.listdir(srcdir)
packtar(tarfile, files, srcdir) | [
"def",
"tar_dir",
"(",
"tarfile",
",",
"srcdir",
")",
":",
"files",
"=",
"os",
".",
"listdir",
"(",
"srcdir",
")",
"packtar",
"(",
"tarfile",
",",
"files",
",",
"srcdir",
")"
] | Pack a tar file using all the files in the given srcdir | [
"Pack",
"a",
"tar",
"file",
"using",
"all",
"the",
"files",
"in",
"the",
"given",
"srcdir"
] | train | https://github.com/mozilla-releng/signtool/blob/0a778778a181cb9cab424b29fa104b70345f53c2/signtool/util/archives.py#L165-L168 |
mozilla-releng/signtool | signtool/util/archives.py | packtar | def packtar(tarfile, files, srcdir):
""" Pack the given files into a tar, setting cwd = srcdir"""
nullfd = open(os.devnull, "w")
tarfile = cygpath(os.path.abspath(tarfile))
log.debug("pack tar %s from folder %s with files ", tarfile, srcdir)
log.debug(files)
try:
check_call([TAR, '-czf', tarfile] + files, cwd=srcdir,
stdout=nullfd, preexec_fn=_noumask)
except Exception:
log.exception("Error packing tar file %s to %s", tarfile, srcdir)
raise
nullfd.close() | python | def packtar(tarfile, files, srcdir):
""" Pack the given files into a tar, setting cwd = srcdir"""
nullfd = open(os.devnull, "w")
tarfile = cygpath(os.path.abspath(tarfile))
log.debug("pack tar %s from folder %s with files ", tarfile, srcdir)
log.debug(files)
try:
check_call([TAR, '-czf', tarfile] + files, cwd=srcdir,
stdout=nullfd, preexec_fn=_noumask)
except Exception:
log.exception("Error packing tar file %s to %s", tarfile, srcdir)
raise
nullfd.close() | [
"def",
"packtar",
"(",
"tarfile",
",",
"files",
",",
"srcdir",
")",
":",
"nullfd",
"=",
"open",
"(",
"os",
".",
"devnull",
",",
"\"w\"",
")",
"tarfile",
"=",
"cygpath",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"tarfile",
")",
")",
"log",
".",
... | Pack the given files into a tar, setting cwd = srcdir | [
"Pack",
"the",
"given",
"files",
"into",
"a",
"tar",
"setting",
"cwd",
"=",
"srcdir"
] | train | https://github.com/mozilla-releng/signtool/blob/0a778778a181cb9cab424b29fa104b70345f53c2/signtool/util/archives.py#L171-L183 |
mozilla-releng/signtool | signtool/util/archives.py | unpackfile | def unpackfile(filename, destdir):
"""Unpack a mar or exe into destdir"""
if filename.endswith(".mar"):
return unpackmar(filename, destdir)
elif filename.endswith(".exe"):
return unpackexe(filename, destdir)
elif filename.endswith(".tar") or filename.endswith(".tar.gz") \
or filename.endswith(".tgz"):
return unpacktar(filename, destdir)
else:
raise ValueError("Unknown file type: %s" % filename) | python | def unpackfile(filename, destdir):
"""Unpack a mar or exe into destdir"""
if filename.endswith(".mar"):
return unpackmar(filename, destdir)
elif filename.endswith(".exe"):
return unpackexe(filename, destdir)
elif filename.endswith(".tar") or filename.endswith(".tar.gz") \
or filename.endswith(".tgz"):
return unpacktar(filename, destdir)
else:
raise ValueError("Unknown file type: %s" % filename) | [
"def",
"unpackfile",
"(",
"filename",
",",
"destdir",
")",
":",
"if",
"filename",
".",
"endswith",
"(",
"\".mar\"",
")",
":",
"return",
"unpackmar",
"(",
"filename",
",",
"destdir",
")",
"elif",
"filename",
".",
"endswith",
"(",
"\".exe\"",
")",
":",
"re... | Unpack a mar or exe into destdir | [
"Unpack",
"a",
"mar",
"or",
"exe",
"into",
"destdir"
] | train | https://github.com/mozilla-releng/signtool/blob/0a778778a181cb9cab424b29fa104b70345f53c2/signtool/util/archives.py#L186-L196 |
mozilla-releng/signtool | signtool/util/archives.py | packfile | def packfile(filename, srcdir):
"""Package up srcdir into filename, archived with 7z for exes or mar for
mar files"""
if filename.endswith(".mar"):
return packmar(filename, srcdir)
elif filename.endswith(".exe"):
return packexe(filename, srcdir)
elif filename.endswith(".tar"):
return tar_dir(filename, srcdir)
else:
raise ValueError("Unknown file type: %s" % filename) | python | def packfile(filename, srcdir):
"""Package up srcdir into filename, archived with 7z for exes or mar for
mar files"""
if filename.endswith(".mar"):
return packmar(filename, srcdir)
elif filename.endswith(".exe"):
return packexe(filename, srcdir)
elif filename.endswith(".tar"):
return tar_dir(filename, srcdir)
else:
raise ValueError("Unknown file type: %s" % filename) | [
"def",
"packfile",
"(",
"filename",
",",
"srcdir",
")",
":",
"if",
"filename",
".",
"endswith",
"(",
"\".mar\"",
")",
":",
"return",
"packmar",
"(",
"filename",
",",
"srcdir",
")",
"elif",
"filename",
".",
"endswith",
"(",
"\".exe\"",
")",
":",
"return",... | Package up srcdir into filename, archived with 7z for exes or mar for
mar files | [
"Package",
"up",
"srcdir",
"into",
"filename",
"archived",
"with",
"7z",
"for",
"exes",
"or",
"mar",
"for",
"mar",
"files"
] | train | https://github.com/mozilla-releng/signtool/blob/0a778778a181cb9cab424b29fa104b70345f53c2/signtool/util/archives.py#L199-L209 |
twisted/mantissa | xmantissa/webapp.py | _reorderForPreference | def _reorderForPreference(themeList, preferredThemeName):
"""
Re-order the input themeList according to the preferred theme.
Returns None.
"""
for theme in themeList:
if preferredThemeName == theme.themeName:
themeList.remove(theme)
themeList.insert(0, theme)
return | python | def _reorderForPreference(themeList, preferredThemeName):
"""
Re-order the input themeList according to the preferred theme.
Returns None.
"""
for theme in themeList:
if preferredThemeName == theme.themeName:
themeList.remove(theme)
themeList.insert(0, theme)
return | [
"def",
"_reorderForPreference",
"(",
"themeList",
",",
"preferredThemeName",
")",
":",
"for",
"theme",
"in",
"themeList",
":",
"if",
"preferredThemeName",
"==",
"theme",
".",
"themeName",
":",
"themeList",
".",
"remove",
"(",
"theme",
")",
"themeList",
".",
"i... | Re-order the input themeList according to the preferred theme.
Returns None. | [
"Re",
"-",
"order",
"the",
"input",
"themeList",
"according",
"to",
"the",
"preferred",
"theme",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/webapp.py#L50-L60 |
twisted/mantissa | xmantissa/webapp.py | upgradePrivateApplication3to4 | def upgradePrivateApplication3to4(old):
"""
Upgrade L{PrivateApplication} from schema version 3 to schema version 4.
Copy all existing attributes to the new version and use the
L{PrivateApplication} to power up the item it is installed on for
L{ITemplateNameResolver}.
"""
new = old.upgradeVersion(
PrivateApplication.typeName, 3, 4,
preferredTheme=old.preferredTheme,
privateKey=old.privateKey,
website=old.website,
customizedPublicPage=old.customizedPublicPage,
authenticationApplication=old.authenticationApplication,
preferenceAggregator=old.preferenceAggregator,
defaultPreferenceCollection=old.defaultPreferenceCollection,
searchAggregator=old.searchAggregator)
# Almost certainly this would be more correctly expressed as
# installedOn(new).powerUp(...), however the 2 to 3 upgrader failed to
# translate the installedOn attribute to state which installedOn can
# recognize, consequently installedOn(new) will return None for an item
# which was created at schema version 2 or earlier. It's not worth dealing
# with this inconsistency, since PrivateApplication is always only
# installed on its store. -exarkun
new.store.powerUp(new, ITemplateNameResolver)
return new | python | def upgradePrivateApplication3to4(old):
"""
Upgrade L{PrivateApplication} from schema version 3 to schema version 4.
Copy all existing attributes to the new version and use the
L{PrivateApplication} to power up the item it is installed on for
L{ITemplateNameResolver}.
"""
new = old.upgradeVersion(
PrivateApplication.typeName, 3, 4,
preferredTheme=old.preferredTheme,
privateKey=old.privateKey,
website=old.website,
customizedPublicPage=old.customizedPublicPage,
authenticationApplication=old.authenticationApplication,
preferenceAggregator=old.preferenceAggregator,
defaultPreferenceCollection=old.defaultPreferenceCollection,
searchAggregator=old.searchAggregator)
# Almost certainly this would be more correctly expressed as
# installedOn(new).powerUp(...), however the 2 to 3 upgrader failed to
# translate the installedOn attribute to state which installedOn can
# recognize, consequently installedOn(new) will return None for an item
# which was created at schema version 2 or earlier. It's not worth dealing
# with this inconsistency, since PrivateApplication is always only
# installed on its store. -exarkun
new.store.powerUp(new, ITemplateNameResolver)
return new | [
"def",
"upgradePrivateApplication3to4",
"(",
"old",
")",
":",
"new",
"=",
"old",
".",
"upgradeVersion",
"(",
"PrivateApplication",
".",
"typeName",
",",
"3",
",",
"4",
",",
"preferredTheme",
"=",
"old",
".",
"preferredTheme",
",",
"privateKey",
"=",
"old",
"... | Upgrade L{PrivateApplication} from schema version 3 to schema version 4.
Copy all existing attributes to the new version and use the
L{PrivateApplication} to power up the item it is installed on for
L{ITemplateNameResolver}. | [
"Upgrade",
"L",
"{",
"PrivateApplication",
"}",
"from",
"schema",
"version",
"3",
"to",
"schema",
"version",
"4",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/webapp.py#L666-L692 |
twisted/mantissa | xmantissa/webapp.py | upgradePrivateApplication4to5 | def upgradePrivateApplication4to5(old):
"""
Install the newly required powerup.
"""
new = old.upgradeVersion(
PrivateApplication.typeName, 4, 5,
preferredTheme=old.preferredTheme,
privateKey=old.privateKey,
website=old.website,
customizedPublicPage=old.customizedPublicPage,
authenticationApplication=old.authenticationApplication,
preferenceAggregator=old.preferenceAggregator,
defaultPreferenceCollection=old.defaultPreferenceCollection,
searchAggregator=old.searchAggregator)
new.store.powerUp(new, IWebViewer)
return new | python | def upgradePrivateApplication4to5(old):
"""
Install the newly required powerup.
"""
new = old.upgradeVersion(
PrivateApplication.typeName, 4, 5,
preferredTheme=old.preferredTheme,
privateKey=old.privateKey,
website=old.website,
customizedPublicPage=old.customizedPublicPage,
authenticationApplication=old.authenticationApplication,
preferenceAggregator=old.preferenceAggregator,
defaultPreferenceCollection=old.defaultPreferenceCollection,
searchAggregator=old.searchAggregator)
new.store.powerUp(new, IWebViewer)
return new | [
"def",
"upgradePrivateApplication4to5",
"(",
"old",
")",
":",
"new",
"=",
"old",
".",
"upgradeVersion",
"(",
"PrivateApplication",
".",
"typeName",
",",
"4",
",",
"5",
",",
"preferredTheme",
"=",
"old",
".",
"preferredTheme",
",",
"privateKey",
"=",
"old",
"... | Install the newly required powerup. | [
"Install",
"the",
"newly",
"required",
"powerup",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/webapp.py#L709-L724 |
twisted/mantissa | xmantissa/webapp.py | _AuthenticatedWebViewer._wrapNavFrag | def _wrapNavFrag(self, frag, useAthena):
"""
Wrap the given L{INavigableFragment} in an appropriate
L{_FragmentWrapperMixin} subclass.
"""
username = self._privateApplication._getUsername()
cf = getattr(frag, 'customizeFor', None)
if cf is not None:
frag = cf(username)
if useAthena:
pageClass = GenericNavigationAthenaPage
else:
pageClass = GenericNavigationPage
return pageClass(self._privateApplication, frag,
self._privateApplication.getPageComponents(),
username) | python | def _wrapNavFrag(self, frag, useAthena):
"""
Wrap the given L{INavigableFragment} in an appropriate
L{_FragmentWrapperMixin} subclass.
"""
username = self._privateApplication._getUsername()
cf = getattr(frag, 'customizeFor', None)
if cf is not None:
frag = cf(username)
if useAthena:
pageClass = GenericNavigationAthenaPage
else:
pageClass = GenericNavigationPage
return pageClass(self._privateApplication, frag,
self._privateApplication.getPageComponents(),
username) | [
"def",
"_wrapNavFrag",
"(",
"self",
",",
"frag",
",",
"useAthena",
")",
":",
"username",
"=",
"self",
".",
"_privateApplication",
".",
"_getUsername",
"(",
")",
"cf",
"=",
"getattr",
"(",
"frag",
",",
"'customizeFor'",
",",
"None",
")",
"if",
"cf",
"is",... | Wrap the given L{INavigableFragment} in an appropriate
L{_FragmentWrapperMixin} subclass. | [
"Wrap",
"the",
"given",
"L",
"{",
"INavigableFragment",
"}",
"in",
"an",
"appropriate",
"L",
"{",
"_FragmentWrapperMixin",
"}",
"subclass",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/webapp.py#L98-L113 |
twisted/mantissa | xmantissa/webapp.py | _ShellRenderingMixin.render_rootURL | def render_rootURL(self, ctx, data):
"""
Add the WebSite's root URL as a child of the given tag.
The root URL is the location of the resource beneath which all standard
Mantissa resources (such as the private application and static content)
is available. This can be important if a page is to be served at a
location which is different from the root URL in order to make links in
static XHTML templates resolve correctly (for example, by adding this
value as the href of a <base> tag).
"""
site = ISiteURLGenerator(self._siteStore())
return ctx.tag[site.rootURL(IRequest(ctx))] | python | def render_rootURL(self, ctx, data):
"""
Add the WebSite's root URL as a child of the given tag.
The root URL is the location of the resource beneath which all standard
Mantissa resources (such as the private application and static content)
is available. This can be important if a page is to be served at a
location which is different from the root URL in order to make links in
static XHTML templates resolve correctly (for example, by adding this
value as the href of a <base> tag).
"""
site = ISiteURLGenerator(self._siteStore())
return ctx.tag[site.rootURL(IRequest(ctx))] | [
"def",
"render_rootURL",
"(",
"self",
",",
"ctx",
",",
"data",
")",
":",
"site",
"=",
"ISiteURLGenerator",
"(",
"self",
".",
"_siteStore",
"(",
")",
")",
"return",
"ctx",
".",
"tag",
"[",
"site",
".",
"rootURL",
"(",
"IRequest",
"(",
"ctx",
")",
")",... | Add the WebSite's root URL as a child of the given tag.
The root URL is the location of the resource beneath which all standard
Mantissa resources (such as the private application and static content)
is available. This can be important if a page is to be served at a
location which is different from the root URL in order to make links in
static XHTML templates resolve correctly (for example, by adding this
value as the href of a <base> tag). | [
"Add",
"the",
"WebSite",
"s",
"root",
"URL",
"as",
"a",
"child",
"of",
"the",
"given",
"tag",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/webapp.py#L167-L179 |
twisted/mantissa | xmantissa/webapp.py | _ShellRenderingMixin.render_startmenu | def render_startmenu(self, ctx, data):
"""
Add start-menu style navigation to the given tag.
@see {xmantissa.webnav.startMenu}
"""
return startMenu(
self.translator, self.pageComponents.navigation, ctx.tag) | python | def render_startmenu(self, ctx, data):
"""
Add start-menu style navigation to the given tag.
@see {xmantissa.webnav.startMenu}
"""
return startMenu(
self.translator, self.pageComponents.navigation, ctx.tag) | [
"def",
"render_startmenu",
"(",
"self",
",",
"ctx",
",",
"data",
")",
":",
"return",
"startMenu",
"(",
"self",
".",
"translator",
",",
"self",
".",
"pageComponents",
".",
"navigation",
",",
"ctx",
".",
"tag",
")"
] | Add start-menu style navigation to the given tag.
@see {xmantissa.webnav.startMenu} | [
"Add",
"start",
"-",
"menu",
"style",
"navigation",
"to",
"the",
"given",
"tag",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/webapp.py#L196-L203 |
twisted/mantissa | xmantissa/webapp.py | _ShellRenderingMixin.render_settingsLink | def render_settingsLink(self, ctx, data):
"""
Add the URL of the settings page to the given tag.
@see L{xmantissa.webnav.settingsLink}
"""
return settingsLink(
self.translator, self.pageComponents.settings, ctx.tag) | python | def render_settingsLink(self, ctx, data):
"""
Add the URL of the settings page to the given tag.
@see L{xmantissa.webnav.settingsLink}
"""
return settingsLink(
self.translator, self.pageComponents.settings, ctx.tag) | [
"def",
"render_settingsLink",
"(",
"self",
",",
"ctx",
",",
"data",
")",
":",
"return",
"settingsLink",
"(",
"self",
".",
"translator",
",",
"self",
".",
"pageComponents",
".",
"settings",
",",
"ctx",
".",
"tag",
")"
] | Add the URL of the settings page to the given tag.
@see L{xmantissa.webnav.settingsLink} | [
"Add",
"the",
"URL",
"of",
"the",
"settings",
"page",
"to",
"the",
"given",
"tag",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/webapp.py#L206-L213 |
twisted/mantissa | xmantissa/webapp.py | _ShellRenderingMixin.render_applicationNavigation | def render_applicationNavigation(self, ctx, data):
"""
Add primary application navigation to the given tag.
@see L{xmantissa.webnav.applicationNavigation}
"""
return applicationNavigation(
ctx, self.translator, self.pageComponents.navigation) | python | def render_applicationNavigation(self, ctx, data):
"""
Add primary application navigation to the given tag.
@see L{xmantissa.webnav.applicationNavigation}
"""
return applicationNavigation(
ctx, self.translator, self.pageComponents.navigation) | [
"def",
"render_applicationNavigation",
"(",
"self",
",",
"ctx",
",",
"data",
")",
":",
"return",
"applicationNavigation",
"(",
"ctx",
",",
"self",
".",
"translator",
",",
"self",
".",
"pageComponents",
".",
"navigation",
")"
] | Add primary application navigation to the given tag.
@see L{xmantissa.webnav.applicationNavigation} | [
"Add",
"primary",
"application",
"navigation",
"to",
"the",
"given",
"tag",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/webapp.py#L216-L223 |
twisted/mantissa | xmantissa/webapp.py | _ShellRenderingMixin.render_urchin | def render_urchin(self, ctx, data):
"""
Render the code for recording Google Analytics statistics, if so
configured.
"""
key = APIKey.getKeyForAPI(self._siteStore(), APIKey.URCHIN)
if key is None:
return ''
return ctx.tag.fillSlots('urchin-key', key.apiKey) | python | def render_urchin(self, ctx, data):
"""
Render the code for recording Google Analytics statistics, if so
configured.
"""
key = APIKey.getKeyForAPI(self._siteStore(), APIKey.URCHIN)
if key is None:
return ''
return ctx.tag.fillSlots('urchin-key', key.apiKey) | [
"def",
"render_urchin",
"(",
"self",
",",
"ctx",
",",
"data",
")",
":",
"key",
"=",
"APIKey",
".",
"getKeyForAPI",
"(",
"self",
".",
"_siteStore",
"(",
")",
",",
"APIKey",
".",
"URCHIN",
")",
"if",
"key",
"is",
"None",
":",
"return",
"''",
"return",
... | Render the code for recording Google Analytics statistics, if so
configured. | [
"Render",
"the",
"code",
"for",
"recording",
"Google",
"Analytics",
"statistics",
"if",
"so",
"configured",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/webapp.py#L226-L234 |
twisted/mantissa | xmantissa/webapp.py | GenericNavigationAthenaPage.beforeRender | def beforeRender(self, ctx):
"""
Call the C{beforeRender} implementations on L{MantissaLivePage} and
L{_FragmentWrapperMixin}.
"""
MantissaLivePage.beforeRender(self, ctx)
return _FragmentWrapperMixin.beforeRender(self, ctx) | python | def beforeRender(self, ctx):
"""
Call the C{beforeRender} implementations on L{MantissaLivePage} and
L{_FragmentWrapperMixin}.
"""
MantissaLivePage.beforeRender(self, ctx)
return _FragmentWrapperMixin.beforeRender(self, ctx) | [
"def",
"beforeRender",
"(",
"self",
",",
"ctx",
")",
":",
"MantissaLivePage",
".",
"beforeRender",
"(",
"self",
",",
"ctx",
")",
"return",
"_FragmentWrapperMixin",
".",
"beforeRender",
"(",
"self",
",",
"ctx",
")"
] | Call the C{beforeRender} implementations on L{MantissaLivePage} and
L{_FragmentWrapperMixin}. | [
"Call",
"the",
"C",
"{",
"beforeRender",
"}",
"implementations",
"on",
"L",
"{",
"MantissaLivePage",
"}",
"and",
"L",
"{",
"_FragmentWrapperMixin",
"}",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/webapp.py#L372-L378 |
twisted/mantissa | xmantissa/webapp.py | _PrivateRootPage.childFactory | def childFactory(self, ctx, name):
"""
Return a shell page wrapped around the Item model described by the
webID, or return None if no such item can be found.
"""
try:
o = self.webapp.fromWebID(name)
except _WebIDFormatException:
return None
if o is None:
return None
return self.webViewer.wrapModel(o) | python | def childFactory(self, ctx, name):
"""
Return a shell page wrapped around the Item model described by the
webID, or return None if no such item can be found.
"""
try:
o = self.webapp.fromWebID(name)
except _WebIDFormatException:
return None
if o is None:
return None
return self.webViewer.wrapModel(o) | [
"def",
"childFactory",
"(",
"self",
",",
"ctx",
",",
"name",
")",
":",
"try",
":",
"o",
"=",
"self",
".",
"webapp",
".",
"fromWebID",
"(",
"name",
")",
"except",
"_WebIDFormatException",
":",
"return",
"None",
"if",
"o",
"is",
"None",
":",
"return",
... | Return a shell page wrapped around the Item model described by the
webID, or return None if no such item can be found. | [
"Return",
"a",
"shell",
"page",
"wrapped",
"around",
"the",
"Item",
"model",
"described",
"by",
"the",
"webID",
"or",
"return",
"None",
"if",
"no",
"such",
"item",
"can",
"be",
"found",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/webapp.py#L431-L442 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.