repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
3 values
summary
stringlengths
4
350
heigeo/climata
climata/acis/__init__.py
StationMetaIO.map_value
def map_value(self, field, value): """ Clean up some values returned from the web service. (overrides wq.io.mappers.BaseMapper) """ if field == 'sids': # Site identifiers are returned as "[id] [auth_id]"; # Map to auth name for easier usability ...
python
def map_value(self, field, value): """ Clean up some values returned from the web service. (overrides wq.io.mappers.BaseMapper) """ if field == 'sids': # Site identifiers are returned as "[id] [auth_id]"; # Map to auth name for easier usability ...
[ "def", "map_value", "(", "self", ",", "field", ",", "value", ")", ":", "if", "field", "==", "'sids'", ":", "# Site identifiers are returned as \"[id] [auth_id]\";", "# Map to auth name for easier usability", "ids", "=", "{", "}", "for", "idinfo", "in", "value", ":",...
Clean up some values returned from the web service. (overrides wq.io.mappers.BaseMapper)
[ "Clean", "up", "some", "values", "returned", "from", "the", "web", "service", ".", "(", "overrides", "wq", ".", "io", ".", "mappers", ".", "BaseMapper", ")" ]
2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd
https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/acis/__init__.py#L95-L124
train
Map the value of a resource field to a dictionary of values.
heigeo/climata
climata/acis/__init__.py
StationDataIO.get_field_names
def get_field_names(self): """ ACIS web service returns "meta" and "data" for each station; Use meta attributes as field names """ field_names = super(StationDataIO, self).get_field_names() if set(field_names) == set(['meta', 'data']): meta_fields = list(self....
python
def get_field_names(self): """ ACIS web service returns "meta" and "data" for each station; Use meta attributes as field names """ field_names = super(StationDataIO, self).get_field_names() if set(field_names) == set(['meta', 'data']): meta_fields = list(self....
[ "def", "get_field_names", "(", "self", ")", ":", "field_names", "=", "super", "(", "StationDataIO", ",", "self", ")", ".", "get_field_names", "(", ")", "if", "set", "(", "field_names", ")", "==", "set", "(", "[", "'meta'", ",", "'data'", "]", ")", ":",...
ACIS web service returns "meta" and "data" for each station; Use meta attributes as field names
[ "ACIS", "web", "service", "returns", "meta", "and", "data", "for", "each", "station", ";", "Use", "meta", "attributes", "as", "field", "names" ]
2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd
https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/acis/__init__.py#L147-L158
train
Return the list of fields that are used for each station in the data IO.
heigeo/climata
climata/acis/__init__.py
StationDataIO.usable_item
def usable_item(self, data): """ ACIS web service returns "meta" and "data" for each station; use meta attributes as item values, and add an IO for iterating over "data" """ # Use metadata as item item = data['meta'] # Add nested IO for data elems, elems...
python
def usable_item(self, data): """ ACIS web service returns "meta" and "data" for each station; use meta attributes as item values, and add an IO for iterating over "data" """ # Use metadata as item item = data['meta'] # Add nested IO for data elems, elems...
[ "def", "usable_item", "(", "self", ",", "data", ")", ":", "# Use metadata as item", "item", "=", "data", "[", "'meta'", "]", "# Add nested IO for data", "elems", ",", "elems_is_complex", "=", "self", ".", "getlist", "(", "'parameter'", ")", "if", "elems_is_compl...
ACIS web service returns "meta" and "data" for each station; use meta attributes as item values, and add an IO for iterating over "data"
[ "ACIS", "web", "service", "returns", "meta", "and", "data", "for", "each", "station", ";", "use", "meta", "attributes", "as", "item", "values", "and", "add", "an", "IO", "for", "iterating", "over", "data" ]
2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd
https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/acis/__init__.py#L175-L199
train
Use meta and data attributes as item values and add nested IOs for iterating over data
heigeo/climata
climata/acis/__init__.py
DataIO.load_data
def load_data(self, data): """ MultiStnData data results are arrays without explicit dates; Infer time series based on start date. """ dates = fill_date_range(self.start_date, self.end_date) for row, date in zip(data, dates): data = {'date': date} ...
python
def load_data(self, data): """ MultiStnData data results are arrays without explicit dates; Infer time series based on start date. """ dates = fill_date_range(self.start_date, self.end_date) for row, date in zip(data, dates): data = {'date': date} ...
[ "def", "load_data", "(", "self", ",", "data", ")", ":", "dates", "=", "fill_date_range", "(", "self", ".", "start_date", ",", "self", ".", "end_date", ")", "for", "row", ",", "date", "in", "zip", "(", "data", ",", "dates", ")", ":", "data", "=", "{...
MultiStnData data results are arrays without explicit dates; Infer time series based on start date.
[ "MultiStnData", "data", "results", "are", "arrays", "without", "explicit", "dates", ";", "Infer", "time", "series", "based", "on", "start", "date", "." ]
2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd
https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/acis/__init__.py#L216-L243
train
Load MultiStnData data from a list of dictionaries.
heigeo/climata
climata/acis/__init__.py
DataIO.get_field_names
def get_field_names(self): """ Different field names depending on self.add setting (see load_data) For BaseIO """ if self.add: return ['date', 'elem', 'value'] + [flag for flag in self.add] else: field_names = ['date'] for elem in self....
python
def get_field_names(self): """ Different field names depending on self.add setting (see load_data) For BaseIO """ if self.add: return ['date', 'elem', 'value'] + [flag for flag in self.add] else: field_names = ['date'] for elem in self....
[ "def", "get_field_names", "(", "self", ")", ":", "if", "self", ".", "add", ":", "return", "[", "'date'", ",", "'elem'", ",", "'value'", "]", "+", "[", "flag", "for", "flag", "in", "self", ".", "add", "]", "else", ":", "field_names", "=", "[", "'dat...
Different field names depending on self.add setting (see load_data) For BaseIO
[ "Different", "field", "names", "depending", "on", "self", ".", "add", "setting", "(", "see", "load_data", ")", "For", "BaseIO" ]
2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd
https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/acis/__init__.py#L250-L264
train
Returns a list of field names depending on self. add setting.
heigeo/climata
climata/base.py
fill_date_range
def fill_date_range(start_date, end_date, date_format=None): """ Function accepts start date, end date, and format (if dates are strings) and returns a list of Python dates. """ if date_format: start_date = datetime.strptime(start_date, date_format).date() end_date = datetime.strpti...
python
def fill_date_range(start_date, end_date, date_format=None): """ Function accepts start date, end date, and format (if dates are strings) and returns a list of Python dates. """ if date_format: start_date = datetime.strptime(start_date, date_format).date() end_date = datetime.strpti...
[ "def", "fill_date_range", "(", "start_date", ",", "end_date", ",", "date_format", "=", "None", ")", ":", "if", "date_format", ":", "start_date", "=", "datetime", ".", "strptime", "(", "start_date", ",", "date_format", ")", ".", "date", "(", ")", "end_date", ...
Function accepts start date, end date, and format (if dates are strings) and returns a list of Python dates.
[ "Function", "accepts", "start", "date", "end", "date", "and", "format", "(", "if", "dates", "are", "strings", ")", "and", "returns", "a", "list", "of", "Python", "dates", "." ]
2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd
https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/base.py#L252-L265
train
Function fills the date_list with the dates in the given date range.
heigeo/climata
climata/base.py
FilterOpt.parse
def parse(self, value): """ Enforce rules and return parsed value """ if self.required and value is None: raise ValueError("%s is required!" % self.name) elif self.ignored and value is not None: warn("%s is ignored for this class!" % self.name) eli...
python
def parse(self, value): """ Enforce rules and return parsed value """ if self.required and value is None: raise ValueError("%s is required!" % self.name) elif self.ignored and value is not None: warn("%s is ignored for this class!" % self.name) eli...
[ "def", "parse", "(", "self", ",", "value", ")", ":", "if", "self", ".", "required", "and", "value", "is", "None", ":", "raise", "ValueError", "(", "\"%s is required!\"", "%", "self", ".", "name", ")", "elif", "self", ".", "ignored", "and", "value", "is...
Enforce rules and return parsed value
[ "Enforce", "rules", "and", "return", "parsed", "value" ]
2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd
https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/base.py#L32-L49
train
Enforces rules and return parsed value
heigeo/climata
climata/base.py
DateOpt.parse
def parse(self, value): """ Parse date """ value = super(DateOpt, self).parse(value) if value is None: return None if isinstance(value, str): value = self.parse_date(value) if isinstance(value, datetime) and self.date_only: valu...
python
def parse(self, value): """ Parse date """ value = super(DateOpt, self).parse(value) if value is None: return None if isinstance(value, str): value = self.parse_date(value) if isinstance(value, datetime) and self.date_only: valu...
[ "def", "parse", "(", "self", ",", "value", ")", ":", "value", "=", "super", "(", "DateOpt", ",", "self", ")", ".", "parse", "(", "value", ")", "if", "value", "is", "None", ":", "return", "None", "if", "isinstance", "(", "value", ",", "str", ")", ...
Parse date
[ "Parse", "date" ]
2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd
https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/base.py#L58-L69
train
Parse value into a base - 10 value.
heigeo/climata
climata/base.py
WebserviceLoader.get_filter_options
def get_filter_options(cls): """ List all filter options defined on class (and superclasses) """ attr = '_filter_options_%s' % id(cls) options = getattr(cls, attr, {}) if options: return options for key in dir(cls): val = getattr(cls, key...
python
def get_filter_options(cls): """ List all filter options defined on class (and superclasses) """ attr = '_filter_options_%s' % id(cls) options = getattr(cls, attr, {}) if options: return options for key in dir(cls): val = getattr(cls, key...
[ "def", "get_filter_options", "(", "cls", ")", ":", "attr", "=", "'_filter_options_%s'", "%", "id", "(", "cls", ")", "options", "=", "getattr", "(", "cls", ",", "attr", ",", "{", "}", ")", "if", "options", ":", "return", "options", "for", "key", "in", ...
List all filter options defined on class (and superclasses)
[ "List", "all", "filter", "options", "defined", "on", "class", "(", "and", "superclasses", ")" ]
2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd
https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/base.py#L135-L151
train
Get all filter options defined on class and superclasses.
heigeo/climata
climata/base.py
WebserviceLoader.getlist
def getlist(self, name): """ Retrieve given property from class/instance, ensuring it is a list. Also determine whether the list contains simple text/numeric values or nested dictionaries (a "complex" list) """ value = self.getvalue(name) complex = {} def...
python
def getlist(self, name): """ Retrieve given property from class/instance, ensuring it is a list. Also determine whether the list contains simple text/numeric values or nested dictionaries (a "complex" list) """ value = self.getvalue(name) complex = {} def...
[ "def", "getlist", "(", "self", ",", "name", ")", ":", "value", "=", "self", ".", "getvalue", "(", "name", ")", "complex", "=", "{", "}", "def", "str_value", "(", "val", ")", ":", "# TODO: nonlocal complex", "if", "isinstance", "(", "val", ",", "dict", ...
Retrieve given property from class/instance, ensuring it is a list. Also determine whether the list contains simple text/numeric values or nested dictionaries (a "complex" list)
[ "Retrieve", "given", "property", "from", "class", "/", "instance", "ensuring", "it", "is", "a", "list", ".", "Also", "determine", "whether", "the", "list", "contains", "simple", "text", "/", "numeric", "values", "or", "nested", "dictionaries", "(", "a", "com...
2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd
https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/base.py#L163-L185
train
Retrieve given property from class or instance ensuring it is a list.
heigeo/climata
climata/base.py
WebserviceLoader.set_param
def set_param(self, into, name): """ Set parameter key, noting whether list value is "complex" """ value, complex = self.getlist(name) if value is not None: into[name] = value return complex
python
def set_param(self, into, name): """ Set parameter key, noting whether list value is "complex" """ value, complex = self.getlist(name) if value is not None: into[name] = value return complex
[ "def", "set_param", "(", "self", ",", "into", ",", "name", ")", ":", "value", ",", "complex", "=", "self", ".", "getlist", "(", "name", ")", "if", "value", "is", "not", "None", ":", "into", "[", "name", "]", "=", "value", "return", "complex" ]
Set parameter key, noting whether list value is "complex"
[ "Set", "parameter", "key", "noting", "whether", "list", "value", "is", "complex" ]
2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd
https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/base.py#L187-L194
train
Set the value of a parameter in a dictionary into.
heigeo/climata
climata/base.py
WebserviceLoader.get_params
def get_params(self): """ Get parameters for web service, noting whether any are "complex" """ params = {} complex = False for name, opt in self.filter_options.items(): if opt.ignored: continue if self.set_param(params, name): ...
python
def get_params(self): """ Get parameters for web service, noting whether any are "complex" """ params = {} complex = False for name, opt in self.filter_options.items(): if opt.ignored: continue if self.set_param(params, name): ...
[ "def", "get_params", "(", "self", ")", ":", "params", "=", "{", "}", "complex", "=", "False", "for", "name", ",", "opt", "in", "self", ".", "filter_options", ".", "items", "(", ")", ":", "if", "opt", ".", "ignored", ":", "continue", "if", "self", "...
Get parameters for web service, noting whether any are "complex"
[ "Get", "parameters", "for", "web", "service", "noting", "whether", "any", "are", "complex" ]
2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd
https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/base.py#L196-L208
train
Get parameters for web service noting whether any are complex
heigeo/climata
climata/base.py
WebserviceLoader.params
def params(self): """ URL parameters for wq.io.loaders.NetLoader """ params, complex = self.get_params() url_params = self.default_params.copy() url_params.update(self.serialize_params(params, complex)) return url_params
python
def params(self): """ URL parameters for wq.io.loaders.NetLoader """ params, complex = self.get_params() url_params = self.default_params.copy() url_params.update(self.serialize_params(params, complex)) return url_params
[ "def", "params", "(", "self", ")", ":", "params", ",", "complex", "=", "self", ".", "get_params", "(", ")", "url_params", "=", "self", ".", "default_params", ".", "copy", "(", ")", "url_params", ".", "update", "(", "self", ".", "serialize_params", "(", ...
URL parameters for wq.io.loaders.NetLoader
[ "URL", "parameters", "for", "wq", ".", "io", ".", "loaders", ".", "NetLoader" ]
2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd
https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/base.py#L211-L218
train
Returns a dictionary of all parameters for this loader.
heigeo/climata
climata/base.py
WebserviceLoader.serialize_params
def serialize_params(self, params, complex=False): """ Serialize parameter names and values to a dict ready for urlencode() """ if complex: # See climata.acis for an example implementation raise NotImplementedError("Cannot serialize %s!" % params) else: ...
python
def serialize_params(self, params, complex=False): """ Serialize parameter names and values to a dict ready for urlencode() """ if complex: # See climata.acis for an example implementation raise NotImplementedError("Cannot serialize %s!" % params) else: ...
[ "def", "serialize_params", "(", "self", ",", "params", ",", "complex", "=", "False", ")", ":", "if", "complex", ":", "# See climata.acis for an example implementation", "raise", "NotImplementedError", "(", "\"Cannot serialize %s!\"", "%", "params", ")", "else", ":", ...
Serialize parameter names and values to a dict ready for urlencode()
[ "Serialize", "parameter", "names", "and", "values", "to", "a", "dict", "ready", "for", "urlencode", "()" ]
2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd
https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/base.py#L220-L232
train
Serialize parameter names and values to a dict ready for urlencode
haydenth/ish_parser
ish_parser/Distance.py
Distance.get_inches
def get_inches(self): ''' convert the measurement to inches ''' if self._obs_value in self.MISSING: return 'MISSING' if self._obs_units == self.MILLIMETERS: return round(self.INCH_CONVERSION_FACTOR * self._obs_value, 4)
python
def get_inches(self): ''' convert the measurement to inches ''' if self._obs_value in self.MISSING: return 'MISSING' if self._obs_units == self.MILLIMETERS: return round(self.INCH_CONVERSION_FACTOR * self._obs_value, 4)
[ "def", "get_inches", "(", "self", ")", ":", "if", "self", ".", "_obs_value", "in", "self", ".", "MISSING", ":", "return", "'MISSING'", "if", "self", ".", "_obs_units", "==", "self", ".", "MILLIMETERS", ":", "return", "round", "(", "self", ".", "INCH_CONV...
convert the measurement to inches
[ "convert", "the", "measurement", "to", "inches" ]
98fe3b3d0e5c672598be878d1715f214d5077869
https://github.com/haydenth/ish_parser/blob/98fe3b3d0e5c672598be878d1715f214d5077869/ish_parser/Distance.py#L13-L18
train
convert the measurement to inches
haydenth/ish_parser
ish_parser/ish_report.py
ish_report.formatted
def formatted(self): ''' print a nicely formatted output of this report ''' return """ Weather Station: %s (%s, %s) Elevation: %s m Time: %s UTC Air Temperature: %s C (%s F) Wind Speed: %s m/s (%s mph) Wind Direction: %s Present Weather Obs: %s Precipitation: %s Cloud Coverage: %s oktas Cloud Summation: %s Sol...
python
def formatted(self): ''' print a nicely formatted output of this report ''' return """ Weather Station: %s (%s, %s) Elevation: %s m Time: %s UTC Air Temperature: %s C (%s F) Wind Speed: %s m/s (%s mph) Wind Direction: %s Present Weather Obs: %s Precipitation: %s Cloud Coverage: %s oktas Cloud Summation: %s Sol...
[ "def", "formatted", "(", "self", ")", ":", "return", "\"\"\"\nWeather Station: %s (%s, %s)\nElevation: %s m\nTime: %s UTC\nAir Temperature: %s C (%s F)\nWind Speed: %s m/s (%s mph)\nWind Direction: %s\nPresent Weather Obs: %s\nPrecipitation: %s\nCloud Coverage: %s oktas\nCloud Summation: %s\nSolar Irr...
print a nicely formatted output of this report
[ "print", "a", "nicely", "formatted", "output", "of", "this", "report" ]
98fe3b3d0e5c672598be878d1715f214d5077869
https://github.com/haydenth/ish_parser/blob/98fe3b3d0e5c672598be878d1715f214d5077869/ish_parser/ish_report.py#L296-L317
train
print a nicely formatted output of this report
haydenth/ish_parser
ish_parser/ish_report.py
ish_report.loads
def loads(self, noaa_string): ''' load in a report (or set) from a string ''' self.raw = noaa_string self.weather_station = noaa_string[4:10] self.wban = noaa_string[10:15] expected_length = int(noaa_string[0:4]) + self.PREAMBLE_LENGTH actual_length = len(noaa_string) if actual_length != exp...
python
def loads(self, noaa_string): ''' load in a report (or set) from a string ''' self.raw = noaa_string self.weather_station = noaa_string[4:10] self.wban = noaa_string[10:15] expected_length = int(noaa_string[0:4]) + self.PREAMBLE_LENGTH actual_length = len(noaa_string) if actual_length != exp...
[ "def", "loads", "(", "self", ",", "noaa_string", ")", ":", "self", ".", "raw", "=", "noaa_string", "self", ".", "weather_station", "=", "noaa_string", "[", "4", ":", "10", "]", "self", ".", "wban", "=", "noaa_string", "[", "10", ":", "15", "]", "expe...
load in a report (or set) from a string
[ "load", "in", "a", "report", "(", "or", "set", ")", "from", "a", "string" ]
98fe3b3d0e5c672598be878d1715f214d5077869
https://github.com/haydenth/ish_parser/blob/98fe3b3d0e5c672598be878d1715f214d5077869/ish_parser/ish_report.py#L319-L399
train
loads in a report from a string
haydenth/ish_parser
ish_parser/ish_report.py
ish_report._get_remarks_component
def _get_remarks_component(self, string, initial_pos): ''' Parse the remarks into the _remarks dict ''' remarks_code = string[initial_pos:initial_pos + self.ADDR_CODE_LENGTH] if remarks_code != 'REM': raise ish_reportException("Parsing remarks. Expected REM but got %s." % (remarks_code,)) expecte...
python
def _get_remarks_component(self, string, initial_pos): ''' Parse the remarks into the _remarks dict ''' remarks_code = string[initial_pos:initial_pos + self.ADDR_CODE_LENGTH] if remarks_code != 'REM': raise ish_reportException("Parsing remarks. Expected REM but got %s." % (remarks_code,)) expecte...
[ "def", "_get_remarks_component", "(", "self", ",", "string", ",", "initial_pos", ")", ":", "remarks_code", "=", "string", "[", "initial_pos", ":", "initial_pos", "+", "self", ".", "ADDR_CODE_LENGTH", "]", "if", "remarks_code", "!=", "'REM'", ":", "raise", "ish...
Parse the remarks into the _remarks dict
[ "Parse", "the", "remarks", "into", "the", "_remarks", "dict" ]
98fe3b3d0e5c672598be878d1715f214d5077869
https://github.com/haydenth/ish_parser/blob/98fe3b3d0e5c672598be878d1715f214d5077869/ish_parser/ish_report.py#L401-L419
train
Parses the remarks from the string into the _remarks dict.
haydenth/ish_parser
ish_parser/ish_report.py
ish_report._get_component
def _get_component(self, string, initial_pos): ''' given a string and a position, return both an updated position and either a Component Object or a String back to the caller ''' add_code = string[initial_pos:initial_pos + self.ADDR_CODE_LENGTH] if add_code == 'REM': raise ish_reportException...
python
def _get_component(self, string, initial_pos): ''' given a string and a position, return both an updated position and either a Component Object or a String back to the caller ''' add_code = string[initial_pos:initial_pos + self.ADDR_CODE_LENGTH] if add_code == 'REM': raise ish_reportException...
[ "def", "_get_component", "(", "self", ",", "string", ",", "initial_pos", ")", ":", "add_code", "=", "string", "[", "initial_pos", ":", "initial_pos", "+", "self", ".", "ADDR_CODE_LENGTH", "]", "if", "add_code", "==", "'REM'", ":", "raise", "ish_reportException...
given a string and a position, return both an updated position and either a Component Object or a String back to the caller
[ "given", "a", "string", "and", "a", "position", "return", "both", "an", "updated", "position", "and", "either", "a", "Component", "Object", "or", "a", "String", "back", "to", "the", "caller" ]
98fe3b3d0e5c672598be878d1715f214d5077869
https://github.com/haydenth/ish_parser/blob/98fe3b3d0e5c672598be878d1715f214d5077869/ish_parser/ish_report.py#L421-L456
train
given a string and a position return both an updated position and a Component Object or a String back to the caller
haydenth/ish_parser
ish_parser/ish_parser.py
ish_parser.loads
def loads(self, string): ''' load from a string ''' for line in string.split("\n"): if len(line) < 10: continue try: report = ish_report() report.loads(line) self._reports.append(report) except BaseException as exp: ''' don't complain TOO much ''' ...
python
def loads(self, string): ''' load from a string ''' for line in string.split("\n"): if len(line) < 10: continue try: report = ish_report() report.loads(line) self._reports.append(report) except BaseException as exp: ''' don't complain TOO much ''' ...
[ "def", "loads", "(", "self", ",", "string", ")", ":", "for", "line", "in", "string", ".", "split", "(", "\"\\n\"", ")", ":", "if", "len", "(", "line", ")", "<", "10", ":", "continue", "try", ":", "report", "=", "ish_report", "(", ")", "report", "...
load from a string
[ "load", "from", "a", "string" ]
98fe3b3d0e5c672598be878d1715f214d5077869
https://github.com/haydenth/ish_parser/blob/98fe3b3d0e5c672598be878d1715f214d5077869/ish_parser/ish_parser.py#L15-L27
train
loads a string into the internal list of reports
haydenth/ish_parser
ish_parser/ish_parser.py
ish_parser.get_observations
def get_observations(self): ''' return only specific weather observations (FM types) and ignore the summary of day reports ''' return [rpt for rpt in self._reports if rpt.report_type in self.OBS_TYPES]
python
def get_observations(self): ''' return only specific weather observations (FM types) and ignore the summary of day reports ''' return [rpt for rpt in self._reports if rpt.report_type in self.OBS_TYPES]
[ "def", "get_observations", "(", "self", ")", ":", "return", "[", "rpt", "for", "rpt", "in", "self", ".", "_reports", "if", "rpt", ".", "report_type", "in", "self", ".", "OBS_TYPES", "]" ]
return only specific weather observations (FM types) and ignore the summary of day reports
[ "return", "only", "specific", "weather", "observations", "(", "FM", "types", ")", "and", "ignore", "the", "summary", "of", "day", "reports" ]
98fe3b3d0e5c672598be878d1715f214d5077869
https://github.com/haydenth/ish_parser/blob/98fe3b3d0e5c672598be878d1715f214d5077869/ish_parser/ish_parser.py#L33-L36
train
return only specific weather observations
haydenth/ish_parser
ish_parser/Speed.py
Speed.get_miles
def get_miles(self): ''' convert the measurement to inches ''' if self._obs_value in self.MISSING: return 'MISSING' if self._obs_units == self.METERSPERSECOND: return round(2.23694 * self._obs_value, 4)
python
def get_miles(self): ''' convert the measurement to inches ''' if self._obs_value in self.MISSING: return 'MISSING' if self._obs_units == self.METERSPERSECOND: return round(2.23694 * self._obs_value, 4)
[ "def", "get_miles", "(", "self", ")", ":", "if", "self", ".", "_obs_value", "in", "self", ".", "MISSING", ":", "return", "'MISSING'", "if", "self", ".", "_obs_units", "==", "self", ".", "METERSPERSECOND", ":", "return", "round", "(", "2.23694", "*", "sel...
convert the measurement to inches
[ "convert", "the", "measurement", "to", "inches" ]
98fe3b3d0e5c672598be878d1715f214d5077869
https://github.com/haydenth/ish_parser/blob/98fe3b3d0e5c672598be878d1715f214d5077869/ish_parser/Speed.py#L10-L15
train
convert the measurement to inches
subdownloader/subdownloader
scripts/distribution/translation_generator.py
TranslationGenerator.do_pot
def do_pot(self): """ Sync the template with the python code. """ files_to_translate = [] log.debug("Collecting python sources for pot ...") for source_path in self._source_paths: for source_path in self._iter_suffix(path=source_path, suffix=".py"): ...
python
def do_pot(self): """ Sync the template with the python code. """ files_to_translate = [] log.debug("Collecting python sources for pot ...") for source_path in self._source_paths: for source_path in self._iter_suffix(path=source_path, suffix=".py"): ...
[ "def", "do_pot", "(", "self", ")", ":", "files_to_translate", "=", "[", "]", "log", ".", "debug", "(", "\"Collecting python sources for pot ...\"", ")", "for", "source_path", "in", "self", ".", "_source_paths", ":", "for", "source_path", "in", "self", ".", "_i...
Sync the template with the python code.
[ "Sync", "the", "template", "with", "the", "python", "code", "." ]
bbccedd11b18d925ad4c062b5eb65981e24d0433
https://github.com/subdownloader/subdownloader/blob/bbccedd11b18d925ad4c062b5eb65981e24d0433/scripts/distribution/translation_generator.py#L47-L70
train
Create the python source files and copy them to the mo path.
subdownloader/subdownloader
scripts/distribution/translation_generator.py
TranslationGenerator.do_po
def do_po(self): """ Update all po files with the data in the pot reference file. """ log.debug("Start updating po files ...") pot_path = (self._po_path / self._basename).with_suffix(".pot") for po_dir_path in self._iter_po_dir(): po_path = (po_dir_path / self...
python
def do_po(self): """ Update all po files with the data in the pot reference file. """ log.debug("Start updating po files ...") pot_path = (self._po_path / self._basename).with_suffix(".pot") for po_dir_path in self._iter_po_dir(): po_path = (po_dir_path / self...
[ "def", "do_po", "(", "self", ")", ":", "log", ".", "debug", "(", "\"Start updating po files ...\"", ")", "pot_path", "=", "(", "self", ".", "_po_path", "/", "self", ".", "_basename", ")", ".", "with_suffix", "(", "\".pot\"", ")", "for", "po_dir_path", "in"...
Update all po files with the data in the pot reference file.
[ "Update", "all", "po", "files", "with", "the", "data", "in", "the", "pot", "reference", "file", "." ]
bbccedd11b18d925ad4c062b5eb65981e24d0433
https://github.com/subdownloader/subdownloader/blob/bbccedd11b18d925ad4c062b5eb65981e24d0433/scripts/distribution/translation_generator.py#L78-L97
train
Update all the po files with the data in the pot reference file.
subdownloader/subdownloader
scripts/distribution/translation_generator.py
TranslationGenerator.do_mo
def do_mo(self): """ Generate mo files for all po files. """ log.debug("Start updating mo files ...") for po_dir_path in self._iter_po_dir(): po_path = (po_dir_path / self._basename).with_suffix(".po") lc_path = self._mo_path / po_dir_path.name / "LC_MESSA...
python
def do_mo(self): """ Generate mo files for all po files. """ log.debug("Start updating mo files ...") for po_dir_path in self._iter_po_dir(): po_path = (po_dir_path / self._basename).with_suffix(".po") lc_path = self._mo_path / po_dir_path.name / "LC_MESSA...
[ "def", "do_mo", "(", "self", ")", ":", "log", ".", "debug", "(", "\"Start updating mo files ...\"", ")", "for", "po_dir_path", "in", "self", ".", "_iter_po_dir", "(", ")", ":", "po_path", "=", "(", "po_dir_path", "/", "self", ".", "_basename", ")", ".", ...
Generate mo files for all po files.
[ "Generate", "mo", "files", "for", "all", "po", "files", "." ]
bbccedd11b18d925ad4c062b5eb65981e24d0433
https://github.com/subdownloader/subdownloader/blob/bbccedd11b18d925ad4c062b5eb65981e24d0433/scripts/distribution/translation_generator.py#L99-L111
train
Generate the MO files for all the po files.
cenkalti/kuyruk
kuyruk/worker.py
Worker.run
def run(self) -> None: """Runs the worker and consumes messages from RabbitMQ. Returns only after `shutdown()` is called. """ if self._logging_level: logging.basicConfig( level=getattr(logging, self._logging_level.upper()), format="%(levelname...
python
def run(self) -> None: """Runs the worker and consumes messages from RabbitMQ. Returns only after `shutdown()` is called. """ if self._logging_level: logging.basicConfig( level=getattr(logging, self._logging_level.upper()), format="%(levelname...
[ "def", "run", "(", "self", ")", "->", "None", ":", "if", "self", ".", "_logging_level", ":", "logging", ".", "basicConfig", "(", "level", "=", "getattr", "(", "logging", ",", "self", ".", "_logging_level", ".", "upper", "(", ")", ")", ",", "format", ...
Runs the worker and consumes messages from RabbitMQ. Returns only after `shutdown()` is called.
[ "Runs", "the", "worker", "and", "consumes", "messages", "from", "RabbitMQ", ".", "Returns", "only", "after", "shutdown", "()", "is", "called", "." ]
c99d66be9d8fb077610f2fa883d5a1d268b42f04
https://github.com/cenkalti/kuyruk/blob/c99d66be9d8fb077610f2fa883d5a1d268b42f04/kuyruk/worker.py#L81-L115
train
Runs the worker and consumes messages from RabbitMQ.
cenkalti/kuyruk
kuyruk/worker.py
Worker._process_message
def _process_message(self, message: amqp.Message) -> None: """Processes the message received from the queue.""" if self.shutdown_pending.is_set(): return try: if isinstance(message.body, bytes): message.body = message.body.decode() description...
python
def _process_message(self, message: amqp.Message) -> None: """Processes the message received from the queue.""" if self.shutdown_pending.is_set(): return try: if isinstance(message.body, bytes): message.body = message.body.decode() description...
[ "def", "_process_message", "(", "self", ",", "message", ":", "amqp", ".", "Message", ")", "->", "None", ":", "if", "self", ".", "shutdown_pending", ".", "is_set", "(", ")", ":", "return", "try", ":", "if", "isinstance", "(", "message", ".", "body", ","...
Processes the message received from the queue.
[ "Processes", "the", "message", "received", "from", "the", "queue", "." ]
c99d66be9d8fb077610f2fa883d5a1d268b42f04
https://github.com/cenkalti/kuyruk/blob/c99d66be9d8fb077610f2fa883d5a1d268b42f04/kuyruk/worker.py#L175-L190
train
Processes the message received from the queue.
cenkalti/kuyruk
kuyruk/worker.py
Worker._apply_task
def _apply_task(task: Task, args: Tuple, kwargs: Dict[str, Any]) -> Any: """Logs the time spent while running the task.""" if args is None: args = () if kwargs is None: kwargs = {} start = monotonic() try: return task.apply(*args, **kwargs) ...
python
def _apply_task(task: Task, args: Tuple, kwargs: Dict[str, Any]) -> Any: """Logs the time spent while running the task.""" if args is None: args = () if kwargs is None: kwargs = {} start = monotonic() try: return task.apply(*args, **kwargs) ...
[ "def", "_apply_task", "(", "task", ":", "Task", ",", "args", ":", "Tuple", ",", "kwargs", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "Any", ":", "if", "args", "is", "None", ":", "args", "=", "(", ")", "if", "kwargs", "is", "None", ":"...
Logs the time spent while running the task.
[ "Logs", "the", "time", "spent", "while", "running", "the", "task", "." ]
c99d66be9d8fb077610f2fa883d5a1d268b42f04
https://github.com/cenkalti/kuyruk/blob/c99d66be9d8fb077610f2fa883d5a1d268b42f04/kuyruk/worker.py#L292-L304
train
Logs the time spent while running the task.
cenkalti/kuyruk
kuyruk/worker.py
Worker._shutdown_timer
def _shutdown_timer(self) -> None: """Counts down from MAX_WORKER_RUN_TIME. When it reaches zero sutdown gracefully. """ remaining = self._max_run_time - self.uptime if not self.shutdown_pending.wait(remaining): logger.warning('Run time reached zero') sel...
python
def _shutdown_timer(self) -> None: """Counts down from MAX_WORKER_RUN_TIME. When it reaches zero sutdown gracefully. """ remaining = self._max_run_time - self.uptime if not self.shutdown_pending.wait(remaining): logger.warning('Run time reached zero') sel...
[ "def", "_shutdown_timer", "(", "self", ")", "->", "None", ":", "remaining", "=", "self", ".", "_max_run_time", "-", "self", ".", "uptime", "if", "not", "self", ".", "shutdown_pending", ".", "wait", "(", "remaining", ")", ":", "logger", ".", "warning", "(...
Counts down from MAX_WORKER_RUN_TIME. When it reaches zero sutdown gracefully.
[ "Counts", "down", "from", "MAX_WORKER_RUN_TIME", ".", "When", "it", "reaches", "zero", "sutdown", "gracefully", "." ]
c99d66be9d8fb077610f2fa883d5a1d268b42f04
https://github.com/cenkalti/kuyruk/blob/c99d66be9d8fb077610f2fa883d5a1d268b42f04/kuyruk/worker.py#L351-L359
train
Counts down from MAX_WORKER_RUN_TIME. When it reaches zero sutdown gracefully.
cenkalti/kuyruk
kuyruk/worker.py
Worker._handle_sigint
def _handle_sigint(self, signum: int, frame: Any) -> None: """Shutdown after processing current task.""" logger.warning("Catched SIGINT") self.shutdown()
python
def _handle_sigint(self, signum: int, frame: Any) -> None: """Shutdown after processing current task.""" logger.warning("Catched SIGINT") self.shutdown()
[ "def", "_handle_sigint", "(", "self", ",", "signum", ":", "int", ",", "frame", ":", "Any", ")", "->", "None", ":", "logger", ".", "warning", "(", "\"Catched SIGINT\"", ")", "self", ".", "shutdown", "(", ")" ]
Shutdown after processing current task.
[ "Shutdown", "after", "processing", "current", "task", "." ]
c99d66be9d8fb077610f2fa883d5a1d268b42f04
https://github.com/cenkalti/kuyruk/blob/c99d66be9d8fb077610f2fa883d5a1d268b42f04/kuyruk/worker.py#L366-L369
train
Handle SIGINT signal.
cenkalti/kuyruk
kuyruk/worker.py
Worker._handle_sighup
def _handle_sighup(self, signum: int, frame: Any) -> None: """Used internally to fail the task when connection to RabbitMQ is lost during the execution of the task. """ logger.warning("Catched SIGHUP") exc_info = self._heartbeat_exc_info self._heartbeat_exc_info = None ...
python
def _handle_sighup(self, signum: int, frame: Any) -> None: """Used internally to fail the task when connection to RabbitMQ is lost during the execution of the task. """ logger.warning("Catched SIGHUP") exc_info = self._heartbeat_exc_info self._heartbeat_exc_info = None ...
[ "def", "_handle_sighup", "(", "self", ",", "signum", ":", "int", ",", "frame", ":", "Any", ")", "->", "None", ":", "logger", ".", "warning", "(", "\"Catched SIGHUP\"", ")", "exc_info", "=", "self", ".", "_heartbeat_exc_info", "self", ".", "_heartbeat_exc_inf...
Used internally to fail the task when connection to RabbitMQ is lost during the execution of the task.
[ "Used", "internally", "to", "fail", "the", "task", "when", "connection", "to", "RabbitMQ", "is", "lost", "during", "the", "execution", "of", "the", "task", "." ]
c99d66be9d8fb077610f2fa883d5a1d268b42f04
https://github.com/cenkalti/kuyruk/blob/c99d66be9d8fb077610f2fa883d5a1d268b42f04/kuyruk/worker.py#L376-L386
train
Called by the process when the process has lost the connection to RabbitMQ.
cenkalti/kuyruk
kuyruk/worker.py
Worker._handle_sigusr1
def _handle_sigusr1(signum: int, frame: Any) -> None: """Print stacktrace.""" print('=' * 70) print(''.join(traceback.format_stack())) print('-' * 70)
python
def _handle_sigusr1(signum: int, frame: Any) -> None: """Print stacktrace.""" print('=' * 70) print(''.join(traceback.format_stack())) print('-' * 70)
[ "def", "_handle_sigusr1", "(", "signum", ":", "int", ",", "frame", ":", "Any", ")", "->", "None", ":", "print", "(", "'='", "*", "70", ")", "print", "(", "''", ".", "join", "(", "traceback", ".", "format_stack", "(", ")", ")", ")", "print", "(", ...
Print stacktrace.
[ "Print", "stacktrace", "." ]
c99d66be9d8fb077610f2fa883d5a1d268b42f04
https://github.com/cenkalti/kuyruk/blob/c99d66be9d8fb077610f2fa883d5a1d268b42f04/kuyruk/worker.py#L389-L393
train
Print stacktrace.
cenkalti/kuyruk
kuyruk/worker.py
Worker._handle_sigusr2
def _handle_sigusr2(self, signum: int, frame: Any) -> None: """Drop current task.""" logger.warning("Catched SIGUSR2") if self.current_task: logger.warning("Dropping current task...") raise Discard
python
def _handle_sigusr2(self, signum: int, frame: Any) -> None: """Drop current task.""" logger.warning("Catched SIGUSR2") if self.current_task: logger.warning("Dropping current task...") raise Discard
[ "def", "_handle_sigusr2", "(", "self", ",", "signum", ":", "int", ",", "frame", ":", "Any", ")", "->", "None", ":", "logger", ".", "warning", "(", "\"Catched SIGUSR2\"", ")", "if", "self", ".", "current_task", ":", "logger", ".", "warning", "(", "\"Dropp...
Drop current task.
[ "Drop", "current", "task", "." ]
c99d66be9d8fb077610f2fa883d5a1d268b42f04
https://github.com/cenkalti/kuyruk/blob/c99d66be9d8fb077610f2fa883d5a1d268b42f04/kuyruk/worker.py#L395-L400
train
Handle SIGUSR2 signal.
subdownloader/subdownloader
subdownloader/client/configuration.py
configuration_get_default_folder
def configuration_get_default_folder(): """ Return the default folder where user-specific data is stored. This depends of the system on which Python is running, :return: path to the user-specific configuration data folder """ system = platform.system() if system == 'Linux': # https:/...
python
def configuration_get_default_folder(): """ Return the default folder where user-specific data is stored. This depends of the system on which Python is running, :return: path to the user-specific configuration data folder """ system = platform.system() if system == 'Linux': # https:/...
[ "def", "configuration_get_default_folder", "(", ")", ":", "system", "=", "platform", ".", "system", "(", ")", "if", "system", "==", "'Linux'", ":", "# https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html", "sys_config_path", "=", "Path", "(", "os",...
Return the default folder where user-specific data is stored. This depends of the system on which Python is running, :return: path to the user-specific configuration data folder
[ "Return", "the", "default", "folder", "where", "user", "-", "specific", "data", "is", "stored", ".", "This", "depends", "of", "the", "system", "on", "which", "Python", "is", "running", ":", "return", ":", "path", "to", "the", "user", "-", "specific", "co...
bbccedd11b18d925ad4c062b5eb65981e24d0433
https://github.com/subdownloader/subdownloader/blob/bbccedd11b18d925ad4c062b5eb65981e24d0433/subdownloader/client/configuration.py#L95-L115
train
Get the default folder where user - specific data is stored.
subdownloader/subdownloader
subdownloader/languages/language.py
Language.from_locale
def from_locale(cls, locale): """ Create a new Language instance from a locale string :param locale: locale as string :return: Language instance with instance.locale() == locale if locale is valid else instance of Unknown Language """ locale = str(locale) if local...
python
def from_locale(cls, locale): """ Create a new Language instance from a locale string :param locale: locale as string :return: Language instance with instance.locale() == locale if locale is valid else instance of Unknown Language """ locale = str(locale) if local...
[ "def", "from_locale", "(", "cls", ",", "locale", ")", ":", "locale", "=", "str", "(", "locale", ")", "if", "locale", "is", "'unknown'", ":", "return", "UnknownLanguage", "(", "locale", ")", "try", ":", "return", "cls", ".", "_from_xyz", "(", "'locale'", ...
Create a new Language instance from a locale string :param locale: locale as string :return: Language instance with instance.locale() == locale if locale is valid else instance of Unknown Language
[ "Create", "a", "new", "Language", "instance", "from", "a", "locale", "string", ":", "param", "locale", ":", "locale", "as", "string", ":", "return", ":", "Language", "instance", "with", "instance", ".", "locale", "()", "==", "locale", "if", "locale", "is",...
bbccedd11b18d925ad4c062b5eb65981e24d0433
https://github.com/subdownloader/subdownloader/blob/bbccedd11b18d925ad4c062b5eb65981e24d0433/subdownloader/languages/language.py#L144-L157
train
Create a new Language instance from a locale string
subdownloader/subdownloader
subdownloader/languages/language.py
Language.from_xx
def from_xx(cls, xx): """ Create a new Language instance from a ISO639 string :param xx: ISO639 as string :return: Language instance with instance.xx() == xx if xx is valid else instance of UnknownLanguage """ xx = str(xx).lower() if xx is 'unknown': r...
python
def from_xx(cls, xx): """ Create a new Language instance from a ISO639 string :param xx: ISO639 as string :return: Language instance with instance.xx() == xx if xx is valid else instance of UnknownLanguage """ xx = str(xx).lower() if xx is 'unknown': r...
[ "def", "from_xx", "(", "cls", ",", "xx", ")", ":", "xx", "=", "str", "(", "xx", ")", ".", "lower", "(", ")", "if", "xx", "is", "'unknown'", ":", "return", "UnknownLanguage", "(", "xx", ")", "try", ":", "return", "cls", ".", "_from_xyz", "(", "'IS...
Create a new Language instance from a ISO639 string :param xx: ISO639 as string :return: Language instance with instance.xx() == xx if xx is valid else instance of UnknownLanguage
[ "Create", "a", "new", "Language", "instance", "from", "a", "ISO639", "string", ":", "param", "xx", ":", "ISO639", "as", "string", ":", "return", ":", "Language", "instance", "with", "instance", ".", "xx", "()", "==", "xx", "if", "xx", "is", "valid", "e...
bbccedd11b18d925ad4c062b5eb65981e24d0433
https://github.com/subdownloader/subdownloader/blob/bbccedd11b18d925ad4c062b5eb65981e24d0433/subdownloader/languages/language.py#L160-L173
train
Create a new Language instance from an ISO639 string.
subdownloader/subdownloader
subdownloader/languages/language.py
Language.from_xxx
def from_xxx(cls, xxx): """ Create a new Language instance from a LanguageID string :param xxx: LanguageID as string :return: Language instance with instance.xxx() == xxx if xxx is valid else instance of UnknownLanguage """ xxx = str(xxx).lower() if xxx is 'unknow...
python
def from_xxx(cls, xxx): """ Create a new Language instance from a LanguageID string :param xxx: LanguageID as string :return: Language instance with instance.xxx() == xxx if xxx is valid else instance of UnknownLanguage """ xxx = str(xxx).lower() if xxx is 'unknow...
[ "def", "from_xxx", "(", "cls", ",", "xxx", ")", ":", "xxx", "=", "str", "(", "xxx", ")", ".", "lower", "(", ")", "if", "xxx", "is", "'unknown'", ":", "return", "UnknownLanguage", "(", "xxx", ")", "try", ":", "return", "cls", ".", "_from_xyz", "(", ...
Create a new Language instance from a LanguageID string :param xxx: LanguageID as string :return: Language instance with instance.xxx() == xxx if xxx is valid else instance of UnknownLanguage
[ "Create", "a", "new", "Language", "instance", "from", "a", "LanguageID", "string", ":", "param", "xxx", ":", "LanguageID", "as", "string", ":", "return", ":", "Language", "instance", "with", "instance", ".", "xxx", "()", "==", "xxx", "if", "xxx", "is", "...
bbccedd11b18d925ad4c062b5eb65981e24d0433
https://github.com/subdownloader/subdownloader/blob/bbccedd11b18d925ad4c062b5eb65981e24d0433/subdownloader/languages/language.py#L176-L189
train
Create a new Language instance from a LanguageID string.
subdownloader/subdownloader
subdownloader/languages/language.py
Language.from_name
def from_name(cls, name): """ Create a new Language instance from a name as string :param name: name as string :return: Language instance with instance.name() == name if name is valid else instance of UnknownLanguage """ name = str(name).lower() if name is 'unknow...
python
def from_name(cls, name): """ Create a new Language instance from a name as string :param name: name as string :return: Language instance with instance.name() == name if name is valid else instance of UnknownLanguage """ name = str(name).lower() if name is 'unknow...
[ "def", "from_name", "(", "cls", ",", "name", ")", ":", "name", "=", "str", "(", "name", ")", ".", "lower", "(", ")", "if", "name", "is", "'unknown'", "or", "name", "is", "_", "(", "'unknown'", ")", ":", "return", "UnknownLanguage", "(", "name", ")"...
Create a new Language instance from a name as string :param name: name as string :return: Language instance with instance.name() == name if name is valid else instance of UnknownLanguage
[ "Create", "a", "new", "Language", "instance", "from", "a", "name", "as", "string", ":", "param", "name", ":", "name", "as", "string", ":", "return", ":", "Language", "instance", "with", "instance", ".", "name", "()", "==", "name", "if", "name", "is", "...
bbccedd11b18d925ad4c062b5eb65981e24d0433
https://github.com/subdownloader/subdownloader/blob/bbccedd11b18d925ad4c062b5eb65981e24d0433/subdownloader/languages/language.py#L192-L205
train
Create a new Language instance from a name as string
subdownloader/subdownloader
subdownloader/languages/language.py
Language._from_xyz
def _from_xyz(cls, xyzkey, xyzvalue): """ Private helper function to create new Language instance. :param xyzkey: one of ('locale', 'ISO639', 'LanguageID', 'LanguageName') :param xyzvalue: corresponding value of xyzkey :return: Language instance """ if xyzvalue ==...
python
def _from_xyz(cls, xyzkey, xyzvalue): """ Private helper function to create new Language instance. :param xyzkey: one of ('locale', 'ISO639', 'LanguageID', 'LanguageName') :param xyzvalue: corresponding value of xyzkey :return: Language instance """ if xyzvalue ==...
[ "def", "_from_xyz", "(", "cls", ",", "xyzkey", ",", "xyzvalue", ")", ":", "if", "xyzvalue", "==", "'unknown'", "or", "xyzvalue", "==", "_", "(", "'unknown'", ")", ":", "return", "UnknownLanguage", "(", "xyzvalue", ")", "for", "lang_id", ",", "lang_data", ...
Private helper function to create new Language instance. :param xyzkey: one of ('locale', 'ISO639', 'LanguageID', 'LanguageName') :param xyzvalue: corresponding value of xyzkey :return: Language instance
[ "Private", "helper", "function", "to", "create", "new", "Language", "instance", ".", ":", "param", "xyzkey", ":", "one", "of", "(", "locale", "ISO639", "LanguageID", "LanguageName", ")", ":", "param", "xyzvalue", ":", "corresponding", "value", "of", "xyzkey", ...
bbccedd11b18d925ad4c062b5eb65981e24d0433
https://github.com/subdownloader/subdownloader/blob/bbccedd11b18d925ad4c062b5eb65981e24d0433/subdownloader/languages/language.py#L208-L221
train
Private helper function to create a new Language instance from a given language key and value.
subdownloader/subdownloader
subdownloader/languages/language.py
Language.from_unknown
def from_unknown(cls, value, xx=False, xxx=False, locale=False, name=False): """ Try to create a Language instance having only some limited data about the Language. If no corresponding Language is found, a NotALanguageException is thrown. :param value: data known about the language as st...
python
def from_unknown(cls, value, xx=False, xxx=False, locale=False, name=False): """ Try to create a Language instance having only some limited data about the Language. If no corresponding Language is found, a NotALanguageException is thrown. :param value: data known about the language as st...
[ "def", "from_unknown", "(", "cls", ",", "value", ",", "xx", "=", "False", ",", "xxx", "=", "False", ",", "locale", "=", "False", ",", "name", "=", "False", ")", ":", "# Use 2 lists instead of dict ==> order known", "keys", "=", "[", "'ISO639'", ",", "'Lang...
Try to create a Language instance having only some limited data about the Language. If no corresponding Language is found, a NotALanguageException is thrown. :param value: data known about the language as string :param xx: True if the value may be a locale :param xxx: True if the value m...
[ "Try", "to", "create", "a", "Language", "instance", "having", "only", "some", "limited", "data", "about", "the", "Language", ".", "If", "no", "corresponding", "Language", "is", "found", "a", "NotALanguageException", "is", "thrown", ".", ":", "param", "value", ...
bbccedd11b18d925ad4c062b5eb65981e24d0433
https://github.com/subdownloader/subdownloader/blob/bbccedd11b18d925ad4c062b5eb65981e24d0433/subdownloader/languages/language.py#L224-L245
train
Try to create a Language instance from an unknown language.
subdownloader/subdownloader
subdownloader/languages/language.py
Language.from_file
def from_file(cls, filepath, chunk_size=None): """ Try do determine the language of a text file. :param filepath: string file path :param chunk_size: amount of bytes of file to read to determine language :return: Language instance if detection succeeded, otherwise return UnknownL...
python
def from_file(cls, filepath, chunk_size=None): """ Try do determine the language of a text file. :param filepath: string file path :param chunk_size: amount of bytes of file to read to determine language :return: Language instance if detection succeeded, otherwise return UnknownL...
[ "def", "from_file", "(", "cls", ",", "filepath", ",", "chunk_size", "=", "None", ")", ":", "log", ".", "debug", "(", "'Language.from_file: \"{}\", chunk={} ...'", ".", "format", "(", "filepath", ",", "chunk_size", ")", ")", "with", "filepath", ".", "open", "...
Try do determine the language of a text file. :param filepath: string file path :param chunk_size: amount of bytes of file to read to determine language :return: Language instance if detection succeeded, otherwise return UnknownLanguage
[ "Try", "do", "determine", "the", "language", "of", "a", "text", "file", ".", ":", "param", "filepath", ":", "string", "file", "path", ":", "param", "chunk_size", ":", "amount", "of", "bytes", "of", "file", "to", "read", "to", "determine", "language", ":"...
bbccedd11b18d925ad4c062b5eb65981e24d0433
https://github.com/subdownloader/subdownloader/blob/bbccedd11b18d925ad4c062b5eb65981e24d0433/subdownloader/languages/language.py#L248-L262
train
Try to determine the language of a text file.
subdownloader/subdownloader
subdownloader/client/gui/searchFileWidget.py
SearchFileWidget.onFolderTreeClicked
def onFolderTreeClicked(self, proxyIndex): """What to do when a Folder in the tree is clicked""" if not proxyIndex.isValid(): return index = self.proxyFileModel.mapToSource(proxyIndex) settings = QSettings() folder_path = self.fileModel.filePath(index) settin...
python
def onFolderTreeClicked(self, proxyIndex): """What to do when a Folder in the tree is clicked""" if not proxyIndex.isValid(): return index = self.proxyFileModel.mapToSource(proxyIndex) settings = QSettings() folder_path = self.fileModel.filePath(index) settin...
[ "def", "onFolderTreeClicked", "(", "self", ",", "proxyIndex", ")", ":", "if", "not", "proxyIndex", ".", "isValid", "(", ")", ":", "return", "index", "=", "self", ".", "proxyFileModel", ".", "mapToSource", "(", "proxyIndex", ")", "settings", "=", "QSettings",...
What to do when a Folder in the tree is clicked
[ "What", "to", "do", "when", "a", "Folder", "in", "the", "tree", "is", "clicked" ]
bbccedd11b18d925ad4c062b5eb65981e24d0433
https://github.com/subdownloader/subdownloader/blob/bbccedd11b18d925ad4c062b5eb65981e24d0433/subdownloader/client/gui/searchFileWidget.py#L214-L222
train
What to do when a Folder in the tree is clicked
cenkalti/kuyruk
kuyruk/task.py
Task.send_to_queue
def send_to_queue( self, args: Tuple=(), kwargs: Dict[str, Any]={}, host: str=None, wait_result: Union[int, float]=None, message_ttl: Union[int, float]=None, ) -> Any: """ Sends a message to the queue. A worker will run ...
python
def send_to_queue( self, args: Tuple=(), kwargs: Dict[str, Any]={}, host: str=None, wait_result: Union[int, float]=None, message_ttl: Union[int, float]=None, ) -> Any: """ Sends a message to the queue. A worker will run ...
[ "def", "send_to_queue", "(", "self", ",", "args", ":", "Tuple", "=", "(", ")", ",", "kwargs", ":", "Dict", "[", "str", ",", "Any", "]", "=", "{", "}", ",", "host", ":", "str", "=", "None", ",", "wait_result", ":", "Union", "[", "int", ",", "flo...
Sends a message to the queue. A worker will run the task's function when it receives the message. :param args: Arguments that will be passed to task on execution. :param kwargs: Keyword arguments that will be passed to task on execution. :param host: Send this task to specif...
[ "Sends", "a", "message", "to", "the", "queue", ".", "A", "worker", "will", "run", "the", "task", "s", "function", "when", "it", "receives", "the", "message", "." ]
c99d66be9d8fb077610f2fa883d5a1d268b42f04
https://github.com/cenkalti/kuyruk/blob/c99d66be9d8fb077610f2fa883d5a1d268b42f04/kuyruk/task.py#L69-L130
train
Sends a message to the queue.
cenkalti/kuyruk
kuyruk/task.py
Task._get_description
def _get_description(self, args: Tuple, kwargs: Dict[str, Any]) -> Dict[str, Any]: """Return the dictionary to be sent to the queue.""" return { 'id': uuid1().hex, 'args': args, 'kwargs': kwargs, 'module': self._module_name, 'function': self.f....
python
def _get_description(self, args: Tuple, kwargs: Dict[str, Any]) -> Dict[str, Any]: """Return the dictionary to be sent to the queue.""" return { 'id': uuid1().hex, 'args': args, 'kwargs': kwargs, 'module': self._module_name, 'function': self.f....
[ "def", "_get_description", "(", "self", ",", "args", ":", "Tuple", ",", "kwargs", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "return", "{", "'id'", ":", "uuid1", "(", ")", ".", "hex", ",", "'a...
Return the dictionary to be sent to the queue.
[ "Return", "the", "dictionary", "to", "be", "sent", "to", "the", "queue", "." ]
c99d66be9d8fb077610f2fa883d5a1d268b42f04
https://github.com/cenkalti/kuyruk/blob/c99d66be9d8fb077610f2fa883d5a1d268b42f04/kuyruk/task.py#L139-L151
train
Return the dictionary to be sent to the queue.
cenkalti/kuyruk
kuyruk/task.py
Task.apply
def apply(self, *args: Any, **kwargs: Any) -> Any: """Called by workers to run the wrapped function. You may call it yourself if you want to run the task in current process without sending to the queue. If task has a `retry` property it will be retried on failure. If task has a...
python
def apply(self, *args: Any, **kwargs: Any) -> Any: """Called by workers to run the wrapped function. You may call it yourself if you want to run the task in current process without sending to the queue. If task has a `retry` property it will be retried on failure. If task has a...
[ "def", "apply", "(", "self", ",", "*", "args", ":", "Any", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "Any", ":", "def", "send_signal", "(", "sig", ":", "Signal", ",", "*", "*", "extra", ":", "Any", ")", "->", "None", ":", "self", ".", "...
Called by workers to run the wrapped function. You may call it yourself if you want to run the task in current process without sending to the queue. If task has a `retry` property it will be retried on failure. If task has a `max_run_time` property the task will not be allowed to ...
[ "Called", "by", "workers", "to", "run", "the", "wrapped", "function", ".", "You", "may", "call", "it", "yourself", "if", "you", "want", "to", "run", "the", "task", "in", "current", "process", "without", "sending", "to", "the", "queue", "." ]
c99d66be9d8fb077610f2fa883d5a1d268b42f04
https://github.com/cenkalti/kuyruk/blob/c99d66be9d8fb077610f2fa883d5a1d268b42f04/kuyruk/task.py#L156-L194
train
Calls the wrapped function and returns the result.
cenkalti/kuyruk
kuyruk/task.py
Task._module_name
def _module_name(self) -> str: """Module name of the wrapped function.""" name = self.f.__module__ if name == '__main__': return importer.main_module_name() return name
python
def _module_name(self) -> str: """Module name of the wrapped function.""" name = self.f.__module__ if name == '__main__': return importer.main_module_name() return name
[ "def", "_module_name", "(", "self", ")", "->", "str", ":", "name", "=", "self", ".", "f", ".", "__module__", "if", "name", "==", "'__main__'", ":", "return", "importer", ".", "main_module_name", "(", ")", "return", "name" ]
Module name of the wrapped function.
[ "Module", "name", "of", "the", "wrapped", "function", "." ]
c99d66be9d8fb077610f2fa883d5a1d268b42f04
https://github.com/cenkalti/kuyruk/blob/c99d66be9d8fb077610f2fa883d5a1d268b42f04/kuyruk/task.py#L205-L210
train
Return the name of the wrapped function.
subdownloader/subdownloader
subdownloader/client/internationalization.py
i18n_install
def i18n_install(lc=None): """ Install internationalization support for the clients using the specified locale. If there is no support for the locale, the default locale will be used. As last resort, a null translator will be installed. :param lc: locale to install. If None, the system default local...
python
def i18n_install(lc=None): """ Install internationalization support for the clients using the specified locale. If there is no support for the locale, the default locale will be used. As last resort, a null translator will be installed. :param lc: locale to install. If None, the system default local...
[ "def", "i18n_install", "(", "lc", "=", "None", ")", ":", "log", ".", "debug", "(", "'i18n_install( {lc} ) called.'", ".", "format", "(", "lc", "=", "lc", ")", ")", "if", "lc", "is", "None", ":", "lc", "=", "i18n_system_locale", "(", ")", "if", "lc", ...
Install internationalization support for the clients using the specified locale. If there is no support for the locale, the default locale will be used. As last resort, a null translator will be installed. :param lc: locale to install. If None, the system default locale will be used.
[ "Install", "internationalization", "support", "for", "the", "clients", "using", "the", "specified", "locale", ".", "If", "there", "is", "no", "support", "for", "the", "locale", "the", "default", "locale", "will", "be", "used", ".", "As", "last", "resort", "a...
bbccedd11b18d925ad4c062b5eb65981e24d0433
https://github.com/subdownloader/subdownloader/blob/bbccedd11b18d925ad4c062b5eb65981e24d0433/subdownloader/client/internationalization.py#L17-L41
train
Install internationalization support for the clients using the specified locale.
subdownloader/subdownloader
subdownloader/client/internationalization.py
i18n_system_locale
def i18n_system_locale(): """ Return the system locale :return: the system locale (as a string) """ log.debug('i18n_system_locale() called') lc, encoding = locale.getlocale() log.debug('locale.getlocale() = (lc="{lc}", encoding="{encoding}).'.format(lc=lc, encoding=encoding)) if lc is No...
python
def i18n_system_locale(): """ Return the system locale :return: the system locale (as a string) """ log.debug('i18n_system_locale() called') lc, encoding = locale.getlocale() log.debug('locale.getlocale() = (lc="{lc}", encoding="{encoding}).'.format(lc=lc, encoding=encoding)) if lc is No...
[ "def", "i18n_system_locale", "(", ")", ":", "log", ".", "debug", "(", "'i18n_system_locale() called'", ")", "lc", ",", "encoding", "=", "locale", ".", "getlocale", "(", ")", "log", ".", "debug", "(", "'locale.getlocale() = (lc=\"{lc}\", encoding=\"{encoding}).'", "....
Return the system locale :return: the system locale (as a string)
[ "Return", "the", "system", "locale", ":", "return", ":", "the", "system", "locale", "(", "as", "a", "string", ")" ]
bbccedd11b18d925ad4c062b5eb65981e24d0433
https://github.com/subdownloader/subdownloader/blob/bbccedd11b18d925ad4c062b5eb65981e24d0433/subdownloader/client/internationalization.py#L44-L55
train
Return the system locale as a string
subdownloader/subdownloader
subdownloader/client/internationalization.py
i18n_locale_fallbacks_calculate
def i18n_locale_fallbacks_calculate(lc): """ Calculate all child locales from a locale. e.g. for locale="pt_BR.us-ascii", returns ["pt_BR.us-ascii", "pt_BR.us", "pt_BR", "pt"] :param lc: locale for which the child locales are needed :return: all child locales (including the parameter lc) """ ...
python
def i18n_locale_fallbacks_calculate(lc): """ Calculate all child locales from a locale. e.g. for locale="pt_BR.us-ascii", returns ["pt_BR.us-ascii", "pt_BR.us", "pt_BR", "pt"] :param lc: locale for which the child locales are needed :return: all child locales (including the parameter lc) """ ...
[ "def", "i18n_locale_fallbacks_calculate", "(", "lc", ")", ":", "log", ".", "debug", "(", "'i18n_locale_fallbacks_calculate( locale=\"{locale}\" ) called'", ".", "format", "(", "locale", "=", "lc", ")", ")", "locales", "=", "[", "]", "lc_original", "=", "lc", "whil...
Calculate all child locales from a locale. e.g. for locale="pt_BR.us-ascii", returns ["pt_BR.us-ascii", "pt_BR.us", "pt_BR", "pt"] :param lc: locale for which the child locales are needed :return: all child locales (including the parameter lc)
[ "Calculate", "all", "child", "locales", "from", "a", "locale", ".", "e", ".", "g", ".", "for", "locale", "=", "pt_BR", ".", "us", "-", "ascii", "returns", "[", "pt_BR", ".", "us", "-", "ascii", "pt_BR", ".", "us", "pt_BR", "pt", "]", ":", "param", ...
bbccedd11b18d925ad4c062b5eb65981e24d0433
https://github.com/subdownloader/subdownloader/blob/bbccedd11b18d925ad4c062b5eb65981e24d0433/subdownloader/client/internationalization.py#L58-L75
train
Calculate all child locales from a locale.
subdownloader/subdownloader
subdownloader/client/internationalization.py
i18n_support_locale
def i18n_support_locale(lc_parent): """ Find out whether lc is supported. Returns all child locales (and eventually lc) which do have support. :param lc_parent: Locale for which we want to know the child locales that are supported :return: list of supported locales """ log.debug('i18n_support_lo...
python
def i18n_support_locale(lc_parent): """ Find out whether lc is supported. Returns all child locales (and eventually lc) which do have support. :param lc_parent: Locale for which we want to know the child locales that are supported :return: list of supported locales """ log.debug('i18n_support_lo...
[ "def", "i18n_support_locale", "(", "lc_parent", ")", ":", "log", ".", "debug", "(", "'i18n_support_locale( locale=\"{locale}\" ) called'", ".", "format", "(", "locale", "=", "lc_parent", ")", ")", "lc_childs", "=", "i18n_locale_fallbacks_calculate", "(", "lc_parent", ...
Find out whether lc is supported. Returns all child locales (and eventually lc) which do have support. :param lc_parent: Locale for which we want to know the child locales that are supported :return: list of supported locales
[ "Find", "out", "whether", "lc", "is", "supported", ".", "Returns", "all", "child", "locales", "(", "and", "eventually", "lc", ")", "which", "do", "have", "support", ".", ":", "param", "lc_parent", ":", "Locale", "for", "which", "we", "want", "to", "know"...
bbccedd11b18d925ad4c062b5eb65981e24d0433
https://github.com/subdownloader/subdownloader/blob/bbccedd11b18d925ad4c062b5eb65981e24d0433/subdownloader/client/internationalization.py#L78-L101
train
Find out whether a locale is supported by the given locale.
subdownloader/subdownloader
subdownloader/client/internationalization.py
i18n_get_path
def i18n_get_path(): """ Get path to the internationalization data. :return: path as a string """ local_locale_path = client_get_path() / 'locale' if platform.system() == 'Linux': if local_locale_path.exists(): return local_locale_path else: return Path('/...
python
def i18n_get_path(): """ Get path to the internationalization data. :return: path as a string """ local_locale_path = client_get_path() / 'locale' if platform.system() == 'Linux': if local_locale_path.exists(): return local_locale_path else: return Path('/...
[ "def", "i18n_get_path", "(", ")", ":", "local_locale_path", "=", "client_get_path", "(", ")", "/", "'locale'", "if", "platform", ".", "system", "(", ")", "==", "'Linux'", ":", "if", "local_locale_path", ".", "exists", "(", ")", ":", "return", "local_locale_p...
Get path to the internationalization data. :return: path as a string
[ "Get", "path", "to", "the", "internationalization", "data", ".", ":", "return", ":", "path", "as", "a", "string" ]
bbccedd11b18d925ad4c062b5eb65981e24d0433
https://github.com/subdownloader/subdownloader/blob/bbccedd11b18d925ad4c062b5eb65981e24d0433/subdownloader/client/internationalization.py#L104-L116
train
Get path to the internationalization data.
subdownloader/subdownloader
subdownloader/client/internationalization.py
i18n_get_supported_locales
def i18n_get_supported_locales(): """ List all locales that have internationalization data for this program :return: List of locales """ locale_path = i18n_get_path() log.debug('Scanning translation files .mo in locale path: {}'.format(locale_path)) langs = [] mo_file = '{project}.mo'.fo...
python
def i18n_get_supported_locales(): """ List all locales that have internationalization data for this program :return: List of locales """ locale_path = i18n_get_path() log.debug('Scanning translation files .mo in locale path: {}'.format(locale_path)) langs = [] mo_file = '{project}.mo'.fo...
[ "def", "i18n_get_supported_locales", "(", ")", ":", "locale_path", "=", "i18n_get_path", "(", ")", "log", ".", "debug", "(", "'Scanning translation files .mo in locale path: {}'", ".", "format", "(", "locale_path", ")", ")", "langs", "=", "[", "]", "mo_file", "=",...
List all locales that have internationalization data for this program :return: List of locales
[ "List", "all", "locales", "that", "have", "internationalization", "data", "for", "this", "program", ":", "return", ":", "List", "of", "locales" ]
bbccedd11b18d925ad4c062b5eb65981e24d0433
https://github.com/subdownloader/subdownloader/blob/bbccedd11b18d925ad4c062b5eb65981e24d0433/subdownloader/client/internationalization.py#L119-L133
train
Returns a list of all locales that have internationalization data for this program
cenkalti/kuyruk
kuyruk/config.py
Config.from_object
def from_object(self, obj: Union[str, Any]) -> None: """Load values from an object.""" if isinstance(obj, str): obj = importer.import_object_str(obj) for key in dir(obj): if key.isupper(): value = getattr(obj, key) self._setattr(key, value...
python
def from_object(self, obj: Union[str, Any]) -> None: """Load values from an object.""" if isinstance(obj, str): obj = importer.import_object_str(obj) for key in dir(obj): if key.isupper(): value = getattr(obj, key) self._setattr(key, value...
[ "def", "from_object", "(", "self", ",", "obj", ":", "Union", "[", "str", ",", "Any", "]", ")", "->", "None", ":", "if", "isinstance", "(", "obj", ",", "str", ")", ":", "obj", "=", "importer", ".", "import_object_str", "(", "obj", ")", "for", "key",...
Load values from an object.
[ "Load", "values", "from", "an", "object", "." ]
c99d66be9d8fb077610f2fa883d5a1d268b42f04
https://github.com/cenkalti/kuyruk/blob/c99d66be9d8fb077610f2fa883d5a1d268b42f04/kuyruk/config.py#L62-L72
train
Load values from an object.
cenkalti/kuyruk
kuyruk/config.py
Config.from_dict
def from_dict(self, d: Dict[str, Any]) -> None: """Load values from a dict.""" for key, value in d.items(): if key.isupper(): self._setattr(key, value) logger.info("Config is loaded from dict: %r", d)
python
def from_dict(self, d: Dict[str, Any]) -> None: """Load values from a dict.""" for key, value in d.items(): if key.isupper(): self._setattr(key, value) logger.info("Config is loaded from dict: %r", d)
[ "def", "from_dict", "(", "self", ",", "d", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "None", ":", "for", "key", ",", "value", "in", "d", ".", "items", "(", ")", ":", "if", "key", ".", "isupper", "(", ")", ":", "self", ".", "_setatt...
Load values from a dict.
[ "Load", "values", "from", "a", "dict", "." ]
c99d66be9d8fb077610f2fa883d5a1d268b42f04
https://github.com/cenkalti/kuyruk/blob/c99d66be9d8fb077610f2fa883d5a1d268b42f04/kuyruk/config.py#L74-L80
train
Load values from a dict.
cenkalti/kuyruk
kuyruk/config.py
Config.from_pyfile
def from_pyfile(self, filename: str) -> None: """Load values from a Python file.""" globals_ = {} # type: Dict[str, Any] locals_ = {} # type: Dict[str, Any] with open(filename, "rb") as f: exec(compile(f.read(), filename, 'exec'), globals_, locals_) for key, value ...
python
def from_pyfile(self, filename: str) -> None: """Load values from a Python file.""" globals_ = {} # type: Dict[str, Any] locals_ = {} # type: Dict[str, Any] with open(filename, "rb") as f: exec(compile(f.read(), filename, 'exec'), globals_, locals_) for key, value ...
[ "def", "from_pyfile", "(", "self", ",", "filename", ":", "str", ")", "->", "None", ":", "globals_", "=", "{", "}", "# type: Dict[str, Any]", "locals_", "=", "{", "}", "# type: Dict[str, Any]", "with", "open", "(", "filename", ",", "\"rb\"", ")", "as", "f",...
Load values from a Python file.
[ "Load", "values", "from", "a", "Python", "file", "." ]
c99d66be9d8fb077610f2fa883d5a1d268b42f04
https://github.com/cenkalti/kuyruk/blob/c99d66be9d8fb077610f2fa883d5a1d268b42f04/kuyruk/config.py#L90-L101
train
Load values from a Python file.
cenkalti/kuyruk
kuyruk/config.py
Config.from_env_vars
def from_env_vars(self) -> None: """Load values from environment variables. Keys must start with `KUYRUK_`.""" for key, value in os.environ.items(): if key.startswith('KUYRUK_'): key = key[7:] if hasattr(Config, key): try: ...
python
def from_env_vars(self) -> None: """Load values from environment variables. Keys must start with `KUYRUK_`.""" for key, value in os.environ.items(): if key.startswith('KUYRUK_'): key = key[7:] if hasattr(Config, key): try: ...
[ "def", "from_env_vars", "(", "self", ")", "->", "None", ":", "for", "key", ",", "value", "in", "os", ".", "environ", ".", "items", "(", ")", ":", "if", "key", ".", "startswith", "(", "'KUYRUK_'", ")", ":", "key", "=", "key", "[", "7", ":", "]", ...
Load values from environment variables. Keys must start with `KUYRUK_`.
[ "Load", "values", "from", "environment", "variables", ".", "Keys", "must", "start", "with", "KUYRUK_", "." ]
c99d66be9d8fb077610f2fa883d5a1d268b42f04
https://github.com/cenkalti/kuyruk/blob/c99d66be9d8fb077610f2fa883d5a1d268b42f04/kuyruk/config.py#L103-L115
train
Load values from environment variables.
jonbretman/jinja-to-js
jinja_to_js/__init__.py
option
def option(current_kwargs, **kwargs): """ Context manager for temporarily setting a keyword argument and then restoring it to whatever it was before. """ tmp_kwargs = dict((key, current_kwargs.get(key)) for key, value in kwargs.items()) current_kwargs.update(kwargs) yield current_kwargs...
python
def option(current_kwargs, **kwargs): """ Context manager for temporarily setting a keyword argument and then restoring it to whatever it was before. """ tmp_kwargs = dict((key, current_kwargs.get(key)) for key, value in kwargs.items()) current_kwargs.update(kwargs) yield current_kwargs...
[ "def", "option", "(", "current_kwargs", ",", "*", "*", "kwargs", ")", ":", "tmp_kwargs", "=", "dict", "(", "(", "key", ",", "current_kwargs", ".", "get", "(", "key", ")", ")", "for", "key", ",", "value", "in", "kwargs", ".", "items", "(", ")", ")",...
Context manager for temporarily setting a keyword argument and then restoring it to whatever it was before.
[ "Context", "manager", "for", "temporarily", "setting", "a", "keyword", "argument", "and", "then", "restoring", "it", "to", "whatever", "it", "was", "before", "." ]
0a784b10a83d37a3171c5797547e9fc460c51289
https://github.com/jonbretman/jinja-to-js/blob/0a784b10a83d37a3171c5797547e9fc460c51289/jinja_to_js/__init__.py#L105-L114
train
Context manager for temporarily setting a keyword argument and then restoring it to whatever it was before.
jonbretman/jinja-to-js
jinja_to_js/__init__.py
is_method_call
def is_method_call(node, method_name): """ Returns True if `node` is a method call for `method_name`. `method_name` can be either a string or an iterable of strings. """ if not isinstance(node, nodes.Call): return False if isinstance(node.node, nodes.Getattr): # e.g. foo.bar() ...
python
def is_method_call(node, method_name): """ Returns True if `node` is a method call for `method_name`. `method_name` can be either a string or an iterable of strings. """ if not isinstance(node, nodes.Call): return False if isinstance(node.node, nodes.Getattr): # e.g. foo.bar() ...
[ "def", "is_method_call", "(", "node", ",", "method_name", ")", ":", "if", "not", "isinstance", "(", "node", ",", "nodes", ".", "Call", ")", ":", "return", "False", "if", "isinstance", "(", "node", ".", "node", ",", "nodes", ".", "Getattr", ")", ":", ...
Returns True if `node` is a method call for `method_name`. `method_name` can be either a string or an iterable of strings.
[ "Returns", "True", "if", "node", "is", "a", "method", "call", "for", "method_name", ".", "method_name", "can", "be", "either", "a", "string", "or", "an", "iterable", "of", "strings", "." ]
0a784b10a83d37a3171c5797547e9fc460c51289
https://github.com/jonbretman/jinja-to-js/blob/0a784b10a83d37a3171c5797547e9fc460c51289/jinja_to_js/__init__.py#L117-L144
train
Returns True if node is a method call for method_name.
jonbretman/jinja-to-js
jinja_to_js/__init__.py
is_loop_helper
def is_loop_helper(node): """ Returns True is node is a loop helper e.g. {{ loop.index }} or {{ loop.first }} """ return hasattr(node, 'node') and isinstance(node.node, nodes.Name) and node.node.name == 'loop'
python
def is_loop_helper(node): """ Returns True is node is a loop helper e.g. {{ loop.index }} or {{ loop.first }} """ return hasattr(node, 'node') and isinstance(node.node, nodes.Name) and node.node.name == 'loop'
[ "def", "is_loop_helper", "(", "node", ")", ":", "return", "hasattr", "(", "node", ",", "'node'", ")", "and", "isinstance", "(", "node", ".", "node", ",", "nodes", ".", "Name", ")", "and", "node", ".", "node", ".", "name", "==", "'loop'" ]
Returns True is node is a loop helper e.g. {{ loop.index }} or {{ loop.first }}
[ "Returns", "True", "is", "node", "is", "a", "loop", "helper", "e", ".", "g", ".", "{{", "loop", ".", "index", "}}", "or", "{{", "loop", ".", "first", "}}" ]
0a784b10a83d37a3171c5797547e9fc460c51289
https://github.com/jonbretman/jinja-to-js/blob/0a784b10a83d37a3171c5797547e9fc460c51289/jinja_to_js/__init__.py#L147-L151
train
Returns True is node is a loop helper e. g. loop. index or loop. first
jonbretman/jinja-to-js
jinja_to_js/__init__.py
JinjaToJS.get_output
def get_output(self): """ Returns the generated JavaScript code. Returns: str """ # generate the JS function string template_function = TEMPLATE_WRAPPER.format( function_name=self.js_function_name, template_code=self.output.getvalue() ...
python
def get_output(self): """ Returns the generated JavaScript code. Returns: str """ # generate the JS function string template_function = TEMPLATE_WRAPPER.format( function_name=self.js_function_name, template_code=self.output.getvalue() ...
[ "def", "get_output", "(", "self", ")", ":", "# generate the JS function string", "template_function", "=", "TEMPLATE_WRAPPER", ".", "format", "(", "function_name", "=", "self", ".", "js_function_name", ",", "template_code", "=", "self", ".", "output", ".", "getvalue...
Returns the generated JavaScript code. Returns: str
[ "Returns", "the", "generated", "JavaScript", "code", "." ]
0a784b10a83d37a3171c5797547e9fc460c51289
https://github.com/jonbretman/jinja-to-js/blob/0a784b10a83d37a3171c5797547e9fc460c51289/jinja_to_js/__init__.py#L251-L268
train
Returns the generated JavaScript code.
jonbretman/jinja-to-js
jinja_to_js/__init__.py
JinjaToJS._get_depencency_var_name
def _get_depencency_var_name(self, dependency): """ Returns the variable name assigned to the given dependency or None if the dependency has not yet been registered. Args: dependency (str): Thet dependency that needs to be imported. Returns: str or None ...
python
def _get_depencency_var_name(self, dependency): """ Returns the variable name assigned to the given dependency or None if the dependency has not yet been registered. Args: dependency (str): Thet dependency that needs to be imported. Returns: str or None ...
[ "def", "_get_depencency_var_name", "(", "self", ",", "dependency", ")", ":", "for", "dep_path", ",", "var_name", "in", "self", ".", "dependencies", ":", "if", "dep_path", "==", "dependency", ":", "return", "var_name" ]
Returns the variable name assigned to the given dependency or None if the dependency has not yet been registered. Args: dependency (str): Thet dependency that needs to be imported. Returns: str or None
[ "Returns", "the", "variable", "name", "assigned", "to", "the", "given", "dependency", "or", "None", "if", "the", "dependency", "has", "not", "yet", "been", "registered", "." ]
0a784b10a83d37a3171c5797547e9fc460c51289
https://github.com/jonbretman/jinja-to-js/blob/0a784b10a83d37a3171c5797547e9fc460c51289/jinja_to_js/__init__.py#L270-L283
train
Returns the variable name assigned to the given dependency.
jonbretman/jinja-to-js
jinja_to_js/__init__.py
JinjaToJS._add_dependency
def _add_dependency(self, dependency, var_name=None): """ Adds the given dependency and returns the variable name to use to access it. If `var_name` is not given then a random one will be created. Args: dependency (str): var_name (str, optional): Returns...
python
def _add_dependency(self, dependency, var_name=None): """ Adds the given dependency and returns the variable name to use to access it. If `var_name` is not given then a random one will be created. Args: dependency (str): var_name (str, optional): Returns...
[ "def", "_add_dependency", "(", "self", ",", "dependency", ",", "var_name", "=", "None", ")", ":", "if", "var_name", "is", "None", ":", "var_name", "=", "next", "(", "self", ".", "temp_var_names", ")", "# Don't add duplicate dependencies", "if", "(", "dependenc...
Adds the given dependency and returns the variable name to use to access it. If `var_name` is not given then a random one will be created. Args: dependency (str): var_name (str, optional): Returns: str
[ "Adds", "the", "given", "dependency", "and", "returns", "the", "variable", "name", "to", "use", "to", "access", "it", ".", "If", "var_name", "is", "not", "given", "then", "a", "random", "one", "will", "be", "created", "." ]
0a784b10a83d37a3171c5797547e9fc460c51289
https://github.com/jonbretman/jinja-to-js/blob/0a784b10a83d37a3171c5797547e9fc460c51289/jinja_to_js/__init__.py#L285-L302
train
Adds the given dependency and returns the variable name to use to access it.
jonbretman/jinja-to-js
jinja_to_js/__init__.py
JinjaToJS._process_extends
def _process_extends(self, node, **kwargs): """ Processes an extends block e.g. `{% extends "some/template.jinja" %}` """ # find all the blocks in this template for b in self.ast.find_all(nodes.Block): # if not already in `child_blocks` then this is the first time a...
python
def _process_extends(self, node, **kwargs): """ Processes an extends block e.g. `{% extends "some/template.jinja" %}` """ # find all the blocks in this template for b in self.ast.find_all(nodes.Block): # if not already in `child_blocks` then this is the first time a...
[ "def", "_process_extends", "(", "self", ",", "node", ",", "*", "*", "kwargs", ")", ":", "# find all the blocks in this template", "for", "b", "in", "self", ".", "ast", ".", "find_all", "(", "nodes", ".", "Block", ")", ":", "# if not already in `child_blocks` the...
Processes an extends block e.g. `{% extends "some/template.jinja" %}`
[ "Processes", "an", "extends", "block", "e", ".", "g", ".", "{", "%", "extends", "some", "/", "template", ".", "jinja", "%", "}" ]
0a784b10a83d37a3171c5797547e9fc460c51289
https://github.com/jonbretman/jinja-to-js/blob/0a784b10a83d37a3171c5797547e9fc460c51289/jinja_to_js/__init__.py#L312-L347
train
Processes an extends block e. g. some. template. jinja
jonbretman/jinja-to-js
jinja_to_js/__init__.py
JinjaToJS._process_block
def _process_block(self, node, **kwargs): """ Processes a block e.g. `{% block my_block %}{% endblock %}` """ # check if this node already has a 'super_block' attribute if not hasattr(node, 'super_block'): # since it doesn't it must be the last block in the inherita...
python
def _process_block(self, node, **kwargs): """ Processes a block e.g. `{% block my_block %}{% endblock %}` """ # check if this node already has a 'super_block' attribute if not hasattr(node, 'super_block'): # since it doesn't it must be the last block in the inherita...
[ "def", "_process_block", "(", "self", ",", "node", ",", "*", "*", "kwargs", ")", ":", "# check if this node already has a 'super_block' attribute", "if", "not", "hasattr", "(", "node", ",", "'super_block'", ")", ":", "# since it doesn't it must be the last block in the in...
Processes a block e.g. `{% block my_block %}{% endblock %}`
[ "Processes", "a", "block", "e", ".", "g", ".", "{", "%", "block", "my_block", "%", "}", "{", "%", "endblock", "%", "}" ]
0a784b10a83d37a3171c5797547e9fc460c51289
https://github.com/jonbretman/jinja-to-js/blob/0a784b10a83d37a3171c5797547e9fc460c51289/jinja_to_js/__init__.py#L349-L381
train
Processes a block e. g. my_block endblock
jonbretman/jinja-to-js
jinja_to_js/__init__.py
JinjaToJS._process_output
def _process_output(self, node, **kwargs): """ Processes an output node, which will contain things like `Name` and `TemplateData` nodes. """ for n in node.nodes: self._process_node(n, **kwargs)
python
def _process_output(self, node, **kwargs): """ Processes an output node, which will contain things like `Name` and `TemplateData` nodes. """ for n in node.nodes: self._process_node(n, **kwargs)
[ "def", "_process_output", "(", "self", ",", "node", ",", "*", "*", "kwargs", ")", ":", "for", "n", "in", "node", ".", "nodes", ":", "self", ".", "_process_node", "(", "n", ",", "*", "*", "kwargs", ")" ]
Processes an output node, which will contain things like `Name` and `TemplateData` nodes.
[ "Processes", "an", "output", "node", "which", "will", "contain", "things", "like", "Name", "and", "TemplateData", "nodes", "." ]
0a784b10a83d37a3171c5797547e9fc460c51289
https://github.com/jonbretman/jinja-to-js/blob/0a784b10a83d37a3171c5797547e9fc460c51289/jinja_to_js/__init__.py#L383-L388
train
Processes an output node which will contain things like Name and TemplateData nodes.
jonbretman/jinja-to-js
jinja_to_js/__init__.py
JinjaToJS._process_templatedata
def _process_templatedata(self, node, **_): """ Processes a `TemplateData` node, this is just a bit of as-is text to be written to the output. """ # escape double quotes value = re.sub('"', r'\\"', node.data) # escape new lines value = re.sub('\n', r'\\n...
python
def _process_templatedata(self, node, **_): """ Processes a `TemplateData` node, this is just a bit of as-is text to be written to the output. """ # escape double quotes value = re.sub('"', r'\\"', node.data) # escape new lines value = re.sub('\n', r'\\n...
[ "def", "_process_templatedata", "(", "self", ",", "node", ",", "*", "*", "_", ")", ":", "# escape double quotes", "value", "=", "re", ".", "sub", "(", "'\"'", ",", "r'\\\\\"'", ",", "node", ".", "data", ")", "# escape new lines", "value", "=", "re", ".",...
Processes a `TemplateData` node, this is just a bit of as-is text to be written to the output.
[ "Processes", "a", "TemplateData", "node", "this", "is", "just", "a", "bit", "of", "as", "-", "is", "text", "to", "be", "written", "to", "the", "output", "." ]
0a784b10a83d37a3171c5797547e9fc460c51289
https://github.com/jonbretman/jinja-to-js/blob/0a784b10a83d37a3171c5797547e9fc460c51289/jinja_to_js/__init__.py#L390-L403
train
Processes a TemplateData node.
jonbretman/jinja-to-js
jinja_to_js/__init__.py
JinjaToJS._process_name
def _process_name(self, node, **kwargs): """ Processes a `Name` node. Some examples of `Name` nodes: {{ foo }} -> 'foo' is a Name {% if foo }} -> 'foo' is a Name """ with self._interpolation(): with self._python_bool_wrapper(**kwargs): ...
python
def _process_name(self, node, **kwargs): """ Processes a `Name` node. Some examples of `Name` nodes: {{ foo }} -> 'foo' is a Name {% if foo }} -> 'foo' is a Name """ with self._interpolation(): with self._python_bool_wrapper(**kwargs): ...
[ "def", "_process_name", "(", "self", ",", "node", ",", "*", "*", "kwargs", ")", ":", "with", "self", ".", "_interpolation", "(", ")", ":", "with", "self", ".", "_python_bool_wrapper", "(", "*", "*", "kwargs", ")", ":", "if", "node", ".", "name", "not...
Processes a `Name` node. Some examples of `Name` nodes: {{ foo }} -> 'foo' is a Name {% if foo }} -> 'foo' is a Name
[ "Processes", "a", "Name", "node", ".", "Some", "examples", "of", "Name", "nodes", ":", "{{", "foo", "}}", "-", ">", "foo", "is", "a", "Name", "{", "%", "if", "foo", "}}", "-", ">", "foo", "is", "a", "Name" ]
0a784b10a83d37a3171c5797547e9fc460c51289
https://github.com/jonbretman/jinja-to-js/blob/0a784b10a83d37a3171c5797547e9fc460c51289/jinja_to_js/__init__.py#L405-L422
train
Processes a Name node.
jonbretman/jinja-to-js
jinja_to_js/__init__.py
JinjaToJS._process_getattr
def _process_getattr(self, node, **kwargs): """ Processes a `GetAttr` node. e.g. {{ foo.bar }} """ with self._interpolation(): with self._python_bool_wrapper(**kwargs) as new_kwargs: if is_loop_helper(node): self._process_loop_helper(node,...
python
def _process_getattr(self, node, **kwargs): """ Processes a `GetAttr` node. e.g. {{ foo.bar }} """ with self._interpolation(): with self._python_bool_wrapper(**kwargs) as new_kwargs: if is_loop_helper(node): self._process_loop_helper(node,...
[ "def", "_process_getattr", "(", "self", ",", "node", ",", "*", "*", "kwargs", ")", ":", "with", "self", ".", "_interpolation", "(", ")", ":", "with", "self", ".", "_python_bool_wrapper", "(", "*", "*", "kwargs", ")", "as", "new_kwargs", ":", "if", "is_...
Processes a `GetAttr` node. e.g. {{ foo.bar }}
[ "Processes", "a", "GetAttr", "node", ".", "e", ".", "g", ".", "{{", "foo", ".", "bar", "}}" ]
0a784b10a83d37a3171c5797547e9fc460c51289
https://github.com/jonbretman/jinja-to-js/blob/0a784b10a83d37a3171c5797547e9fc460c51289/jinja_to_js/__init__.py#L424-L436
train
Processes a GetAttr node. e. g. foo. bar.
jonbretman/jinja-to-js
jinja_to_js/__init__.py
JinjaToJS._process_getitem
def _process_getitem(self, node, **kwargs): """ Processes a `GetItem` node e.g. {{ foo["bar"] }} """ with self._interpolation(): with self._python_bool_wrapper(**kwargs) as new_kwargs: self._process_node(node.node, **new_kwargs) if isinstance...
python
def _process_getitem(self, node, **kwargs): """ Processes a `GetItem` node e.g. {{ foo["bar"] }} """ with self._interpolation(): with self._python_bool_wrapper(**kwargs) as new_kwargs: self._process_node(node.node, **new_kwargs) if isinstance...
[ "def", "_process_getitem", "(", "self", ",", "node", ",", "*", "*", "kwargs", ")", ":", "with", "self", ".", "_interpolation", "(", ")", ":", "with", "self", ".", "_python_bool_wrapper", "(", "*", "*", "kwargs", ")", "as", "new_kwargs", ":", "self", "....
Processes a `GetItem` node e.g. {{ foo["bar"] }}
[ "Processes", "a", "GetItem", "node", "e", ".", "g", ".", "{{", "foo", "[", "bar", "]", "}}" ]
0a784b10a83d37a3171c5797547e9fc460c51289
https://github.com/jonbretman/jinja-to-js/blob/0a784b10a83d37a3171c5797547e9fc460c51289/jinja_to_js/__init__.py#L438-L467
train
Processes a GetItem node e. g. foo. bar.
jonbretman/jinja-to-js
jinja_to_js/__init__.py
JinjaToJS._process_for
def _process_for(self, node, **kwargs): """ Processes a for loop. e.g. {% for number in numbers %} {{ number }} {% endfor %} {% for key, value in somemap.items() %} {{ key }} -> {{ value }} {% %} """ # since...
python
def _process_for(self, node, **kwargs): """ Processes a for loop. e.g. {% for number in numbers %} {{ number }} {% endfor %} {% for key, value in somemap.items() %} {{ key }} -> {{ value }} {% %} """ # since...
[ "def", "_process_for", "(", "self", ",", "node", ",", "*", "*", "kwargs", ")", ":", "# since a for loop can introduce new names into the context", "# we need to remember the ones that existed outside the loop", "previous_stored_names", "=", "self", ".", "stored_names", ".", "...
Processes a for loop. e.g. {% for number in numbers %} {{ number }} {% endfor %} {% for key, value in somemap.items() %} {{ key }} -> {{ value }} {% %}
[ "Processes", "a", "for", "loop", ".", "e", ".", "g", ".", "{", "%", "for", "number", "in", "numbers", "%", "}", "{{", "number", "}}", "{", "%", "endfor", "%", "}", "{", "%", "for", "key", "value", "in", "somemap", ".", "items", "()", "%", "}", ...
0a784b10a83d37a3171c5797547e9fc460c51289
https://github.com/jonbretman/jinja-to-js/blob/0a784b10a83d37a3171c5797547e9fc460c51289/jinja_to_js/__init__.py#L469-L531
train
Processes a for loop. e. g. for loops.
jonbretman/jinja-to-js
jinja_to_js/__init__.py
JinjaToJS._process_math
def _process_math(self, node, math_operator=None, function=None, **kwargs): """ Processes a math node e.g. `Div`, `Sub`, `Add`, `Mul` etc... If `function` is provided the expression is wrapped in a call to that function. """ with self._interpolation(): if function: ...
python
def _process_math(self, node, math_operator=None, function=None, **kwargs): """ Processes a math node e.g. `Div`, `Sub`, `Add`, `Mul` etc... If `function` is provided the expression is wrapped in a call to that function. """ with self._interpolation(): if function: ...
[ "def", "_process_math", "(", "self", ",", "node", ",", "math_operator", "=", "None", ",", "function", "=", "None", ",", "*", "*", "kwargs", ")", ":", "with", "self", ".", "_interpolation", "(", ")", ":", "if", "function", ":", "self", ".", "output", ...
Processes a math node e.g. `Div`, `Sub`, `Add`, `Mul` etc... If `function` is provided the expression is wrapped in a call to that function.
[ "Processes", "a", "math", "node", "e", ".", "g", ".", "Div", "Sub", "Add", "Mul", "etc", "...", "If", "function", "is", "provided", "the", "expression", "is", "wrapped", "in", "a", "call", "to", "that", "function", "." ]
0a784b10a83d37a3171c5797547e9fc460c51289
https://github.com/jonbretman/jinja-to-js/blob/0a784b10a83d37a3171c5797547e9fc460c51289/jinja_to_js/__init__.py#L1010-L1026
train
Processes a math node e. g. Div Sub Add Mul etc...
jonbretman/jinja-to-js
jinja_to_js/__init__.py
JinjaToJS._process_loop_helper
def _process_loop_helper(self, node, **kwargs): """ Processes a loop helper e.g. {{ loop.first }} or {{ loop.index }} """ if node.attr == LOOP_HELPER_INDEX: self.output.write('(arguments[1] + 1)') elif node.attr == LOOP_HELPER_INDEX_0: self.output.write('...
python
def _process_loop_helper(self, node, **kwargs): """ Processes a loop helper e.g. {{ loop.first }} or {{ loop.index }} """ if node.attr == LOOP_HELPER_INDEX: self.output.write('(arguments[1] + 1)') elif node.attr == LOOP_HELPER_INDEX_0: self.output.write('...
[ "def", "_process_loop_helper", "(", "self", ",", "node", ",", "*", "*", "kwargs", ")", ":", "if", "node", ".", "attr", "==", "LOOP_HELPER_INDEX", ":", "self", ".", "output", ".", "write", "(", "'(arguments[1] + 1)'", ")", "elif", "node", ".", "attr", "==...
Processes a loop helper e.g. {{ loop.first }} or {{ loop.index }}
[ "Processes", "a", "loop", "helper", "e", ".", "g", ".", "{{", "loop", ".", "first", "}}", "or", "{{", "loop", ".", "index", "}}" ]
0a784b10a83d37a3171c5797547e9fc460c51289
https://github.com/jonbretman/jinja-to-js/blob/0a784b10a83d37a3171c5797547e9fc460c51289/jinja_to_js/__init__.py#L1028-L1042
train
Processes a loop helper e. g. loop. first or loop. last.
jonbretman/jinja-to-js
jinja_to_js/__init__.py
JinjaToJS._execution
def _execution(self): """ Context manager for executing some JavaScript inside a template. """ did_start_executing = False if self.state == STATE_DEFAULT: did_start_executing = True self.state = STATE_EXECUTING def close(): if did_st...
python
def _execution(self): """ Context manager for executing some JavaScript inside a template. """ did_start_executing = False if self.state == STATE_DEFAULT: did_start_executing = True self.state = STATE_EXECUTING def close(): if did_st...
[ "def", "_execution", "(", "self", ")", ":", "did_start_executing", "=", "False", "if", "self", ".", "state", "==", "STATE_DEFAULT", ":", "did_start_executing", "=", "True", "self", ".", "state", "=", "STATE_EXECUTING", "def", "close", "(", ")", ":", "if", ...
Context manager for executing some JavaScript inside a template.
[ "Context", "manager", "for", "executing", "some", "JavaScript", "inside", "a", "template", "." ]
0a784b10a83d37a3171c5797547e9fc460c51289
https://github.com/jonbretman/jinja-to-js/blob/0a784b10a83d37a3171c5797547e9fc460c51289/jinja_to_js/__init__.py#L1054-L1070
train
Context manager for executing some JavaScript inside a template.
jonbretman/jinja-to-js
jinja_to_js/__init__.py
JinjaToJS._scoped_variables
def _scoped_variables(self, nodes_list, **kwargs): """ Context manager for creating scoped variables defined by the nodes in `nodes_list`. These variables will be added to the context, and when the context manager exits the context object will be restored to it's previous state. ...
python
def _scoped_variables(self, nodes_list, **kwargs): """ Context manager for creating scoped variables defined by the nodes in `nodes_list`. These variables will be added to the context, and when the context manager exits the context object will be restored to it's previous state. ...
[ "def", "_scoped_variables", "(", "self", ",", "nodes_list", ",", "*", "*", "kwargs", ")", ":", "tmp_vars", "=", "[", "]", "for", "node", "in", "nodes_list", ":", "is_assign_node", "=", "isinstance", "(", "node", ",", "nodes", ".", "Assign", ")", "name", ...
Context manager for creating scoped variables defined by the nodes in `nodes_list`. These variables will be added to the context, and when the context manager exits the context object will be restored to it's previous state.
[ "Context", "manager", "for", "creating", "scoped", "variables", "defined", "by", "the", "nodes", "in", "nodes_list", ".", "These", "variables", "will", "be", "added", "to", "the", "context", "and", "when", "the", "context", "manager", "exits", "the", "context"...
0a784b10a83d37a3171c5797547e9fc460c51289
https://github.com/jonbretman/jinja-to-js/blob/0a784b10a83d37a3171c5797547e9fc460c51289/jinja_to_js/__init__.py#L1094-L1133
train
Context manager for creating scoped variables defined by the nodes in nodes_list.
subdownloader/subdownloader
subdownloader/webutil.py
download_raw
def download_raw(url, local_path, callback): """ Download an url to a local file. :param url: url of the file to download :param local_path: path where the downloaded file should be saved :param callback: instance of ProgressCallback :return: True is succeeded """ log.debug('download_raw...
python
def download_raw(url, local_path, callback): """ Download an url to a local file. :param url: url of the file to download :param local_path: path where the downloaded file should be saved :param callback: instance of ProgressCallback :return: True is succeeded """ log.debug('download_raw...
[ "def", "download_raw", "(", "url", ",", "local_path", ",", "callback", ")", ":", "log", ".", "debug", "(", "'download_raw(url={url}, local_path={local_path})'", ".", "format", "(", "url", "=", "url", ",", "local_path", "=", "local_path", ")", ")", "raw_progress"...
Download an url to a local file. :param url: url of the file to download :param local_path: path where the downloaded file should be saved :param callback: instance of ProgressCallback :return: True is succeeded
[ "Download", "an", "url", "to", "a", "local", "file", ".", ":", "param", "url", ":", "url", "of", "the", "file", "to", "download", ":", "param", "local_path", ":", "path", "where", "the", "downloaded", "file", "should", "be", "saved", ":", "param", "cal...
bbccedd11b18d925ad4c062b5eb65981e24d0433
https://github.com/subdownloader/subdownloader/blob/bbccedd11b18d925ad4c062b5eb65981e24d0433/subdownloader/webutil.py#L47-L67
train
Download an url to a local file.
subdownloader/subdownloader
subdownloader/webutil.py
RawDownloadProgress.get_report_hook
def get_report_hook(self): """ Return a callback function suitable for using reporthook argument of urllib(.request).urlretrieve :return: function object """ def report_hook(chunkNumber, chunkSize, totalSize): if totalSize != -1 and not self._callback.range_initialize...
python
def get_report_hook(self): """ Return a callback function suitable for using reporthook argument of urllib(.request).urlretrieve :return: function object """ def report_hook(chunkNumber, chunkSize, totalSize): if totalSize != -1 and not self._callback.range_initialize...
[ "def", "get_report_hook", "(", "self", ")", ":", "def", "report_hook", "(", "chunkNumber", ",", "chunkSize", ",", "totalSize", ")", ":", "if", "totalSize", "!=", "-", "1", "and", "not", "self", ".", "_callback", ".", "range_initialized", "(", ")", ":", "...
Return a callback function suitable for using reporthook argument of urllib(.request).urlretrieve :return: function object
[ "Return", "a", "callback", "function", "suitable", "for", "using", "reporthook", "argument", "of", "urllib", "(", ".", "request", ")", ".", "urlretrieve", ":", "return", ":", "function", "object" ]
bbccedd11b18d925ad4c062b5eb65981e24d0433
https://github.com/subdownloader/subdownloader/blob/bbccedd11b18d925ad4c062b5eb65981e24d0433/subdownloader/webutil.py#L83-L99
train
Returns a callback function suitable for using reporthook argument of urllib. request. urlretrieve
subdownloader/subdownloader
subdownloader/provider/__init__.py
window_iterator
def window_iterator(data, width): """ Instead of iterating element by element, get a number of elements at each iteration step. :param data: data to iterate on :param width: maximum number of elements to get in each iteration step :return: """ start = 0 while start < len(data): y...
python
def window_iterator(data, width): """ Instead of iterating element by element, get a number of elements at each iteration step. :param data: data to iterate on :param width: maximum number of elements to get in each iteration step :return: """ start = 0 while start < len(data): y...
[ "def", "window_iterator", "(", "data", ",", "width", ")", ":", "start", "=", "0", "while", "start", "<", "len", "(", "data", ")", ":", "yield", "data", "[", "start", ":", "start", "+", "width", "]", "start", "+=", "width" ]
Instead of iterating element by element, get a number of elements at each iteration step. :param data: data to iterate on :param width: maximum number of elements to get in each iteration step :return:
[ "Instead", "of", "iterating", "element", "by", "element", "get", "a", "number", "of", "elements", "at", "each", "iteration", "step", ".", ":", "param", "data", ":", "data", "to", "iterate", "on", ":", "param", "width", ":", "maximum", "number", "of", "el...
bbccedd11b18d925ad4c062b5eb65981e24d0433
https://github.com/subdownloader/subdownloader/blob/bbccedd11b18d925ad4c062b5eb65981e24d0433/subdownloader/provider/__init__.py#L5-L15
train
This function is used to iterate over the data in a window.
subdownloader/subdownloader
subdownloader/callback.py
ProgressCallback.set_range
def set_range(self, minimum, maximum): """ Set a range. The range is passed unchanged to the rangeChanged member function. :param minimum: minimum value of the range (None if no percentage is required) :param maximum: maximum value of the range (None if no percentage is required)...
python
def set_range(self, minimum, maximum): """ Set a range. The range is passed unchanged to the rangeChanged member function. :param minimum: minimum value of the range (None if no percentage is required) :param maximum: maximum value of the range (None if no percentage is required)...
[ "def", "set_range", "(", "self", ",", "minimum", ",", "maximum", ")", ":", "self", ".", "_min", "=", "minimum", "self", ".", "_max", "=", "maximum", "self", ".", "on_rangeChange", "(", "minimum", ",", "maximum", ")" ]
Set a range. The range is passed unchanged to the rangeChanged member function. :param minimum: minimum value of the range (None if no percentage is required) :param maximum: maximum value of the range (None if no percentage is required)
[ "Set", "a", "range", ".", "The", "range", "is", "passed", "unchanged", "to", "the", "rangeChanged", "member", "function", ".", ":", "param", "minimum", ":", "minimum", "value", "of", "the", "range", "(", "None", "if", "no", "percentage", "is", "required", ...
bbccedd11b18d925ad4c062b5eb65981e24d0433
https://github.com/subdownloader/subdownloader/blob/bbccedd11b18d925ad4c062b5eb65981e24d0433/subdownloader/callback.py#L32-L41
train
Set the minimum and maximum value of the cache entry.
subdownloader/subdownloader
subdownloader/callback.py
ProgressCallback.get_child_progress
def get_child_progress(self, parent_min, parent_max): """ Create a new child ProgressCallback. Minimum and maximum values of the child are mapped to parent_min and parent_max of this parent ProgressCallback. :param parent_min: minimum value of the child is mapped to parent_min of this pa...
python
def get_child_progress(self, parent_min, parent_max): """ Create a new child ProgressCallback. Minimum and maximum values of the child are mapped to parent_min and parent_max of this parent ProgressCallback. :param parent_min: minimum value of the child is mapped to parent_min of this pa...
[ "def", "get_child_progress", "(", "self", ",", "parent_min", ",", "parent_max", ")", ":", "return", "SubProgressCallback", "(", "parent", "=", "self", ",", "parent_min", "=", "parent_min", ",", "parent_max", "=", "parent_max", ")" ]
Create a new child ProgressCallback. Minimum and maximum values of the child are mapped to parent_min and parent_max of this parent ProgressCallback. :param parent_min: minimum value of the child is mapped to parent_min of this parent ProgressCallback :param parent_max: maximum value of the chil...
[ "Create", "a", "new", "child", "ProgressCallback", ".", "Minimum", "and", "maximum", "values", "of", "the", "child", "are", "mapped", "to", "parent_min", "and", "parent_max", "of", "this", "parent", "ProgressCallback", ".", ":", "param", "parent_min", ":", "mi...
bbccedd11b18d925ad4c062b5eb65981e24d0433
https://github.com/subdownloader/subdownloader/blob/bbccedd11b18d925ad4c062b5eb65981e24d0433/subdownloader/callback.py#L50-L58
train
Create a new child ProgressCallback instance.
subdownloader/subdownloader
subdownloader/callback.py
ProgressCallback.update
def update(self, value, *args, **kwargs): """ Call this function to inform that an update is available. This function does NOT call finish when value == maximum. :param value: The current index/position of the action. (Should be, but must not be, in the range [min, max]) :param a...
python
def update(self, value, *args, **kwargs): """ Call this function to inform that an update is available. This function does NOT call finish when value == maximum. :param value: The current index/position of the action. (Should be, but must not be, in the range [min, max]) :param a...
[ "def", "update", "(", "self", ",", "value", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "log", ".", "debug", "(", "'update(value={value}, args={args}, kwargs={kwargs})'", ".", "format", "(", "value", "=", "value", ",", "args", "=", "args", ",", ...
Call this function to inform that an update is available. This function does NOT call finish when value == maximum. :param value: The current index/position of the action. (Should be, but must not be, in the range [min, max]) :param args: extra positional arguments to pass on :param kwar...
[ "Call", "this", "function", "to", "inform", "that", "an", "update", "is", "available", ".", "This", "function", "does", "NOT", "call", "finish", "when", "value", "==", "maximum", ".", ":", "param", "value", ":", "The", "current", "index", "/", "position", ...
bbccedd11b18d925ad4c062b5eb65981e24d0433
https://github.com/subdownloader/subdownloader/blob/bbccedd11b18d925ad4c062b5eb65981e24d0433/subdownloader/callback.py#L60-L69
train
This function is called when an update is available.
subdownloader/subdownloader
subdownloader/callback.py
ProgressCallback.finish
def finish(self, *args, **kwargs): """ Call this function to inform that the operation is finished. :param args: extra positional arguments to pass on :param kwargs: extra keyword arguments to pass on """ log.debug('finish(args={args}, kwargs={kwargs})'.format(args=args, ...
python
def finish(self, *args, **kwargs): """ Call this function to inform that the operation is finished. :param args: extra positional arguments to pass on :param kwargs: extra keyword arguments to pass on """ log.debug('finish(args={args}, kwargs={kwargs})'.format(args=args, ...
[ "def", "finish", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "log", ".", "debug", "(", "'finish(args={args}, kwargs={kwargs})'", ".", "format", "(", "args", "=", "args", ",", "kwargs", "=", "kwargs", ")", ")", "self", ".", "on_fin...
Call this function to inform that the operation is finished. :param args: extra positional arguments to pass on :param kwargs: extra keyword arguments to pass on
[ "Call", "this", "function", "to", "inform", "that", "the", "operation", "is", "finished", ".", ":", "param", "args", ":", "extra", "positional", "arguments", "to", "pass", "on", ":", "param", "kwargs", ":", "extra", "keyword", "arguments", "to", "pass", "o...
bbccedd11b18d925ad4c062b5eb65981e24d0433
https://github.com/subdownloader/subdownloader/blob/bbccedd11b18d925ad4c062b5eb65981e24d0433/subdownloader/callback.py#L71-L78
train
Call this function to inform that the operation is finished.
subdownloader/subdownloader
subdownloader/callback.py
SubProgressCallback.on_update
def on_update(self, value, *args, **kwargs): """ Inform the parent of progress. :param value: The value of this subprogresscallback :param args: Extra positional arguments :param kwargs: Extra keyword arguments """ parent_value = self._parent_min if self._...
python
def on_update(self, value, *args, **kwargs): """ Inform the parent of progress. :param value: The value of this subprogresscallback :param args: Extra positional arguments :param kwargs: Extra keyword arguments """ parent_value = self._parent_min if self._...
[ "def", "on_update", "(", "self", ",", "value", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "parent_value", "=", "self", ".", "_parent_min", "if", "self", ".", "_max", "!=", "self", ".", "_min", ":", "sub_progress", "=", "(", "value", "-", ...
Inform the parent of progress. :param value: The value of this subprogresscallback :param args: Extra positional arguments :param kwargs: Extra keyword arguments
[ "Inform", "the", "parent", "of", "progress", ".", ":", "param", "value", ":", "The", "value", "of", "this", "subprogresscallback", ":", "param", "args", ":", "Extra", "positional", "arguments", ":", "param", "kwargs", ":", "Extra", "keyword", "arguments" ]
bbccedd11b18d925ad4c062b5eb65981e24d0433
https://github.com/subdownloader/subdownloader/blob/bbccedd11b18d925ad4c062b5eb65981e24d0433/subdownloader/callback.py#L145-L156
train
Informs the parent of progress.
subdownloader/subdownloader
subdownloader/provider/SDService.py
SDService._login
def _login(self, username="", password=""): """Login to the Server using username/password, empty parameters means an anonymously login Returns True if login sucessful, and False if not. """ self.log.debug("----------------") self.log.debug("Logging in (username: %s)..." ...
python
def _login(self, username="", password=""): """Login to the Server using username/password, empty parameters means an anonymously login Returns True if login sucessful, and False if not. """ self.log.debug("----------------") self.log.debug("Logging in (username: %s)..." ...
[ "def", "_login", "(", "self", ",", "username", "=", "\"\"", ",", "password", "=", "\"\"", ")", ":", "self", ".", "log", ".", "debug", "(", "\"----------------\"", ")", "self", ".", "log", ".", "debug", "(", "\"Logging in (username: %s)...\"", "%", "usernam...
Login to the Server using username/password, empty parameters means an anonymously login Returns True if login sucessful, and False if not.
[ "Login", "to", "the", "Server", "using", "username", "/", "password", "empty", "parameters", "means", "an", "anonymously", "login", "Returns", "True", "if", "login", "sucessful", "and", "False", "if", "not", "." ]
bbccedd11b18d925ad4c062b5eb65981e24d0433
https://github.com/subdownloader/subdownloader/blob/bbccedd11b18d925ad4c062b5eb65981e24d0433/subdownloader/provider/SDService.py#L248-L277
train
Login to the Server using username and password. Returns True if successful and False if not.
subdownloader/subdownloader
subdownloader/provider/SDService.py
SDService._logout
def _logout(self): """Logout from current session(token) This functions doesn't return any boolean value, since it can 'fail' for anonymous logins """ self.log.debug("Logging out from session ID: %s" % self._token) try: info = self._xmlrpc_server.LogOut(self._token) ...
python
def _logout(self): """Logout from current session(token) This functions doesn't return any boolean value, since it can 'fail' for anonymous logins """ self.log.debug("Logging out from session ID: %s" % self._token) try: info = self._xmlrpc_server.LogOut(self._token) ...
[ "def", "_logout", "(", "self", ")", ":", "self", ".", "log", ".", "debug", "(", "\"Logging out from session ID: %s\"", "%", "self", ".", "_token", ")", "try", ":", "info", "=", "self", ".", "_xmlrpc_server", ".", "LogOut", "(", "self", ".", "_token", ")"...
Logout from current session(token) This functions doesn't return any boolean value, since it can 'fail' for anonymous logins
[ "Logout", "from", "current", "session", "(", "token", ")", "This", "functions", "doesn", "t", "return", "any", "boolean", "value", "since", "it", "can", "fail", "for", "anonymous", "logins" ]
bbccedd11b18d925ad4c062b5eb65981e24d0433
https://github.com/subdownloader/subdownloader/blob/bbccedd11b18d925ad4c062b5eb65981e24d0433/subdownloader/provider/SDService.py#L288-L308
train
Logout from current session
subdownloader/subdownloader
subdownloader/client/arguments.py
parse_arguments
def parse_arguments(args=None): """ Parse the program arguments. :return: argparse.Namespace object with the parsed arguments """ parser = get_argument_parser() # Autocomplete arguments autocomplete(parser) ns = parser.parse_args(args=args) return ArgumentSettings( program=...
python
def parse_arguments(args=None): """ Parse the program arguments. :return: argparse.Namespace object with the parsed arguments """ parser = get_argument_parser() # Autocomplete arguments autocomplete(parser) ns = parser.parse_args(args=args) return ArgumentSettings( program=...
[ "def", "parse_arguments", "(", "args", "=", "None", ")", ":", "parser", "=", "get_argument_parser", "(", ")", "# Autocomplete arguments", "autocomplete", "(", "parser", ")", "ns", "=", "parser", ".", "parse_args", "(", "args", "=", "args", ")", "return", "Ar...
Parse the program arguments. :return: argparse.Namespace object with the parsed arguments
[ "Parse", "the", "program", "arguments", ".", ":", "return", ":", "argparse", ".", "Namespace", "object", "with", "the", "parsed", "arguments" ]
bbccedd11b18d925ad4c062b5eb65981e24d0433
https://github.com/subdownloader/subdownloader/blob/bbccedd11b18d925ad4c062b5eb65981e24d0433/subdownloader/client/arguments.py#L18-L60
train
Parse the program arguments.
subdownloader/subdownloader
subdownloader/client/arguments.py
get_argument_parser
def get_argument_parser(): """ Get a parser that is able to parse program arguments. :return: instance of arparse.ArgumentParser """ parser = argparse.ArgumentParser(description=project.get_description(), epilog=_('Visit us at {website}.').format(website=project....
python
def get_argument_parser(): """ Get a parser that is able to parse program arguments. :return: instance of arparse.ArgumentParser """ parser = argparse.ArgumentParser(description=project.get_description(), epilog=_('Visit us at {website}.').format(website=project....
[ "def", "get_argument_parser", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "project", ".", "get_description", "(", ")", ",", "epilog", "=", "_", "(", "'Visit us at {website}.'", ")", ".", "format", "(", "website", ...
Get a parser that is able to parse program arguments. :return: instance of arparse.ArgumentParser
[ "Get", "a", "parser", "that", "is", "able", "to", "parse", "program", "arguments", ".", ":", "return", ":", "instance", "of", "arparse", ".", "ArgumentParser" ]
bbccedd11b18d925ad4c062b5eb65981e24d0433
https://github.com/subdownloader/subdownloader/blob/bbccedd11b18d925ad4c062b5eb65981e24d0433/subdownloader/client/arguments.py#L192-L290
train
Returns an argument parser that can parse program arguments.
cenkalti/kuyruk
kuyruk/kuyruk.py
Kuyruk.task
def task(self, queue: str = 'kuyruk', **kwargs: Any) -> Callable: """ Wrap functions with this decorator to convert them to *tasks*. After wrapping, calling the function will send a message to a queue instead of running the function. :param queue: Queue name for the tasks. ...
python
def task(self, queue: str = 'kuyruk', **kwargs: Any) -> Callable: """ Wrap functions with this decorator to convert them to *tasks*. After wrapping, calling the function will send a message to a queue instead of running the function. :param queue: Queue name for the tasks. ...
[ "def", "task", "(", "self", ",", "queue", ":", "str", "=", "'kuyruk'", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "Callable", ":", "def", "wrapper", "(", "f", ":", "Callable", ")", "->", "Task", ":", "return", "Task", "(", "f", ",", "self", ...
Wrap functions with this decorator to convert them to *tasks*. After wrapping, calling the function will send a message to a queue instead of running the function. :param queue: Queue name for the tasks. :param kwargs: Keyword arguments will be passed to :class:`~kuyruk.Task...
[ "Wrap", "functions", "with", "this", "decorator", "to", "convert", "them", "to", "*", "tasks", "*", ".", "After", "wrapping", "calling", "the", "function", "will", "send", "a", "message", "to", "a", "queue", "instead", "of", "running", "the", "function", "...
c99d66be9d8fb077610f2fa883d5a1d268b42f04
https://github.com/cenkalti/kuyruk/blob/c99d66be9d8fb077610f2fa883d5a1d268b42f04/kuyruk/kuyruk.py#L37-L53
train
Decorator to convert functions to * tasks*.
cenkalti/kuyruk
kuyruk/kuyruk.py
Kuyruk.channel
def channel(self) -> Iterator[amqp.Channel]: """Returns a new channel from a new connection as a context manager.""" with self.connection() as conn: ch = conn.channel() logger.info('Opened new channel') with _safe_close(ch): yield ch
python
def channel(self) -> Iterator[amqp.Channel]: """Returns a new channel from a new connection as a context manager.""" with self.connection() as conn: ch = conn.channel() logger.info('Opened new channel') with _safe_close(ch): yield ch
[ "def", "channel", "(", "self", ")", "->", "Iterator", "[", "amqp", ".", "Channel", "]", ":", "with", "self", ".", "connection", "(", ")", "as", "conn", ":", "ch", "=", "conn", ".", "channel", "(", ")", "logger", ".", "info", "(", "'Opened new channel...
Returns a new channel from a new connection as a context manager.
[ "Returns", "a", "new", "channel", "from", "a", "new", "connection", "as", "a", "context", "manager", "." ]
c99d66be9d8fb077610f2fa883d5a1d268b42f04
https://github.com/cenkalti/kuyruk/blob/c99d66be9d8fb077610f2fa883d5a1d268b42f04/kuyruk/kuyruk.py#L56-L62
train
Returns a new channel from a new connection as a context manager.
cenkalti/kuyruk
kuyruk/kuyruk.py
Kuyruk.connection
def connection(self) -> Iterator[amqp.Connection]: """Returns a new connection as a context manager.""" TCP_USER_TIMEOUT = 18 # constant is available on Python 3.6+. socket_settings = {TCP_USER_TIMEOUT: self.config.TCP_USER_TIMEOUT} if sys.platform.startswith('darwin'): del...
python
def connection(self) -> Iterator[amqp.Connection]: """Returns a new connection as a context manager.""" TCP_USER_TIMEOUT = 18 # constant is available on Python 3.6+. socket_settings = {TCP_USER_TIMEOUT: self.config.TCP_USER_TIMEOUT} if sys.platform.startswith('darwin'): del...
[ "def", "connection", "(", "self", ")", "->", "Iterator", "[", "amqp", ".", "Connection", "]", ":", "TCP_USER_TIMEOUT", "=", "18", "# constant is available on Python 3.6+.", "socket_settings", "=", "{", "TCP_USER_TIMEOUT", ":", "self", ".", "config", ".", "TCP_USER...
Returns a new connection as a context manager.
[ "Returns", "a", "new", "connection", "as", "a", "context", "manager", "." ]
c99d66be9d8fb077610f2fa883d5a1d268b42f04
https://github.com/cenkalti/kuyruk/blob/c99d66be9d8fb077610f2fa883d5a1d268b42f04/kuyruk/kuyruk.py#L65-L87
train
Returns an iterator over the connection to RabbitMQ.
subdownloader/subdownloader
subdownloader/filescan.py
scan_videopath
def scan_videopath(videopath, callback, recursive=False): """ Scan the videopath string for video files. :param videopath: Path object :param callback: Instance of ProgressCallback :param recursive: True if the scanning should happen recursive :return: tuple with list of videos and list of subti...
python
def scan_videopath(videopath, callback, recursive=False): """ Scan the videopath string for video files. :param videopath: Path object :param callback: Instance of ProgressCallback :param recursive: True if the scanning should happen recursive :return: tuple with list of videos and list of subti...
[ "def", "scan_videopath", "(", "videopath", ",", "callback", ",", "recursive", "=", "False", ")", ":", "log", ".", "debug", "(", "'scan_videopath(videopath=\"{videopath}\", recursive={recursive})'", ".", "format", "(", "videopath", "=", "videopath", ",", "recursive", ...
Scan the videopath string for video files. :param videopath: Path object :param callback: Instance of ProgressCallback :param recursive: True if the scanning should happen recursive :return: tuple with list of videos and list of subtitles (videos have matched subtitles)
[ "Scan", "the", "videopath", "string", "for", "video", "files", ".", ":", "param", "videopath", ":", "Path", "object", ":", "param", "callback", ":", "Instance", "of", "ProgressCallback", ":", "param", "recursive", ":", "True", "if", "the", "scanning", "shoul...
bbccedd11b18d925ad4c062b5eb65981e24d0433
https://github.com/subdownloader/subdownloader/blob/bbccedd11b18d925ad4c062b5eb65981e24d0433/subdownloader/filescan.py#L30-L56
train
Scan the videopath string for video files and return a tuple with list of videos and list of subtitles that match the video files.
subdownloader/subdownloader
subdownloader/filescan.py
__scan_folder
def __scan_folder(folder_path, callback, recursive=False): """ Scan a folder for videos and subtitles :param folder_path: String of a directory :param callback: Instance of ProgressCallback :param recursive: True if the scanning should happen recursive :return: tuple with list of videos and list...
python
def __scan_folder(folder_path, callback, recursive=False): """ Scan a folder for videos and subtitles :param folder_path: String of a directory :param callback: Instance of ProgressCallback :param recursive: True if the scanning should happen recursive :return: tuple with list of videos and list...
[ "def", "__scan_folder", "(", "folder_path", ",", "callback", ",", "recursive", "=", "False", ")", ":", "log", ".", "debug", "(", "'__scan_folder(folder_path=\"{folder_path}\", recursive={recursive})'", ".", "format", "(", "folder_path", "=", "folder_path", ",", "recur...
Scan a folder for videos and subtitles :param folder_path: String of a directory :param callback: Instance of ProgressCallback :param recursive: True if the scanning should happen recursive :return: tuple with list of videos and list of subtitles (videos have matched subtitles)
[ "Scan", "a", "folder", "for", "videos", "and", "subtitles", ":", "param", "folder_path", ":", "String", "of", "a", "directory", ":", "param", "callback", ":", "Instance", "of", "ProgressCallback", ":", "param", "recursive", ":", "True", "if", "the", "scannin...
bbccedd11b18d925ad4c062b5eb65981e24d0433
https://github.com/subdownloader/subdownloader/blob/bbccedd11b18d925ad4c062b5eb65981e24d0433/subdownloader/filescan.py#L59-L81
train
Scan a folder for videos and subtitles.
subdownloader/subdownloader
subdownloader/filescan.py
merge_path_subvideo
def merge_path_subvideo(path_subvideos, callback): """ Merge subtitles into videos. :param path_subvideos: a dict with paths as key and a list of lists of videos and subtitles :param callback: Instance of ProgressCallback :return: tuple with list of videos and list of subtitles (videos have matched ...
python
def merge_path_subvideo(path_subvideos, callback): """ Merge subtitles into videos. :param path_subvideos: a dict with paths as key and a list of lists of videos and subtitles :param callback: Instance of ProgressCallback :return: tuple with list of videos and list of subtitles (videos have matched ...
[ "def", "merge_path_subvideo", "(", "path_subvideos", ",", "callback", ")", ":", "log", ".", "debug", "(", "'merge_path_subvideo(path_subvideos=<#paths={nb_paths}>)'", ".", "format", "(", "nb_paths", "=", "len", "(", "path_subvideos", ")", ")", ")", "# FIXME: add loggi...
Merge subtitles into videos. :param path_subvideos: a dict with paths as key and a list of lists of videos and subtitles :param callback: Instance of ProgressCallback :return: tuple with list of videos and list of subtitles (videos have matched subtitles)
[ "Merge", "subtitles", "into", "videos", ".", ":", "param", "path_subvideos", ":", "a", "dict", "with", "paths", "as", "key", "and", "a", "list", "of", "lists", "of", "videos", "and", "subtitles", ":", "param", "callback", ":", "Instance", "of", "ProgressCa...
bbccedd11b18d925ad4c062b5eb65981e24d0433
https://github.com/subdownloader/subdownloader/blob/bbccedd11b18d925ad4c062b5eb65981e24d0433/subdownloader/filescan.py#L84-L121
train
Merge subtitles into videos.
subdownloader/subdownloader
subdownloader/filescan.py
filter_files_extensions
def filter_files_extensions(files, extension_lists): """ Put the files in buckets according to extension_lists files=[movie.avi, movie.srt], extension_lists=[[avi],[srt]] ==> [[movie.avi],[movie.srt]] :param files: A list of files :param extension_lists: A list of list of extensions :return: The...
python
def filter_files_extensions(files, extension_lists): """ Put the files in buckets according to extension_lists files=[movie.avi, movie.srt], extension_lists=[[avi],[srt]] ==> [[movie.avi],[movie.srt]] :param files: A list of files :param extension_lists: A list of list of extensions :return: The...
[ "def", "filter_files_extensions", "(", "files", ",", "extension_lists", ")", ":", "log", ".", "debug", "(", "'filter_files_extensions: files=\"{}\"'", ".", "format", "(", "files", ")", ")", "result", "=", "[", "[", "]", "for", "_", "in", "extension_lists", "]"...
Put the files in buckets according to extension_lists files=[movie.avi, movie.srt], extension_lists=[[avi],[srt]] ==> [[movie.avi],[movie.srt]] :param files: A list of files :param extension_lists: A list of list of extensions :return: The files filtered and sorted according to extension_lists
[ "Put", "the", "files", "in", "buckets", "according", "to", "extension_lists", "files", "=", "[", "movie", ".", "avi", "movie", ".", "srt", "]", "extension_lists", "=", "[[", "avi", "]", "[", "srt", "]]", "==", ">", "[[", "movie", ".", "avi", "]", "["...
bbccedd11b18d925ad4c062b5eb65981e24d0433
https://github.com/subdownloader/subdownloader/blob/bbccedd11b18d925ad4c062b5eb65981e24d0433/subdownloader/filescan.py#L124-L140
train
Filter the files in buckets according to extension_lists.
subdownloader/subdownloader
subdownloader/subtitle2.py
SubtitleFile.detect_language_filename
def detect_language_filename(cls, filename): """ Detect the language of a subtitle filename :param filename: filename of a subtitle :return: Language object, None if language could not be detected. """ log.debug('detect_language(filename="{}") ...'.format(filename)) ...
python
def detect_language_filename(cls, filename): """ Detect the language of a subtitle filename :param filename: filename of a subtitle :return: Language object, None if language could not be detected. """ log.debug('detect_language(filename="{}") ...'.format(filename)) ...
[ "def", "detect_language_filename", "(", "cls", ",", "filename", ")", ":", "log", ".", "debug", "(", "'detect_language(filename=\"{}\") ...'", ".", "format", "(", "filename", ")", ")", "root", ",", "_", "=", "os", ".", "path", ".", "splitext", "(", "filename"...
Detect the language of a subtitle filename :param filename: filename of a subtitle :return: Language object, None if language could not be detected.
[ "Detect", "the", "language", "of", "a", "subtitle", "filename", ":", "param", "filename", ":", "filename", "of", "a", "subtitle", ":", "return", ":", "Language", "object", "None", "if", "language", "could", "not", "be", "detected", "." ]
bbccedd11b18d925ad4c062b5eb65981e24d0433
https://github.com/subdownloader/subdownloader/blob/bbccedd11b18d925ad4c062b5eb65981e24d0433/subdownloader/subtitle2.py#L57-L76
train
Detect the language of a filename.
subdownloader/subdownloader
subdownloader/subtitle2.py
SubtitleFileStorage.matches_video_filename
def matches_video_filename(self, video): """ Detect whether the filename of videofile matches with this SubtitleFile. :param video: VideoFile instance :return: True if match """ vid_fn = video.get_filename() vid_base, _ = os.path.splitext(vid_fn) vid_base...
python
def matches_video_filename(self, video): """ Detect whether the filename of videofile matches with this SubtitleFile. :param video: VideoFile instance :return: True if match """ vid_fn = video.get_filename() vid_base, _ = os.path.splitext(vid_fn) vid_base...
[ "def", "matches_video_filename", "(", "self", ",", "video", ")", ":", "vid_fn", "=", "video", ".", "get_filename", "(", ")", "vid_base", ",", "_", "=", "os", ".", "path", ".", "splitext", "(", "vid_fn", ")", "vid_base", "=", "vid_base", ".", "lower", "...
Detect whether the filename of videofile matches with this SubtitleFile. :param video: VideoFile instance :return: True if match
[ "Detect", "whether", "the", "filename", "of", "videofile", "matches", "with", "this", "SubtitleFile", ".", ":", "param", "video", ":", "VideoFile", "instance", ":", "return", ":", "True", "if", "match" ]
bbccedd11b18d925ad4c062b5eb65981e24d0433
https://github.com/subdownloader/subdownloader/blob/bbccedd11b18d925ad4c062b5eb65981e24d0433/subdownloader/subtitle2.py#L159-L197
train
Detect whether the filename of videofile matches with this SubtitleFile.
subdownloader/subdownloader
subdownloader/client/logger.py
logging_file_install
def logging_file_install(path): """ Install logger that will write to file. If this function has already installed a handler, replace it. :param path: path to the log file, Use None for default file location. """ if path is None: path = configuration_get_default_folder() / LOGGING_DEFAULTNAM...
python
def logging_file_install(path): """ Install logger that will write to file. If this function has already installed a handler, replace it. :param path: path to the log file, Use None for default file location. """ if path is None: path = configuration_get_default_folder() / LOGGING_DEFAULTNAM...
[ "def", "logging_file_install", "(", "path", ")", ":", "if", "path", "is", "None", ":", "path", "=", "configuration_get_default_folder", "(", ")", "/", "LOGGING_DEFAULTNAME", "if", "not", "path", ".", "parent", ".", "exists", "(", ")", ":", "log", ".", "err...
Install logger that will write to file. If this function has already installed a handler, replace it. :param path: path to the log file, Use None for default file location.
[ "Install", "logger", "that", "will", "write", "to", "file", ".", "If", "this", "function", "has", "already", "installed", "a", "handler", "replace", "it", ".", ":", "param", "path", ":", "path", "to", "the", "log", "file", "Use", "None", "for", "default"...
bbccedd11b18d925ad4c062b5eb65981e24d0433
https://github.com/subdownloader/subdownloader/blob/bbccedd11b18d925ad4c062b5eb65981e24d0433/subdownloader/client/logger.py#L24-L51
train
Install logger that will write to file.
subdownloader/subdownloader
subdownloader/client/logger.py
logging_stream_install
def logging_stream_install(loglevel): """ Install logger that will output to stderr. If this function ha already installed a handler, replace it. :param loglevel: log level for the stream """ formatter = logging.Formatter(LOGGING_FORMAT) logger = logging.getLogger() logger.removeHandler(LOG...
python
def logging_stream_install(loglevel): """ Install logger that will output to stderr. If this function ha already installed a handler, replace it. :param loglevel: log level for the stream """ formatter = logging.Formatter(LOGGING_FORMAT) logger = logging.getLogger() logger.removeHandler(LOG...
[ "def", "logging_stream_install", "(", "loglevel", ")", ":", "formatter", "=", "logging", ".", "Formatter", "(", "LOGGING_FORMAT", ")", "logger", "=", "logging", ".", "getLogger", "(", ")", "logger", ".", "removeHandler", "(", "LOGGING_HANDLERS", "[", "'stream'",...
Install logger that will output to stderr. If this function ha already installed a handler, replace it. :param loglevel: log level for the stream
[ "Install", "logger", "that", "will", "output", "to", "stderr", ".", "If", "this", "function", "ha", "already", "installed", "a", "handler", "replace", "it", ".", ":", "param", "loglevel", ":", "log", "level", "for", "the", "stream" ]
bbccedd11b18d925ad4c062b5eb65981e24d0433
https://github.com/subdownloader/subdownloader/blob/bbccedd11b18d925ad4c062b5eb65981e24d0433/subdownloader/client/logger.py#L54-L74
train
Installs a stream handler that will output to stderr.
stanfordnlp/python-corenlp-protobuf
corenlp_protobuf/__init__.py
parseFromDelimitedString
def parseFromDelimitedString(obj, buf, offset=0): """ Stanford CoreNLP uses the Java "writeDelimitedTo" function, which writes the size (and offset) of the buffer before writing the object. This function handles parsing this message starting from offset 0. @returns how many bytes of @buf were consu...
python
def parseFromDelimitedString(obj, buf, offset=0): """ Stanford CoreNLP uses the Java "writeDelimitedTo" function, which writes the size (and offset) of the buffer before writing the object. This function handles parsing this message starting from offset 0. @returns how many bytes of @buf were consu...
[ "def", "parseFromDelimitedString", "(", "obj", ",", "buf", ",", "offset", "=", "0", ")", ":", "size", ",", "pos", "=", "_DecodeVarint", "(", "buf", ",", "offset", ")", "obj", ".", "ParseFromString", "(", "buf", "[", "offset", "+", "pos", ":", "offset",...
Stanford CoreNLP uses the Java "writeDelimitedTo" function, which writes the size (and offset) of the buffer before writing the object. This function handles parsing this message starting from offset 0. @returns how many bytes of @buf were consumed.
[ "Stanford", "CoreNLP", "uses", "the", "Java", "writeDelimitedTo", "function", "which", "writes", "the", "size", "(", "and", "offset", ")", "of", "the", "buffer", "before", "writing", "the", "object", ".", "This", "function", "handles", "parsing", "this", "mess...
508284aa16afaedba57e0e18dd82ebb6ec63101a
https://github.com/stanfordnlp/python-corenlp-protobuf/blob/508284aa16afaedba57e0e18dd82ebb6ec63101a/corenlp_protobuf/__init__.py#L9-L19
train
Parses a TLE string into an object.
stanfordnlp/python-corenlp-protobuf
corenlp_protobuf/__init__.py
writeToDelimitedString
def writeToDelimitedString(obj, stream=None): """ Stanford CoreNLP uses the Java "writeDelimitedTo" function, which writes the size (and offset) of the buffer before writing the object. This function handles parsing this message starting from offset 0. @returns how many bytes of @buf were consumed....
python
def writeToDelimitedString(obj, stream=None): """ Stanford CoreNLP uses the Java "writeDelimitedTo" function, which writes the size (and offset) of the buffer before writing the object. This function handles parsing this message starting from offset 0. @returns how many bytes of @buf were consumed....
[ "def", "writeToDelimitedString", "(", "obj", ",", "stream", "=", "None", ")", ":", "if", "stream", "is", "None", ":", "stream", "=", "BytesIO", "(", ")", "_EncodeVarint", "(", "stream", ".", "write", ",", "obj", ".", "ByteSize", "(", ")", ",", "True", ...
Stanford CoreNLP uses the Java "writeDelimitedTo" function, which writes the size (and offset) of the buffer before writing the object. This function handles parsing this message starting from offset 0. @returns how many bytes of @buf were consumed.
[ "Stanford", "CoreNLP", "uses", "the", "Java", "writeDelimitedTo", "function", "which", "writes", "the", "size", "(", "and", "offset", ")", "of", "the", "buffer", "before", "writing", "the", "object", ".", "This", "function", "handles", "parsing", "this", "mess...
508284aa16afaedba57e0e18dd82ebb6ec63101a
https://github.com/stanfordnlp/python-corenlp-protobuf/blob/508284aa16afaedba57e0e18dd82ebb6ec63101a/corenlp_protobuf/__init__.py#L21-L34
train
Writes a unicode object to a delimited string.
stanfordnlp/python-corenlp-protobuf
corenlp_protobuf/__init__.py
to_text
def to_text(sentence): """ Helper routine that converts a Sentence protobuf to a string from its tokens. """ text = "" for i, tok in enumerate(sentence.token): if i != 0: text += tok.before text += tok.word return text
python
def to_text(sentence): """ Helper routine that converts a Sentence protobuf to a string from its tokens. """ text = "" for i, tok in enumerate(sentence.token): if i != 0: text += tok.before text += tok.word return text
[ "def", "to_text", "(", "sentence", ")", ":", "text", "=", "\"\"", "for", "i", ",", "tok", "in", "enumerate", "(", "sentence", ".", "token", ")", ":", "if", "i", "!=", "0", ":", "text", "+=", "tok", ".", "before", "text", "+=", "tok", ".", "word",...
Helper routine that converts a Sentence protobuf to a string from its tokens.
[ "Helper", "routine", "that", "converts", "a", "Sentence", "protobuf", "to", "a", "string", "from", "its", "tokens", "." ]
508284aa16afaedba57e0e18dd82ebb6ec63101a
https://github.com/stanfordnlp/python-corenlp-protobuf/blob/508284aa16afaedba57e0e18dd82ebb6ec63101a/corenlp_protobuf/__init__.py#L36-L46
train
Converts a Sentence protobuf to a string from its tokens.