repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
toumorokoshi/sprinter
sprinter/formula/base.py
FormulaBase.should_run
def should_run(self): """ Returns true if the feature should run """ should_run = True config = self.target or self.source if config.has('systems'): should_run = False valid_systems = [s.lower() for s in config.get('systems').split(",")] for system_type, param in [('is_osx', 'osx'), ('is_debian', 'debian')]: if param in valid_systems and getattr(system, system_type)(): should_run = True return should_run
python
def should_run(self): """ Returns true if the feature should run """ should_run = True config = self.target or self.source if config.has('systems'): should_run = False valid_systems = [s.lower() for s in config.get('systems').split(",")] for system_type, param in [('is_osx', 'osx'), ('is_debian', 'debian')]: if param in valid_systems and getattr(system, system_type)(): should_run = True return should_run
[ "def", "should_run", "(", "self", ")", ":", "should_run", "=", "True", "config", "=", "self", ".", "target", "or", "self", ".", "source", "if", "config", ".", "has", "(", "'systems'", ")", ":", "should_run", "=", "False", "valid_systems", "=", "[", "s"...
Returns true if the feature should run
[ "Returns", "true", "if", "the", "feature", "should", "run" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/formula/base.py#L166-L177
train
54,500
toumorokoshi/sprinter
sprinter/formula/base.py
FormulaBase.resolve
def resolve(self): """ Resolve differences between the target and the source configuration """ if self.source and self.target: for key in self.source.keys(): if (key not in self.dont_carry_over_options and not self.target.has(key)): self.target.set(key, self.source.get(key))
python
def resolve(self): """ Resolve differences between the target and the source configuration """ if self.source and self.target: for key in self.source.keys(): if (key not in self.dont_carry_over_options and not self.target.has(key)): self.target.set(key, self.source.get(key))
[ "def", "resolve", "(", "self", ")", ":", "if", "self", ".", "source", "and", "self", ".", "target", ":", "for", "key", "in", "self", ".", "source", ".", "keys", "(", ")", ":", "if", "(", "key", "not", "in", "self", ".", "dont_carry_over_options", "...
Resolve differences between the target and the source configuration
[ "Resolve", "differences", "between", "the", "target", "and", "the", "source", "configuration" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/formula/base.py#L179-L185
train
54,501
toumorokoshi/sprinter
sprinter/formula/base.py
FormulaBase._log_error
def _log_error(self, message): """ Log an error for the feature """ key = (self.feature_name, self.target.get('formula')) self.environment.log_feature_error(key, "ERROR: " + message)
python
def _log_error(self, message): """ Log an error for the feature """ key = (self.feature_name, self.target.get('formula')) self.environment.log_feature_error(key, "ERROR: " + message)
[ "def", "_log_error", "(", "self", ",", "message", ")", ":", "key", "=", "(", "self", ".", "feature_name", ",", "self", ".", "target", ".", "get", "(", "'formula'", ")", ")", "self", ".", "environment", ".", "log_feature_error", "(", "key", ",", "\"ERRO...
Log an error for the feature
[ "Log", "an", "error", "for", "the", "feature" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/formula/base.py#L187-L190
train
54,502
frascoweb/frasco
frasco/templating/extensions.py
jinja_fragment_extension
def jinja_fragment_extension(tag, endtag=None, name=None, tag_only=False, allow_args=True, callblock_args=None): """Decorator to easily create a jinja extension which acts as a fragment. """ if endtag is None: endtag = "end" + tag def decorator(f): def parse(self, parser): lineno = parser.stream.next().lineno args = [] kwargs = [] if allow_args: args, kwargs = parse_block_signature(parser) call = self.call_method("support_method", args, kwargs, lineno=lineno) if tag_only: return nodes.Output([call], lineno=lineno) call_args = [] if callblock_args is not None: for arg in callblock_args: call_args.append(nodes.Name(arg, 'param', lineno=lineno)) body = parser.parse_statements(['name:' + endtag], drop_needle=True) return nodes.CallBlock(call, call_args, [], body, lineno=lineno) def support_method(self, *args, **kwargs): return f(*args, **kwargs) attrs = {"tags": set([tag]), "parse": parse, "support_method": support_method} return type(name or f.__name__, (Extension,), attrs) return decorator
python
def jinja_fragment_extension(tag, endtag=None, name=None, tag_only=False, allow_args=True, callblock_args=None): """Decorator to easily create a jinja extension which acts as a fragment. """ if endtag is None: endtag = "end" + tag def decorator(f): def parse(self, parser): lineno = parser.stream.next().lineno args = [] kwargs = [] if allow_args: args, kwargs = parse_block_signature(parser) call = self.call_method("support_method", args, kwargs, lineno=lineno) if tag_only: return nodes.Output([call], lineno=lineno) call_args = [] if callblock_args is not None: for arg in callblock_args: call_args.append(nodes.Name(arg, 'param', lineno=lineno)) body = parser.parse_statements(['name:' + endtag], drop_needle=True) return nodes.CallBlock(call, call_args, [], body, lineno=lineno) def support_method(self, *args, **kwargs): return f(*args, **kwargs) attrs = {"tags": set([tag]), "parse": parse, "support_method": support_method} return type(name or f.__name__, (Extension,), attrs) return decorator
[ "def", "jinja_fragment_extension", "(", "tag", ",", "endtag", "=", "None", ",", "name", "=", "None", ",", "tag_only", "=", "False", ",", "allow_args", "=", "True", ",", "callblock_args", "=", "None", ")", ":", "if", "endtag", "is", "None", ":", "endtag",...
Decorator to easily create a jinja extension which acts as a fragment.
[ "Decorator", "to", "easily", "create", "a", "jinja", "extension", "which", "acts", "as", "a", "fragment", "." ]
ea519d69dd5ca6deaf3650175692ee4a1a02518f
https://github.com/frascoweb/frasco/blob/ea519d69dd5ca6deaf3650175692ee4a1a02518f/frasco/templating/extensions.py#L36-L68
train
54,503
frascoweb/frasco
frasco/templating/extensions.py
jinja_block_as_fragment_extension
def jinja_block_as_fragment_extension(name, tagname=None, classname=None): """Creates a fragment extension which will just act as a replacement of the block statement. """ if tagname is None: tagname = name if classname is None: classname = "%sBlockFragmentExtension" % name.capitalize() return type(classname, (BaseJinjaBlockAsFragmentExtension,), { "tags": set([tagname]), "end_tag": "end" + tagname, "block_name": name})
python
def jinja_block_as_fragment_extension(name, tagname=None, classname=None): """Creates a fragment extension which will just act as a replacement of the block statement. """ if tagname is None: tagname = name if classname is None: classname = "%sBlockFragmentExtension" % name.capitalize() return type(classname, (BaseJinjaBlockAsFragmentExtension,), { "tags": set([tagname]), "end_tag": "end" + tagname, "block_name": name})
[ "def", "jinja_block_as_fragment_extension", "(", "name", ",", "tagname", "=", "None", ",", "classname", "=", "None", ")", ":", "if", "tagname", "is", "None", ":", "tagname", "=", "name", "if", "classname", "is", "None", ":", "classname", "=", "\"%sBlockFragm...
Creates a fragment extension which will just act as a replacement of the block statement.
[ "Creates", "a", "fragment", "extension", "which", "will", "just", "act", "as", "a", "replacement", "of", "the", "block", "statement", "." ]
ea519d69dd5ca6deaf3650175692ee4a1a02518f
https://github.com/frascoweb/frasco/blob/ea519d69dd5ca6deaf3650175692ee4a1a02518f/frasco/templating/extensions.py#L78-L87
train
54,504
evansde77/dockerstache
src/dockerstache/templates.py
find_copies
def find_copies(input_dir, exclude_list): """ find files that are not templates and not in the exclude_list for copying from template to image """ copies = [] def copy_finder(copies, dirname): for obj in os.listdir(dirname): pathname = os.path.join(dirname, obj) if os.path.isdir(pathname): continue if obj in exclude_list: continue if obj.endswith('.mustache'): continue copies.append(os.path.join(dirname, obj)) dir_visitor( input_dir, functools.partial(copy_finder, copies) ) return copies
python
def find_copies(input_dir, exclude_list): """ find files that are not templates and not in the exclude_list for copying from template to image """ copies = [] def copy_finder(copies, dirname): for obj in os.listdir(dirname): pathname = os.path.join(dirname, obj) if os.path.isdir(pathname): continue if obj in exclude_list: continue if obj.endswith('.mustache'): continue copies.append(os.path.join(dirname, obj)) dir_visitor( input_dir, functools.partial(copy_finder, copies) ) return copies
[ "def", "find_copies", "(", "input_dir", ",", "exclude_list", ")", ":", "copies", "=", "[", "]", "def", "copy_finder", "(", "copies", ",", "dirname", ")", ":", "for", "obj", "in", "os", ".", "listdir", "(", "dirname", ")", ":", "pathname", "=", "os", ...
find files that are not templates and not in the exclude_list for copying from template to image
[ "find", "files", "that", "are", "not", "templates", "and", "not", "in", "the", "exclude_list", "for", "copying", "from", "template", "to", "image" ]
929c102e9fffde322dbf17f8e69533a00976aacb
https://github.com/evansde77/dockerstache/blob/929c102e9fffde322dbf17f8e69533a00976aacb/src/dockerstache/templates.py#L84-L107
train
54,505
majuss/lupupy
lupupy/__init__.py
Lupusec.get_devices
def get_devices(self, refresh=False, generic_type=None): """Get all devices from Lupusec.""" _LOGGER.info("Updating all devices...") if refresh or self._devices is None: if self._devices is None: self._devices = {} responseObject = self.get_sensors() if (responseObject and not isinstance(responseObject, (tuple, list))): responseObject = responseObject for deviceJson in responseObject: # Attempt to reuse an existing device device = self._devices.get(deviceJson['name']) # No existing device, create a new one if device: device.update(deviceJson) else: device = newDevice(deviceJson, self) if not device: _LOGGER.info('Device is unknown') continue self._devices[device.device_id] = device # We will be treating the Lupusec panel itself as an armable device. panelJson = self.get_panel() _LOGGER.debug("Get the panel in get_devices: %s", panelJson) self._panel.update(panelJson) alarmDevice = self._devices.get('0') if alarmDevice: alarmDevice.update(panelJson) else: alarmDevice = ALARM.create_alarm(panelJson, self) self._devices['0'] = alarmDevice # Now we will handle the power switches switches = self.get_power_switches() _LOGGER.debug( 'Get active the power switches in get_devices: %s', switches) for deviceJson in switches: # Attempt to reuse an existing device device = self._devices.get(deviceJson['name']) # No existing device, create a new one if device: device.update(deviceJson) else: device = newDevice(deviceJson, self) if not device: _LOGGER.info('Device is unknown') continue self._devices[device.device_id] = device if generic_type: devices = [] for device in self._devices.values(): if (device.type is not None and device.type in generic_type[0]): devices.append(device) return devices return list(self._devices.values())
python
def get_devices(self, refresh=False, generic_type=None): """Get all devices from Lupusec.""" _LOGGER.info("Updating all devices...") if refresh or self._devices is None: if self._devices is None: self._devices = {} responseObject = self.get_sensors() if (responseObject and not isinstance(responseObject, (tuple, list))): responseObject = responseObject for deviceJson in responseObject: # Attempt to reuse an existing device device = self._devices.get(deviceJson['name']) # No existing device, create a new one if device: device.update(deviceJson) else: device = newDevice(deviceJson, self) if not device: _LOGGER.info('Device is unknown') continue self._devices[device.device_id] = device # We will be treating the Lupusec panel itself as an armable device. panelJson = self.get_panel() _LOGGER.debug("Get the panel in get_devices: %s", panelJson) self._panel.update(panelJson) alarmDevice = self._devices.get('0') if alarmDevice: alarmDevice.update(panelJson) else: alarmDevice = ALARM.create_alarm(panelJson, self) self._devices['0'] = alarmDevice # Now we will handle the power switches switches = self.get_power_switches() _LOGGER.debug( 'Get active the power switches in get_devices: %s', switches) for deviceJson in switches: # Attempt to reuse an existing device device = self._devices.get(deviceJson['name']) # No existing device, create a new one if device: device.update(deviceJson) else: device = newDevice(deviceJson, self) if not device: _LOGGER.info('Device is unknown') continue self._devices[device.device_id] = device if generic_type: devices = [] for device in self._devices.values(): if (device.type is not None and device.type in generic_type[0]): devices.append(device) return devices return list(self._devices.values())
[ "def", "get_devices", "(", "self", ",", "refresh", "=", "False", ",", "generic_type", "=", "None", ")", ":", "_LOGGER", ".", "info", "(", "\"Updating all devices...\"", ")", "if", "refresh", "or", "self", ".", "_devices", "is", "None", ":", "if", "self", ...
Get all devices from Lupusec.
[ "Get", "all", "devices", "from", "Lupusec", "." ]
71af6c397837ffc393c7b8122be175602638d3c6
https://github.com/majuss/lupupy/blob/71af6c397837ffc393c7b8122be175602638d3c6/lupupy/__init__.py#L142-L211
train
54,506
gtaylor/EVE-Market-Data-Structures
emds/formats/unified/history.py
parse_from_dict
def parse_from_dict(json_dict): """ Given a Unified Uploader message, parse the contents and return a MarketHistoryList instance. :param dict json_dict: A Unified Uploader message as a dict. :rtype: MarketOrderList :returns: An instance of MarketOrderList, containing the orders within. """ history_columns = json_dict['columns'] history_list = MarketHistoryList( upload_keys=json_dict['uploadKeys'], history_generator=json_dict['generator'], ) for rowset in json_dict['rowsets']: generated_at = parse_datetime(rowset['generatedAt']) region_id = rowset['regionID'] type_id = rowset['typeID'] history_list.set_empty_region(region_id, type_id, generated_at) for row in rowset['rows']: history_kwargs = _columns_to_kwargs( SPEC_TO_KWARG_CONVERSION, history_columns, row) historical_date = parse_datetime(history_kwargs['historical_date']) history_kwargs.update({ 'type_id': type_id, 'region_id': region_id, 'historical_date': historical_date, 'generated_at': generated_at, }) history_list.add_entry(MarketHistoryEntry(**history_kwargs)) return history_list
python
def parse_from_dict(json_dict): """ Given a Unified Uploader message, parse the contents and return a MarketHistoryList instance. :param dict json_dict: A Unified Uploader message as a dict. :rtype: MarketOrderList :returns: An instance of MarketOrderList, containing the orders within. """ history_columns = json_dict['columns'] history_list = MarketHistoryList( upload_keys=json_dict['uploadKeys'], history_generator=json_dict['generator'], ) for rowset in json_dict['rowsets']: generated_at = parse_datetime(rowset['generatedAt']) region_id = rowset['regionID'] type_id = rowset['typeID'] history_list.set_empty_region(region_id, type_id, generated_at) for row in rowset['rows']: history_kwargs = _columns_to_kwargs( SPEC_TO_KWARG_CONVERSION, history_columns, row) historical_date = parse_datetime(history_kwargs['historical_date']) history_kwargs.update({ 'type_id': type_id, 'region_id': region_id, 'historical_date': historical_date, 'generated_at': generated_at, }) history_list.add_entry(MarketHistoryEntry(**history_kwargs)) return history_list
[ "def", "parse_from_dict", "(", "json_dict", ")", ":", "history_columns", "=", "json_dict", "[", "'columns'", "]", "history_list", "=", "MarketHistoryList", "(", "upload_keys", "=", "json_dict", "[", "'uploadKeys'", "]", ",", "history_generator", "=", "json_dict", ...
Given a Unified Uploader message, parse the contents and return a MarketHistoryList instance. :param dict json_dict: A Unified Uploader message as a dict. :rtype: MarketOrderList :returns: An instance of MarketOrderList, containing the orders within.
[ "Given", "a", "Unified", "Uploader", "message", "parse", "the", "contents", "and", "return", "a", "MarketHistoryList", "instance", "." ]
77d69b24f2aada3aeff8fba3d75891bfba8fdcf3
https://github.com/gtaylor/EVE-Market-Data-Structures/blob/77d69b24f2aada3aeff8fba3d75891bfba8fdcf3/emds/formats/unified/history.py#L30-L67
train
54,507
gtaylor/EVE-Market-Data-Structures
emds/formats/unified/history.py
encode_to_json
def encode_to_json(history_list): """ Encodes this MarketHistoryList instance to a JSON string. :param MarketHistoryList history_list: The history instance to serialize. :rtype: str """ rowsets = [] for items_in_region_list in history_list._history.values(): region_id = items_in_region_list.region_id type_id = items_in_region_list.type_id generated_at = gen_iso_datetime_str(items_in_region_list.generated_at) rows = [] for entry in items_in_region_list.entries: historical_date = gen_iso_datetime_str(entry.historical_date) # The order in which these values are added is crucial. It must # match STANDARD_ENCODED_COLUMNS. rows.append([ historical_date, entry.num_orders, entry.total_quantity, entry.low_price, entry.high_price, entry.average_price, ]) rowsets.append(dict( generatedAt = generated_at, regionID = region_id, typeID = type_id, rows = rows, )) json_dict = { 'resultType': 'history', 'version': '0.1', 'uploadKeys': history_list.upload_keys, 'generator': history_list.history_generator, 'currentTime': gen_iso_datetime_str(now_dtime_in_utc()), # This must match the order of the values in the row assembling portion # above this. 'columns': STANDARD_ENCODED_COLUMNS, 'rowsets': rowsets, } return json.dumps(json_dict)
python
def encode_to_json(history_list): """ Encodes this MarketHistoryList instance to a JSON string. :param MarketHistoryList history_list: The history instance to serialize. :rtype: str """ rowsets = [] for items_in_region_list in history_list._history.values(): region_id = items_in_region_list.region_id type_id = items_in_region_list.type_id generated_at = gen_iso_datetime_str(items_in_region_list.generated_at) rows = [] for entry in items_in_region_list.entries: historical_date = gen_iso_datetime_str(entry.historical_date) # The order in which these values are added is crucial. It must # match STANDARD_ENCODED_COLUMNS. rows.append([ historical_date, entry.num_orders, entry.total_quantity, entry.low_price, entry.high_price, entry.average_price, ]) rowsets.append(dict( generatedAt = generated_at, regionID = region_id, typeID = type_id, rows = rows, )) json_dict = { 'resultType': 'history', 'version': '0.1', 'uploadKeys': history_list.upload_keys, 'generator': history_list.history_generator, 'currentTime': gen_iso_datetime_str(now_dtime_in_utc()), # This must match the order of the values in the row assembling portion # above this. 'columns': STANDARD_ENCODED_COLUMNS, 'rowsets': rowsets, } return json.dumps(json_dict)
[ "def", "encode_to_json", "(", "history_list", ")", ":", "rowsets", "=", "[", "]", "for", "items_in_region_list", "in", "history_list", ".", "_history", ".", "values", "(", ")", ":", "region_id", "=", "items_in_region_list", ".", "region_id", "type_id", "=", "i...
Encodes this MarketHistoryList instance to a JSON string. :param MarketHistoryList history_list: The history instance to serialize. :rtype: str
[ "Encodes", "this", "MarketHistoryList", "instance", "to", "a", "JSON", "string", "." ]
77d69b24f2aada3aeff8fba3d75891bfba8fdcf3
https://github.com/gtaylor/EVE-Market-Data-Structures/blob/77d69b24f2aada3aeff8fba3d75891bfba8fdcf3/emds/formats/unified/history.py#L69-L116
train
54,508
KvasirSecurity/kvasirapi-python
KvasirAPI/config.py
Configuration.load
def load(self, configuration): """ Load a YAML configuration file. :param configuration: Configuration filename or YAML string """ try: self.config = yaml.load(open(configuration, "rb")) except IOError: try: self.config = yaml.load(configuration) except ParserError, e: raise ParserError('Error parsing config: %s' % e) # put customer data into self.customer if isinstance(self.config, dict): self.customer = self.config.get('customer', {}) self.instances_dict = self.config.get('instances', {}) self.web2py_dir = self.config.get('web2py', None) self.api_type = self.config.get('api_type', 'jsonrpc') self.valid = True else: self.customer = {} self.instances_dict = {} self.web2py_dir = None self.valid = False
python
def load(self, configuration): """ Load a YAML configuration file. :param configuration: Configuration filename or YAML string """ try: self.config = yaml.load(open(configuration, "rb")) except IOError: try: self.config = yaml.load(configuration) except ParserError, e: raise ParserError('Error parsing config: %s' % e) # put customer data into self.customer if isinstance(self.config, dict): self.customer = self.config.get('customer', {}) self.instances_dict = self.config.get('instances', {}) self.web2py_dir = self.config.get('web2py', None) self.api_type = self.config.get('api_type', 'jsonrpc') self.valid = True else: self.customer = {} self.instances_dict = {} self.web2py_dir = None self.valid = False
[ "def", "load", "(", "self", ",", "configuration", ")", ":", "try", ":", "self", ".", "config", "=", "yaml", ".", "load", "(", "open", "(", "configuration", ",", "\"rb\"", ")", ")", "except", "IOError", ":", "try", ":", "self", ".", "config", "=", "...
Load a YAML configuration file. :param configuration: Configuration filename or YAML string
[ "Load", "a", "YAML", "configuration", "file", "." ]
ec8c5818bd5913f3afd150f25eaec6e7cc732f4c
https://github.com/KvasirSecurity/kvasirapi-python/blob/ec8c5818bd5913f3afd150f25eaec6e7cc732f4c/KvasirAPI/config.py#L51-L76
train
54,509
KvasirSecurity/kvasirapi-python
KvasirAPI/config.py
Configuration.instances
def instances(self, test_type=".*"): """ Returns a dict of all instances defined using a regex :param test_type: Regular expression to match for self.instance['test_type'] value names """ import re data = {} for k, v in self.instances_dict.iteritems(): if re.match(test_type, v.get('test_type'), re.IGNORECASE): if 'filter_type' in v: hostfilter = { 'filtertype': v['filter_type'], 'content': v['filter_value'] } else: hostfilter = {} data[k] = { 'name': v.get('name'), 'start': v.get('start'), 'end': v.get('end'), 'url': v.get('url'), 'hostfilter': hostfilter, 'test_type': v.get('test_type') } return data
python
def instances(self, test_type=".*"): """ Returns a dict of all instances defined using a regex :param test_type: Regular expression to match for self.instance['test_type'] value names """ import re data = {} for k, v in self.instances_dict.iteritems(): if re.match(test_type, v.get('test_type'), re.IGNORECASE): if 'filter_type' in v: hostfilter = { 'filtertype': v['filter_type'], 'content': v['filter_value'] } else: hostfilter = {} data[k] = { 'name': v.get('name'), 'start': v.get('start'), 'end': v.get('end'), 'url': v.get('url'), 'hostfilter': hostfilter, 'test_type': v.get('test_type') } return data
[ "def", "instances", "(", "self", ",", "test_type", "=", "\".*\"", ")", ":", "import", "re", "data", "=", "{", "}", "for", "k", ",", "v", "in", "self", ".", "instances_dict", ".", "iteritems", "(", ")", ":", "if", "re", ".", "match", "(", "test_type...
Returns a dict of all instances defined using a regex :param test_type: Regular expression to match for self.instance['test_type'] value names
[ "Returns", "a", "dict", "of", "all", "instances", "defined", "using", "a", "regex" ]
ec8c5818bd5913f3afd150f25eaec6e7cc732f4c
https://github.com/KvasirSecurity/kvasirapi-python/blob/ec8c5818bd5913f3afd150f25eaec6e7cc732f4c/KvasirAPI/config.py#L78-L103
train
54,510
KvasirSecurity/kvasirapi-python
KvasirAPI/utils.py
none_to_blank
def none_to_blank(s, exchange=''): """Replaces NoneType with '' >>> none_to_blank(None, '') '' >>> none_to_blank(None) '' >>> none_to_blank('something', '') u'something' >>> none_to_blank(['1', None]) [u'1', ''] :param s: String to replace :para exchange: Character to return for None, default is blank ('') :return: If s is None, returns exchange """ if isinstance(s, list): return [none_to_blank(z) for y, z in enumerate(s)] return exchange if s is None else unicode(s)
python
def none_to_blank(s, exchange=''): """Replaces NoneType with '' >>> none_to_blank(None, '') '' >>> none_to_blank(None) '' >>> none_to_blank('something', '') u'something' >>> none_to_blank(['1', None]) [u'1', ''] :param s: String to replace :para exchange: Character to return for None, default is blank ('') :return: If s is None, returns exchange """ if isinstance(s, list): return [none_to_blank(z) for y, z in enumerate(s)] return exchange if s is None else unicode(s)
[ "def", "none_to_blank", "(", "s", ",", "exchange", "=", "''", ")", ":", "if", "isinstance", "(", "s", ",", "list", ")", ":", "return", "[", "none_to_blank", "(", "z", ")", "for", "y", ",", "z", "in", "enumerate", "(", "s", ")", "]", "return", "ex...
Replaces NoneType with '' >>> none_to_blank(None, '') '' >>> none_to_blank(None) '' >>> none_to_blank('something', '') u'something' >>> none_to_blank(['1', None]) [u'1', ''] :param s: String to replace :para exchange: Character to return for None, default is blank ('') :return: If s is None, returns exchange
[ "Replaces", "NoneType", "with" ]
ec8c5818bd5913f3afd150f25eaec6e7cc732f4c
https://github.com/KvasirSecurity/kvasirapi-python/blob/ec8c5818bd5913f3afd150f25eaec6e7cc732f4c/KvasirAPI/utils.py#L24-L42
train
54,511
KvasirSecurity/kvasirapi-python
KvasirAPI/utils.py
make_good_url
def make_good_url(url=None, addition="/"): """Appends addition to url, ensuring the right number of slashes exist and the path doesn't get clobbered. >>> make_good_url('http://www.server.com/anywhere', 'else') 'http://www.server.com/anywhere/else' >>> make_good_url('http://test.com/', '/somewhere/over/the/rainbow/') 'http://test.com/somewhere/over/the/rainbow/' >>> make_good_url('None') 'None/' >>> make_good_url() >>> make_good_url({}) >>> make_good_url(addition='{}') :param url: URL :param addition: Something to add to the URL :return: New URL with addition""" if url is None: return None if isinstance(url, str) and isinstance(addition, str): return "%s/%s" % (url.rstrip('/'), addition.lstrip('/')) else: return None
python
def make_good_url(url=None, addition="/"): """Appends addition to url, ensuring the right number of slashes exist and the path doesn't get clobbered. >>> make_good_url('http://www.server.com/anywhere', 'else') 'http://www.server.com/anywhere/else' >>> make_good_url('http://test.com/', '/somewhere/over/the/rainbow/') 'http://test.com/somewhere/over/the/rainbow/' >>> make_good_url('None') 'None/' >>> make_good_url() >>> make_good_url({}) >>> make_good_url(addition='{}') :param url: URL :param addition: Something to add to the URL :return: New URL with addition""" if url is None: return None if isinstance(url, str) and isinstance(addition, str): return "%s/%s" % (url.rstrip('/'), addition.lstrip('/')) else: return None
[ "def", "make_good_url", "(", "url", "=", "None", ",", "addition", "=", "\"/\"", ")", ":", "if", "url", "is", "None", ":", "return", "None", "if", "isinstance", "(", "url", ",", "str", ")", "and", "isinstance", "(", "addition", ",", "str", ")", ":", ...
Appends addition to url, ensuring the right number of slashes exist and the path doesn't get clobbered. >>> make_good_url('http://www.server.com/anywhere', 'else') 'http://www.server.com/anywhere/else' >>> make_good_url('http://test.com/', '/somewhere/over/the/rainbow/') 'http://test.com/somewhere/over/the/rainbow/' >>> make_good_url('None') 'None/' >>> make_good_url() >>> make_good_url({}) >>> make_good_url(addition='{}') :param url: URL :param addition: Something to add to the URL :return: New URL with addition
[ "Appends", "addition", "to", "url", "ensuring", "the", "right", "number", "of", "slashes", "exist", "and", "the", "path", "doesn", "t", "get", "clobbered", "." ]
ec8c5818bd5913f3afd150f25eaec6e7cc732f4c
https://github.com/KvasirSecurity/kvasirapi-python/blob/ec8c5818bd5913f3afd150f25eaec6e7cc732f4c/KvasirAPI/utils.py#L47-L71
train
54,512
KvasirSecurity/kvasirapi-python
KvasirAPI/utils.py
build_kvasir_url
def build_kvasir_url( proto="https", server="localhost", port="8443", base="Kvasir", user="test", password="test", path=KVASIR_JSONRPC_PATH): """ Creates a full URL to reach Kvasir given specific data >>> build_kvasir_url('https', 'localhost', '8443', 'Kvasir', 'test', 'test') 'https://test@test/localhost:8443/Kvasir/api/call/jsonrpc' >>> build_kvasir_url() 'https://test@test/localhost:8443/Kvasir/api/call/jsonrpc' >>> build_kvasir_url(server='localhost', port='443', password='password', path='bad/path') 'https://test@password/localhost:443/Kvasir/bad/path' :param proto: Protocol type - http or https :param server: Hostname or IP address of Web2py server :param port: Port to reach server :param base: Base application name :param user: Username for basic auth :param password: Password for basic auth :param path: Full path to JSONRPC (/api/call/jsonrpc) :return: A full URL that can reach Kvasir's JSONRPC interface """ uri = proto + '://' + user + '@' + password + '/' + server + ':' + port + '/' + base return make_good_url(uri, path)
python
def build_kvasir_url( proto="https", server="localhost", port="8443", base="Kvasir", user="test", password="test", path=KVASIR_JSONRPC_PATH): """ Creates a full URL to reach Kvasir given specific data >>> build_kvasir_url('https', 'localhost', '8443', 'Kvasir', 'test', 'test') 'https://test@test/localhost:8443/Kvasir/api/call/jsonrpc' >>> build_kvasir_url() 'https://test@test/localhost:8443/Kvasir/api/call/jsonrpc' >>> build_kvasir_url(server='localhost', port='443', password='password', path='bad/path') 'https://test@password/localhost:443/Kvasir/bad/path' :param proto: Protocol type - http or https :param server: Hostname or IP address of Web2py server :param port: Port to reach server :param base: Base application name :param user: Username for basic auth :param password: Password for basic auth :param path: Full path to JSONRPC (/api/call/jsonrpc) :return: A full URL that can reach Kvasir's JSONRPC interface """ uri = proto + '://' + user + '@' + password + '/' + server + ':' + port + '/' + base return make_good_url(uri, path)
[ "def", "build_kvasir_url", "(", "proto", "=", "\"https\"", ",", "server", "=", "\"localhost\"", ",", "port", "=", "\"8443\"", ",", "base", "=", "\"Kvasir\"", ",", "user", "=", "\"test\"", ",", "password", "=", "\"test\"", ",", "path", "=", "KVASIR_JSONRPC_PA...
Creates a full URL to reach Kvasir given specific data >>> build_kvasir_url('https', 'localhost', '8443', 'Kvasir', 'test', 'test') 'https://test@test/localhost:8443/Kvasir/api/call/jsonrpc' >>> build_kvasir_url() 'https://test@test/localhost:8443/Kvasir/api/call/jsonrpc' >>> build_kvasir_url(server='localhost', port='443', password='password', path='bad/path') 'https://test@password/localhost:443/Kvasir/bad/path' :param proto: Protocol type - http or https :param server: Hostname or IP address of Web2py server :param port: Port to reach server :param base: Base application name :param user: Username for basic auth :param password: Password for basic auth :param path: Full path to JSONRPC (/api/call/jsonrpc) :return: A full URL that can reach Kvasir's JSONRPC interface
[ "Creates", "a", "full", "URL", "to", "reach", "Kvasir", "given", "specific", "data" ]
ec8c5818bd5913f3afd150f25eaec6e7cc732f4c
https://github.com/KvasirSecurity/kvasirapi-python/blob/ec8c5818bd5913f3afd150f25eaec6e7cc732f4c/KvasirAPI/utils.py#L76-L100
train
54,513
evansde77/dockerstache
setup.py
get_default
def get_default(parser, section, option, default): """helper to get config settings with a default if not present""" try: result = parser.get(section, option) except (ConfigParser.NoSectionError, ConfigParser.NoOptionError): result = default return result
python
def get_default(parser, section, option, default): """helper to get config settings with a default if not present""" try: result = parser.get(section, option) except (ConfigParser.NoSectionError, ConfigParser.NoOptionError): result = default return result
[ "def", "get_default", "(", "parser", ",", "section", ",", "option", ",", "default", ")", ":", "try", ":", "result", "=", "parser", ".", "get", "(", "section", ",", "option", ")", "except", "(", "ConfigParser", ".", "NoSectionError", ",", "ConfigParser", ...
helper to get config settings with a default if not present
[ "helper", "to", "get", "config", "settings", "with", "a", "default", "if", "not", "present" ]
929c102e9fffde322dbf17f8e69533a00976aacb
https://github.com/evansde77/dockerstache/blob/929c102e9fffde322dbf17f8e69533a00976aacb/setup.py#L16-L22
train
54,514
memphis-iis/GLUDB
gludb/config.py
set_db_application_prefix
def set_db_application_prefix(prefix, sep=None): """Set the global app prefix and separator.""" global _APPLICATION_PREFIX, _APPLICATION_SEP _APPLICATION_PREFIX = prefix if (sep is not None): _APPLICATION_SEP = sep
python
def set_db_application_prefix(prefix, sep=None): """Set the global app prefix and separator.""" global _APPLICATION_PREFIX, _APPLICATION_SEP _APPLICATION_PREFIX = prefix if (sep is not None): _APPLICATION_SEP = sep
[ "def", "set_db_application_prefix", "(", "prefix", ",", "sep", "=", "None", ")", ":", "global", "_APPLICATION_PREFIX", ",", "_APPLICATION_SEP", "_APPLICATION_PREFIX", "=", "prefix", "if", "(", "sep", "is", "not", "None", ")", ":", "_APPLICATION_SEP", "=", "sep" ...
Set the global app prefix and separator.
[ "Set", "the", "global", "app", "prefix", "and", "separator", "." ]
25692528ff6fe8184a3570f61f31f1a90088a388
https://github.com/memphis-iis/GLUDB/blob/25692528ff6fe8184a3570f61f31f1a90088a388/gludb/config.py#L173-L178
train
54,515
memphis-iis/GLUDB
gludb/config.py
Database.find_by_index
def find_by_index(self, cls, index_name, value): """Find records matching index query - defer to backend.""" return self.backend.find_by_index(cls, index_name, value)
python
def find_by_index(self, cls, index_name, value): """Find records matching index query - defer to backend.""" return self.backend.find_by_index(cls, index_name, value)
[ "def", "find_by_index", "(", "self", ",", "cls", ",", "index_name", ",", "value", ")", ":", "return", "self", ".", "backend", ".", "find_by_index", "(", "cls", ",", "index_name", ",", "value", ")" ]
Find records matching index query - defer to backend.
[ "Find", "records", "matching", "index", "query", "-", "defer", "to", "backend", "." ]
25692528ff6fe8184a3570f61f31f1a90088a388
https://github.com/memphis-iis/GLUDB/blob/25692528ff6fe8184a3570f61f31f1a90088a388/gludb/config.py#L80-L82
train
54,516
unixorn/logrus
logrus/time.py
humanTime
def humanTime(seconds): ''' Convert seconds to something more human-friendly ''' intervals = ['days', 'hours', 'minutes', 'seconds'] x = deltaTime(seconds=seconds) return ' '.join('{} {}'.format(getattr(x, k), k) for k in intervals if getattr(x, k))
python
def humanTime(seconds): ''' Convert seconds to something more human-friendly ''' intervals = ['days', 'hours', 'minutes', 'seconds'] x = deltaTime(seconds=seconds) return ' '.join('{} {}'.format(getattr(x, k), k) for k in intervals if getattr(x, k))
[ "def", "humanTime", "(", "seconds", ")", ":", "intervals", "=", "[", "'days'", ",", "'hours'", ",", "'minutes'", ",", "'seconds'", "]", "x", "=", "deltaTime", "(", "seconds", "=", "seconds", ")", "return", "' '", ".", "join", "(", "'{} {}'", ".", "form...
Convert seconds to something more human-friendly
[ "Convert", "seconds", "to", "something", "more", "human", "-", "friendly" ]
d1af28639fd42968acc257476d526d9bbe57719f
https://github.com/unixorn/logrus/blob/d1af28639fd42968acc257476d526d9bbe57719f/logrus/time.py#L23-L29
train
54,517
unixorn/logrus
logrus/time.py
humanTimeConverter
def humanTimeConverter(): ''' Cope whether we're passed a time in seconds on the command line or via stdin ''' if len(sys.argv) == 2: print humanFriendlyTime(seconds=int(sys.argv[1])) else: for line in sys.stdin: print humanFriendlyTime(int(line)) sys.exit(0)
python
def humanTimeConverter(): ''' Cope whether we're passed a time in seconds on the command line or via stdin ''' if len(sys.argv) == 2: print humanFriendlyTime(seconds=int(sys.argv[1])) else: for line in sys.stdin: print humanFriendlyTime(int(line)) sys.exit(0)
[ "def", "humanTimeConverter", "(", ")", ":", "if", "len", "(", "sys", ".", "argv", ")", "==", "2", ":", "print", "humanFriendlyTime", "(", "seconds", "=", "int", "(", "sys", ".", "argv", "[", "1", "]", ")", ")", "else", ":", "for", "line", "in", "...
Cope whether we're passed a time in seconds on the command line or via stdin
[ "Cope", "whether", "we", "re", "passed", "a", "time", "in", "seconds", "on", "the", "command", "line", "or", "via", "stdin" ]
d1af28639fd42968acc257476d526d9bbe57719f
https://github.com/unixorn/logrus/blob/d1af28639fd42968acc257476d526d9bbe57719f/logrus/time.py#L32-L41
train
54,518
VikParuchuri/percept
percept/tasks/preprocess.py
Normalize.train
def train(self, data, **kwargs): """ Calculate the standard deviations and means in the training data """ self.data = data for i in xrange(0,data.shape[1]): column_mean = np.mean(data.icol(i)) column_stdev = np.std(data.icol(i)) #Have to do += or "list" type will fail (ie with append) self.column_means += [column_mean] self.column_stdevs += [column_stdev] self.data = self.predict(data)
python
def train(self, data, **kwargs): """ Calculate the standard deviations and means in the training data """ self.data = data for i in xrange(0,data.shape[1]): column_mean = np.mean(data.icol(i)) column_stdev = np.std(data.icol(i)) #Have to do += or "list" type will fail (ie with append) self.column_means += [column_mean] self.column_stdevs += [column_stdev] self.data = self.predict(data)
[ "def", "train", "(", "self", ",", "data", ",", "*", "*", "kwargs", ")", ":", "self", ".", "data", "=", "data", "for", "i", "in", "xrange", "(", "0", ",", "data", ".", "shape", "[", "1", "]", ")", ":", "column_mean", "=", "np", ".", "mean", "(...
Calculate the standard deviations and means in the training data
[ "Calculate", "the", "standard", "deviations", "and", "means", "in", "the", "training", "data" ]
90304ba82053e2a9ad2bacaab3479403d3923bcf
https://github.com/VikParuchuri/percept/blob/90304ba82053e2a9ad2bacaab3479403d3923bcf/percept/tasks/preprocess.py#L31-L44
train
54,519
VikParuchuri/percept
percept/tasks/preprocess.py
Normalize.predict
def predict(self, test_data, **kwargs): """ Adjust new input by the values in the training data """ if test_data.shape[1]!=self.data.shape[1]: raise Exception("Test data has different number of columns than training data.") for i in xrange(0,test_data.shape[1]): test_data.loc[:,i] = test_data.icol(i) - self.column_means[i] if int(self.column_stdevs[i])!=0: test_data.loc[:,i] = test_data.icol(i) / self.column_stdevs[i] return test_data
python
def predict(self, test_data, **kwargs): """ Adjust new input by the values in the training data """ if test_data.shape[1]!=self.data.shape[1]: raise Exception("Test data has different number of columns than training data.") for i in xrange(0,test_data.shape[1]): test_data.loc[:,i] = test_data.icol(i) - self.column_means[i] if int(self.column_stdevs[i])!=0: test_data.loc[:,i] = test_data.icol(i) / self.column_stdevs[i] return test_data
[ "def", "predict", "(", "self", ",", "test_data", ",", "*", "*", "kwargs", ")", ":", "if", "test_data", ".", "shape", "[", "1", "]", "!=", "self", ".", "data", ".", "shape", "[", "1", "]", ":", "raise", "Exception", "(", "\"Test data has different numbe...
Adjust new input by the values in the training data
[ "Adjust", "new", "input", "by", "the", "values", "in", "the", "training", "data" ]
90304ba82053e2a9ad2bacaab3479403d3923bcf
https://github.com/VikParuchuri/percept/blob/90304ba82053e2a9ad2bacaab3479403d3923bcf/percept/tasks/preprocess.py#L46-L56
train
54,520
frascoweb/frasco
frasco/actions/decorators.py
action_decorator
def action_decorator(name): """Decorator to register an action decorator """ def decorator(cls): action_decorators.append((name, cls)) return cls return decorator
python
def action_decorator(name): """Decorator to register an action decorator """ def decorator(cls): action_decorators.append((name, cls)) return cls return decorator
[ "def", "action_decorator", "(", "name", ")", ":", "def", "decorator", "(", "cls", ")", ":", "action_decorators", ".", "append", "(", "(", "name", ",", "cls", ")", ")", "return", "cls", "return", "decorator" ]
Decorator to register an action decorator
[ "Decorator", "to", "register", "an", "action", "decorator" ]
ea519d69dd5ca6deaf3650175692ee4a1a02518f
https://github.com/frascoweb/frasco/blob/ea519d69dd5ca6deaf3650175692ee4a1a02518f/frasco/actions/decorators.py#L10-L16
train
54,521
toumorokoshi/sprinter
sprinter/core/globals.py
load_global_config
def load_global_config(config_path): """ Load a global configuration object, and query for any required variables along the way """ config = configparser.RawConfigParser() if os.path.exists(config_path): logger.debug("Checking and setting global parameters...") config.read(config_path) else: _initial_run() logger.info("Unable to find a global sprinter configuration!") logger.info("Creating one now. Please answer some questions" + " about what you would like sprinter to do.") logger.info("") # checks and sets sections if not config.has_section('global'): config.add_section('global') configure_config(config) write_config(config, config_path) return config
python
def load_global_config(config_path): """ Load a global configuration object, and query for any required variables along the way """ config = configparser.RawConfigParser() if os.path.exists(config_path): logger.debug("Checking and setting global parameters...") config.read(config_path) else: _initial_run() logger.info("Unable to find a global sprinter configuration!") logger.info("Creating one now. Please answer some questions" + " about what you would like sprinter to do.") logger.info("") # checks and sets sections if not config.has_section('global'): config.add_section('global') configure_config(config) write_config(config, config_path) return config
[ "def", "load_global_config", "(", "config_path", ")", ":", "config", "=", "configparser", ".", "RawConfigParser", "(", ")", "if", "os", ".", "path", ".", "exists", "(", "config_path", ")", ":", "logger", ".", "debug", "(", "\"Checking and setting global paramete...
Load a global configuration object, and query for any required variables along the way
[ "Load", "a", "global", "configuration", "object", "and", "query", "for", "any", "required", "variables", "along", "the", "way" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/core/globals.py#L34-L53
train
54,522
toumorokoshi/sprinter
sprinter/core/globals.py
print_global_config
def print_global_config(global_config): """ print the global configuration """ if global_config.has_section('shell'): print("\nShell configurations:") for shell_type, set_value in global_config.items('shell'): print("{0}: {1}".format(shell_type, set_value)) if global_config.has_option('global', 'env_source_rc'): print("\nHave sprinter env source rc: {0}".format( global_config.get('global', 'env_source_rc')))
python
def print_global_config(global_config): """ print the global configuration """ if global_config.has_section('shell'): print("\nShell configurations:") for shell_type, set_value in global_config.items('shell'): print("{0}: {1}".format(shell_type, set_value)) if global_config.has_option('global', 'env_source_rc'): print("\nHave sprinter env source rc: {0}".format( global_config.get('global', 'env_source_rc')))
[ "def", "print_global_config", "(", "global_config", ")", ":", "if", "global_config", ".", "has_section", "(", "'shell'", ")", ":", "print", "(", "\"\\nShell configurations:\"", ")", "for", "shell_type", ",", "set_value", "in", "global_config", ".", "items", "(", ...
print the global configuration
[ "print", "the", "global", "configuration" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/core/globals.py#L73-L82
train
54,523
toumorokoshi/sprinter
sprinter/core/globals.py
create_default_config
def create_default_config(): """ Create a default configuration object, with all parameters filled """ config = configparser.RawConfigParser() config.add_section('global') config.set('global', 'env_source_rc', False) config.add_section('shell') config.set('shell', 'bash', "true") config.set('shell', 'zsh', "true") config.set('shell', 'gui', "true") return config
python
def create_default_config(): """ Create a default configuration object, with all parameters filled """ config = configparser.RawConfigParser() config.add_section('global') config.set('global', 'env_source_rc', False) config.add_section('shell') config.set('shell', 'bash', "true") config.set('shell', 'zsh', "true") config.set('shell', 'gui', "true") return config
[ "def", "create_default_config", "(", ")", ":", "config", "=", "configparser", ".", "RawConfigParser", "(", ")", "config", ".", "add_section", "(", "'global'", ")", "config", ".", "set", "(", "'global'", ",", "'env_source_rc'", ",", "False", ")", "config", "....
Create a default configuration object, with all parameters filled
[ "Create", "a", "default", "configuration", "object", "with", "all", "parameters", "filled" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/core/globals.py#L85-L94
train
54,524
toumorokoshi/sprinter
sprinter/core/globals.py
_initial_run
def _initial_run(): """ Check things during the initial setting of sprinter's global config """ if not system.is_officially_supported(): logger.warn(warning_template + "===========================================================\n" + "Sprinter is not officially supported on {0}! Please use at your own risk.\n\n".format(system.operating_system()) + "You can find the supported platforms here:\n" + "(http://sprinter.readthedocs.org/en/latest/index.html#compatible-systems)\n\n" + "Conversely, please help us support your system by reporting on issues\n" + "(http://sprinter.readthedocs.org/en/latest/faq.html#i-need-help-who-do-i-talk-to)\n" + "===========================================================") else: logger.info( "\nThanks for using \n" + "=" * 60 + sprinter_template + "=" * 60 )
python
def _initial_run(): """ Check things during the initial setting of sprinter's global config """ if not system.is_officially_supported(): logger.warn(warning_template + "===========================================================\n" + "Sprinter is not officially supported on {0}! Please use at your own risk.\n\n".format(system.operating_system()) + "You can find the supported platforms here:\n" + "(http://sprinter.readthedocs.org/en/latest/index.html#compatible-systems)\n\n" + "Conversely, please help us support your system by reporting on issues\n" + "(http://sprinter.readthedocs.org/en/latest/faq.html#i-need-help-who-do-i-talk-to)\n" + "===========================================================") else: logger.info( "\nThanks for using \n" + "=" * 60 + sprinter_template + "=" * 60 )
[ "def", "_initial_run", "(", ")", ":", "if", "not", "system", ".", "is_officially_supported", "(", ")", ":", "logger", ".", "warn", "(", "warning_template", "+", "\"===========================================================\\n\"", "+", "\"Sprinter is not officially supporte...
Check things during the initial setting of sprinter's global config
[ "Check", "things", "during", "the", "initial", "setting", "of", "sprinter", "s", "global", "config" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/core/globals.py#L97-L114
train
54,525
toumorokoshi/sprinter
sprinter/core/globals.py
_configure_shell
def _configure_shell(config): """ Checks and queries values for the shell """ config.has_section('shell') or config.add_section('shell') logger.info( "What shells or environments would you like sprinter to work with?\n" "(Sprinter will not try to inject into environments not specified here.)\n" "If you specify 'gui', sprinter will attempt to inject it's state into graphical programs as well.\n" "i.e. environment variables sprinter set will affect programs as well, not just shells\n" "WARNING: injecting into the GUI can be very dangerous. it usually requires a restart\n" " to modify any environmental configuration." ) environments = list(enumerate(sorted(SHELL_CONFIG), start=1)) logger.info("[0]: All, " + ", ".join(["[%d]: %s" % (index, val) for index, val in environments])) desired_environments = lib.prompt("type the environment, comma-separated", default="0") for index, val in environments: if str(index) in desired_environments or "0" in desired_environments: config.set('shell', val, 'true') else: config.set('shell', val, 'false')
python
def _configure_shell(config): """ Checks and queries values for the shell """ config.has_section('shell') or config.add_section('shell') logger.info( "What shells or environments would you like sprinter to work with?\n" "(Sprinter will not try to inject into environments not specified here.)\n" "If you specify 'gui', sprinter will attempt to inject it's state into graphical programs as well.\n" "i.e. environment variables sprinter set will affect programs as well, not just shells\n" "WARNING: injecting into the GUI can be very dangerous. it usually requires a restart\n" " to modify any environmental configuration." ) environments = list(enumerate(sorted(SHELL_CONFIG), start=1)) logger.info("[0]: All, " + ", ".join(["[%d]: %s" % (index, val) for index, val in environments])) desired_environments = lib.prompt("type the environment, comma-separated", default="0") for index, val in environments: if str(index) in desired_environments or "0" in desired_environments: config.set('shell', val, 'true') else: config.set('shell', val, 'false')
[ "def", "_configure_shell", "(", "config", ")", ":", "config", ".", "has_section", "(", "'shell'", ")", "or", "config", ".", "add_section", "(", "'shell'", ")", "logger", ".", "info", "(", "\"What shells or environments would you like sprinter to work with?\\n\"", "\"(...
Checks and queries values for the shell
[ "Checks", "and", "queries", "values", "for", "the", "shell" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/core/globals.py#L117-L135
train
54,526
toumorokoshi/sprinter
sprinter/core/globals.py
_configure_env_source_rc
def _configure_env_source_rc(config): """ Configures wether to have .env source .rc """ config.set('global', 'env_source_rc', False) if system.is_osx(): logger.info("On OSX, login shells are default, which only source sprinter's 'env' configuration.") logger.info("I.E. environment variables would be sourced, but not shell functions " + "or terminal status lines.") logger.info("The typical solution to get around this is to source your rc file (.bashrc, .zshrc) " + "from your login shell.") env_source_rc = lib.prompt("would you like sprinter to source the rc file too?", default="yes", boolean=True) config.set('global', 'env_source_rc', env_source_rc)
python
def _configure_env_source_rc(config): """ Configures wether to have .env source .rc """ config.set('global', 'env_source_rc', False) if system.is_osx(): logger.info("On OSX, login shells are default, which only source sprinter's 'env' configuration.") logger.info("I.E. environment variables would be sourced, but not shell functions " + "or terminal status lines.") logger.info("The typical solution to get around this is to source your rc file (.bashrc, .zshrc) " + "from your login shell.") env_source_rc = lib.prompt("would you like sprinter to source the rc file too?", default="yes", boolean=True) config.set('global', 'env_source_rc', env_source_rc)
[ "def", "_configure_env_source_rc", "(", "config", ")", ":", "config", ".", "set", "(", "'global'", ",", "'env_source_rc'", ",", "False", ")", "if", "system", ".", "is_osx", "(", ")", ":", "logger", ".", "info", "(", "\"On OSX, login shells are default, which onl...
Configures wether to have .env source .rc
[ "Configures", "wether", "to", "have", ".", "env", "source", ".", "rc" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/core/globals.py#L138-L149
train
54,527
liam-middlebrook/csh_ldap
csh_ldap/group.py
CSHGroup.get_members
def get_members(self): """Return all members in the group as CSHMember objects""" res = self.__con__.search_s( self.__ldap_base_dn__, ldap.SCOPE_SUBTREE, "(memberof=%s)" % self.__dn__, ['uid']) ret = [] for val in res: val = val[1]['uid'][0] try: ret.append(val.decode('utf-8')) except UnicodeDecodeError: ret.append(val) except KeyError: continue return [CSHMember(self.__lib__, result, uid=True) for result in ret]
python
def get_members(self): """Return all members in the group as CSHMember objects""" res = self.__con__.search_s( self.__ldap_base_dn__, ldap.SCOPE_SUBTREE, "(memberof=%s)" % self.__dn__, ['uid']) ret = [] for val in res: val = val[1]['uid'][0] try: ret.append(val.decode('utf-8')) except UnicodeDecodeError: ret.append(val) except KeyError: continue return [CSHMember(self.__lib__, result, uid=True) for result in ret]
[ "def", "get_members", "(", "self", ")", ":", "res", "=", "self", ".", "__con__", ".", "search_s", "(", "self", ".", "__ldap_base_dn__", ",", "ldap", ".", "SCOPE_SUBTREE", ",", "\"(memberof=%s)\"", "%", "self", ".", "__dn__", ",", "[", "'uid'", "]", ")", ...
Return all members in the group as CSHMember objects
[ "Return", "all", "members", "in", "the", "group", "as", "CSHMember", "objects" ]
90bd334a20e13c03af07bce4f104ad96baf620e4
https://github.com/liam-middlebrook/csh_ldap/blob/90bd334a20e13c03af07bce4f104ad96baf620e4/csh_ldap/group.py#L30-L51
train
54,528
liam-middlebrook/csh_ldap
csh_ldap/group.py
CSHGroup.check_member
def check_member(self, member, dn=False): """Check if a Member is in the bound group. Arguments: member -- the CSHMember object (or distinguished name) of the member to check against Keyword arguments: dn -- whether or not member is a distinguished name """ if dn: res = self.__con__.search_s( self.__dn__, ldap.SCOPE_BASE, "(member=%s)" % dn, ['ipaUniqueID']) else: res = self.__con__.search_s( self.__dn__, ldap.SCOPE_BASE, "(member=%s)" % member.get_dn(), ['ipaUniqueID']) return len(res) > 0
python
def check_member(self, member, dn=False): """Check if a Member is in the bound group. Arguments: member -- the CSHMember object (or distinguished name) of the member to check against Keyword arguments: dn -- whether or not member is a distinguished name """ if dn: res = self.__con__.search_s( self.__dn__, ldap.SCOPE_BASE, "(member=%s)" % dn, ['ipaUniqueID']) else: res = self.__con__.search_s( self.__dn__, ldap.SCOPE_BASE, "(member=%s)" % member.get_dn(), ['ipaUniqueID']) return len(res) > 0
[ "def", "check_member", "(", "self", ",", "member", ",", "dn", "=", "False", ")", ":", "if", "dn", ":", "res", "=", "self", ".", "__con__", ".", "search_s", "(", "self", ".", "__dn__", ",", "ldap", ".", "SCOPE_BASE", ",", "\"(member=%s)\"", "%", "dn",...
Check if a Member is in the bound group. Arguments: member -- the CSHMember object (or distinguished name) of the member to check against Keyword arguments: dn -- whether or not member is a distinguished name
[ "Check", "if", "a", "Member", "is", "in", "the", "bound", "group", "." ]
90bd334a20e13c03af07bce4f104ad96baf620e4
https://github.com/liam-middlebrook/csh_ldap/blob/90bd334a20e13c03af07bce4f104ad96baf620e4/csh_ldap/group.py#L53-L76
train
54,529
liam-middlebrook/csh_ldap
csh_ldap/group.py
CSHGroup.add_member
def add_member(self, member, dn=False): """Add a member to the bound group Arguments: member -- the CSHMember object (or distinguished name) of the member Keyword arguments: dn -- whether or not member is a distinguished name """ if dn: if self.check_member(member, dn=True): return mod = (ldap.MOD_ADD, 'member', member.encode('ascii')) else: if self.check_member(member): return mod = (ldap.MOD_ADD, 'member', member.get_dn().encode('ascii')) if self.__lib__.__batch_mods__: self.__lib__.enqueue_mod(self.__dn__, mod) elif not self.__lib__.__ro__: mod_attrs = [mod] self.__con__.modify_s(self.__dn__, mod_attrs) else: print("ADD VALUE member = {} FOR {}".format(mod[2], self.__dn__))
python
def add_member(self, member, dn=False): """Add a member to the bound group Arguments: member -- the CSHMember object (or distinguished name) of the member Keyword arguments: dn -- whether or not member is a distinguished name """ if dn: if self.check_member(member, dn=True): return mod = (ldap.MOD_ADD, 'member', member.encode('ascii')) else: if self.check_member(member): return mod = (ldap.MOD_ADD, 'member', member.get_dn().encode('ascii')) if self.__lib__.__batch_mods__: self.__lib__.enqueue_mod(self.__dn__, mod) elif not self.__lib__.__ro__: mod_attrs = [mod] self.__con__.modify_s(self.__dn__, mod_attrs) else: print("ADD VALUE member = {} FOR {}".format(mod[2], self.__dn__))
[ "def", "add_member", "(", "self", ",", "member", ",", "dn", "=", "False", ")", ":", "if", "dn", ":", "if", "self", ".", "check_member", "(", "member", ",", "dn", "=", "True", ")", ":", "return", "mod", "=", "(", "ldap", ".", "MOD_ADD", ",", "'mem...
Add a member to the bound group Arguments: member -- the CSHMember object (or distinguished name) of the member Keyword arguments: dn -- whether or not member is a distinguished name
[ "Add", "a", "member", "to", "the", "bound", "group" ]
90bd334a20e13c03af07bce4f104ad96baf620e4
https://github.com/liam-middlebrook/csh_ldap/blob/90bd334a20e13c03af07bce4f104ad96baf620e4/csh_ldap/group.py#L78-L103
train
54,530
smarie/python-parsyfiles
parsyfiles/plugins_optional/support_for_yaml.py
read_object_from_yaml
def read_object_from_yaml(desired_type: Type[Any], file_object: TextIOBase, logger: Logger, fix_imports: bool = True, errors: str = 'strict', *args, **kwargs) -> Any: """ Parses a yaml file. :param desired_type: :param file_object: :param logger: :param fix_imports: :param errors: :param args: :param kwargs: :return: """ return yaml.load(file_object)
python
def read_object_from_yaml(desired_type: Type[Any], file_object: TextIOBase, logger: Logger, fix_imports: bool = True, errors: str = 'strict', *args, **kwargs) -> Any: """ Parses a yaml file. :param desired_type: :param file_object: :param logger: :param fix_imports: :param errors: :param args: :param kwargs: :return: """ return yaml.load(file_object)
[ "def", "read_object_from_yaml", "(", "desired_type", ":", "Type", "[", "Any", "]", ",", "file_object", ":", "TextIOBase", ",", "logger", ":", "Logger", ",", "fix_imports", ":", "bool", "=", "True", ",", "errors", ":", "str", "=", "'strict'", ",", "*", "a...
Parses a yaml file. :param desired_type: :param file_object: :param logger: :param fix_imports: :param errors: :param args: :param kwargs: :return:
[ "Parses", "a", "yaml", "file", "." ]
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/plugins_optional/support_for_yaml.py#L12-L26
train
54,531
smarie/python-parsyfiles
parsyfiles/plugins_optional/support_for_yaml.py
read_collection_from_yaml
def read_collection_from_yaml(desired_type: Type[Any], file_object: TextIOBase, logger: Logger, conversion_finder: ConversionFinder, fix_imports: bool = True, errors: str = 'strict', **kwargs) -> Any: """ Parses a collection from a yaml file. :param desired_type: :param file_object: :param logger: :param fix_imports: :param errors: :param args: :param kwargs: :return: """ res = yaml.load(file_object) # convert if required return ConversionFinder.convert_collection_values_according_to_pep(res, desired_type, conversion_finder, logger, **kwargs)
python
def read_collection_from_yaml(desired_type: Type[Any], file_object: TextIOBase, logger: Logger, conversion_finder: ConversionFinder, fix_imports: bool = True, errors: str = 'strict', **kwargs) -> Any: """ Parses a collection from a yaml file. :param desired_type: :param file_object: :param logger: :param fix_imports: :param errors: :param args: :param kwargs: :return: """ res = yaml.load(file_object) # convert if required return ConversionFinder.convert_collection_values_according_to_pep(res, desired_type, conversion_finder, logger, **kwargs)
[ "def", "read_collection_from_yaml", "(", "desired_type", ":", "Type", "[", "Any", "]", ",", "file_object", ":", "TextIOBase", ",", "logger", ":", "Logger", ",", "conversion_finder", ":", "ConversionFinder", ",", "fix_imports", ":", "bool", "=", "True", ",", "e...
Parses a collection from a yaml file. :param desired_type: :param file_object: :param logger: :param fix_imports: :param errors: :param args: :param kwargs: :return:
[ "Parses", "a", "collection", "from", "a", "yaml", "file", "." ]
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/plugins_optional/support_for_yaml.py#L29-L48
train
54,532
frascoweb/frasco
frasco/features.py
pass_feature
def pass_feature(*feature_names): """Injects a feature instance into the kwargs """ def decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): for name in feature_names: kwargs[name] = feature_proxy(name) return f(*args, **kwargs) return wrapper return decorator
python
def pass_feature(*feature_names): """Injects a feature instance into the kwargs """ def decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): for name in feature_names: kwargs[name] = feature_proxy(name) return f(*args, **kwargs) return wrapper return decorator
[ "def", "pass_feature", "(", "*", "feature_names", ")", ":", "def", "decorator", "(", "f", ")", ":", "@", "functools", ".", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "name", "in", "feature_...
Injects a feature instance into the kwargs
[ "Injects", "a", "feature", "instance", "into", "the", "kwargs" ]
ea519d69dd5ca6deaf3650175692ee4a1a02518f
https://github.com/frascoweb/frasco/blob/ea519d69dd5ca6deaf3650175692ee4a1a02518f/frasco/features.py#L205-L215
train
54,533
toumorokoshi/sprinter
sprinter/lib/extract.py
extract_tar
def extract_tar(url, target_dir, additional_compression="", remove_common_prefix=False, overwrite=False): """ extract a targz and install to the target directory """ try: if not os.path.exists(target_dir): os.makedirs(target_dir) tf = tarfile.TarFile.open(fileobj=download_to_bytesio(url)) if not os.path.exists(target_dir): os.makedirs(target_dir) common_prefix = os.path.commonprefix(tf.getnames()) if not common_prefix.endswith('/'): common_prefix += "/" for tfile in tf.getmembers(): if remove_common_prefix: tfile.name = tfile.name.replace(common_prefix, "", 1) if tfile.name != "": target_path = os.path.join(target_dir, tfile.name) if target_path != target_dir and os.path.exists(target_path): if overwrite: remove_path(target_path) else: continue tf.extract(tfile, target_dir) except OSError: e = sys.exc_info()[1] raise ExtractException(str(e)) except IOError: e = sys.exc_info()[1] raise ExtractException(str(e))
python
def extract_tar(url, target_dir, additional_compression="", remove_common_prefix=False, overwrite=False): """ extract a targz and install to the target directory """ try: if not os.path.exists(target_dir): os.makedirs(target_dir) tf = tarfile.TarFile.open(fileobj=download_to_bytesio(url)) if not os.path.exists(target_dir): os.makedirs(target_dir) common_prefix = os.path.commonprefix(tf.getnames()) if not common_prefix.endswith('/'): common_prefix += "/" for tfile in tf.getmembers(): if remove_common_prefix: tfile.name = tfile.name.replace(common_prefix, "", 1) if tfile.name != "": target_path = os.path.join(target_dir, tfile.name) if target_path != target_dir and os.path.exists(target_path): if overwrite: remove_path(target_path) else: continue tf.extract(tfile, target_dir) except OSError: e = sys.exc_info()[1] raise ExtractException(str(e)) except IOError: e = sys.exc_info()[1] raise ExtractException(str(e))
[ "def", "extract_tar", "(", "url", ",", "target_dir", ",", "additional_compression", "=", "\"\"", ",", "remove_common_prefix", "=", "False", ",", "overwrite", "=", "False", ")", ":", "try", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "target_di...
extract a targz and install to the target directory
[ "extract", "a", "targz", "and", "install", "to", "the", "target", "directory" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/lib/extract.py#L23-L50
train
54,534
toumorokoshi/sprinter
sprinter/lib/extract.py
remove_path
def remove_path(target_path): """ Delete the target path """ if os.path.isdir(target_path): shutil.rmtree(target_path) else: os.unlink(target_path)
python
def remove_path(target_path): """ Delete the target path """ if os.path.isdir(target_path): shutil.rmtree(target_path) else: os.unlink(target_path)
[ "def", "remove_path", "(", "target_path", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "target_path", ")", ":", "shutil", ".", "rmtree", "(", "target_path", ")", "else", ":", "os", ".", "unlink", "(", "target_path", ")" ]
Delete the target path
[ "Delete", "the", "target", "path" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/lib/extract.py#L112-L117
train
54,535
VikParuchuri/percept
percept/workflows/datastores.py
BaseStore.save
def save(self, obj, id_code): """ Save an object, and use id_code in the filename obj - any object id_code - unique identifier """ filestream = open('{0}/{1}'.format(self.data_path, id_code), 'w+') pickle.dump(obj, filestream) filestream.close()
python
def save(self, obj, id_code): """ Save an object, and use id_code in the filename obj - any object id_code - unique identifier """ filestream = open('{0}/{1}'.format(self.data_path, id_code), 'w+') pickle.dump(obj, filestream) filestream.close()
[ "def", "save", "(", "self", ",", "obj", ",", "id_code", ")", ":", "filestream", "=", "open", "(", "'{0}/{1}'", ".", "format", "(", "self", ".", "data_path", ",", "id_code", ")", ",", "'w+'", ")", "pickle", ".", "dump", "(", "obj", ",", "filestream", ...
Save an object, and use id_code in the filename obj - any object id_code - unique identifier
[ "Save", "an", "object", "and", "use", "id_code", "in", "the", "filename", "obj", "-", "any", "object", "id_code", "-", "unique", "identifier" ]
90304ba82053e2a9ad2bacaab3479403d3923bcf
https://github.com/VikParuchuri/percept/blob/90304ba82053e2a9ad2bacaab3479403d3923bcf/percept/workflows/datastores.py#L19-L27
train
54,536
VikParuchuri/percept
percept/workflows/datastores.py
BaseStore.load
def load(self, id_code): """ Loads a workflow identified by id_code id_code - unique identifier, previously must have called save with same id_code """ filestream = open('{0}/{1}'.format(self.data_path, id_code), 'rb') workflow = pickle.load(filestream) return workflow
python
def load(self, id_code): """ Loads a workflow identified by id_code id_code - unique identifier, previously must have called save with same id_code """ filestream = open('{0}/{1}'.format(self.data_path, id_code), 'rb') workflow = pickle.load(filestream) return workflow
[ "def", "load", "(", "self", ",", "id_code", ")", ":", "filestream", "=", "open", "(", "'{0}/{1}'", ".", "format", "(", "self", ".", "data_path", ",", "id_code", ")", ",", "'rb'", ")", "workflow", "=", "pickle", ".", "load", "(", "filestream", ")", "r...
Loads a workflow identified by id_code id_code - unique identifier, previously must have called save with same id_code
[ "Loads", "a", "workflow", "identified", "by", "id_code", "id_code", "-", "unique", "identifier", "previously", "must", "have", "called", "save", "with", "same", "id_code" ]
90304ba82053e2a9ad2bacaab3479403d3923bcf
https://github.com/VikParuchuri/percept/blob/90304ba82053e2a9ad2bacaab3479403d3923bcf/percept/workflows/datastores.py#L29-L36
train
54,537
smarie/python-parsyfiles
parsyfiles/plugins_base/support_for_objects.py
read_object_from_pickle
def read_object_from_pickle(desired_type: Type[T], file_path: str, encoding: str, fix_imports: bool = True, errors: str = 'strict', *args, **kwargs) -> Any: """ Parses a pickle file. :param desired_type: :param file_path: :param encoding: :param fix_imports: :param errors: :param args: :param kwargs: :return: """ import pickle file_object = open(file_path, mode='rb') try: return pickle.load(file_object, fix_imports=fix_imports, encoding=encoding, errors=errors) finally: file_object.close()
python
def read_object_from_pickle(desired_type: Type[T], file_path: str, encoding: str, fix_imports: bool = True, errors: str = 'strict', *args, **kwargs) -> Any: """ Parses a pickle file. :param desired_type: :param file_path: :param encoding: :param fix_imports: :param errors: :param args: :param kwargs: :return: """ import pickle file_object = open(file_path, mode='rb') try: return pickle.load(file_object, fix_imports=fix_imports, encoding=encoding, errors=errors) finally: file_object.close()
[ "def", "read_object_from_pickle", "(", "desired_type", ":", "Type", "[", "T", "]", ",", "file_path", ":", "str", ",", "encoding", ":", "str", ",", "fix_imports", ":", "bool", "=", "True", ",", "errors", ":", "str", "=", "'strict'", ",", "*", "args", ",...
Parses a pickle file. :param desired_type: :param file_path: :param encoding: :param fix_imports: :param errors: :param args: :param kwargs: :return:
[ "Parses", "a", "pickle", "file", "." ]
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/plugins_base/support_for_objects.py#L21-L40
train
54,538
smarie/python-parsyfiles
parsyfiles/plugins_base/support_for_objects.py
should_display_warnings_for
def should_display_warnings_for(to_type): """ Central method where we control whether warnings should be displayed """ if not hasattr(to_type, '__module__'): return True elif to_type.__module__ in {'builtins'} or to_type.__module__.startswith('parsyfiles') \ or to_type.__name__ in {'DataFrame'}: return False elif issubclass(to_type, int) or issubclass(to_type, str) \ or issubclass(to_type, float) or issubclass(to_type, bool): return False else: return True
python
def should_display_warnings_for(to_type): """ Central method where we control whether warnings should be displayed """ if not hasattr(to_type, '__module__'): return True elif to_type.__module__ in {'builtins'} or to_type.__module__.startswith('parsyfiles') \ or to_type.__name__ in {'DataFrame'}: return False elif issubclass(to_type, int) or issubclass(to_type, str) \ or issubclass(to_type, float) or issubclass(to_type, bool): return False else: return True
[ "def", "should_display_warnings_for", "(", "to_type", ")", ":", "if", "not", "hasattr", "(", "to_type", ",", "'__module__'", ")", ":", "return", "True", "elif", "to_type", ".", "__module__", "in", "{", "'builtins'", "}", "or", "to_type", ".", "__module__", "...
Central method where we control whether warnings should be displayed
[ "Central", "method", "where", "we", "control", "whether", "warnings", "should", "be", "displayed" ]
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/plugins_base/support_for_objects.py#L191-L202
train
54,539
smarie/python-parsyfiles
parsyfiles/plugins_base/support_for_objects.py
print_dict
def print_dict(dict_name, dict_value, logger: Logger = None): """ Utility method to print a named dictionary :param dict_name: :param dict_value: :return: """ if logger is None: print(dict_name + ' = ') try: from pprint import pprint pprint(dict_value) except: print(dict_value) else: logger.info(dict_name + ' = ') try: from pprint import pformat logger.info(pformat(dict_value)) except: logger.info(dict_value)
python
def print_dict(dict_name, dict_value, logger: Logger = None): """ Utility method to print a named dictionary :param dict_name: :param dict_value: :return: """ if logger is None: print(dict_name + ' = ') try: from pprint import pprint pprint(dict_value) except: print(dict_value) else: logger.info(dict_name + ' = ') try: from pprint import pformat logger.info(pformat(dict_value)) except: logger.info(dict_value)
[ "def", "print_dict", "(", "dict_name", ",", "dict_value", ",", "logger", ":", "Logger", "=", "None", ")", ":", "if", "logger", "is", "None", ":", "print", "(", "dict_name", "+", "' = '", ")", "try", ":", "from", "pprint", "import", "pprint", "pprint", ...
Utility method to print a named dictionary :param dict_name: :param dict_value: :return:
[ "Utility", "method", "to", "print", "a", "named", "dictionary" ]
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/plugins_base/support_for_objects.py#L485-L506
train
54,540
smarie/python-parsyfiles
parsyfiles/plugins_base/support_for_objects.py
MultifileObjectParser.is_able_to_parse_detailed
def is_able_to_parse_detailed(self, desired_type: Type[Any], desired_ext: str, strict: bool): """ Explicitly declare that we are not able to parse collections :param desired_type: :param desired_ext: :param strict: :return: """ if not _is_valid_for_dict_to_object_conversion(strict, None, None if desired_type is JOKER else desired_type): return False, None else: return super(MultifileObjectParser, self).is_able_to_parse_detailed(desired_type, desired_ext, strict)
python
def is_able_to_parse_detailed(self, desired_type: Type[Any], desired_ext: str, strict: bool): """ Explicitly declare that we are not able to parse collections :param desired_type: :param desired_ext: :param strict: :return: """ if not _is_valid_for_dict_to_object_conversion(strict, None, None if desired_type is JOKER else desired_type): return False, None else: return super(MultifileObjectParser, self).is_able_to_parse_detailed(desired_type, desired_ext, strict)
[ "def", "is_able_to_parse_detailed", "(", "self", ",", "desired_type", ":", "Type", "[", "Any", "]", ",", "desired_ext", ":", "str", ",", "strict", ":", "bool", ")", ":", "if", "not", "_is_valid_for_dict_to_object_conversion", "(", "strict", ",", "None", ",", ...
Explicitly declare that we are not able to parse collections :param desired_type: :param desired_ext: :param strict: :return:
[ "Explicitly", "declare", "that", "we", "are", "not", "able", "to", "parse", "collections" ]
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/plugins_base/support_for_objects.py#L562-L575
train
54,541
smarie/python-parsyfiles
parsyfiles/global_config.py
parsyfiles_global_config
def parsyfiles_global_config(multiple_errors_tb_limit: int = None, full_paths_in_logs: bool = None, dict_to_object_subclass_limit: int = None): """ This is the method you should use to configure the parsyfiles library :param multiple_errors_tb_limit: the traceback size (default is 3) of individual parsers exceptions displayed when parsyfiles tries several parsing chains and all of them fail. :param full_paths_in_logs: if True, full file paths will be displayed in logs. Otherwise only the parent path will be displayed and children paths will be indented (default is False) :param dict_to_object_subclass_limit: the number of subclasses that the <dict_to_object> converter will try, when instantiating an object from a dictionary. Default is 50 :return: """ if multiple_errors_tb_limit is not None: GLOBAL_CONFIG.multiple_errors_tb_limit = multiple_errors_tb_limit if full_paths_in_logs is not None: GLOBAL_CONFIG.full_paths_in_logs = full_paths_in_logs if dict_to_object_subclass_limit is not None: GLOBAL_CONFIG.dict_to_object_subclass_limit = dict_to_object_subclass_limit
python
def parsyfiles_global_config(multiple_errors_tb_limit: int = None, full_paths_in_logs: bool = None, dict_to_object_subclass_limit: int = None): """ This is the method you should use to configure the parsyfiles library :param multiple_errors_tb_limit: the traceback size (default is 3) of individual parsers exceptions displayed when parsyfiles tries several parsing chains and all of them fail. :param full_paths_in_logs: if True, full file paths will be displayed in logs. Otherwise only the parent path will be displayed and children paths will be indented (default is False) :param dict_to_object_subclass_limit: the number of subclasses that the <dict_to_object> converter will try, when instantiating an object from a dictionary. Default is 50 :return: """ if multiple_errors_tb_limit is not None: GLOBAL_CONFIG.multiple_errors_tb_limit = multiple_errors_tb_limit if full_paths_in_logs is not None: GLOBAL_CONFIG.full_paths_in_logs = full_paths_in_logs if dict_to_object_subclass_limit is not None: GLOBAL_CONFIG.dict_to_object_subclass_limit = dict_to_object_subclass_limit
[ "def", "parsyfiles_global_config", "(", "multiple_errors_tb_limit", ":", "int", "=", "None", ",", "full_paths_in_logs", ":", "bool", "=", "None", ",", "dict_to_object_subclass_limit", ":", "int", "=", "None", ")", ":", "if", "multiple_errors_tb_limit", "is", "not", ...
This is the method you should use to configure the parsyfiles library :param multiple_errors_tb_limit: the traceback size (default is 3) of individual parsers exceptions displayed when parsyfiles tries several parsing chains and all of them fail. :param full_paths_in_logs: if True, full file paths will be displayed in logs. Otherwise only the parent path will be displayed and children paths will be indented (default is False) :param dict_to_object_subclass_limit: the number of subclasses that the <dict_to_object> converter will try, when instantiating an object from a dictionary. Default is 50 :return:
[ "This", "is", "the", "method", "you", "should", "use", "to", "configure", "the", "parsyfiles", "library" ]
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/global_config.py#L17-L35
train
54,542
frascoweb/frasco
frasco/actions/core.py
Action.is_valid
def is_valid(self, context): """Checks through the previous_actions iterable if required actions have been executed """ if self.requires: for r in self.requires: if not r in context.executed_actions: raise RequirementMissingError("Action '%s' requires '%s'" % (self.name, r)) return True
python
def is_valid(self, context): """Checks through the previous_actions iterable if required actions have been executed """ if self.requires: for r in self.requires: if not r in context.executed_actions: raise RequirementMissingError("Action '%s' requires '%s'" % (self.name, r)) return True
[ "def", "is_valid", "(", "self", ",", "context", ")", ":", "if", "self", ".", "requires", ":", "for", "r", "in", "self", ".", "requires", ":", "if", "not", "r", "in", "context", ".", "executed_actions", ":", "raise", "RequirementMissingError", "(", "\"Act...
Checks through the previous_actions iterable if required actions have been executed
[ "Checks", "through", "the", "previous_actions", "iterable", "if", "required", "actions", "have", "been", "executed" ]
ea519d69dd5ca6deaf3650175692ee4a1a02518f
https://github.com/frascoweb/frasco/blob/ea519d69dd5ca6deaf3650175692ee4a1a02518f/frasco/actions/core.py#L50-L58
train
54,543
nikcub/floyd
setup.py
get_file_contents
def get_file_contents(file_path): """Get the context of the file using full path name""" full_path = os.path.join(package_dir, file_path) return open(full_path, 'r').read()
python
def get_file_contents(file_path): """Get the context of the file using full path name""" full_path = os.path.join(package_dir, file_path) return open(full_path, 'r').read()
[ "def", "get_file_contents", "(", "file_path", ")", ":", "full_path", "=", "os", ".", "path", ".", "join", "(", "package_dir", ",", "file_path", ")", "return", "open", "(", "full_path", ",", "'r'", ")", ".", "read", "(", ")" ]
Get the context of the file using full path name
[ "Get", "the", "context", "of", "the", "file", "using", "full", "path", "name" ]
5772d0047efb11c9ce5f7d234a9da4576ce24edc
https://github.com/nikcub/floyd/blob/5772d0047efb11c9ce5f7d234a9da4576ce24edc/setup.py#L33-L36
train
54,544
majuss/lupupy
lupupy/devices/__init__.py
LupusecDevice.refresh
def refresh(self): """Refresh a device""" # new_device = {} if self.type in CONST.BINARY_SENSOR_TYPES: response = self._lupusec.get_sensors() for device in response: if device['device_id'] == self._device_id: self.update(device) return device elif self.type == CONST.ALARM_TYPE: response = self._lupusec.get_panel() self.update(response) return response elif self.type == CONST.TYPE_POWER_SWITCH: response = self._lupusec.get_power_switches() for pss in response: if pss['device_id'] == self._device_id: self.update(pss) return pss
python
def refresh(self): """Refresh a device""" # new_device = {} if self.type in CONST.BINARY_SENSOR_TYPES: response = self._lupusec.get_sensors() for device in response: if device['device_id'] == self._device_id: self.update(device) return device elif self.type == CONST.ALARM_TYPE: response = self._lupusec.get_panel() self.update(response) return response elif self.type == CONST.TYPE_POWER_SWITCH: response = self._lupusec.get_power_switches() for pss in response: if pss['device_id'] == self._device_id: self.update(pss) return pss
[ "def", "refresh", "(", "self", ")", ":", "# new_device = {}", "if", "self", ".", "type", "in", "CONST", ".", "BINARY_SENSOR_TYPES", ":", "response", "=", "self", ".", "_lupusec", ".", "get_sensors", "(", ")", "for", "device", "in", "response", ":", "if", ...
Refresh a device
[ "Refresh", "a", "device" ]
71af6c397837ffc393c7b8122be175602638d3c6
https://github.com/majuss/lupupy/blob/71af6c397837ffc393c7b8122be175602638d3c6/lupupy/devices/__init__.py#L34-L55
train
54,545
majuss/lupupy
lupupy/devices/__init__.py
LupusecDevice.desc
def desc(self): """Get a short description of the device.""" return '{0} (ID: {1}) - {2} - {3}'.format( self.name, self.device_id, self.type, self.status)
python
def desc(self): """Get a short description of the device.""" return '{0} (ID: {1}) - {2} - {3}'.format( self.name, self.device_id, self.type, self.status)
[ "def", "desc", "(", "self", ")", ":", "return", "'{0} (ID: {1}) - {2} - {3}'", ".", "format", "(", "self", ".", "name", ",", "self", ".", "device_id", ",", "self", ".", "type", ",", "self", ".", "status", ")" ]
Get a short description of the device.
[ "Get", "a", "short", "description", "of", "the", "device", "." ]
71af6c397837ffc393c7b8122be175602638d3c6
https://github.com/majuss/lupupy/blob/71af6c397837ffc393c7b8122be175602638d3c6/lupupy/devices/__init__.py#L124-L127
train
54,546
inveniosoftware/invenio-queues
invenio_queues/cli.py
list
def list(declared, undeclared): """List configured queues.""" queues = current_queues.queues.values() if declared: queues = filter(lambda queue: queue.exists, queues) elif undeclared: queues = filter(lambda queue: not queue.exists, queues) queue_names = [queue.routing_key for queue in queues] queue_names.sort() for queue in queue_names: click.secho(queue)
python
def list(declared, undeclared): """List configured queues.""" queues = current_queues.queues.values() if declared: queues = filter(lambda queue: queue.exists, queues) elif undeclared: queues = filter(lambda queue: not queue.exists, queues) queue_names = [queue.routing_key for queue in queues] queue_names.sort() for queue in queue_names: click.secho(queue)
[ "def", "list", "(", "declared", ",", "undeclared", ")", ":", "queues", "=", "current_queues", ".", "queues", ".", "values", "(", ")", "if", "declared", ":", "queues", "=", "filter", "(", "lambda", "queue", ":", "queue", ".", "exists", ",", "queues", ")...
List configured queues.
[ "List", "configured", "queues", "." ]
1dd9112d7c5fe72a428c86f21f6d02cdb0595921
https://github.com/inveniosoftware/invenio-queues/blob/1dd9112d7c5fe72a428c86f21f6d02cdb0595921/invenio_queues/cli.py#L46-L56
train
54,547
inveniosoftware/invenio-queues
invenio_queues/cli.py
declare
def declare(queues): """Initialize the given queues.""" current_queues.declare(queues=queues) click.secho( 'Queues {} have been declared.'.format( queues or current_queues.queues.keys()), fg='green' )
python
def declare(queues): """Initialize the given queues.""" current_queues.declare(queues=queues) click.secho( 'Queues {} have been declared.'.format( queues or current_queues.queues.keys()), fg='green' )
[ "def", "declare", "(", "queues", ")", ":", "current_queues", ".", "declare", "(", "queues", "=", "queues", ")", "click", ".", "secho", "(", "'Queues {} have been declared.'", ".", "format", "(", "queues", "or", "current_queues", ".", "queues", ".", "keys", "...
Initialize the given queues.
[ "Initialize", "the", "given", "queues", "." ]
1dd9112d7c5fe72a428c86f21f6d02cdb0595921
https://github.com/inveniosoftware/invenio-queues/blob/1dd9112d7c5fe72a428c86f21f6d02cdb0595921/invenio_queues/cli.py#L62-L69
train
54,548
inveniosoftware/invenio-queues
invenio_queues/cli.py
purge_queues
def purge_queues(queues=None): """Purge the given queues.""" current_queues.purge(queues=queues) click.secho( 'Queues {} have been purged.'.format( queues or current_queues.queues.keys()), fg='green' )
python
def purge_queues(queues=None): """Purge the given queues.""" current_queues.purge(queues=queues) click.secho( 'Queues {} have been purged.'.format( queues or current_queues.queues.keys()), fg='green' )
[ "def", "purge_queues", "(", "queues", "=", "None", ")", ":", "current_queues", ".", "purge", "(", "queues", "=", "queues", ")", "click", ".", "secho", "(", "'Queues {} have been purged.'", ".", "format", "(", "queues", "or", "current_queues", ".", "queues", ...
Purge the given queues.
[ "Purge", "the", "given", "queues", "." ]
1dd9112d7c5fe72a428c86f21f6d02cdb0595921
https://github.com/inveniosoftware/invenio-queues/blob/1dd9112d7c5fe72a428c86f21f6d02cdb0595921/invenio_queues/cli.py#L75-L82
train
54,549
inveniosoftware/invenio-queues
invenio_queues/cli.py
delete_queue
def delete_queue(queues): """Delete the given queues.""" current_queues.delete(queues=queues) click.secho( 'Queues {} have been deleted.'.format( queues or current_queues.queues.keys()), fg='green' )
python
def delete_queue(queues): """Delete the given queues.""" current_queues.delete(queues=queues) click.secho( 'Queues {} have been deleted.'.format( queues or current_queues.queues.keys()), fg='green' )
[ "def", "delete_queue", "(", "queues", ")", ":", "current_queues", ".", "delete", "(", "queues", "=", "queues", ")", "click", ".", "secho", "(", "'Queues {} have been deleted.'", ".", "format", "(", "queues", "or", "current_queues", ".", "queues", ".", "keys", ...
Delete the given queues.
[ "Delete", "the", "given", "queues", "." ]
1dd9112d7c5fe72a428c86f21f6d02cdb0595921
https://github.com/inveniosoftware/invenio-queues/blob/1dd9112d7c5fe72a428c86f21f6d02cdb0595921/invenio_queues/cli.py#L88-L95
train
54,550
VikParuchuri/percept
percept/utils/models.py
find_needed_formatter
def find_needed_formatter(input_format, output_format): """ Find a data formatter given an input and output format input_format - needed input format. see utils.input.dataformats output_format - needed output format. see utils.input.dataformats """ #Only take the formatters in the registry selected_registry = [re.cls for re in registry if re.category==RegistryCategories.formatters] needed_formatters = [] for formatter in selected_registry: #Initialize the formatter (needed so it can discover its formats) formatter_inst = formatter() if input_format in formatter_inst.input_formats and output_format in formatter_inst.output_formats: needed_formatters.append(formatter) if len(needed_formatters)>0: return needed_formatters[0] return None
python
def find_needed_formatter(input_format, output_format): """ Find a data formatter given an input and output format input_format - needed input format. see utils.input.dataformats output_format - needed output format. see utils.input.dataformats """ #Only take the formatters in the registry selected_registry = [re.cls for re in registry if re.category==RegistryCategories.formatters] needed_formatters = [] for formatter in selected_registry: #Initialize the formatter (needed so it can discover its formats) formatter_inst = formatter() if input_format in formatter_inst.input_formats and output_format in formatter_inst.output_formats: needed_formatters.append(formatter) if len(needed_formatters)>0: return needed_formatters[0] return None
[ "def", "find_needed_formatter", "(", "input_format", ",", "output_format", ")", ":", "#Only take the formatters in the registry", "selected_registry", "=", "[", "re", ".", "cls", "for", "re", "in", "registry", "if", "re", ".", "category", "==", "RegistryCategories", ...
Find a data formatter given an input and output format input_format - needed input format. see utils.input.dataformats output_format - needed output format. see utils.input.dataformats
[ "Find", "a", "data", "formatter", "given", "an", "input", "and", "output", "format", "input_format", "-", "needed", "input", "format", ".", "see", "utils", ".", "input", ".", "dataformats", "output_format", "-", "needed", "output", "format", ".", "see", "uti...
90304ba82053e2a9ad2bacaab3479403d3923bcf
https://github.com/VikParuchuri/percept/blob/90304ba82053e2a9ad2bacaab3479403d3923bcf/percept/utils/models.py#L24-L40
train
54,551
VikParuchuri/percept
percept/utils/models.py
find_needed_input
def find_needed_input(input_format): """ Find a needed input class input_format - needed input format, see utils.input.dataformats """ needed_inputs = [re.cls for re in registry if re.category==RegistryCategories.inputs and re.cls.input_format == input_format] if len(needed_inputs)>0: return needed_inputs[0] return None
python
def find_needed_input(input_format): """ Find a needed input class input_format - needed input format, see utils.input.dataformats """ needed_inputs = [re.cls for re in registry if re.category==RegistryCategories.inputs and re.cls.input_format == input_format] if len(needed_inputs)>0: return needed_inputs[0] return None
[ "def", "find_needed_input", "(", "input_format", ")", ":", "needed_inputs", "=", "[", "re", ".", "cls", "for", "re", "in", "registry", "if", "re", ".", "category", "==", "RegistryCategories", ".", "inputs", "and", "re", ".", "cls", ".", "input_format", "==...
Find a needed input class input_format - needed input format, see utils.input.dataformats
[ "Find", "a", "needed", "input", "class", "input_format", "-", "needed", "input", "format", "see", "utils", ".", "input", ".", "dataformats" ]
90304ba82053e2a9ad2bacaab3479403d3923bcf
https://github.com/VikParuchuri/percept/blob/90304ba82053e2a9ad2bacaab3479403d3923bcf/percept/utils/models.py#L42-L50
train
54,552
VikParuchuri/percept
percept/utils/models.py
exists_in_registry
def exists_in_registry(category, namespace, name): """ See if a given category, namespace, name combination exists in the registry category - See registrycategories. Type of module namespace - Namespace of the module, defined in settings name - the lowercase name of the module """ selected_registry = [re for re in registry if re.category==category and re.namespace==namespace and re.name == name] if len(selected_registry)>0: return True return False
python
def exists_in_registry(category, namespace, name): """ See if a given category, namespace, name combination exists in the registry category - See registrycategories. Type of module namespace - Namespace of the module, defined in settings name - the lowercase name of the module """ selected_registry = [re for re in registry if re.category==category and re.namespace==namespace and re.name == name] if len(selected_registry)>0: return True return False
[ "def", "exists_in_registry", "(", "category", ",", "namespace", ",", "name", ")", ":", "selected_registry", "=", "[", "re", "for", "re", "in", "registry", "if", "re", ".", "category", "==", "category", "and", "re", ".", "namespace", "==", "namespace", "and...
See if a given category, namespace, name combination exists in the registry category - See registrycategories. Type of module namespace - Namespace of the module, defined in settings name - the lowercase name of the module
[ "See", "if", "a", "given", "category", "namespace", "name", "combination", "exists", "in", "the", "registry", "category", "-", "See", "registrycategories", ".", "Type", "of", "module", "namespace", "-", "Namespace", "of", "the", "module", "defined", "in", "set...
90304ba82053e2a9ad2bacaab3479403d3923bcf
https://github.com/VikParuchuri/percept/blob/90304ba82053e2a9ad2bacaab3479403d3923bcf/percept/utils/models.py#L52-L62
train
54,553
VikParuchuri/percept
percept/utils/models.py
register
def register(cls): """ Register a given model in the registry """ registry_entry = RegistryEntry(category = cls.category, namespace = cls.namespace, name = cls.name, cls=cls) if registry_entry not in registry and not exists_in_registry(cls.category, cls.namespace, cls.name): registry.append(registry_entry) else: log.warn("Class {0} already in registry".format(cls))
python
def register(cls): """ Register a given model in the registry """ registry_entry = RegistryEntry(category = cls.category, namespace = cls.namespace, name = cls.name, cls=cls) if registry_entry not in registry and not exists_in_registry(cls.category, cls.namespace, cls.name): registry.append(registry_entry) else: log.warn("Class {0} already in registry".format(cls))
[ "def", "register", "(", "cls", ")", ":", "registry_entry", "=", "RegistryEntry", "(", "category", "=", "cls", ".", "category", ",", "namespace", "=", "cls", ".", "namespace", ",", "name", "=", "cls", ".", "name", ",", "cls", "=", "cls", ")", "if", "r...
Register a given model in the registry
[ "Register", "a", "given", "model", "in", "the", "registry" ]
90304ba82053e2a9ad2bacaab3479403d3923bcf
https://github.com/VikParuchuri/percept/blob/90304ba82053e2a9ad2bacaab3479403d3923bcf/percept/utils/models.py#L81-L89
train
54,554
VikParuchuri/percept
percept/utils/models.py
FieldModel._set_fields
def _set_fields(self): """ Initialize the fields for data caching. """ self.fields = [] self.required_input = [] for member_name, member_object in inspect.getmembers(self.__class__): if inspect.isdatadescriptor(member_object) and not member_name.startswith("__"): self.fields.append(member_name) if member_object.required_input: self.required_input.append(member_name)
python
def _set_fields(self): """ Initialize the fields for data caching. """ self.fields = [] self.required_input = [] for member_name, member_object in inspect.getmembers(self.__class__): if inspect.isdatadescriptor(member_object) and not member_name.startswith("__"): self.fields.append(member_name) if member_object.required_input: self.required_input.append(member_name)
[ "def", "_set_fields", "(", "self", ")", ":", "self", ".", "fields", "=", "[", "]", "self", ".", "required_input", "=", "[", "]", "for", "member_name", ",", "member_object", "in", "inspect", ".", "getmembers", "(", "self", ".", "__class__", ")", ":", "i...
Initialize the fields for data caching.
[ "Initialize", "the", "fields", "for", "data", "caching", "." ]
90304ba82053e2a9ad2bacaab3479403d3923bcf
https://github.com/VikParuchuri/percept/blob/90304ba82053e2a9ad2bacaab3479403d3923bcf/percept/utils/models.py#L119-L129
train
54,555
supercoderz/pyzmq-wrapper
zmqwrapper/subscribers.py
subscriber
def subscriber(address,topics,callback,message_type): """ Creates a subscriber binding to the given address and subscribe the given topics. The callback is invoked for every message received. Args: - address: the address to bind the PUB socket to. - topics: the topics to subscribe - callback: the callback to invoke for every message. Must accept 2 variables - topic and message - message_type: the type of message to receive """ return Subscriber(address,topics,callback,message_type)
python
def subscriber(address,topics,callback,message_type): """ Creates a subscriber binding to the given address and subscribe the given topics. The callback is invoked for every message received. Args: - address: the address to bind the PUB socket to. - topics: the topics to subscribe - callback: the callback to invoke for every message. Must accept 2 variables - topic and message - message_type: the type of message to receive """ return Subscriber(address,topics,callback,message_type)
[ "def", "subscriber", "(", "address", ",", "topics", ",", "callback", ",", "message_type", ")", ":", "return", "Subscriber", "(", "address", ",", "topics", ",", "callback", ",", "message_type", ")" ]
Creates a subscriber binding to the given address and subscribe the given topics. The callback is invoked for every message received. Args: - address: the address to bind the PUB socket to. - topics: the topics to subscribe - callback: the callback to invoke for every message. Must accept 2 variables - topic and message - message_type: the type of message to receive
[ "Creates", "a", "subscriber", "binding", "to", "the", "given", "address", "and", "subscribe", "the", "given", "topics", ".", "The", "callback", "is", "invoked", "for", "every", "message", "received", "." ]
b16c0313dd10febd5060ee0589285025a09fa26a
https://github.com/supercoderz/pyzmq-wrapper/blob/b16c0313dd10febd5060ee0589285025a09fa26a/zmqwrapper/subscribers.py#L6-L18
train
54,556
supercoderz/pyzmq-wrapper
zmqwrapper/subscribers.py
Subscriber.start
def start(self): """ Start a thread that consumes the messages and invokes the callback """ t=threading.Thread(target=self._consume) t.start()
python
def start(self): """ Start a thread that consumes the messages and invokes the callback """ t=threading.Thread(target=self._consume) t.start()
[ "def", "start", "(", "self", ")", ":", "t", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "_consume", ")", "t", ".", "start", "(", ")" ]
Start a thread that consumes the messages and invokes the callback
[ "Start", "a", "thread", "that", "consumes", "the", "messages", "and", "invokes", "the", "callback" ]
b16c0313dd10febd5060ee0589285025a09fa26a
https://github.com/supercoderz/pyzmq-wrapper/blob/b16c0313dd10febd5060ee0589285025a09fa26a/zmqwrapper/subscribers.py#L51-L56
train
54,557
helto4real/python-packages
smhi/smhi/smhi_lib.py
SmhiAPI.get_forecast_api
def get_forecast_api(self, longitude: str, latitude: str) -> {}: """gets data from API""" api_url = APIURL_TEMPLATE.format(longitude, latitude) response = urlopen(api_url) data = response.read().decode('utf-8') json_data = json.loads(data) return json_data
python
def get_forecast_api(self, longitude: str, latitude: str) -> {}: """gets data from API""" api_url = APIURL_TEMPLATE.format(longitude, latitude) response = urlopen(api_url) data = response.read().decode('utf-8') json_data = json.loads(data) return json_data
[ "def", "get_forecast_api", "(", "self", ",", "longitude", ":", "str", ",", "latitude", ":", "str", ")", "->", "{", "}", ":", "api_url", "=", "APIURL_TEMPLATE", ".", "format", "(", "longitude", ",", "latitude", ")", "response", "=", "urlopen", "(", "api_u...
gets data from API
[ "gets", "data", "from", "API" ]
8b65342eea34e370ea6fc5abdcb55e544c51fec5
https://github.com/helto4real/python-packages/blob/8b65342eea34e370ea6fc5abdcb55e544c51fec5/smhi/smhi/smhi_lib.py#L197-L205
train
54,558
helto4real/python-packages
smhi/smhi/smhi_lib.py
SmhiAPI.async_get_forecast_api
async def async_get_forecast_api(self, longitude: str, latitude: str) -> {}: """gets data from API asyncronious""" api_url = APIURL_TEMPLATE.format(longitude, latitude) if self.session is None: self.session = aiohttp.ClientSession() async with self.session.get(api_url) as response: if response.status != 200: raise SmhiForecastException( "Failed to access weather API with status code {}".format( response.status) ) data = await response.text() return json.loads(data)
python
async def async_get_forecast_api(self, longitude: str, latitude: str) -> {}: """gets data from API asyncronious""" api_url = APIURL_TEMPLATE.format(longitude, latitude) if self.session is None: self.session = aiohttp.ClientSession() async with self.session.get(api_url) as response: if response.status != 200: raise SmhiForecastException( "Failed to access weather API with status code {}".format( response.status) ) data = await response.text() return json.loads(data)
[ "async", "def", "async_get_forecast_api", "(", "self", ",", "longitude", ":", "str", ",", "latitude", ":", "str", ")", "->", "{", "}", ":", "api_url", "=", "APIURL_TEMPLATE", ".", "format", "(", "longitude", ",", "latitude", ")", "if", "self", ".", "sess...
gets data from API asyncronious
[ "gets", "data", "from", "API", "asyncronious" ]
8b65342eea34e370ea6fc5abdcb55e544c51fec5
https://github.com/helto4real/python-packages/blob/8b65342eea34e370ea6fc5abdcb55e544c51fec5/smhi/smhi/smhi_lib.py#L207-L222
train
54,559
wearpants/instrument
instrument/__init__.py
all
def all(iterable = None, *, name = None, metric = call_default): """Measure total time and item count for consuming an iterable :arg iterable: any iterable :arg function metric: f(name, count, total_time) :arg str name: name for the metric """ if iterable is None: return _iter_decorator(name, metric) else: return _do_all(iterable, name, metric)
python
def all(iterable = None, *, name = None, metric = call_default): """Measure total time and item count for consuming an iterable :arg iterable: any iterable :arg function metric: f(name, count, total_time) :arg str name: name for the metric """ if iterable is None: return _iter_decorator(name, metric) else: return _do_all(iterable, name, metric)
[ "def", "all", "(", "iterable", "=", "None", ",", "*", ",", "name", "=", "None", ",", "metric", "=", "call_default", ")", ":", "if", "iterable", "is", "None", ":", "return", "_iter_decorator", "(", "name", ",", "metric", ")", "else", ":", "return", "_...
Measure total time and item count for consuming an iterable :arg iterable: any iterable :arg function metric: f(name, count, total_time) :arg str name: name for the metric
[ "Measure", "total", "time", "and", "item", "count", "for", "consuming", "an", "iterable" ]
a0f6103574ab58a82361a951e5e56b69aedfe294
https://github.com/wearpants/instrument/blob/a0f6103574ab58a82361a951e5e56b69aedfe294/instrument/__init__.py#L111-L121
train
54,560
wearpants/instrument
instrument/__init__.py
each
def each(iterable = None, *, name = None, metric = call_default): """Measure time elapsed to produce each item of an iterable :arg iterable: any iterable :arg function metric: f(name, 1, time) :arg str name: name for the metric """ if iterable is None: return _each_decorator(name, metric) else: return _do_each(iterable, name, metric)
python
def each(iterable = None, *, name = None, metric = call_default): """Measure time elapsed to produce each item of an iterable :arg iterable: any iterable :arg function metric: f(name, 1, time) :arg str name: name for the metric """ if iterable is None: return _each_decorator(name, metric) else: return _do_each(iterable, name, metric)
[ "def", "each", "(", "iterable", "=", "None", ",", "*", ",", "name", "=", "None", ",", "metric", "=", "call_default", ")", ":", "if", "iterable", "is", "None", ":", "return", "_each_decorator", "(", "name", ",", "metric", ")", "else", ":", "return", "...
Measure time elapsed to produce each item of an iterable :arg iterable: any iterable :arg function metric: f(name, 1, time) :arg str name: name for the metric
[ "Measure", "time", "elapsed", "to", "produce", "each", "item", "of", "an", "iterable" ]
a0f6103574ab58a82361a951e5e56b69aedfe294
https://github.com/wearpants/instrument/blob/a0f6103574ab58a82361a951e5e56b69aedfe294/instrument/__init__.py#L124-L134
train
54,561
wearpants/instrument
instrument/__init__.py
first
def first(iterable = None, *, name = None, metric = call_default): """Measure time elapsed to produce first item of an iterable :arg iterable: any iterable :arg function metric: f(name, 1, time) :arg str name: name for the metric """ if iterable is None: return _first_decorator(name, metric) else: return _do_first(iterable, name, metric)
python
def first(iterable = None, *, name = None, metric = call_default): """Measure time elapsed to produce first item of an iterable :arg iterable: any iterable :arg function metric: f(name, 1, time) :arg str name: name for the metric """ if iterable is None: return _first_decorator(name, metric) else: return _do_first(iterable, name, metric)
[ "def", "first", "(", "iterable", "=", "None", ",", "*", ",", "name", "=", "None", ",", "metric", "=", "call_default", ")", ":", "if", "iterable", "is", "None", ":", "return", "_first_decorator", "(", "name", ",", "metric", ")", "else", ":", "return", ...
Measure time elapsed to produce first item of an iterable :arg iterable: any iterable :arg function metric: f(name, 1, time) :arg str name: name for the metric
[ "Measure", "time", "elapsed", "to", "produce", "first", "item", "of", "an", "iterable" ]
a0f6103574ab58a82361a951e5e56b69aedfe294
https://github.com/wearpants/instrument/blob/a0f6103574ab58a82361a951e5e56b69aedfe294/instrument/__init__.py#L137-L147
train
54,562
wearpants/instrument
instrument/__init__.py
reducer
def reducer(*, name = None, metric = call_default): """Decorator to measure a function that consumes many items. The wrapped ``func`` should take either a single ``iterable`` argument or ``*args`` (plus keyword arguments). :arg function metric: f(name, count, total_time) :arg str name: name for the metric """ class instrument_reducer_decorator(object): def __init__(self, func): self.orig_func = func self.wrapping = wraps(func) self.metric_name = name if name is not None else func.__module__ + '.' +func.__name__ self.varargs = inspect.getargspec(func).varargs is not None if self.varargs: self.method = _varargs_to_iterable_method(func) self.func = _varargs_to_iterable_func(func) self.callme = _iterable_to_varargs_func(self._call) else: self.method = func self.func = func self.callme = self._call # we need _call/callme b/c CPython short-circurits CALL_FUNCTION to # directly access __call__, bypassing our varargs decorator def __call__(self, *args, **kwargs): return self.callme(*args, **kwargs) def _call(self, iterable, **kwargs): it = counted_iterable(iterable) t = time.time() try: return self.func(it, **kwargs) finally: metric(self.metric_name, it.count, time.time() - t) def __get__(self, instance, class_): metric_name = name if name is not None else\ ".".join((class_.__module__, class_.__name__, self.orig_func.__name__)) def wrapped_method(iterable, **kwargs): it = counted_iterable(iterable) t = time.time() try: return self.method(instance, it, **kwargs) finally: metric(metric_name, it.count, time.time() - t) # wrap in func version b/c self is handled for us by descriptor (ie, `instance`) if self.varargs: wrapped_method = _iterable_to_varargs_func(wrapped_method) wrapped_method = self.wrapping(wrapped_method) return wrapped_method return instrument_reducer_decorator
python
def reducer(*, name = None, metric = call_default): """Decorator to measure a function that consumes many items. The wrapped ``func`` should take either a single ``iterable`` argument or ``*args`` (plus keyword arguments). :arg function metric: f(name, count, total_time) :arg str name: name for the metric """ class instrument_reducer_decorator(object): def __init__(self, func): self.orig_func = func self.wrapping = wraps(func) self.metric_name = name if name is not None else func.__module__ + '.' +func.__name__ self.varargs = inspect.getargspec(func).varargs is not None if self.varargs: self.method = _varargs_to_iterable_method(func) self.func = _varargs_to_iterable_func(func) self.callme = _iterable_to_varargs_func(self._call) else: self.method = func self.func = func self.callme = self._call # we need _call/callme b/c CPython short-circurits CALL_FUNCTION to # directly access __call__, bypassing our varargs decorator def __call__(self, *args, **kwargs): return self.callme(*args, **kwargs) def _call(self, iterable, **kwargs): it = counted_iterable(iterable) t = time.time() try: return self.func(it, **kwargs) finally: metric(self.metric_name, it.count, time.time() - t) def __get__(self, instance, class_): metric_name = name if name is not None else\ ".".join((class_.__module__, class_.__name__, self.orig_func.__name__)) def wrapped_method(iterable, **kwargs): it = counted_iterable(iterable) t = time.time() try: return self.method(instance, it, **kwargs) finally: metric(metric_name, it.count, time.time() - t) # wrap in func version b/c self is handled for us by descriptor (ie, `instance`) if self.varargs: wrapped_method = _iterable_to_varargs_func(wrapped_method) wrapped_method = self.wrapping(wrapped_method) return wrapped_method return instrument_reducer_decorator
[ "def", "reducer", "(", "*", ",", "name", "=", "None", ",", "metric", "=", "call_default", ")", ":", "class", "instrument_reducer_decorator", "(", "object", ")", ":", "def", "__init__", "(", "self", ",", "func", ")", ":", "self", ".", "orig_func", "=", ...
Decorator to measure a function that consumes many items. The wrapped ``func`` should take either a single ``iterable`` argument or ``*args`` (plus keyword arguments). :arg function metric: f(name, count, total_time) :arg str name: name for the metric
[ "Decorator", "to", "measure", "a", "function", "that", "consumes", "many", "items", "." ]
a0f6103574ab58a82361a951e5e56b69aedfe294
https://github.com/wearpants/instrument/blob/a0f6103574ab58a82361a951e5e56b69aedfe294/instrument/__init__.py#L190-L244
train
54,563
wearpants/instrument
instrument/__init__.py
producer
def producer(*, name = None, metric = call_default): """Decorator to measure a function that produces many items. The function should return an object that supports ``__len__`` (ie, a list). If the function returns an iterator, use :func:`all` instead. :arg function metric: f(name, count, total_time) :arg str name: name for the metric """ def wrapper(func): def instrumenter(name_, *args, **kwargs): t = time.time() try: ret = func(*args, **kwargs) except Exception: # record a metric for other exceptions, than raise metric(name_, 0, time.time() - t) raise else: # normal path, record metric & return metric(name_, len(ret), time.time() - t) return ret name_ = name if name is not None else func.__module__ + '.' +func.__name__ class instrument_decorator(object): # must be a class for descriptor magic to work @wraps(func) def __call__(self, *args, **kwargs): return instrumenter(name_, *args, **kwargs) def __get__(self, instance, class_): name_ = name if name is not None else\ ".".join((class_.__module__, class_.__name__, func.__name__)) @wraps(func) def wrapped_method(*args, **kwargs): return instrumenter(name_, instance, *args, **kwargs) return wrapped_method return instrument_decorator() return wrapper
python
def producer(*, name = None, metric = call_default): """Decorator to measure a function that produces many items. The function should return an object that supports ``__len__`` (ie, a list). If the function returns an iterator, use :func:`all` instead. :arg function metric: f(name, count, total_time) :arg str name: name for the metric """ def wrapper(func): def instrumenter(name_, *args, **kwargs): t = time.time() try: ret = func(*args, **kwargs) except Exception: # record a metric for other exceptions, than raise metric(name_, 0, time.time() - t) raise else: # normal path, record metric & return metric(name_, len(ret), time.time() - t) return ret name_ = name if name is not None else func.__module__ + '.' +func.__name__ class instrument_decorator(object): # must be a class for descriptor magic to work @wraps(func) def __call__(self, *args, **kwargs): return instrumenter(name_, *args, **kwargs) def __get__(self, instance, class_): name_ = name if name is not None else\ ".".join((class_.__module__, class_.__name__, func.__name__)) @wraps(func) def wrapped_method(*args, **kwargs): return instrumenter(name_, instance, *args, **kwargs) return wrapped_method return instrument_decorator() return wrapper
[ "def", "producer", "(", "*", ",", "name", "=", "None", ",", "metric", "=", "call_default", ")", ":", "def", "wrapper", "(", "func", ")", ":", "def", "instrumenter", "(", "name_", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "t", "=", "tim...
Decorator to measure a function that produces many items. The function should return an object that supports ``__len__`` (ie, a list). If the function returns an iterator, use :func:`all` instead. :arg function metric: f(name, count, total_time) :arg str name: name for the metric
[ "Decorator", "to", "measure", "a", "function", "that", "produces", "many", "items", "." ]
a0f6103574ab58a82361a951e5e56b69aedfe294
https://github.com/wearpants/instrument/blob/a0f6103574ab58a82361a951e5e56b69aedfe294/instrument/__init__.py#L246-L285
train
54,564
wearpants/instrument
instrument/__init__.py
block
def block(*, name = None, metric = call_default, count = 1): """Context manager to measure execution time of a block :arg function metric: f(name, 1, time) :arg str name: name for the metric :arg int count: user-supplied number of items, defaults to 1 """ t = time.time() try: yield finally: metric(name, count, time.time() - t)
python
def block(*, name = None, metric = call_default, count = 1): """Context manager to measure execution time of a block :arg function metric: f(name, 1, time) :arg str name: name for the metric :arg int count: user-supplied number of items, defaults to 1 """ t = time.time() try: yield finally: metric(name, count, time.time() - t)
[ "def", "block", "(", "*", ",", "name", "=", "None", ",", "metric", "=", "call_default", ",", "count", "=", "1", ")", ":", "t", "=", "time", ".", "time", "(", ")", "try", ":", "yield", "finally", ":", "metric", "(", "name", ",", "count", ",", "t...
Context manager to measure execution time of a block :arg function metric: f(name, 1, time) :arg str name: name for the metric :arg int count: user-supplied number of items, defaults to 1
[ "Context", "manager", "to", "measure", "execution", "time", "of", "a", "block" ]
a0f6103574ab58a82361a951e5e56b69aedfe294
https://github.com/wearpants/instrument/blob/a0f6103574ab58a82361a951e5e56b69aedfe294/instrument/__init__.py#L319-L330
train
54,565
toumorokoshi/sprinter
sprinter/formula/package.py
PackageFormula.__get_package_manager
def __get_package_manager(self): """ Installs and verifies package manager """ package_manager = "" args = "" sudo_required = True if system.is_osx(): package_manager = "brew" sudo_required = False args = " install" elif system.is_debian(): package_manager = "apt-get" args = " -y install" elif system.is_fedora(): package_manager = "yum" args = " install" elif system.is_arch(): package_manager = "pacman" args = " --noconfirm -S" if lib.which(package_manager) is None: self.logger.warn("Package manager %s not installed! Packages will not be installed." % package_manager) self.package_manager = None self.package_manager = package_manager self.sudo_required = sudo_required self.args = args
python
def __get_package_manager(self): """ Installs and verifies package manager """ package_manager = "" args = "" sudo_required = True if system.is_osx(): package_manager = "brew" sudo_required = False args = " install" elif system.is_debian(): package_manager = "apt-get" args = " -y install" elif system.is_fedora(): package_manager = "yum" args = " install" elif system.is_arch(): package_manager = "pacman" args = " --noconfirm -S" if lib.which(package_manager) is None: self.logger.warn("Package manager %s not installed! Packages will not be installed." % package_manager) self.package_manager = None self.package_manager = package_manager self.sudo_required = sudo_required self.args = args
[ "def", "__get_package_manager", "(", "self", ")", ":", "package_manager", "=", "\"\"", "args", "=", "\"\"", "sudo_required", "=", "True", "if", "system", ".", "is_osx", "(", ")", ":", "package_manager", "=", "\"brew\"", "sudo_required", "=", "False", "args", ...
Installs and verifies package manager
[ "Installs", "and", "verifies", "package", "manager" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/formula/package.py#L56-L82
train
54,566
thewca/wca-regulations-compiler
wrc/parse/parser.py
WCAParser.parse
def parse(self, data, doctype): ''' Parse an input string, and return an AST doctype must have WCADocument as a baseclass ''' self.doctype = doctype self.lexer.lineno = 0 del self.errors[:] del self.warnings[:] self.lexer.lexerror = False ast = self.parser.parse(data, lexer=self.lexer) if self.lexer.lexerror: ast = None if ast is None: self.errors.append("Couldn't build AST.") else: for check in self.sema[self.doctype]: visitor = check() if not visitor.visit(ast): self.errors.append("Couldn't visit AST.") self.errors.extend(visitor.errors) self.warnings.extend(visitor.warnings) return (ast, list(self.errors), list(self.warnings))
python
def parse(self, data, doctype): ''' Parse an input string, and return an AST doctype must have WCADocument as a baseclass ''' self.doctype = doctype self.lexer.lineno = 0 del self.errors[:] del self.warnings[:] self.lexer.lexerror = False ast = self.parser.parse(data, lexer=self.lexer) if self.lexer.lexerror: ast = None if ast is None: self.errors.append("Couldn't build AST.") else: for check in self.sema[self.doctype]: visitor = check() if not visitor.visit(ast): self.errors.append("Couldn't visit AST.") self.errors.extend(visitor.errors) self.warnings.extend(visitor.warnings) return (ast, list(self.errors), list(self.warnings))
[ "def", "parse", "(", "self", ",", "data", ",", "doctype", ")", ":", "self", ".", "doctype", "=", "doctype", "self", ".", "lexer", ".", "lineno", "=", "0", "del", "self", ".", "errors", "[", ":", "]", "del", "self", ".", "warnings", "[", ":", "]",...
Parse an input string, and return an AST doctype must have WCADocument as a baseclass
[ "Parse", "an", "input", "string", "and", "return", "an", "AST", "doctype", "must", "have", "WCADocument", "as", "a", "baseclass" ]
3ebbd8fe8fec7c9167296f59b2677696fe61a954
https://github.com/thewca/wca-regulations-compiler/blob/3ebbd8fe8fec7c9167296f59b2677696fe61a954/wrc/parse/parser.py#L41-L63
train
54,567
thewca/wca-regulations-compiler
wrc/parse/parser.py
WCAParser.p_error
def p_error(self, elem): '''Handle syntax error''' self.errors.append("Syntax error on line " + str(self.lexer.lineno) + ". Got unexpected token " + elem.type)
python
def p_error(self, elem): '''Handle syntax error''' self.errors.append("Syntax error on line " + str(self.lexer.lineno) + ". Got unexpected token " + elem.type)
[ "def", "p_error", "(", "self", ",", "elem", ")", ":", "self", ".", "errors", ".", "append", "(", "\"Syntax error on line \"", "+", "str", "(", "self", ".", "lexer", ".", "lineno", ")", "+", "\". Got unexpected token \"", "+", "elem", ".", "type", ")" ]
Handle syntax error
[ "Handle", "syntax", "error" ]
3ebbd8fe8fec7c9167296f59b2677696fe61a954
https://github.com/thewca/wca-regulations-compiler/blob/3ebbd8fe8fec7c9167296f59b2677696fe61a954/wrc/parse/parser.py#L251-L254
train
54,568
mailund/statusbar
statusbar/__init__.py
ProgressBar.set_progress_brackets
def set_progress_brackets(self, start, end): """Set brackets to set around a progress bar.""" self.sep_start = start self.sep_end = end
python
def set_progress_brackets(self, start, end): """Set brackets to set around a progress bar.""" self.sep_start = start self.sep_end = end
[ "def", "set_progress_brackets", "(", "self", ",", "start", ",", "end", ")", ":", "self", ".", "sep_start", "=", "start", "self", ".", "sep_end", "=", "end" ]
Set brackets to set around a progress bar.
[ "Set", "brackets", "to", "set", "around", "a", "progress", "bar", "." ]
e42ac88cdaae281d47318dd8dcf156bfff2a7b2a
https://github.com/mailund/statusbar/blob/e42ac88cdaae281d47318dd8dcf156bfff2a7b2a/statusbar/__init__.py#L43-L46
train
54,569
mailund/statusbar
statusbar/__init__.py
ProgressBar.format_progress
def format_progress(self, width): """Create the formatted string that displays the progress.""" chunk_widths = self._get_chunk_sizes(width) progress_chunks = [chunk.format_chunk(chunk_width) for (chunk, chunk_width) in zip(self._progress_chunks, chunk_widths)] return "{sep_start}{progress}{sep_end}".format( sep_start=self.sep_start, progress="".join(progress_chunks), sep_end=self.sep_end )
python
def format_progress(self, width): """Create the formatted string that displays the progress.""" chunk_widths = self._get_chunk_sizes(width) progress_chunks = [chunk.format_chunk(chunk_width) for (chunk, chunk_width) in zip(self._progress_chunks, chunk_widths)] return "{sep_start}{progress}{sep_end}".format( sep_start=self.sep_start, progress="".join(progress_chunks), sep_end=self.sep_end )
[ "def", "format_progress", "(", "self", ",", "width", ")", ":", "chunk_widths", "=", "self", ".", "_get_chunk_sizes", "(", "width", ")", "progress_chunks", "=", "[", "chunk", ".", "format_chunk", "(", "chunk_width", ")", "for", "(", "chunk", ",", "chunk_width...
Create the formatted string that displays the progress.
[ "Create", "the", "formatted", "string", "that", "displays", "the", "progress", "." ]
e42ac88cdaae281d47318dd8dcf156bfff2a7b2a
https://github.com/mailund/statusbar/blob/e42ac88cdaae281d47318dd8dcf156bfff2a7b2a/statusbar/__init__.py#L83-L93
train
54,570
mailund/statusbar
statusbar/__init__.py
ProgressBar.summary_width
def summary_width(self): """Calculate how long a string is needed to show a summary string. This is not simply the length of the formatted summary string since that string might contain ANSI codes. """ chunk_counts = [chunk.count for chunk in self._progress_chunks] numbers_width = sum(max(1, ceil(log10(count + 1))) for count in chunk_counts) separators_with = len(chunk_counts) - 1 return numbers_width + separators_with
python
def summary_width(self): """Calculate how long a string is needed to show a summary string. This is not simply the length of the formatted summary string since that string might contain ANSI codes. """ chunk_counts = [chunk.count for chunk in self._progress_chunks] numbers_width = sum(max(1, ceil(log10(count + 1))) for count in chunk_counts) separators_with = len(chunk_counts) - 1 return numbers_width + separators_with
[ "def", "summary_width", "(", "self", ")", ":", "chunk_counts", "=", "[", "chunk", ".", "count", "for", "chunk", "in", "self", ".", "_progress_chunks", "]", "numbers_width", "=", "sum", "(", "max", "(", "1", ",", "ceil", "(", "log10", "(", "count", "+",...
Calculate how long a string is needed to show a summary string. This is not simply the length of the formatted summary string since that string might contain ANSI codes.
[ "Calculate", "how", "long", "a", "string", "is", "needed", "to", "show", "a", "summary", "string", "." ]
e42ac88cdaae281d47318dd8dcf156bfff2a7b2a
https://github.com/mailund/statusbar/blob/e42ac88cdaae281d47318dd8dcf156bfff2a7b2a/statusbar/__init__.py#L95-L105
train
54,571
mailund/statusbar
statusbar/__init__.py
ProgressBar.format_summary
def format_summary(self): """Generate a summary string for the progress bar.""" chunks = [chunk.format_chunk_summary() for chunk in self._progress_chunks] return "/".join(chunks)
python
def format_summary(self): """Generate a summary string for the progress bar.""" chunks = [chunk.format_chunk_summary() for chunk in self._progress_chunks] return "/".join(chunks)
[ "def", "format_summary", "(", "self", ")", ":", "chunks", "=", "[", "chunk", ".", "format_chunk_summary", "(", ")", "for", "chunk", "in", "self", ".", "_progress_chunks", "]", "return", "\"/\"", ".", "join", "(", "chunks", ")" ]
Generate a summary string for the progress bar.
[ "Generate", "a", "summary", "string", "for", "the", "progress", "bar", "." ]
e42ac88cdaae281d47318dd8dcf156bfff2a7b2a
https://github.com/mailund/statusbar/blob/e42ac88cdaae281d47318dd8dcf156bfff2a7b2a/statusbar/__init__.py#L107-L111
train
54,572
mailund/statusbar
statusbar/__init__.py
StatusBar.format_status
def format_status(self, width=None, label_width=None, progress_width=None, summary_width=None): """Generate the formatted status bar string.""" if width is None: # pragma: no cover width = shutil.get_terminal_size()[0] if label_width is None: label_width = len(self.label) if summary_width is None: summary_width = self.summary_width() if progress_width is None: progress_width = width - label_width - summary_width - 2 if len(self.label) > label_width: # FIXME: This actually *will* break if we ever have fewer than # three characters assigned to format the label, but that would # be an extreme situation so I won't fix it just yet. label = self.label[:label_width - 3] + "..." else: label_format = "{{label:{fill_char}<{width}}}".format( width=label_width, fill_char=self.fill_char) label = label_format.format(label=self.label) summary_format = "{{:>{width}}}".format(width=summary_width) summary = summary_format.format(self._progress.format_summary()) progress = self._progress.format_progress(width=progress_width) return "{label} {progress} {summary}".format( label=label, progress=progress, summary=summary )
python
def format_status(self, width=None, label_width=None, progress_width=None, summary_width=None): """Generate the formatted status bar string.""" if width is None: # pragma: no cover width = shutil.get_terminal_size()[0] if label_width is None: label_width = len(self.label) if summary_width is None: summary_width = self.summary_width() if progress_width is None: progress_width = width - label_width - summary_width - 2 if len(self.label) > label_width: # FIXME: This actually *will* break if we ever have fewer than # three characters assigned to format the label, but that would # be an extreme situation so I won't fix it just yet. label = self.label[:label_width - 3] + "..." else: label_format = "{{label:{fill_char}<{width}}}".format( width=label_width, fill_char=self.fill_char) label = label_format.format(label=self.label) summary_format = "{{:>{width}}}".format(width=summary_width) summary = summary_format.format(self._progress.format_summary()) progress = self._progress.format_progress(width=progress_width) return "{label} {progress} {summary}".format( label=label, progress=progress, summary=summary )
[ "def", "format_status", "(", "self", ",", "width", "=", "None", ",", "label_width", "=", "None", ",", "progress_width", "=", "None", ",", "summary_width", "=", "None", ")", ":", "if", "width", "is", "None", ":", "# pragma: no cover", "width", "=", "shutil"...
Generate the formatted status bar string.
[ "Generate", "the", "formatted", "status", "bar", "string", "." ]
e42ac88cdaae281d47318dd8dcf156bfff2a7b2a
https://github.com/mailund/statusbar/blob/e42ac88cdaae281d47318dd8dcf156bfff2a7b2a/statusbar/__init__.py#L153-L188
train
54,573
mailund/statusbar
statusbar/__init__.py
StatusTable.add_status_line
def add_status_line(self, label): """Add a status bar line to the table. This function returns the status bar and it can be modified from this return value. """ status_line = StatusBar(label, self._sep_start, self._sep_end, self._fill_char) self._lines.append(status_line) return status_line
python
def add_status_line(self, label): """Add a status bar line to the table. This function returns the status bar and it can be modified from this return value. """ status_line = StatusBar(label, self._sep_start, self._sep_end, self._fill_char) self._lines.append(status_line) return status_line
[ "def", "add_status_line", "(", "self", ",", "label", ")", ":", "status_line", "=", "StatusBar", "(", "label", ",", "self", ".", "_sep_start", ",", "self", ".", "_sep_end", ",", "self", ".", "_fill_char", ")", "self", ".", "_lines", ".", "append", "(", ...
Add a status bar line to the table. This function returns the status bar and it can be modified from this return value.
[ "Add", "a", "status", "bar", "line", "to", "the", "table", "." ]
e42ac88cdaae281d47318dd8dcf156bfff2a7b2a
https://github.com/mailund/statusbar/blob/e42ac88cdaae281d47318dd8dcf156bfff2a7b2a/statusbar/__init__.py#L203-L213
train
54,574
mailund/statusbar
statusbar/__init__.py
StatusTable.calculate_field_widths
def calculate_field_widths(self, width=None, min_label_width=10, min_progress_width=10): """Calculate how wide each field should be so we can align them. We always find room for the summaries since these are short and packed with information. If possible, we will also find room for labels, but if this would make the progress bar width shorter than the specified minium then we will shorten the labels, though never below the minium there. If this mean we have bars that are too wide for the terminal, then your terminal needs to be wider. """ if width is None: # pragma: no cover width = shutil.get_terminal_size()[0] summary_width = self.summary_width() label_width = self.label_width() remaining = width - summary_width - label_width - 2 if remaining >= min_progress_width: progress_width = remaining else: progress_width = min_progress_width remaining = width - summary_width - progress_width - 2 if remaining >= min_label_width: label_width = remaining else: label_width = min_label_width return (label_width, progress_width, summary_width)
python
def calculate_field_widths(self, width=None, min_label_width=10, min_progress_width=10): """Calculate how wide each field should be so we can align them. We always find room for the summaries since these are short and packed with information. If possible, we will also find room for labels, but if this would make the progress bar width shorter than the specified minium then we will shorten the labels, though never below the minium there. If this mean we have bars that are too wide for the terminal, then your terminal needs to be wider. """ if width is None: # pragma: no cover width = shutil.get_terminal_size()[0] summary_width = self.summary_width() label_width = self.label_width() remaining = width - summary_width - label_width - 2 if remaining >= min_progress_width: progress_width = remaining else: progress_width = min_progress_width remaining = width - summary_width - progress_width - 2 if remaining >= min_label_width: label_width = remaining else: label_width = min_label_width return (label_width, progress_width, summary_width)
[ "def", "calculate_field_widths", "(", "self", ",", "width", "=", "None", ",", "min_label_width", "=", "10", ",", "min_progress_width", "=", "10", ")", ":", "if", "width", "is", "None", ":", "# pragma: no cover", "width", "=", "shutil", ".", "get_terminal_size"...
Calculate how wide each field should be so we can align them. We always find room for the summaries since these are short and packed with information. If possible, we will also find room for labels, but if this would make the progress bar width shorter than the specified minium then we will shorten the labels, though never below the minium there. If this mean we have bars that are too wide for the terminal, then your terminal needs to be wider.
[ "Calculate", "how", "wide", "each", "field", "should", "be", "so", "we", "can", "align", "them", "." ]
e42ac88cdaae281d47318dd8dcf156bfff2a7b2a
https://github.com/mailund/statusbar/blob/e42ac88cdaae281d47318dd8dcf156bfff2a7b2a/statusbar/__init__.py#L231-L260
train
54,575
mailund/statusbar
statusbar/__init__.py
StatusTable.format_table
def format_table(self, width=None, min_label_width=10, min_progress_width=10): """Format the entire table of progress bars. The function first computes the widths of the fields so they can be aligned across lines and then returns formatted lines as a list of strings. """ # handle the special case of an empty table. if len(self._lines) == 0: return [] if width is None: # pragma: no cover width = shutil.get_terminal_size()[0] labelw, progw, summaryw = self.calculate_field_widths( width=width, min_label_width=min_label_width, min_progress_width=min_progress_width ) output = [ sb.format_status( label_width=labelw, progress_width=progw, summary_width=summaryw ) for sb in self._lines ] return output
python
def format_table(self, width=None, min_label_width=10, min_progress_width=10): """Format the entire table of progress bars. The function first computes the widths of the fields so they can be aligned across lines and then returns formatted lines as a list of strings. """ # handle the special case of an empty table. if len(self._lines) == 0: return [] if width is None: # pragma: no cover width = shutil.get_terminal_size()[0] labelw, progw, summaryw = self.calculate_field_widths( width=width, min_label_width=min_label_width, min_progress_width=min_progress_width ) output = [ sb.format_status( label_width=labelw, progress_width=progw, summary_width=summaryw ) for sb in self._lines ] return output
[ "def", "format_table", "(", "self", ",", "width", "=", "None", ",", "min_label_width", "=", "10", ",", "min_progress_width", "=", "10", ")", ":", "# handle the special case of an empty table.", "if", "len", "(", "self", ".", "_lines", ")", "==", "0", ":", "r...
Format the entire table of progress bars. The function first computes the widths of the fields so they can be aligned across lines and then returns formatted lines as a list of strings.
[ "Format", "the", "entire", "table", "of", "progress", "bars", "." ]
e42ac88cdaae281d47318dd8dcf156bfff2a7b2a
https://github.com/mailund/statusbar/blob/e42ac88cdaae281d47318dd8dcf156bfff2a7b2a/statusbar/__init__.py#L262-L291
train
54,576
jsmits/django-logutils
django_logutils/middleware.py
create_log_dict
def create_log_dict(request, response): """ Create a dictionary with logging data. """ remote_addr = request.META.get('REMOTE_ADDR') if remote_addr in getattr(settings, 'INTERNAL_IPS', []): remote_addr = request.META.get( 'HTTP_X_FORWARDED_FOR') or remote_addr user_email = "-" if hasattr(request, 'user'): user_email = getattr(request.user, 'email', '-') if response.streaming: content_length = 'streaming' else: content_length = len(response.content) return { # 'event' makes event-based filtering possible in logging backends # like logstash 'event': settings.LOGUTILS_LOGGING_MIDDLEWARE_EVENT, 'remote_address': remote_addr, 'user_email': user_email, 'method': request.method, 'url': request.get_full_path(), 'status': response.status_code, 'content_length': content_length, 'request_time': -1, # NA value: real value added by LoggingMiddleware }
python
def create_log_dict(request, response): """ Create a dictionary with logging data. """ remote_addr = request.META.get('REMOTE_ADDR') if remote_addr in getattr(settings, 'INTERNAL_IPS', []): remote_addr = request.META.get( 'HTTP_X_FORWARDED_FOR') or remote_addr user_email = "-" if hasattr(request, 'user'): user_email = getattr(request.user, 'email', '-') if response.streaming: content_length = 'streaming' else: content_length = len(response.content) return { # 'event' makes event-based filtering possible in logging backends # like logstash 'event': settings.LOGUTILS_LOGGING_MIDDLEWARE_EVENT, 'remote_address': remote_addr, 'user_email': user_email, 'method': request.method, 'url': request.get_full_path(), 'status': response.status_code, 'content_length': content_length, 'request_time': -1, # NA value: real value added by LoggingMiddleware }
[ "def", "create_log_dict", "(", "request", ",", "response", ")", ":", "remote_addr", "=", "request", ".", "META", ".", "get", "(", "'REMOTE_ADDR'", ")", "if", "remote_addr", "in", "getattr", "(", "settings", ",", "'INTERNAL_IPS'", ",", "[", "]", ")", ":", ...
Create a dictionary with logging data.
[ "Create", "a", "dictionary", "with", "logging", "data", "." ]
e88f6e0a08c6f3df9e61f96cfb6cd79bc5ea8a88
https://github.com/jsmits/django-logutils/blob/e88f6e0a08c6f3df9e61f96cfb6cd79bc5ea8a88/django_logutils/middleware.py#L17-L46
train
54,577
jsmits/django-logutils
django_logutils/middleware.py
create_log_message
def create_log_message(log_dict, use_sql_info=False, fmt=True): """ Create the logging message string. """ log_msg = ( "%(remote_address)s %(user_email)s %(method)s %(url)s %(status)d " "%(content_length)d (%(request_time).2f seconds)" ) if use_sql_info: sql_time = sum( float(q['time']) for q in connection.queries) * 1000 extra_log = { 'nr_queries': len(connection.queries), 'sql_time': sql_time} log_msg += " (%(nr_queries)d SQL queries, %(sql_time)f ms)" log_dict.update(extra_log) return log_msg % log_dict if fmt else log_msg
python
def create_log_message(log_dict, use_sql_info=False, fmt=True): """ Create the logging message string. """ log_msg = ( "%(remote_address)s %(user_email)s %(method)s %(url)s %(status)d " "%(content_length)d (%(request_time).2f seconds)" ) if use_sql_info: sql_time = sum( float(q['time']) for q in connection.queries) * 1000 extra_log = { 'nr_queries': len(connection.queries), 'sql_time': sql_time} log_msg += " (%(nr_queries)d SQL queries, %(sql_time)f ms)" log_dict.update(extra_log) return log_msg % log_dict if fmt else log_msg
[ "def", "create_log_message", "(", "log_dict", ",", "use_sql_info", "=", "False", ",", "fmt", "=", "True", ")", ":", "log_msg", "=", "(", "\"%(remote_address)s %(user_email)s %(method)s %(url)s %(status)d \"", "\"%(content_length)d (%(request_time).2f seconds)\"", ")", "if", ...
Create the logging message string.
[ "Create", "the", "logging", "message", "string", "." ]
e88f6e0a08c6f3df9e61f96cfb6cd79bc5ea8a88
https://github.com/jsmits/django-logutils/blob/e88f6e0a08c6f3df9e61f96cfb6cd79bc5ea8a88/django_logutils/middleware.py#L49-L65
train
54,578
jsmits/django-logutils
django_logutils/middleware.py
LoggingMiddleware.process_response
def process_response(self, request, response): """ Create the logging message.. """ try: log_dict = create_log_dict(request, response) # add the request time to the log_dict; if no start time is # available, use -1 as NA value request_time = ( time.time() - self.start_time if hasattr(self, 'start_time') and self.start_time else -1) log_dict.update({'request_time': request_time}) is_request_time_too_high = ( request_time > float(settings.LOGUTILS_REQUEST_TIME_THRESHOLD)) use_sql_info = settings.DEBUG or is_request_time_too_high log_msg = create_log_message(log_dict, use_sql_info, fmt=False) if is_request_time_too_high: logger.warning(log_msg, log_dict, extra=log_dict) else: logger.info(log_msg, log_dict, extra=log_dict) except Exception as e: logger.exception(e) return response
python
def process_response(self, request, response): """ Create the logging message.. """ try: log_dict = create_log_dict(request, response) # add the request time to the log_dict; if no start time is # available, use -1 as NA value request_time = ( time.time() - self.start_time if hasattr(self, 'start_time') and self.start_time else -1) log_dict.update({'request_time': request_time}) is_request_time_too_high = ( request_time > float(settings.LOGUTILS_REQUEST_TIME_THRESHOLD)) use_sql_info = settings.DEBUG or is_request_time_too_high log_msg = create_log_message(log_dict, use_sql_info, fmt=False) if is_request_time_too_high: logger.warning(log_msg, log_dict, extra=log_dict) else: logger.info(log_msg, log_dict, extra=log_dict) except Exception as e: logger.exception(e) return response
[ "def", "process_response", "(", "self", ",", "request", ",", "response", ")", ":", "try", ":", "log_dict", "=", "create_log_dict", "(", "request", ",", "response", ")", "# add the request time to the log_dict; if no start time is", "# available, use -1 as NA value", "requ...
Create the logging message..
[ "Create", "the", "logging", "message", ".." ]
e88f6e0a08c6f3df9e61f96cfb6cd79bc5ea8a88
https://github.com/jsmits/django-logutils/blob/e88f6e0a08c6f3df9e61f96cfb6cd79bc5ea8a88/django_logutils/middleware.py#L102-L129
train
54,579
NiklasRosenstein-Python/nr-deprecated
nr/concurrency.py
as_completed
def as_completed(jobs): ''' Generator function that yields the jobs in order of their completion. Attaches a new listener to each job. ''' jobs = tuple(jobs) event = threading.Event() callback = lambda f, ev: event.set() [job.add_listener(Job.SUCCESS, callback, once=True) for job in jobs] [job.add_listener(Job.ERROR, callback, once=True) for job in jobs] while jobs: event.wait() event.clear() jobs, finished = split_list_by(jobs, lambda x: x.finished) for job in finished: yield job
python
def as_completed(jobs): ''' Generator function that yields the jobs in order of their completion. Attaches a new listener to each job. ''' jobs = tuple(jobs) event = threading.Event() callback = lambda f, ev: event.set() [job.add_listener(Job.SUCCESS, callback, once=True) for job in jobs] [job.add_listener(Job.ERROR, callback, once=True) for job in jobs] while jobs: event.wait() event.clear() jobs, finished = split_list_by(jobs, lambda x: x.finished) for job in finished: yield job
[ "def", "as_completed", "(", "jobs", ")", ":", "jobs", "=", "tuple", "(", "jobs", ")", "event", "=", "threading", ".", "Event", "(", ")", "callback", "=", "lambda", "f", ",", "ev", ":", "event", ".", "set", "(", ")", "[", "job", ".", "add_listener",...
Generator function that yields the jobs in order of their completion. Attaches a new listener to each job.
[ "Generator", "function", "that", "yields", "the", "jobs", "in", "order", "of", "their", "completion", ".", "Attaches", "a", "new", "listener", "to", "each", "job", "." ]
f9f8b89ea1b084841a8ab65784eaf68852686b2a
https://github.com/NiklasRosenstein-Python/nr-deprecated/blob/f9f8b89ea1b084841a8ab65784eaf68852686b2a/nr/concurrency.py#L682-L698
train
54,580
NiklasRosenstein-Python/nr-deprecated
nr/concurrency.py
reraise
def reraise(tpe, value, tb=None): " Reraise an exception from an exception info tuple. " Py3 = (sys.version_info[0] == 3) if value is None: value = tpe() if Py3: if value.__traceback__ is not tb: raise value.with_traceback(tb) raise value else: exec('raise tpe, value, tb')
python
def reraise(tpe, value, tb=None): " Reraise an exception from an exception info tuple. " Py3 = (sys.version_info[0] == 3) if value is None: value = tpe() if Py3: if value.__traceback__ is not tb: raise value.with_traceback(tb) raise value else: exec('raise tpe, value, tb')
[ "def", "reraise", "(", "tpe", ",", "value", ",", "tb", "=", "None", ")", ":", "Py3", "=", "(", "sys", ".", "version_info", "[", "0", "]", "==", "3", ")", "if", "value", "is", "None", ":", "value", "=", "tpe", "(", ")", "if", "Py3", ":", "if",...
Reraise an exception from an exception info tuple.
[ "Reraise", "an", "exception", "from", "an", "exception", "info", "tuple", "." ]
f9f8b89ea1b084841a8ab65784eaf68852686b2a
https://github.com/NiklasRosenstein-Python/nr-deprecated/blob/f9f8b89ea1b084841a8ab65784eaf68852686b2a/nr/concurrency.py#L1280-L1291
train
54,581
NiklasRosenstein-Python/nr-deprecated
nr/concurrency.py
Job.finished
def finished(self): """ True if the job run and finished. There is no difference if the job finished successfully or errored. """ return self.__state in (Job.ERROR, Job.SUCCESS, Job.CANCELLED)
python
def finished(self): """ True if the job run and finished. There is no difference if the job finished successfully or errored. """ return self.__state in (Job.ERROR, Job.SUCCESS, Job.CANCELLED)
[ "def", "finished", "(", "self", ")", ":", "return", "self", ".", "__state", "in", "(", "Job", ".", "ERROR", ",", "Job", ".", "SUCCESS", ",", "Job", ".", "CANCELLED", ")" ]
True if the job run and finished. There is no difference if the job finished successfully or errored.
[ "True", "if", "the", "job", "run", "and", "finished", ".", "There", "is", "no", "difference", "if", "the", "job", "finished", "successfully", "or", "errored", "." ]
f9f8b89ea1b084841a8ab65784eaf68852686b2a
https://github.com/NiklasRosenstein-Python/nr-deprecated/blob/f9f8b89ea1b084841a8ab65784eaf68852686b2a/nr/concurrency.py#L423-L429
train
54,582
NiklasRosenstein-Python/nr-deprecated
nr/concurrency.py
Job._trigger_event
def _trigger_event(self, event): """ Private. Triggers and event and removes all one-off listeners for that event. """ if event is None or event not in self.__listeners: raise ValueError('invalid event type: {0!r}'.format(event)) # Check the event has not already been triggered, then mark # the event as triggered. if event in self.__event_set: raise RuntimeError('event already triggered: {0!r}'.format(event)) self.__event_set.add(event) listeners = self.__listeners[event] + self.__listeners[None] # Remove one-off listeners. self.__listeners[event][:] = (l for l in self.__listeners[event] if not l.once) self.__listeners[None][:] = (l for l in self.__listeners[None] if not l.once) for listener in listeners: # XXX: What to do on exceptions? Catch and make sure all listeners # run through? What to do with the exception(s) then? listener.callback(self, event)
python
def _trigger_event(self, event): """ Private. Triggers and event and removes all one-off listeners for that event. """ if event is None or event not in self.__listeners: raise ValueError('invalid event type: {0!r}'.format(event)) # Check the event has not already been triggered, then mark # the event as triggered. if event in self.__event_set: raise RuntimeError('event already triggered: {0!r}'.format(event)) self.__event_set.add(event) listeners = self.__listeners[event] + self.__listeners[None] # Remove one-off listeners. self.__listeners[event][:] = (l for l in self.__listeners[event] if not l.once) self.__listeners[None][:] = (l for l in self.__listeners[None] if not l.once) for listener in listeners: # XXX: What to do on exceptions? Catch and make sure all listeners # run through? What to do with the exception(s) then? listener.callback(self, event)
[ "def", "_trigger_event", "(", "self", ",", "event", ")", ":", "if", "event", "is", "None", "or", "event", "not", "in", "self", ".", "__listeners", ":", "raise", "ValueError", "(", "'invalid event type: {0!r}'", ".", "format", "(", "event", ")", ")", "# Che...
Private. Triggers and event and removes all one-off listeners for that event.
[ "Private", ".", "Triggers", "and", "event", "and", "removes", "all", "one", "-", "off", "listeners", "for", "that", "event", "." ]
f9f8b89ea1b084841a8ab65784eaf68852686b2a
https://github.com/NiklasRosenstein-Python/nr-deprecated/blob/f9f8b89ea1b084841a8ab65784eaf68852686b2a/nr/concurrency.py#L475-L497
train
54,583
NiklasRosenstein-Python/nr-deprecated
nr/concurrency.py
Job.wait
def wait(self, timeout=None): """ Waits for the job to finish and returns the result. # Arguments timeout (number, None): A number of seconds to wait for the result before raising a #Timeout exception. # Raises Timeout: If the timeout limit is exceeded. """ def cond(self): return self.__state not in (Job.PENDING, Job.RUNNING) or self.__cancelled if not wait_for_condition(self, cond, timeout): raise Job.Timeout return self.result
python
def wait(self, timeout=None): """ Waits for the job to finish and returns the result. # Arguments timeout (number, None): A number of seconds to wait for the result before raising a #Timeout exception. # Raises Timeout: If the timeout limit is exceeded. """ def cond(self): return self.__state not in (Job.PENDING, Job.RUNNING) or self.__cancelled if not wait_for_condition(self, cond, timeout): raise Job.Timeout return self.result
[ "def", "wait", "(", "self", ",", "timeout", "=", "None", ")", ":", "def", "cond", "(", "self", ")", ":", "return", "self", ".", "__state", "not", "in", "(", "Job", ".", "PENDING", ",", "Job", ".", "RUNNING", ")", "or", "self", ".", "__cancelled", ...
Waits for the job to finish and returns the result. # Arguments timeout (number, None): A number of seconds to wait for the result before raising a #Timeout exception. # Raises Timeout: If the timeout limit is exceeded.
[ "Waits", "for", "the", "job", "to", "finish", "and", "returns", "the", "result", "." ]
f9f8b89ea1b084841a8ab65784eaf68852686b2a
https://github.com/NiklasRosenstein-Python/nr-deprecated/blob/f9f8b89ea1b084841a8ab65784eaf68852686b2a/nr/concurrency.py#L535-L551
train
54,584
NiklasRosenstein-Python/nr-deprecated
nr/concurrency.py
Job.factory
def factory(start_immediately=True): """ This is a decorator function that creates new `Job`s with the wrapped function as the target. # Example ```python @Job.factory() def some_longish_function(job, seconds): time.sleep(seconds) return 42 job = some_longish_function(2) print(job.wait()) ``` # Arguments start_immediately (bool): #True if the factory should call #Job.start() immediately, #False if it should return the job in pending state. """ def decorator(func): def wrapper(*args, **kwargs): job = Job(task=lambda j: func(j, *args, **kwargs)) if start_immediately: job.start() return job return wrapper return decorator
python
def factory(start_immediately=True): """ This is a decorator function that creates new `Job`s with the wrapped function as the target. # Example ```python @Job.factory() def some_longish_function(job, seconds): time.sleep(seconds) return 42 job = some_longish_function(2) print(job.wait()) ``` # Arguments start_immediately (bool): #True if the factory should call #Job.start() immediately, #False if it should return the job in pending state. """ def decorator(func): def wrapper(*args, **kwargs): job = Job(task=lambda j: func(j, *args, **kwargs)) if start_immediately: job.start() return job return wrapper return decorator
[ "def", "factory", "(", "start_immediately", "=", "True", ")", ":", "def", "decorator", "(", "func", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "job", "=", "Job", "(", "task", "=", "lambda", "j", ":", "func", ...
This is a decorator function that creates new `Job`s with the wrapped function as the target. # Example ```python @Job.factory() def some_longish_function(job, seconds): time.sleep(seconds) return 42 job = some_longish_function(2) print(job.wait()) ``` # Arguments start_immediately (bool): #True if the factory should call #Job.start() immediately, #False if it should return the job in pending state.
[ "This", "is", "a", "decorator", "function", "that", "creates", "new", "Job", "s", "with", "the", "wrapped", "function", "as", "the", "target", "." ]
f9f8b89ea1b084841a8ab65784eaf68852686b2a
https://github.com/NiklasRosenstein-Python/nr-deprecated/blob/f9f8b89ea1b084841a8ab65784eaf68852686b2a/nr/concurrency.py#L651-L679
train
54,585
NiklasRosenstein-Python/nr-deprecated
nr/concurrency.py
ThreadPool.wait
def wait(self, timeout=None): """ Block until all jobs in the ThreadPool are finished. Beware that this can make the program run into a deadlock if another thread adds new jobs to the pool! # Raises Timeout: If the timeout is exceeded. """ if not self.__running: raise RuntimeError("ThreadPool ain't running") self.__queue.wait(timeout)
python
def wait(self, timeout=None): """ Block until all jobs in the ThreadPool are finished. Beware that this can make the program run into a deadlock if another thread adds new jobs to the pool! # Raises Timeout: If the timeout is exceeded. """ if not self.__running: raise RuntimeError("ThreadPool ain't running") self.__queue.wait(timeout)
[ "def", "wait", "(", "self", ",", "timeout", "=", "None", ")", ":", "if", "not", "self", ".", "__running", ":", "raise", "RuntimeError", "(", "\"ThreadPool ain't running\"", ")", "self", ".", "__queue", ".", "wait", "(", "timeout", ")" ]
Block until all jobs in the ThreadPool are finished. Beware that this can make the program run into a deadlock if another thread adds new jobs to the pool! # Raises Timeout: If the timeout is exceeded.
[ "Block", "until", "all", "jobs", "in", "the", "ThreadPool", "are", "finished", ".", "Beware", "that", "this", "can", "make", "the", "program", "run", "into", "a", "deadlock", "if", "another", "thread", "adds", "new", "jobs", "to", "the", "pool!" ]
f9f8b89ea1b084841a8ab65784eaf68852686b2a
https://github.com/NiklasRosenstein-Python/nr-deprecated/blob/f9f8b89ea1b084841a8ab65784eaf68852686b2a/nr/concurrency.py#L894-L906
train
54,586
NiklasRosenstein-Python/nr-deprecated
nr/concurrency.py
ThreadPool.shutdown
def shutdown(self, wait=True): """ Shut down the ThreadPool. # Arguments wait (bool): If #True, wait until all worker threads end. Note that pending jobs are still executed. If you want to cancel any pending jobs, use the #clear() or #cancel_all() methods. """ if self.__running: # Add a Non-entry for every worker thread we have. for thread in self.__threads: assert thread.isAlive() self.__queue.append(None) self.__running = False if wait: self.__queue.wait() for thread in self.__threads: thread.join()
python
def shutdown(self, wait=True): """ Shut down the ThreadPool. # Arguments wait (bool): If #True, wait until all worker threads end. Note that pending jobs are still executed. If you want to cancel any pending jobs, use the #clear() or #cancel_all() methods. """ if self.__running: # Add a Non-entry for every worker thread we have. for thread in self.__threads: assert thread.isAlive() self.__queue.append(None) self.__running = False if wait: self.__queue.wait() for thread in self.__threads: thread.join()
[ "def", "shutdown", "(", "self", ",", "wait", "=", "True", ")", ":", "if", "self", ".", "__running", ":", "# Add a Non-entry for every worker thread we have.", "for", "thread", "in", "self", ".", "__threads", ":", "assert", "thread", ".", "isAlive", "(", ")", ...
Shut down the ThreadPool. # Arguments wait (bool): If #True, wait until all worker threads end. Note that pending jobs are still executed. If you want to cancel any pending jobs, use the #clear() or #cancel_all() methods.
[ "Shut", "down", "the", "ThreadPool", "." ]
f9f8b89ea1b084841a8ab65784eaf68852686b2a
https://github.com/NiklasRosenstein-Python/nr-deprecated/blob/f9f8b89ea1b084841a8ab65784eaf68852686b2a/nr/concurrency.py#L908-L928
train
54,587
NiklasRosenstein-Python/nr-deprecated
nr/concurrency.py
EventQueue.new_event_type
def new_event_type(self, name, mergeable=False): ''' Declare a new event. May overwrite an existing entry. ''' self.event_types[name] = self.EventType(name, mergeable)
python
def new_event_type(self, name, mergeable=False): ''' Declare a new event. May overwrite an existing entry. ''' self.event_types[name] = self.EventType(name, mergeable)
[ "def", "new_event_type", "(", "self", ",", "name", ",", "mergeable", "=", "False", ")", ":", "self", ".", "event_types", "[", "name", "]", "=", "self", ".", "EventType", "(", "name", ",", "mergeable", ")" ]
Declare a new event. May overwrite an existing entry.
[ "Declare", "a", "new", "event", ".", "May", "overwrite", "an", "existing", "entry", "." ]
f9f8b89ea1b084841a8ab65784eaf68852686b2a
https://github.com/NiklasRosenstein-Python/nr-deprecated/blob/f9f8b89ea1b084841a8ab65784eaf68852686b2a/nr/concurrency.py#L994-L997
train
54,588
NiklasRosenstein-Python/nr-deprecated
nr/concurrency.py
EventQueue.pop_event
def pop_event(self): ''' Pop the next queued event from the queue. :raise ValueError: If there is no event queued. ''' with self.lock: if not self.events: raise ValueError('no events queued') return self.events.popleft()
python
def pop_event(self): ''' Pop the next queued event from the queue. :raise ValueError: If there is no event queued. ''' with self.lock: if not self.events: raise ValueError('no events queued') return self.events.popleft()
[ "def", "pop_event", "(", "self", ")", ":", "with", "self", ".", "lock", ":", "if", "not", "self", ".", "events", ":", "raise", "ValueError", "(", "'no events queued'", ")", "return", "self", ".", "events", ".", "popleft", "(", ")" ]
Pop the next queued event from the queue. :raise ValueError: If there is no event queued.
[ "Pop", "the", "next", "queued", "event", "from", "the", "queue", "." ]
f9f8b89ea1b084841a8ab65784eaf68852686b2a
https://github.com/NiklasRosenstein-Python/nr-deprecated/blob/f9f8b89ea1b084841a8ab65784eaf68852686b2a/nr/concurrency.py#L1025-L1035
train
54,589
ludeeus/pytautulli
pytautulli/__init__.py
logger
def logger(message, level=10): """Handle logging.""" logging.getLogger(__name__).log(level, str(message))
python
def logger(message, level=10): """Handle logging.""" logging.getLogger(__name__).log(level, str(message))
[ "def", "logger", "(", "message", ",", "level", "=", "10", ")", ":", "logging", ".", "getLogger", "(", "__name__", ")", ".", "log", "(", "level", ",", "str", "(", "message", ")", ")" ]
Handle logging.
[ "Handle", "logging", "." ]
0cf602f6720a105abb2311c8fbc8c6b2f9581276
https://github.com/ludeeus/pytautulli/blob/0cf602f6720a105abb2311c8fbc8c6b2f9581276/pytautulli/__init__.py#L196-L198
train
54,590
ludeeus/pytautulli
pytautulli/__init__.py
Tautulli.get_data
async def get_data(self): """Get Tautulli data.""" try: await self.get_session_data() await self.get_home_data() await self.get_users() await self.get_user_data() except (asyncio.TimeoutError, aiohttp.ClientError, socket.gaierror): msg = "Can not load data from Tautulli." logger(msg, 40)
python
async def get_data(self): """Get Tautulli data.""" try: await self.get_session_data() await self.get_home_data() await self.get_users() await self.get_user_data() except (asyncio.TimeoutError, aiohttp.ClientError, socket.gaierror): msg = "Can not load data from Tautulli." logger(msg, 40)
[ "async", "def", "get_data", "(", "self", ")", ":", "try", ":", "await", "self", ".", "get_session_data", "(", ")", "await", "self", ".", "get_home_data", "(", ")", "await", "self", ".", "get_users", "(", ")", "await", "self", ".", "get_user_data", "(", ...
Get Tautulli data.
[ "Get", "Tautulli", "data", "." ]
0cf602f6720a105abb2311c8fbc8c6b2f9581276
https://github.com/ludeeus/pytautulli/blob/0cf602f6720a105abb2311c8fbc8c6b2f9581276/pytautulli/__init__.py#L61-L70
train
54,591
ludeeus/pytautulli
pytautulli/__init__.py
Tautulli.get_session_data
async def get_session_data(self): """Get Tautulli sessions.""" cmd = 'get_activity' url = self.base_url + cmd try: async with async_timeout.timeout(8, loop=self._loop): response = await self._session.get(url) logger("Status from Tautulli: " + str(response.status)) self.tautulli_session_data = await response.json() logger(self.tautulli_session_data) except (asyncio.TimeoutError, aiohttp.ClientError, socket.gaierror, AttributeError) as error: msg = "Can not load data from Tautulli: {} - {}".format(url, error) logger(msg, 40)
python
async def get_session_data(self): """Get Tautulli sessions.""" cmd = 'get_activity' url = self.base_url + cmd try: async with async_timeout.timeout(8, loop=self._loop): response = await self._session.get(url) logger("Status from Tautulli: " + str(response.status)) self.tautulli_session_data = await response.json() logger(self.tautulli_session_data) except (asyncio.TimeoutError, aiohttp.ClientError, socket.gaierror, AttributeError) as error: msg = "Can not load data from Tautulli: {} - {}".format(url, error) logger(msg, 40)
[ "async", "def", "get_session_data", "(", "self", ")", ":", "cmd", "=", "'get_activity'", "url", "=", "self", ".", "base_url", "+", "cmd", "try", ":", "async", "with", "async_timeout", ".", "timeout", "(", "8", ",", "loop", "=", "self", ".", "_loop", ")...
Get Tautulli sessions.
[ "Get", "Tautulli", "sessions", "." ]
0cf602f6720a105abb2311c8fbc8c6b2f9581276
https://github.com/ludeeus/pytautulli/blob/0cf602f6720a105abb2311c8fbc8c6b2f9581276/pytautulli/__init__.py#L72-L87
train
54,592
ludeeus/pytautulli
pytautulli/__init__.py
Tautulli.get_home_data
async def get_home_data(self): """Get Tautulli home stats.""" cmd = 'get_home_stats' url = self.base_url + cmd data = {} try: async with async_timeout.timeout(8, loop=self._loop): request = await self._session.get(url) response = await request.json() for stat in response.get('response', {}).get('data', {}): if stat.get('stat_id') == 'top_movies': try: row = stat.get('rows', {})[0] data['movie'] = row.get('title') except (IndexError, KeyError): data['movie'] = None if stat.get('stat_id') == 'top_tv': try: row = stat.get('rows', {})[0] data['tv'] = row.get('title') except (IndexError, KeyError): data['tv'] = None if stat.get('stat_id') == 'top_users': try: row = stat.get('rows', {})[0] data['user'] = row.get('user') except (IndexError, KeyError): data['user'] = None logger("Status from Tautulli: " + str(request.status)) self.tautulli_home_data = data logger(self.tautulli_home_data) except (asyncio.TimeoutError, aiohttp.ClientError, socket.gaierror, AttributeError) as error: msg = "Can not load data from Tautulli: {} - {}".format(url, error) logger(msg, 40)
python
async def get_home_data(self): """Get Tautulli home stats.""" cmd = 'get_home_stats' url = self.base_url + cmd data = {} try: async with async_timeout.timeout(8, loop=self._loop): request = await self._session.get(url) response = await request.json() for stat in response.get('response', {}).get('data', {}): if stat.get('stat_id') == 'top_movies': try: row = stat.get('rows', {})[0] data['movie'] = row.get('title') except (IndexError, KeyError): data['movie'] = None if stat.get('stat_id') == 'top_tv': try: row = stat.get('rows', {})[0] data['tv'] = row.get('title') except (IndexError, KeyError): data['tv'] = None if stat.get('stat_id') == 'top_users': try: row = stat.get('rows', {})[0] data['user'] = row.get('user') except (IndexError, KeyError): data['user'] = None logger("Status from Tautulli: " + str(request.status)) self.tautulli_home_data = data logger(self.tautulli_home_data) except (asyncio.TimeoutError, aiohttp.ClientError, socket.gaierror, AttributeError) as error: msg = "Can not load data from Tautulli: {} - {}".format(url, error) logger(msg, 40)
[ "async", "def", "get_home_data", "(", "self", ")", ":", "cmd", "=", "'get_home_stats'", "url", "=", "self", ".", "base_url", "+", "cmd", "data", "=", "{", "}", "try", ":", "async", "with", "async_timeout", ".", "timeout", "(", "8", ",", "loop", "=", ...
Get Tautulli home stats.
[ "Get", "Tautulli", "home", "stats", "." ]
0cf602f6720a105abb2311c8fbc8c6b2f9581276
https://github.com/ludeeus/pytautulli/blob/0cf602f6720a105abb2311c8fbc8c6b2f9581276/pytautulli/__init__.py#L89-L124
train
54,593
ludeeus/pytautulli
pytautulli/__init__.py
Tautulli.get_users
async def get_users(self): """Get Tautulli users.""" cmd = 'get_users' url = self.base_url + cmd users = [] try: async with async_timeout.timeout(8, loop=self._loop): response = await self._session.get(url) logger("Status from Tautulli: " + str(response.status)) all_user_data = await response.json() for user in all_user_data['response']['data']: if user['username'] != 'Local': users.append(user['username']) self.tautulli_users = users logger(self.tautulli_users) except (asyncio.TimeoutError, aiohttp.ClientError, socket.gaierror, AttributeError) as error: msg = "Can not load data from Tautulli: {} - {}".format(url, error) logger(msg, 40)
python
async def get_users(self): """Get Tautulli users.""" cmd = 'get_users' url = self.base_url + cmd users = [] try: async with async_timeout.timeout(8, loop=self._loop): response = await self._session.get(url) logger("Status from Tautulli: " + str(response.status)) all_user_data = await response.json() for user in all_user_data['response']['data']: if user['username'] != 'Local': users.append(user['username']) self.tautulli_users = users logger(self.tautulli_users) except (asyncio.TimeoutError, aiohttp.ClientError, socket.gaierror, AttributeError) as error: msg = "Can not load data from Tautulli: {} - {}".format(url, error) logger(msg, 40)
[ "async", "def", "get_users", "(", "self", ")", ":", "cmd", "=", "'get_users'", "url", "=", "self", ".", "base_url", "+", "cmd", "users", "=", "[", "]", "try", ":", "async", "with", "async_timeout", ".", "timeout", "(", "8", ",", "loop", "=", "self", ...
Get Tautulli users.
[ "Get", "Tautulli", "users", "." ]
0cf602f6720a105abb2311c8fbc8c6b2f9581276
https://github.com/ludeeus/pytautulli/blob/0cf602f6720a105abb2311c8fbc8c6b2f9581276/pytautulli/__init__.py#L126-L146
train
54,594
ludeeus/pytautulli
pytautulli/__init__.py
Tautulli.get_user_data
async def get_user_data(self): """Get Tautulli userdata.""" userdata = {} sessions = self.session_data.get('sessions', {}) try: async with async_timeout.timeout(8, loop=self._loop): for username in self.tautulli_users: userdata[username] = {} userdata[username]['Activity'] = None for session in sessions: if session['username'].lower() == username.lower(): userdata[username]['Activity'] = session['state'] for key in session: if key != 'Username': userdata[username][key] = session[key] break self.tautulli_user_data = userdata except (asyncio.TimeoutError, aiohttp.ClientError, KeyError): msg = "Can not load data from Tautulli." logger(msg, 40)
python
async def get_user_data(self): """Get Tautulli userdata.""" userdata = {} sessions = self.session_data.get('sessions', {}) try: async with async_timeout.timeout(8, loop=self._loop): for username in self.tautulli_users: userdata[username] = {} userdata[username]['Activity'] = None for session in sessions: if session['username'].lower() == username.lower(): userdata[username]['Activity'] = session['state'] for key in session: if key != 'Username': userdata[username][key] = session[key] break self.tautulli_user_data = userdata except (asyncio.TimeoutError, aiohttp.ClientError, KeyError): msg = "Can not load data from Tautulli." logger(msg, 40)
[ "async", "def", "get_user_data", "(", "self", ")", ":", "userdata", "=", "{", "}", "sessions", "=", "self", ".", "session_data", ".", "get", "(", "'sessions'", ",", "{", "}", ")", "try", ":", "async", "with", "async_timeout", ".", "timeout", "(", "8", ...
Get Tautulli userdata.
[ "Get", "Tautulli", "userdata", "." ]
0cf602f6720a105abb2311c8fbc8c6b2f9581276
https://github.com/ludeeus/pytautulli/blob/0cf602f6720a105abb2311c8fbc8c6b2f9581276/pytautulli/__init__.py#L148-L168
train
54,595
frascoweb/frasco
frasco/utils.py
find_classes_in_module
def find_classes_in_module(module, clstypes): """Find classes of clstypes in module """ classes = [] for item in dir(module): item = getattr(module, item) try: for cls in clstypes: if issubclass(item, cls) and item != cls: classes.append(item) except Exception as e: pass return classes
python
def find_classes_in_module(module, clstypes): """Find classes of clstypes in module """ classes = [] for item in dir(module): item = getattr(module, item) try: for cls in clstypes: if issubclass(item, cls) and item != cls: classes.append(item) except Exception as e: pass return classes
[ "def", "find_classes_in_module", "(", "module", ",", "clstypes", ")", ":", "classes", "=", "[", "]", "for", "item", "in", "dir", "(", "module", ")", ":", "item", "=", "getattr", "(", "module", ",", "item", ")", "try", ":", "for", "cls", "in", "clstyp...
Find classes of clstypes in module
[ "Find", "classes", "of", "clstypes", "in", "module" ]
ea519d69dd5ca6deaf3650175692ee4a1a02518f
https://github.com/frascoweb/frasco/blob/ea519d69dd5ca6deaf3650175692ee4a1a02518f/frasco/utils.py#L82-L94
train
54,596
frascoweb/frasco
frasco/utils.py
remove_yaml_frontmatter
def remove_yaml_frontmatter(source, return_frontmatter=False): """If there's one, remove the YAML front-matter from the source """ if source.startswith("---\n"): frontmatter_end = source.find("\n---\n", 4) if frontmatter_end == -1: frontmatter = source source = "" else: frontmatter = source[0:frontmatter_end] source = source[frontmatter_end + 5:] if return_frontmatter: return (source, frontmatter) return source if return_frontmatter: return (source, None) return source
python
def remove_yaml_frontmatter(source, return_frontmatter=False): """If there's one, remove the YAML front-matter from the source """ if source.startswith("---\n"): frontmatter_end = source.find("\n---\n", 4) if frontmatter_end == -1: frontmatter = source source = "" else: frontmatter = source[0:frontmatter_end] source = source[frontmatter_end + 5:] if return_frontmatter: return (source, frontmatter) return source if return_frontmatter: return (source, None) return source
[ "def", "remove_yaml_frontmatter", "(", "source", ",", "return_frontmatter", "=", "False", ")", ":", "if", "source", ".", "startswith", "(", "\"---\\n\"", ")", ":", "frontmatter_end", "=", "source", ".", "find", "(", "\"\\n---\\n\"", ",", "4", ")", "if", "fro...
If there's one, remove the YAML front-matter from the source
[ "If", "there", "s", "one", "remove", "the", "YAML", "front", "-", "matter", "from", "the", "source" ]
ea519d69dd5ca6deaf3650175692ee4a1a02518f
https://github.com/frascoweb/frasco/blob/ea519d69dd5ca6deaf3650175692ee4a1a02518f/frasco/utils.py#L97-L113
train
54,597
frascoweb/frasco
frasco/utils.py
populate_obj
def populate_obj(obj, attrs): """Populates an object's attributes using the provided dict """ for k, v in attrs.iteritems(): setattr(obj, k, v)
python
def populate_obj(obj, attrs): """Populates an object's attributes using the provided dict """ for k, v in attrs.iteritems(): setattr(obj, k, v)
[ "def", "populate_obj", "(", "obj", ",", "attrs", ")", ":", "for", "k", ",", "v", "in", "attrs", ".", "iteritems", "(", ")", ":", "setattr", "(", "obj", ",", "k", ",", "v", ")" ]
Populates an object's attributes using the provided dict
[ "Populates", "an", "object", "s", "attributes", "using", "the", "provided", "dict" ]
ea519d69dd5ca6deaf3650175692ee4a1a02518f
https://github.com/frascoweb/frasco/blob/ea519d69dd5ca6deaf3650175692ee4a1a02518f/frasco/utils.py#L123-L127
train
54,598
smarie/python-parsyfiles
parsyfiles/parsing_registries.py
ParserFinder.build_parser_for_fileobject_and_desiredtype
def build_parser_for_fileobject_and_desiredtype(self, obj_on_filesystem: PersistedObject, object_type: Type[T], logger: Logger = None) -> Parser: """ Returns the most appropriate parser to use to parse object obj_on_filesystem as an object of type object_type :param obj_on_filesystem: the filesystem object to parse :param object_type: the type of object that the parser is expected to produce :param logger: :return: """ pass
python
def build_parser_for_fileobject_and_desiredtype(self, obj_on_filesystem: PersistedObject, object_type: Type[T], logger: Logger = None) -> Parser: """ Returns the most appropriate parser to use to parse object obj_on_filesystem as an object of type object_type :param obj_on_filesystem: the filesystem object to parse :param object_type: the type of object that the parser is expected to produce :param logger: :return: """ pass
[ "def", "build_parser_for_fileobject_and_desiredtype", "(", "self", ",", "obj_on_filesystem", ":", "PersistedObject", ",", "object_type", ":", "Type", "[", "T", "]", ",", "logger", ":", "Logger", "=", "None", ")", "->", "Parser", ":", "pass" ]
Returns the most appropriate parser to use to parse object obj_on_filesystem as an object of type object_type :param obj_on_filesystem: the filesystem object to parse :param object_type: the type of object that the parser is expected to produce :param logger: :return:
[ "Returns", "the", "most", "appropriate", "parser", "to", "use", "to", "parse", "object", "obj_on_filesystem", "as", "an", "object", "of", "type", "object_type" ]
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/parsing_registries.py#L29-L39
train
54,599