repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
unt-libraries/pypairtree
pypairtree/pairtreelist.py
listIDs
def listIDs(basedir): """Lists digital object identifiers of Pairtree directory structure. Walks a Pairtree directory structure to get IDs. Prepends prefix found in pairtree_prefix file. Outputs to standard output. """ prefix = '' # check for pairtree_prefix file prefixfile = os.path.join(basedir, 'pairtree_prefix') if os.path.isfile(prefixfile): rff = open(prefixfile, 'r') prefix = rff.readline().strip() rff.close() # check for pairtree_root dir root = os.path.join(basedir, 'pairtree_root') if os.path.isdir(root): objects = pairtree.findObjects(root) for obj in objects: doi = os.path.split(obj)[1] # print with prefix and original chars in place print(prefix + pairtree.deSanitizeString(doi)) else: print('pairtree_root directory not found')
python
def listIDs(basedir): """Lists digital object identifiers of Pairtree directory structure. Walks a Pairtree directory structure to get IDs. Prepends prefix found in pairtree_prefix file. Outputs to standard output. """ prefix = '' # check for pairtree_prefix file prefixfile = os.path.join(basedir, 'pairtree_prefix') if os.path.isfile(prefixfile): rff = open(prefixfile, 'r') prefix = rff.readline().strip() rff.close() # check for pairtree_root dir root = os.path.join(basedir, 'pairtree_root') if os.path.isdir(root): objects = pairtree.findObjects(root) for obj in objects: doi = os.path.split(obj)[1] # print with prefix and original chars in place print(prefix + pairtree.deSanitizeString(doi)) else: print('pairtree_root directory not found')
[ "def", "listIDs", "(", "basedir", ")", ":", "prefix", "=", "''", "# check for pairtree_prefix file", "prefixfile", "=", "os", ".", "path", ".", "join", "(", "basedir", ",", "'pairtree_prefix'", ")", "if", "os", ".", "path", ".", "isfile", "(", "prefixfile", ...
Lists digital object identifiers of Pairtree directory structure. Walks a Pairtree directory structure to get IDs. Prepends prefix found in pairtree_prefix file. Outputs to standard output.
[ "Lists", "digital", "object", "identifiers", "of", "Pairtree", "directory", "structure", "." ]
train
https://github.com/unt-libraries/pypairtree/blob/2107b46718bbf9ef7ef3d5c63d557d1f772e5d69/pypairtree/pairtreelist.py#L18-L40
peterpakos/ppipa
ppipa/freeipaserver.py
FreeIPAServer._set_conn
def _set_conn(self): """Establish connection to the server""" if self._tls: ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER) try: conn = ldap.initialize(self._url) conn.set_option(ldap.OPT_NETWORK_TIMEOUT, self._timeout) conn.simple_bind_s(self._binddn, self._bindpw) except Exception as e: if hasattr(e, 'message') and 'desc' in e.message: msg = e.message['desc'] else: msg = e.args[0]['desc'] log.critical(msg) raise log.debug('%s connection established' % ('LDAPS' if self._tls else 'LDAP')) self._conn = conn
python
def _set_conn(self): """Establish connection to the server""" if self._tls: ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER) try: conn = ldap.initialize(self._url) conn.set_option(ldap.OPT_NETWORK_TIMEOUT, self._timeout) conn.simple_bind_s(self._binddn, self._bindpw) except Exception as e: if hasattr(e, 'message') and 'desc' in e.message: msg = e.message['desc'] else: msg = e.args[0]['desc'] log.critical(msg) raise log.debug('%s connection established' % ('LDAPS' if self._tls else 'LDAP')) self._conn = conn
[ "def", "_set_conn", "(", "self", ")", ":", "if", "self", ".", "_tls", ":", "ldap", ".", "set_option", "(", "ldap", ".", "OPT_X_TLS_REQUIRE_CERT", ",", "ldap", ".", "OPT_X_TLS_NEVER", ")", "try", ":", "conn", "=", "ldap", ".", "initialize", "(", "self", ...
Establish connection to the server
[ "Establish", "connection", "to", "the", "server" ]
train
https://github.com/peterpakos/ppipa/blob/cc7565fe9afa079437cccfaf8d6b8c3da3f080ee/ppipa/freeipaserver.py#L58-L74
peterpakos/ppipa
ppipa/freeipaserver.py
FreeIPAServer._get_ldap_msg
def _get_ldap_msg(e): """Extract LDAP exception message""" msg = e if hasattr(e, 'message'): msg = e.message if 'desc' in e.message: msg = e.message['desc'] elif hasattr(e, 'args'): msg = e.args[0]['desc'] return msg
python
def _get_ldap_msg(e): """Extract LDAP exception message""" msg = e if hasattr(e, 'message'): msg = e.message if 'desc' in e.message: msg = e.message['desc'] elif hasattr(e, 'args'): msg = e.args[0]['desc'] return msg
[ "def", "_get_ldap_msg", "(", "e", ")", ":", "msg", "=", "e", "if", "hasattr", "(", "e", ",", "'message'", ")", ":", "msg", "=", "e", ".", "message", "if", "'desc'", "in", "e", ".", "message", ":", "msg", "=", "e", ".", "message", "[", "'desc'", ...
Extract LDAP exception message
[ "Extract", "LDAP", "exception", "message" ]
train
https://github.com/peterpakos/ppipa/blob/cc7565fe9afa079437cccfaf8d6b8c3da3f080ee/ppipa/freeipaserver.py#L77-L86
peterpakos/ppipa
ppipa/freeipaserver.py
FreeIPAServer._search
def _search(self, base, fltr, attrs=None, scope=ldap.SCOPE_SUBTREE): """Perform LDAP search""" try: results = self._conn.search_s(base, scope, fltr, attrs) except Exception as e: log.exception(self._get_ldap_msg(e)) results = False return results
python
def _search(self, base, fltr, attrs=None, scope=ldap.SCOPE_SUBTREE): """Perform LDAP search""" try: results = self._conn.search_s(base, scope, fltr, attrs) except Exception as e: log.exception(self._get_ldap_msg(e)) results = False return results
[ "def", "_search", "(", "self", ",", "base", ",", "fltr", ",", "attrs", "=", "None", ",", "scope", "=", "ldap", ".", "SCOPE_SUBTREE", ")", ":", "try", ":", "results", "=", "self", ".", "_conn", ".", "search_s", "(", "base", ",", "scope", ",", "fltr"...
Perform LDAP search
[ "Perform", "LDAP", "search" ]
train
https://github.com/peterpakos/ppipa/blob/cc7565fe9afa079437cccfaf8d6b8c3da3f080ee/ppipa/freeipaserver.py#L88-L95
peterpakos/ppipa
ppipa/freeipaserver.py
FreeIPAServer._set_fqdn
def _set_fqdn(self): """Get FQDN from LDAP""" results = self._search( 'cn=config', '(objectClass=*)', ['nsslapd-localhost'], scope=ldap.SCOPE_BASE ) if not results and type(results) is not list: r = None else: dn, attrs = results[0] r = attrs['nsslapd-localhost'][0].decode('utf-8') self._fqdn = r log.debug('FQDN: %s' % self._fqdn)
python
def _set_fqdn(self): """Get FQDN from LDAP""" results = self._search( 'cn=config', '(objectClass=*)', ['nsslapd-localhost'], scope=ldap.SCOPE_BASE ) if not results and type(results) is not list: r = None else: dn, attrs = results[0] r = attrs['nsslapd-localhost'][0].decode('utf-8') self._fqdn = r log.debug('FQDN: %s' % self._fqdn)
[ "def", "_set_fqdn", "(", "self", ")", ":", "results", "=", "self", ".", "_search", "(", "'cn=config'", ",", "'(objectClass=*)'", ",", "[", "'nsslapd-localhost'", "]", ",", "scope", "=", "ldap", ".", "SCOPE_BASE", ")", "if", "not", "results", "and", "type",...
Get FQDN from LDAP
[ "Get", "FQDN", "from", "LDAP" ]
train
https://github.com/peterpakos/ppipa/blob/cc7565fe9afa079437cccfaf8d6b8c3da3f080ee/ppipa/freeipaserver.py#L97-L111
peterpakos/ppipa
ppipa/freeipaserver.py
FreeIPAServer._set_hostname_domain
def _set_hostname_domain(self): """Extract hostname and domain""" self._hostname, _, self._domain = str(self._fqdn).partition('.') log.debug('Hostname: %s, Domain: %s' % (self._hostname, self._domain))
python
def _set_hostname_domain(self): """Extract hostname and domain""" self._hostname, _, self._domain = str(self._fqdn).partition('.') log.debug('Hostname: %s, Domain: %s' % (self._hostname, self._domain))
[ "def", "_set_hostname_domain", "(", "self", ")", ":", "self", ".", "_hostname", ",", "_", ",", "self", ".", "_domain", "=", "str", "(", "self", ".", "_fqdn", ")", ".", "partition", "(", "'.'", ")", "log", ".", "debug", "(", "'Hostname: %s, Domain: %s'", ...
Extract hostname and domain
[ "Extract", "hostname", "and", "domain" ]
train
https://github.com/peterpakos/ppipa/blob/cc7565fe9afa079437cccfaf8d6b8c3da3f080ee/ppipa/freeipaserver.py#L113-L116
peterpakos/ppipa
ppipa/freeipaserver.py
FreeIPAServer._set_ip
def _set_ip(self): """Resolve FQDN to IP address""" self._ip = socket.gethostbyname(self._fqdn) log.debug('IP: %s' % self._ip)
python
def _set_ip(self): """Resolve FQDN to IP address""" self._ip = socket.gethostbyname(self._fqdn) log.debug('IP: %s' % self._ip)
[ "def", "_set_ip", "(", "self", ")", ":", "self", ".", "_ip", "=", "socket", ".", "gethostbyname", "(", "self", ".", "_fqdn", ")", "log", ".", "debug", "(", "'IP: %s'", "%", "self", ".", "_ip", ")" ]
Resolve FQDN to IP address
[ "Resolve", "FQDN", "to", "IP", "address" ]
train
https://github.com/peterpakos/ppipa/blob/cc7565fe9afa079437cccfaf8d6b8c3da3f080ee/ppipa/freeipaserver.py#L118-L121
peterpakos/ppipa
ppipa/freeipaserver.py
FreeIPAServer._set_base_dn
def _set_base_dn(self): """Get Base DN from LDAP""" results = self._search( 'cn=config', '(objectClass=*)', ['nsslapd-defaultnamingcontext'], scope=ldap.SCOPE_BASE ) if results and type(results) is list: dn, attrs = results[0] r = attrs['nsslapd-defaultnamingcontext'][0].decode('utf-8') else: raise Exception self._base_dn = r self._active_user_base = 'cn=users,cn=accounts,' + self._base_dn self._stage_user_base = 'cn=staged users,cn=accounts,cn=provisioning,' + self._base_dn self._preserved_user_base = 'cn=deleted users,cn=accounts,cn=provisioning,' + self._base_dn self._groups_base = 'cn=groups,cn=accounts,' + self._base_dn log.debug('Base DN: %s' % self._base_dn)
python
def _set_base_dn(self): """Get Base DN from LDAP""" results = self._search( 'cn=config', '(objectClass=*)', ['nsslapd-defaultnamingcontext'], scope=ldap.SCOPE_BASE ) if results and type(results) is list: dn, attrs = results[0] r = attrs['nsslapd-defaultnamingcontext'][0].decode('utf-8') else: raise Exception self._base_dn = r self._active_user_base = 'cn=users,cn=accounts,' + self._base_dn self._stage_user_base = 'cn=staged users,cn=accounts,cn=provisioning,' + self._base_dn self._preserved_user_base = 'cn=deleted users,cn=accounts,cn=provisioning,' + self._base_dn self._groups_base = 'cn=groups,cn=accounts,' + self._base_dn log.debug('Base DN: %s' % self._base_dn)
[ "def", "_set_base_dn", "(", "self", ")", ":", "results", "=", "self", ".", "_search", "(", "'cn=config'", ",", "'(objectClass=*)'", ",", "[", "'nsslapd-defaultnamingcontext'", "]", ",", "scope", "=", "ldap", ".", "SCOPE_BASE", ")", "if", "results", "and", "t...
Get Base DN from LDAP
[ "Get", "Base", "DN", "from", "LDAP" ]
train
https://github.com/peterpakos/ppipa/blob/cc7565fe9afa079437cccfaf8d6b8c3da3f080ee/ppipa/freeipaserver.py#L123-L141
peterpakos/ppipa
ppipa/freeipaserver.py
FreeIPAServer.users
def users(self, user_base='active'): """Return dict of users""" if not getattr(self, '_%s_users' % user_base): self._get_users(user_base) return getattr(self, '_%s_users' % user_base)
python
def users(self, user_base='active'): """Return dict of users""" if not getattr(self, '_%s_users' % user_base): self._get_users(user_base) return getattr(self, '_%s_users' % user_base)
[ "def", "users", "(", "self", ",", "user_base", "=", "'active'", ")", ":", "if", "not", "getattr", "(", "self", ",", "'_%s_users'", "%", "user_base", ")", ":", "self", ".", "_get_users", "(", "user_base", ")", "return", "getattr", "(", "self", ",", "'_%...
Return dict of users
[ "Return", "dict", "of", "users" ]
train
https://github.com/peterpakos/ppipa/blob/cc7565fe9afa079437cccfaf8d6b8c3da3f080ee/ppipa/freeipaserver.py#L143-L147
peterpakos/ppipa
ppipa/freeipaserver.py
FreeIPAServer._get_users
def _get_users(self, user_base): """"Get users from LDAP""" results = self._search( getattr(self, '_%s_user_base' % user_base), '(objectClass=*)', ['*'], scope=ldap.SCOPE_ONELEVEL ) for dn, attrs in results: uid = attrs.get('uid')[0].decode('utf-8', 'ignore') getattr(self, '_%s_users' % user_base)[uid] = FreeIPAUser(dn, attrs) # print(attrs) log.debug('%s users: %s' % (user_base.capitalize(), len(getattr(self, '_%s_users' % user_base))))
python
def _get_users(self, user_base): """"Get users from LDAP""" results = self._search( getattr(self, '_%s_user_base' % user_base), '(objectClass=*)', ['*'], scope=ldap.SCOPE_ONELEVEL ) for dn, attrs in results: uid = attrs.get('uid')[0].decode('utf-8', 'ignore') getattr(self, '_%s_users' % user_base)[uid] = FreeIPAUser(dn, attrs) # print(attrs) log.debug('%s users: %s' % (user_base.capitalize(), len(getattr(self, '_%s_users' % user_base))))
[ "def", "_get_users", "(", "self", ",", "user_base", ")", ":", "results", "=", "self", ".", "_search", "(", "getattr", "(", "self", ",", "'_%s_user_base'", "%", "user_base", ")", ",", "'(objectClass=*)'", ",", "[", "'*'", "]", ",", "scope", "=", "ldap", ...
Get users from LDAP
[ "Get", "users", "from", "LDAP" ]
train
https://github.com/peterpakos/ppipa/blob/cc7565fe9afa079437cccfaf8d6b8c3da3f080ee/ppipa/freeipaserver.py#L149-L161
peterpakos/ppipa
ppipa/freeipaserver.py
FreeIPAServer.find_users_by_email
def find_users_by_email(self, email, user_base='active'): """Return list of users with given email address""" users = [] for user in getattr(self, 'users')(user_base).values(): mail = user.mail if mail and email in mail: users.append(user) log.debug('%s users with email address %s: %s' % (user_base.capitalize(), email, len(users))) return users
python
def find_users_by_email(self, email, user_base='active'): """Return list of users with given email address""" users = [] for user in getattr(self, 'users')(user_base).values(): mail = user.mail if mail and email in mail: users.append(user) log.debug('%s users with email address %s: %s' % (user_base.capitalize(), email, len(users))) return users
[ "def", "find_users_by_email", "(", "self", ",", "email", ",", "user_base", "=", "'active'", ")", ":", "users", "=", "[", "]", "for", "user", "in", "getattr", "(", "self", ",", "'users'", ")", "(", "user_base", ")", ".", "values", "(", ")", ":", "mail...
Return list of users with given email address
[ "Return", "list", "of", "users", "with", "given", "email", "address" ]
train
https://github.com/peterpakos/ppipa/blob/cc7565fe9afa079437cccfaf8d6b8c3da3f080ee/ppipa/freeipaserver.py#L163-L171
peterpakos/ppipa
ppipa/freeipaserver.py
FreeIPAServer._get_anon_bind
def _get_anon_bind(self): """Check anonymous bind :return: 'on', 'off', 'rootdse' or None """ r = self._search( 'cn=config', '(objectClass=*)', ['nsslapd-allow-anonymous-access'], scope=ldap.SCOPE_BASE ) dn, attrs = r[0] state = attrs.get('nsslapd-allow-anonymous-access')[0].decode('utf-8', 'ignore') if state in ['on', 'off', 'rootdse']: r = state else: r = None self._anon_bind = r
python
def _get_anon_bind(self): """Check anonymous bind :return: 'on', 'off', 'rootdse' or None """ r = self._search( 'cn=config', '(objectClass=*)', ['nsslapd-allow-anonymous-access'], scope=ldap.SCOPE_BASE ) dn, attrs = r[0] state = attrs.get('nsslapd-allow-anonymous-access')[0].decode('utf-8', 'ignore') if state in ['on', 'off', 'rootdse']: r = state else: r = None self._anon_bind = r
[ "def", "_get_anon_bind", "(", "self", ")", ":", "r", "=", "self", ".", "_search", "(", "'cn=config'", ",", "'(objectClass=*)'", ",", "[", "'nsslapd-allow-anonymous-access'", "]", ",", "scope", "=", "ldap", ".", "SCOPE_BASE", ")", "dn", ",", "attrs", "=", "...
Check anonymous bind :return: 'on', 'off', 'rootdse' or None
[ "Check", "anonymous", "bind", ":", "return", ":", "on", "off", "rootdse", "or", "None" ]
train
https://github.com/peterpakos/ppipa/blob/cc7565fe9afa079437cccfaf8d6b8c3da3f080ee/ppipa/freeipaserver.py#L177-L193
bioidiap/gridtk
gridtk/generator.py
_ordered_load
def _ordered_load(stream, Loader=yaml.Loader, object_pairs_hook=dict): '''Loads the contents of the YAML stream into :py:class:`collections.OrderedDict`'s See: https://stackoverflow.com/questions/5121931/in-python-how-can-you-load-yaml-mappings-as-ordereddicts ''' class OrderedLoader(Loader): pass def construct_mapping(loader, node): loader.flatten_mapping(node) return object_pairs_hook(loader.construct_pairs(node)) OrderedLoader.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, construct_mapping) return yaml.load(stream, OrderedLoader)
python
def _ordered_load(stream, Loader=yaml.Loader, object_pairs_hook=dict): '''Loads the contents of the YAML stream into :py:class:`collections.OrderedDict`'s See: https://stackoverflow.com/questions/5121931/in-python-how-can-you-load-yaml-mappings-as-ordereddicts ''' class OrderedLoader(Loader): pass def construct_mapping(loader, node): loader.flatten_mapping(node) return object_pairs_hook(loader.construct_pairs(node)) OrderedLoader.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, construct_mapping) return yaml.load(stream, OrderedLoader)
[ "def", "_ordered_load", "(", "stream", ",", "Loader", "=", "yaml", ".", "Loader", ",", "object_pairs_hook", "=", "dict", ")", ":", "class", "OrderedLoader", "(", "Loader", ")", ":", "pass", "def", "construct_mapping", "(", "loader", ",", "node", ")", ":", ...
Loads the contents of the YAML stream into :py:class:`collections.OrderedDict`'s See: https://stackoverflow.com/questions/5121931/in-python-how-can-you-load-yaml-mappings-as-ordereddicts
[ "Loads", "the", "contents", "of", "the", "YAML", "stream", "into", ":", "py", ":", "class", ":", "collections", ".", "OrderedDict", "s" ]
train
https://github.com/bioidiap/gridtk/blob/9e3291b8b50388682908927231b2730db1da147d/gridtk/generator.py#L22-L39
bioidiap/gridtk
gridtk/generator.py
expand
def expand(data): '''Generates configuration sets based on the YAML input contents For an introduction to the YAML mark-up, just search the net. Here is one of its references: https://en.wikipedia.org/wiki/YAML A configuration set corresponds to settings for **all** variables in the input template that needs replacing. For example, if your template mentions the variables ``name`` and ``version``, then each configuration set should yield values for both ``name`` and ``version``. For example: .. code-block:: yaml name: [john, lisa] version: [v1, v2] This should yield to the following configuration sets: .. code-block:: python [ {'name': 'john', 'version': 'v1'}, {'name': 'john', 'version': 'v2'}, {'name': 'lisa', 'version': 'v1'}, {'name': 'lisa', 'version': 'v2'}, ] Each key in the input file should correspond to either an object or a YAML array. If the object is a list, then we'll iterate over it for every possible combination of elements in the lists. If the element in question is not a list, then it is considered unique and repeated for each yielded configuration set. Example .. code-block:: yaml name: [john, lisa] version: [v1, v2] text: > hello, world! Should yield to the following configuration sets: .. code-block:: python [ {'name': 'john', 'version': 'v1', 'text': 'hello, world!'}, {'name': 'john', 'version': 'v2', 'text': 'hello, world!'}, {'name': 'lisa', 'version': 'v1', 'text': 'hello, world!'}, {'name': 'lisa', 'version': 'v2', 'text': 'hello, world!'}, ] Keys starting with one `_` (underscore) are treated as "unique" objects as well. Example: .. code-block:: yaml name: [john, lisa] version: [v1, v2] _unique: [i1, i2] Should yield to the following configuration sets: .. code-block:: python [ {'name': 'john', 'version': 'v1', '_unique': ['i1', 'i2']}, {'name': 'john', 'version': 'v2', '_unique': ['i1', 'i2']}, {'name': 'lisa', 'version': 'v1', '_unique': ['i1', 'i2']}, {'name': 'lisa', 'version': 'v2', '_unique': ['i1', 'i2']}, ] Parameters: data (str): YAML data to be parsed Yields: dict: A dictionary of key-value pairs for building the templates ''' data = _ordered_load(data, yaml.SafeLoader) # separates "unique" objects from the ones we have to iterate # pre-assemble return dictionary iterables = dict() unique = dict() for key, value in data.items(): if isinstance(value, list) and not key.startswith('_'): iterables[key] = value else: unique[key] = value # generates all possible combinations of iterables for values in itertools.product(*iterables.values()): retval = dict(unique) keys = list(iterables.keys()) retval.update(dict(zip(keys, values))) yield retval
python
def expand(data): '''Generates configuration sets based on the YAML input contents For an introduction to the YAML mark-up, just search the net. Here is one of its references: https://en.wikipedia.org/wiki/YAML A configuration set corresponds to settings for **all** variables in the input template that needs replacing. For example, if your template mentions the variables ``name`` and ``version``, then each configuration set should yield values for both ``name`` and ``version``. For example: .. code-block:: yaml name: [john, lisa] version: [v1, v2] This should yield to the following configuration sets: .. code-block:: python [ {'name': 'john', 'version': 'v1'}, {'name': 'john', 'version': 'v2'}, {'name': 'lisa', 'version': 'v1'}, {'name': 'lisa', 'version': 'v2'}, ] Each key in the input file should correspond to either an object or a YAML array. If the object is a list, then we'll iterate over it for every possible combination of elements in the lists. If the element in question is not a list, then it is considered unique and repeated for each yielded configuration set. Example .. code-block:: yaml name: [john, lisa] version: [v1, v2] text: > hello, world! Should yield to the following configuration sets: .. code-block:: python [ {'name': 'john', 'version': 'v1', 'text': 'hello, world!'}, {'name': 'john', 'version': 'v2', 'text': 'hello, world!'}, {'name': 'lisa', 'version': 'v1', 'text': 'hello, world!'}, {'name': 'lisa', 'version': 'v2', 'text': 'hello, world!'}, ] Keys starting with one `_` (underscore) are treated as "unique" objects as well. Example: .. code-block:: yaml name: [john, lisa] version: [v1, v2] _unique: [i1, i2] Should yield to the following configuration sets: .. code-block:: python [ {'name': 'john', 'version': 'v1', '_unique': ['i1', 'i2']}, {'name': 'john', 'version': 'v2', '_unique': ['i1', 'i2']}, {'name': 'lisa', 'version': 'v1', '_unique': ['i1', 'i2']}, {'name': 'lisa', 'version': 'v2', '_unique': ['i1', 'i2']}, ] Parameters: data (str): YAML data to be parsed Yields: dict: A dictionary of key-value pairs for building the templates ''' data = _ordered_load(data, yaml.SafeLoader) # separates "unique" objects from the ones we have to iterate # pre-assemble return dictionary iterables = dict() unique = dict() for key, value in data.items(): if isinstance(value, list) and not key.startswith('_'): iterables[key] = value else: unique[key] = value # generates all possible combinations of iterables for values in itertools.product(*iterables.values()): retval = dict(unique) keys = list(iterables.keys()) retval.update(dict(zip(keys, values))) yield retval
[ "def", "expand", "(", "data", ")", ":", "data", "=", "_ordered_load", "(", "data", ",", "yaml", ".", "SafeLoader", ")", "# separates \"unique\" objects from the ones we have to iterate", "# pre-assemble return dictionary", "iterables", "=", "dict", "(", ")", "unique", ...
Generates configuration sets based on the YAML input contents For an introduction to the YAML mark-up, just search the net. Here is one of its references: https://en.wikipedia.org/wiki/YAML A configuration set corresponds to settings for **all** variables in the input template that needs replacing. For example, if your template mentions the variables ``name`` and ``version``, then each configuration set should yield values for both ``name`` and ``version``. For example: .. code-block:: yaml name: [john, lisa] version: [v1, v2] This should yield to the following configuration sets: .. code-block:: python [ {'name': 'john', 'version': 'v1'}, {'name': 'john', 'version': 'v2'}, {'name': 'lisa', 'version': 'v1'}, {'name': 'lisa', 'version': 'v2'}, ] Each key in the input file should correspond to either an object or a YAML array. If the object is a list, then we'll iterate over it for every possible combination of elements in the lists. If the element in question is not a list, then it is considered unique and repeated for each yielded configuration set. Example .. code-block:: yaml name: [john, lisa] version: [v1, v2] text: > hello, world! Should yield to the following configuration sets: .. code-block:: python [ {'name': 'john', 'version': 'v1', 'text': 'hello, world!'}, {'name': 'john', 'version': 'v2', 'text': 'hello, world!'}, {'name': 'lisa', 'version': 'v1', 'text': 'hello, world!'}, {'name': 'lisa', 'version': 'v2', 'text': 'hello, world!'}, ] Keys starting with one `_` (underscore) are treated as "unique" objects as well. Example: .. code-block:: yaml name: [john, lisa] version: [v1, v2] _unique: [i1, i2] Should yield to the following configuration sets: .. code-block:: python [ {'name': 'john', 'version': 'v1', '_unique': ['i1', 'i2']}, {'name': 'john', 'version': 'v2', '_unique': ['i1', 'i2']}, {'name': 'lisa', 'version': 'v1', '_unique': ['i1', 'i2']}, {'name': 'lisa', 'version': 'v2', '_unique': ['i1', 'i2']}, ] Parameters: data (str): YAML data to be parsed Yields: dict: A dictionary of key-value pairs for building the templates
[ "Generates", "configuration", "sets", "based", "on", "the", "YAML", "input", "contents" ]
train
https://github.com/bioidiap/gridtk/blob/9e3291b8b50388682908927231b2730db1da147d/gridtk/generator.py#L42-L147
bioidiap/gridtk
gridtk/generator.py
generate
def generate(variables, template): '''Yields a resolved "template" for each config set and dumps on output This function will extrapolate the ``template`` file using the contents of ``variables`` and will output individual (extrapolated, expanded) files in the output directory ``output``. Parameters: variables (str): A string stream containing the variables to parse, in YAML format as explained on :py:func:`expand`. template (str): A string stream containing the template to extrapolate Yields: str: A generated template you can save Raises: jinja2.UndefinedError: if a variable used in the template is undefined ''' env = jinja2.Environment(undefined=jinja2.StrictUndefined) for c in expand(variables): c['rc'] = rc yield env.from_string(template).render(c)
python
def generate(variables, template): '''Yields a resolved "template" for each config set and dumps on output This function will extrapolate the ``template`` file using the contents of ``variables`` and will output individual (extrapolated, expanded) files in the output directory ``output``. Parameters: variables (str): A string stream containing the variables to parse, in YAML format as explained on :py:func:`expand`. template (str): A string stream containing the template to extrapolate Yields: str: A generated template you can save Raises: jinja2.UndefinedError: if a variable used in the template is undefined ''' env = jinja2.Environment(undefined=jinja2.StrictUndefined) for c in expand(variables): c['rc'] = rc yield env.from_string(template).render(c)
[ "def", "generate", "(", "variables", ",", "template", ")", ":", "env", "=", "jinja2", ".", "Environment", "(", "undefined", "=", "jinja2", ".", "StrictUndefined", ")", "for", "c", "in", "expand", "(", "variables", ")", ":", "c", "[", "'rc'", "]", "=", ...
Yields a resolved "template" for each config set and dumps on output This function will extrapolate the ``template`` file using the contents of ``variables`` and will output individual (extrapolated, expanded) files in the output directory ``output``. Parameters: variables (str): A string stream containing the variables to parse, in YAML format as explained on :py:func:`expand`. template (str): A string stream containing the template to extrapolate Yields: str: A generated template you can save Raises: jinja2.UndefinedError: if a variable used in the template is undefined
[ "Yields", "a", "resolved", "template", "for", "each", "config", "set", "and", "dumps", "on", "output" ]
train
https://github.com/bioidiap/gridtk/blob/9e3291b8b50388682908927231b2730db1da147d/gridtk/generator.py#L150-L180
bioidiap/gridtk
gridtk/generator.py
aggregate
def aggregate(variables, template): '''Generates a resolved "template" for **all** config sets and returns This function will extrapolate the ``template`` file using the contents of ``variables`` and will output a single (extrapolated, expanded) file. Parameters: variables (str): A string stream containing the variables to parse, in YAML format as explained on :py:func:`expand`. template (str): A string stream containing the template to extrapolate Returns: str: A generated template you can save Raises: jinja2.UndefinedError: if a variable used in the template is undefined ''' env = jinja2.Environment(undefined=jinja2.StrictUndefined) d = {'cfgset': list(expand(variables)), 'rc': rc} return env.from_string(template).render(d)
python
def aggregate(variables, template): '''Generates a resolved "template" for **all** config sets and returns This function will extrapolate the ``template`` file using the contents of ``variables`` and will output a single (extrapolated, expanded) file. Parameters: variables (str): A string stream containing the variables to parse, in YAML format as explained on :py:func:`expand`. template (str): A string stream containing the template to extrapolate Returns: str: A generated template you can save Raises: jinja2.UndefinedError: if a variable used in the template is undefined ''' env = jinja2.Environment(undefined=jinja2.StrictUndefined) d = {'cfgset': list(expand(variables)), 'rc': rc} return env.from_string(template).render(d)
[ "def", "aggregate", "(", "variables", ",", "template", ")", ":", "env", "=", "jinja2", ".", "Environment", "(", "undefined", "=", "jinja2", ".", "StrictUndefined", ")", "d", "=", "{", "'cfgset'", ":", "list", "(", "expand", "(", "variables", ")", ")", ...
Generates a resolved "template" for **all** config sets and returns This function will extrapolate the ``template`` file using the contents of ``variables`` and will output a single (extrapolated, expanded) file. Parameters: variables (str): A string stream containing the variables to parse, in YAML format as explained on :py:func:`expand`. template (str): A string stream containing the template to extrapolate Returns: str: A generated template you can save Raises: jinja2.UndefinedError: if a variable used in the template is undefined
[ "Generates", "a", "resolved", "template", "for", "**", "all", "**", "config", "sets", "and", "returns" ]
train
https://github.com/bioidiap/gridtk/blob/9e3291b8b50388682908927231b2730db1da147d/gridtk/generator.py#L183-L211
BD2KOnFHIR/i2b2model
i2b2model/shared/i2b2core.py
I2B2Core._delete_sourcesystem_cd
def _delete_sourcesystem_cd(conn: Connection, table: Table, sourcesystem_cd: str) -> int: """ Remove all table records with the supplied upload_id :param conn: sql connection :param table: table to modify :param sourcesystem_cd: target sourcesystem code :return: number of records removed """ return conn.execute(delete(table).where(table.c.sourcesystem_cd == sourcesystem_cd)).rowcount \ if sourcesystem_cd else 0
python
def _delete_sourcesystem_cd(conn: Connection, table: Table, sourcesystem_cd: str) -> int: """ Remove all table records with the supplied upload_id :param conn: sql connection :param table: table to modify :param sourcesystem_cd: target sourcesystem code :return: number of records removed """ return conn.execute(delete(table).where(table.c.sourcesystem_cd == sourcesystem_cd)).rowcount \ if sourcesystem_cd else 0
[ "def", "_delete_sourcesystem_cd", "(", "conn", ":", "Connection", ",", "table", ":", "Table", ",", "sourcesystem_cd", ":", "str", ")", "->", "int", ":", "return", "conn", ".", "execute", "(", "delete", "(", "table", ")", ".", "where", "(", "table", ".", ...
Remove all table records with the supplied upload_id :param conn: sql connection :param table: table to modify :param sourcesystem_cd: target sourcesystem code :return: number of records removed
[ "Remove", "all", "table", "records", "with", "the", "supplied", "upload_id" ]
train
https://github.com/BD2KOnFHIR/i2b2model/blob/9d49bb53b0733dd83ab5b716014865e270a3c903/i2b2model/shared/i2b2core.py#L21-L30
BD2KOnFHIR/i2b2model
i2b2model/shared/i2b2core.py
I2B2CoreWithUploadId._delete_upload_id
def _delete_upload_id(conn: Connection, table: Table, upload_id: int) -> int: """Remove all table records with the supplied upload_id :param conn: sql connection :param table: table to modify :param upload_id: target upload_id :return: number of records removed """ return conn.execute(delete(table).where(table.c.upload_id == upload_id)).rowcount if upload_id else 0
python
def _delete_upload_id(conn: Connection, table: Table, upload_id: int) -> int: """Remove all table records with the supplied upload_id :param conn: sql connection :param table: table to modify :param upload_id: target upload_id :return: number of records removed """ return conn.execute(delete(table).where(table.c.upload_id == upload_id)).rowcount if upload_id else 0
[ "def", "_delete_upload_id", "(", "conn", ":", "Connection", ",", "table", ":", "Table", ",", "upload_id", ":", "int", ")", "->", "int", ":", "return", "conn", ".", "execute", "(", "delete", "(", "table", ")", ".", "where", "(", "table", ".", "c", "."...
Remove all table records with the supplied upload_id :param conn: sql connection :param table: table to modify :param upload_id: target upload_id :return: number of records removed
[ "Remove", "all", "table", "records", "with", "the", "supplied", "upload_id" ]
train
https://github.com/BD2KOnFHIR/i2b2model/blob/9d49bb53b0733dd83ab5b716014865e270a3c903/i2b2model/shared/i2b2core.py#L43-L51
BD2KOnFHIR/i2b2model
i2b2model/shared/i2b2core.py
I2B2CoreWithUploadId._nested_fcn
def _nested_fcn(f: Callable, filters: List): """ Distribute binary function f across list L :param f: Binary function :param filters: function arguments :return: chain of binary filters """ return None if len(filters) == 0 \ else filters[0] if len(filters) == 1 \ else f(filters[0], I2B2CoreWithUploadId._nested_fcn(f, filters[1:]))
python
def _nested_fcn(f: Callable, filters: List): """ Distribute binary function f across list L :param f: Binary function :param filters: function arguments :return: chain of binary filters """ return None if len(filters) == 0 \ else filters[0] if len(filters) == 1 \ else f(filters[0], I2B2CoreWithUploadId._nested_fcn(f, filters[1:]))
[ "def", "_nested_fcn", "(", "f", ":", "Callable", ",", "filters", ":", "List", ")", ":", "return", "None", "if", "len", "(", "filters", ")", "==", "0", "else", "filters", "[", "0", "]", "if", "len", "(", "filters", ")", "==", "1", "else", "f", "("...
Distribute binary function f across list L :param f: Binary function :param filters: function arguments :return: chain of binary filters
[ "Distribute", "binary", "function", "f", "across", "list", "L" ]
train
https://github.com/BD2KOnFHIR/i2b2model/blob/9d49bb53b0733dd83ab5b716014865e270a3c903/i2b2model/shared/i2b2core.py#L54-L63
BD2KOnFHIR/i2b2model
i2b2model/shared/i2b2core.py
I2B2CoreWithUploadId._add_or_update_records
def _add_or_update_records(cls, conn: Connection, table: Table, records: List["I2B2CoreWithUploadId"]) -> Tuple[int, int]: """Add or update the supplied table as needed to reflect the contents of records :param table: i2b2 sql connection :param records: records to apply :return: number of records added / modified """ num_updates = 0 num_inserts = 0 inserts = [] # Iterate over the records doing updates # Note: This is slow as molasses - definitely not optimal for batch work, but hopefully we'll be dealing with # thousands to tens of thousands of records. May want to move to ORM model if this gets to be an issue for record in records: keys = [(table.c[k] == getattr(record, k)) for k in cls.key_fields] key_filter = I2B2CoreWithUploadId._nested_fcn(and_, keys) rec_exists = conn.execute(select([table.c.upload_id]).where(key_filter)).rowcount if rec_exists: known_values = {k: v for k, v in as_dict(record).items() if v is not None and k not in cls._no_update_fields and k not in cls.key_fields} vals = [table.c[k] != v for k, v in known_values.items()] val_filter = I2B2CoreWithUploadId._nested_fcn(or_, vals) known_values['update_date'] = record.update_date upd = update(table).where(and_(key_filter, val_filter)).values(known_values) num_updates += conn.execute(upd).rowcount else: inserts.append(as_dict(record)) if inserts: if cls._check_dups: dups = cls._check_for_dups(inserts) nprints = 0 if dups: print("{} duplicate records encountered".format(len(dups))) for k, vals in dups.items(): if len(vals) == 2 and vals[0] == vals[1]: inserts.remove(vals[1]) else: if nprints < 20: print("Key: {} has a non-identical dup".format(k)) elif nprints == 20: print(".... more ...") nprints += 1 for v in vals[1:]: inserts.remove(v) # TODO: refactor this to load on a per-resource basis. Temporary fix for insert in ListChunker(inserts, 500): num_inserts += conn.execute(table.insert(), insert).rowcount return num_inserts, num_updates
python
def _add_or_update_records(cls, conn: Connection, table: Table, records: List["I2B2CoreWithUploadId"]) -> Tuple[int, int]: """Add or update the supplied table as needed to reflect the contents of records :param table: i2b2 sql connection :param records: records to apply :return: number of records added / modified """ num_updates = 0 num_inserts = 0 inserts = [] # Iterate over the records doing updates # Note: This is slow as molasses - definitely not optimal for batch work, but hopefully we'll be dealing with # thousands to tens of thousands of records. May want to move to ORM model if this gets to be an issue for record in records: keys = [(table.c[k] == getattr(record, k)) for k in cls.key_fields] key_filter = I2B2CoreWithUploadId._nested_fcn(and_, keys) rec_exists = conn.execute(select([table.c.upload_id]).where(key_filter)).rowcount if rec_exists: known_values = {k: v for k, v in as_dict(record).items() if v is not None and k not in cls._no_update_fields and k not in cls.key_fields} vals = [table.c[k] != v for k, v in known_values.items()] val_filter = I2B2CoreWithUploadId._nested_fcn(or_, vals) known_values['update_date'] = record.update_date upd = update(table).where(and_(key_filter, val_filter)).values(known_values) num_updates += conn.execute(upd).rowcount else: inserts.append(as_dict(record)) if inserts: if cls._check_dups: dups = cls._check_for_dups(inserts) nprints = 0 if dups: print("{} duplicate records encountered".format(len(dups))) for k, vals in dups.items(): if len(vals) == 2 and vals[0] == vals[1]: inserts.remove(vals[1]) else: if nprints < 20: print("Key: {} has a non-identical dup".format(k)) elif nprints == 20: print(".... more ...") nprints += 1 for v in vals[1:]: inserts.remove(v) # TODO: refactor this to load on a per-resource basis. Temporary fix for insert in ListChunker(inserts, 500): num_inserts += conn.execute(table.insert(), insert).rowcount return num_inserts, num_updates
[ "def", "_add_or_update_records", "(", "cls", ",", "conn", ":", "Connection", ",", "table", ":", "Table", ",", "records", ":", "List", "[", "\"I2B2CoreWithUploadId\"", "]", ")", "->", "Tuple", "[", "int", ",", "int", "]", ":", "num_updates", "=", "0", "nu...
Add or update the supplied table as needed to reflect the contents of records :param table: i2b2 sql connection :param records: records to apply :return: number of records added / modified
[ "Add", "or", "update", "the", "supplied", "table", "as", "needed", "to", "reflect", "the", "contents", "of", "records" ]
train
https://github.com/BD2KOnFHIR/i2b2model/blob/9d49bb53b0733dd83ab5b716014865e270a3c903/i2b2model/shared/i2b2core.py#L79-L128
jacebrowning/comparable
comparable/compound.py
Group.equality
def equality(self, other): """Calculate equality based on equality of all group items.""" if not len(self) == len(other): return False return super().equality(other)
python
def equality(self, other): """Calculate equality based on equality of all group items.""" if not len(self) == len(other): return False return super().equality(other)
[ "def", "equality", "(", "self", ",", "other", ")", ":", "if", "not", "len", "(", "self", ")", "==", "len", "(", "other", ")", ":", "return", "False", "return", "super", "(", ")", ".", "equality", "(", "other", ")" ]
Calculate equality based on equality of all group items.
[ "Calculate", "equality", "based", "on", "equality", "of", "all", "group", "items", "." ]
train
https://github.com/jacebrowning/comparable/blob/48455e613650e22412d31109681368fcc479298d/comparable/compound.py#L42-L46
jacebrowning/comparable
comparable/compound.py
Group.similarity
def similarity(self, other): """Calculate similarity based on best matching permutation of items.""" # Select the longer list as the basis for comparison if len(self.items) > len(other.items): first, second = self, other else: first, second = other, self items = list(first.items) # backup items list length = len(items) sim = self.Similarity(0.0 if length else 1.0) # Calculate the similarity for each permutation of items cname = self.__class__.__name__ for num, perm in enumerate(permutations(items, length), start=1): first.items = perm aname = 'items-p{}'.format(num) self.log(first, second, '%', cname=cname, aname=aname) permutation_sim = super(Group, first).similarity(second) self.log(first, second, '%', cname=cname, aname=aname, result=permutation_sim) sim = max(sim, permutation_sim) logging.debug("highest similarity: %s", sim) first.items = items # restore original items list return sim
python
def similarity(self, other): """Calculate similarity based on best matching permutation of items.""" # Select the longer list as the basis for comparison if len(self.items) > len(other.items): first, second = self, other else: first, second = other, self items = list(first.items) # backup items list length = len(items) sim = self.Similarity(0.0 if length else 1.0) # Calculate the similarity for each permutation of items cname = self.__class__.__name__ for num, perm in enumerate(permutations(items, length), start=1): first.items = perm aname = 'items-p{}'.format(num) self.log(first, second, '%', cname=cname, aname=aname) permutation_sim = super(Group, first).similarity(second) self.log(first, second, '%', cname=cname, aname=aname, result=permutation_sim) sim = max(sim, permutation_sim) logging.debug("highest similarity: %s", sim) first.items = items # restore original items list return sim
[ "def", "similarity", "(", "self", ",", "other", ")", ":", "# Select the longer list as the basis for comparison", "if", "len", "(", "self", ".", "items", ")", ">", "len", "(", "other", ".", "items", ")", ":", "first", ",", "second", "=", "self", ",", "othe...
Calculate similarity based on best matching permutation of items.
[ "Calculate", "similarity", "based", "on", "best", "matching", "permutation", "of", "items", "." ]
train
https://github.com/jacebrowning/comparable/blob/48455e613650e22412d31109681368fcc479298d/comparable/compound.py#L48-L75
duniter/duniter-python-api
duniterpy/api/bma/network.py
peers
async def peers(client: Client, leaves: bool = False, leaf: str = "") -> dict: """ GET peering entries of every node inside the currency network :param client: Client to connect to the api :param leaves: True if leaves should be requested :param leaf: True if leaf should be requested :return: """ if leaves is True: return await client.get(MODULE + '/peering/peers', {"leaves": "true"}, schema=PEERS_SCHEMA) else: return await client.get(MODULE + '/peering/peers', {"leaf": leaf}, schema=PEERS_SCHEMA)
python
async def peers(client: Client, leaves: bool = False, leaf: str = "") -> dict: """ GET peering entries of every node inside the currency network :param client: Client to connect to the api :param leaves: True if leaves should be requested :param leaf: True if leaf should be requested :return: """ if leaves is True: return await client.get(MODULE + '/peering/peers', {"leaves": "true"}, schema=PEERS_SCHEMA) else: return await client.get(MODULE + '/peering/peers', {"leaf": leaf}, schema=PEERS_SCHEMA)
[ "async", "def", "peers", "(", "client", ":", "Client", ",", "leaves", ":", "bool", "=", "False", ",", "leaf", ":", "str", "=", "\"\"", ")", "->", "dict", ":", "if", "leaves", "is", "True", ":", "return", "await", "client", ".", "get", "(", "MODULE"...
GET peering entries of every node inside the currency network :param client: Client to connect to the api :param leaves: True if leaves should be requested :param leaf: True if leaf should be requested :return:
[ "GET", "peering", "entries", "of", "every", "node", "inside", "the", "currency", "network" ]
train
https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/api/bma/network.py#L117-L129
duniter/duniter-python-api
duniterpy/api/bma/network.py
peer
async def peer(client: Client, peer_signed_raw: str) -> ClientResponse: """ POST a Peer signed raw document :param client: Client to connect to the api :param peer_signed_raw: Peer signed raw document :return: """ return await client.post(MODULE + '/peering/peers', {'peer': peer_signed_raw}, rtype=RESPONSE_AIOHTTP)
python
async def peer(client: Client, peer_signed_raw: str) -> ClientResponse: """ POST a Peer signed raw document :param client: Client to connect to the api :param peer_signed_raw: Peer signed raw document :return: """ return await client.post(MODULE + '/peering/peers', {'peer': peer_signed_raw}, rtype=RESPONSE_AIOHTTP)
[ "async", "def", "peer", "(", "client", ":", "Client", ",", "peer_signed_raw", ":", "str", ")", "->", "ClientResponse", ":", "return", "await", "client", ".", "post", "(", "MODULE", "+", "'/peering/peers'", ",", "{", "'peer'", ":", "peer_signed_raw", "}", "...
POST a Peer signed raw document :param client: Client to connect to the api :param peer_signed_raw: Peer signed raw document :return:
[ "POST", "a", "Peer", "signed", "raw", "document" ]
train
https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/api/bma/network.py#L132-L140
mixmastamyk/fr
fr/linux.py
check_optical
def check_optical(disk): ''' Try to determine if a device is optical technology. Needs improvement. ''' dev = disk.dev if dev.startswith('sr') or ('cd' in dev): return True elif disk.fmt in optical_fs: return True else: return None
python
def check_optical(disk): ''' Try to determine if a device is optical technology. Needs improvement. ''' dev = disk.dev if dev.startswith('sr') or ('cd' in dev): return True elif disk.fmt in optical_fs: return True else: return None
[ "def", "check_optical", "(", "disk", ")", ":", "dev", "=", "disk", ".", "dev", "if", "dev", ".", "startswith", "(", "'sr'", ")", "or", "(", "'cd'", "in", "dev", ")", ":", "return", "True", "elif", "disk", ".", "fmt", "in", "optical_fs", ":", "retur...
Try to determine if a device is optical technology. Needs improvement.
[ "Try", "to", "determine", "if", "a", "device", "is", "optical", "technology", ".", "Needs", "improvement", "." ]
train
https://github.com/mixmastamyk/fr/blob/f96df8ed7210a033b9e711bbed768d4116213bfb/fr/linux.py#L59-L69
mixmastamyk/fr
fr/linux.py
check_removable
def check_removable(dev, opts): ''' Removable drives can be identified under /sys. ''' try: # get parent device from sys filesystem, look from right. :-/ parent = os.readlink(f'/sys/class/block/{dev}').rsplit("/", 2)[1] with open(f'/sys/block/{parent}/removable') as f: return f.read() == '1\n' except IndexError as err: if opts.debug: print('ERROR: parent block device not found.', err) except IOError as err: if opts.debug: print('ERROR:', err)
python
def check_removable(dev, opts): ''' Removable drives can be identified under /sys. ''' try: # get parent device from sys filesystem, look from right. :-/ parent = os.readlink(f'/sys/class/block/{dev}').rsplit("/", 2)[1] with open(f'/sys/block/{parent}/removable') as f: return f.read() == '1\n' except IndexError as err: if opts.debug: print('ERROR: parent block device not found.', err) except IOError as err: if opts.debug: print('ERROR:', err)
[ "def", "check_removable", "(", "dev", ",", "opts", ")", ":", "try", ":", "# get parent device from sys filesystem, look from right. :-/", "parent", "=", "os", ".", "readlink", "(", "f'/sys/class/block/{dev}'", ")", ".", "rsplit", "(", "\"/\"", ",", "2", ")", "[",...
Removable drives can be identified under /sys.
[ "Removable", "drives", "can", "be", "identified", "under", "/", "sys", "." ]
train
https://github.com/mixmastamyk/fr/blob/f96df8ed7210a033b9e711bbed768d4116213bfb/fr/linux.py#L72-L84
mixmastamyk/fr
fr/linux.py
decode_mntp
def decode_mntp(mntp): ''' Mount point strings have a unique encoding for whitespace. :-/ https://stackoverflow.com/a/13576641/450917 https://stackoverflow.com/a/6117124/450917 ''' import re replacements = { r'\\040': ' ', r'\\011': '\t', r'\\012': '\n', r'\\134': '\\', } pattern = re.compile('|'.join(replacements.keys())) return pattern.sub(lambda m: replacements[re.escape(m.group(0))], mntp)
python
def decode_mntp(mntp): ''' Mount point strings have a unique encoding for whitespace. :-/ https://stackoverflow.com/a/13576641/450917 https://stackoverflow.com/a/6117124/450917 ''' import re replacements = { r'\\040': ' ', r'\\011': '\t', r'\\012': '\n', r'\\134': '\\', } pattern = re.compile('|'.join(replacements.keys())) return pattern.sub(lambda m: replacements[re.escape(m.group(0))], mntp)
[ "def", "decode_mntp", "(", "mntp", ")", ":", "import", "re", "replacements", "=", "{", "r'\\\\040'", ":", "' '", ",", "r'\\\\011'", ":", "'\\t'", ",", "r'\\\\012'", ":", "'\\n'", ",", "r'\\\\134'", ":", "'\\\\'", ",", "}", "pattern", "=", "re", ".", "c...
Mount point strings have a unique encoding for whitespace. :-/ https://stackoverflow.com/a/13576641/450917 https://stackoverflow.com/a/6117124/450917
[ "Mount", "point", "strings", "have", "a", "unique", "encoding", "for", "whitespace", ".", ":", "-", "/", "https", ":", "//", "stackoverflow", ".", "com", "/", "a", "/", "13576641", "/", "450917", "https", ":", "//", "stackoverflow", ".", "com", "/", "a...
train
https://github.com/mixmastamyk/fr/blob/f96df8ed7210a033b9e711bbed768d4116213bfb/fr/linux.py#L87-L100
mixmastamyk/fr
fr/linux.py
get_label_map
def get_label_map(opts): ''' Find volume labels from filesystem and return in dict format. ''' results = {} try: for entry in os.scandir(diskdir): target = normpath(join(diskdir, os.readlink(entry.path))) decoded_name = entry.name.encode('utf8').decode('unicode_escape') results[target] = decoded_name if opts.debug: print('\n\nlabel_map:', results) except FileNotFoundError: pass return results
python
def get_label_map(opts): ''' Find volume labels from filesystem and return in dict format. ''' results = {} try: for entry in os.scandir(diskdir): target = normpath(join(diskdir, os.readlink(entry.path))) decoded_name = entry.name.encode('utf8').decode('unicode_escape') results[target] = decoded_name if opts.debug: print('\n\nlabel_map:', results) except FileNotFoundError: pass return results
[ "def", "get_label_map", "(", "opts", ")", ":", "results", "=", "{", "}", "try", ":", "for", "entry", "in", "os", ".", "scandir", "(", "diskdir", ")", ":", "target", "=", "normpath", "(", "join", "(", "diskdir", ",", "os", ".", "readlink", "(", "ent...
Find volume labels from filesystem and return in dict format.
[ "Find", "volume", "labels", "from", "filesystem", "and", "return", "in", "dict", "format", "." ]
train
https://github.com/mixmastamyk/fr/blob/f96df8ed7210a033b9e711bbed768d4116213bfb/fr/linux.py#L103-L115
mixmastamyk/fr
fr/linux.py
get_diskinfo
def get_diskinfo(opts, show_all=False, local_only=False): ''' Returns a list holding the current disk info. Stats are divided by the outputunit. ''' disks = [] outunit = opts.outunit label_map = get_label_map(opts) # get mount info try: with open(mntfname) as infile: lines = infile.readlines() lines.sort() except IOError: return None # build list of disks for i, line in enumerate(lines): device, mntp, fmt, mntops, *_ = line.split() if device in ('cgroup',): # never want these continue disk = DiskInfo() dev = basename(device) # short name disk.isnet = ':' in device # cheesy but works if local_only and disk.isnet: continue disk.isimg = is_img = dev.startswith('loop') # could be better is_tmpfs = (device == 'tmpfs') # lots of junk here, so we throw away most entries for selector in selectors: if selector in device: if show_all: if is_tmpfs: disk.isram = True else: # skip these: if (is_img or is_tmpfs or mntp == '/boot/efi'): continue break # found a useful entry, stop here else: # no-break, nothing was found continue # skip this one disk.dev = dev disk.fmt = fmt disk.mntp = mntp = decode_mntp(mntp) if '\\' in mntp else mntp disk.ismntd = bool(mntp) disk.isopt = check_optical(disk) if device[0] == '/': # .startswith('/dev'): disk.isrem = check_removable(dev, opts) disk.label = label_map.get(device) # get disk usage information # http://pubs.opengroup.org/onlinepubs/009695399/basedefs/sys/statvfs.h.html # convert to bytes, then output units stat = os.statvfs(mntp) disk.ocap = stat.f_frsize * stat.f_blocks # keep for later disk.cap = disk.ocap / outunit disk.free = stat.f_frsize * stat.f_bavail / outunit disk.oused = stat.f_frsize * (stat.f_blocks - stat.f_bfree) # for later disk.used = disk.oused / outunit disk.pcnt = disk.oused / disk.ocap * 100 if mntops.startswith('rw'): # read only disk.rw = True elif mntops.startswith('ro'): disk.rw = False else: disk.rw = not bool(stat.f_flag & os.ST_RDONLY) disks.append(disk) if show_all: # look at /dev/disks again for the unmounted for devname in label_map: dev = basename(devname) exists = [ disk for disk in disks if disk.dev == dev ] if not exists: disk = DiskInfo( cap=0, free=0, ocap=0, pcnt=0, used=0, dev = dev, ismntd = False, mntp = '', isnet = False, isopt = check_optical(DiskInfo(dev=dev, fmt=None)), isram = False, # no such thing? isrem = check_removable(dev, opts), label = label_map[devname], rw = None, ) disks.append(disk) disks.sort(key=lambda disk: disk.dev) # sort again :-/ if opts.debug: print() for disk in disks: print(disk.dev, disk) print() return disks
python
def get_diskinfo(opts, show_all=False, local_only=False): ''' Returns a list holding the current disk info. Stats are divided by the outputunit. ''' disks = [] outunit = opts.outunit label_map = get_label_map(opts) # get mount info try: with open(mntfname) as infile: lines = infile.readlines() lines.sort() except IOError: return None # build list of disks for i, line in enumerate(lines): device, mntp, fmt, mntops, *_ = line.split() if device in ('cgroup',): # never want these continue disk = DiskInfo() dev = basename(device) # short name disk.isnet = ':' in device # cheesy but works if local_only and disk.isnet: continue disk.isimg = is_img = dev.startswith('loop') # could be better is_tmpfs = (device == 'tmpfs') # lots of junk here, so we throw away most entries for selector in selectors: if selector in device: if show_all: if is_tmpfs: disk.isram = True else: # skip these: if (is_img or is_tmpfs or mntp == '/boot/efi'): continue break # found a useful entry, stop here else: # no-break, nothing was found continue # skip this one disk.dev = dev disk.fmt = fmt disk.mntp = mntp = decode_mntp(mntp) if '\\' in mntp else mntp disk.ismntd = bool(mntp) disk.isopt = check_optical(disk) if device[0] == '/': # .startswith('/dev'): disk.isrem = check_removable(dev, opts) disk.label = label_map.get(device) # get disk usage information # http://pubs.opengroup.org/onlinepubs/009695399/basedefs/sys/statvfs.h.html # convert to bytes, then output units stat = os.statvfs(mntp) disk.ocap = stat.f_frsize * stat.f_blocks # keep for later disk.cap = disk.ocap / outunit disk.free = stat.f_frsize * stat.f_bavail / outunit disk.oused = stat.f_frsize * (stat.f_blocks - stat.f_bfree) # for later disk.used = disk.oused / outunit disk.pcnt = disk.oused / disk.ocap * 100 if mntops.startswith('rw'): # read only disk.rw = True elif mntops.startswith('ro'): disk.rw = False else: disk.rw = not bool(stat.f_flag & os.ST_RDONLY) disks.append(disk) if show_all: # look at /dev/disks again for the unmounted for devname in label_map: dev = basename(devname) exists = [ disk for disk in disks if disk.dev == dev ] if not exists: disk = DiskInfo( cap=0, free=0, ocap=0, pcnt=0, used=0, dev = dev, ismntd = False, mntp = '', isnet = False, isopt = check_optical(DiskInfo(dev=dev, fmt=None)), isram = False, # no such thing? isrem = check_removable(dev, opts), label = label_map[devname], rw = None, ) disks.append(disk) disks.sort(key=lambda disk: disk.dev) # sort again :-/ if opts.debug: print() for disk in disks: print(disk.dev, disk) print() return disks
[ "def", "get_diskinfo", "(", "opts", ",", "show_all", "=", "False", ",", "local_only", "=", "False", ")", ":", "disks", "=", "[", "]", "outunit", "=", "opts", ".", "outunit", "label_map", "=", "get_label_map", "(", "opts", ")", "# get mount info", "try", ...
Returns a list holding the current disk info. Stats are divided by the outputunit.
[ "Returns", "a", "list", "holding", "the", "current", "disk", "info", ".", "Stats", "are", "divided", "by", "the", "outputunit", "." ]
train
https://github.com/mixmastamyk/fr/blob/f96df8ed7210a033b9e711bbed768d4116213bfb/fr/linux.py#L118-L216
mixmastamyk/fr
fr/linux.py
get_meminfo
def get_meminfo(opts): ''' Returns a dictionary holding the current memory info, divided by the ouptut unit. If mem info can't be read, returns None. ''' meminfo = MemInfo() outunit = opts.outunit try: with open(memfname) as infile: lines = infile.readlines() except IOError: return None for line in lines: # format: 'MemTotal: 511456 kB\n' tokens = line.split() if tokens: name, value = tokens[0][:-1].lower(), tokens[1] # rm : if len(tokens) == 2: continue unit = tokens[2].lower() # parse_result to bytes TODO value = int(value) if unit == 'kb': value = value * 1024 # most likely elif unit == 'b': value = value elif unit == 'mb': value = value * 1024 * 1024 elif unit == 'gb': value = value * 1024 * 1024 * 1024 setattr(meminfo, name, value / outunit) cache = meminfo.cached + meminfo.buffers meminfo.used = meminfo.memtotal - meminfo.memfree - cache meminfo.swapused = (meminfo.swaptotal - meminfo.swapcached - meminfo.swapfree) return meminfo
python
def get_meminfo(opts): ''' Returns a dictionary holding the current memory info, divided by the ouptut unit. If mem info can't be read, returns None. ''' meminfo = MemInfo() outunit = opts.outunit try: with open(memfname) as infile: lines = infile.readlines() except IOError: return None for line in lines: # format: 'MemTotal: 511456 kB\n' tokens = line.split() if tokens: name, value = tokens[0][:-1].lower(), tokens[1] # rm : if len(tokens) == 2: continue unit = tokens[2].lower() # parse_result to bytes TODO value = int(value) if unit == 'kb': value = value * 1024 # most likely elif unit == 'b': value = value elif unit == 'mb': value = value * 1024 * 1024 elif unit == 'gb': value = value * 1024 * 1024 * 1024 setattr(meminfo, name, value / outunit) cache = meminfo.cached + meminfo.buffers meminfo.used = meminfo.memtotal - meminfo.memfree - cache meminfo.swapused = (meminfo.swaptotal - meminfo.swapcached - meminfo.swapfree) return meminfo
[ "def", "get_meminfo", "(", "opts", ")", ":", "meminfo", "=", "MemInfo", "(", ")", "outunit", "=", "opts", ".", "outunit", "try", ":", "with", "open", "(", "memfname", ")", "as", "infile", ":", "lines", "=", "infile", ".", "readlines", "(", ")", "exce...
Returns a dictionary holding the current memory info, divided by the ouptut unit. If mem info can't be read, returns None.
[ "Returns", "a", "dictionary", "holding", "the", "current", "memory", "info", "divided", "by", "the", "ouptut", "unit", ".", "If", "mem", "info", "can", "t", "be", "read", "returns", "None", "." ]
train
https://github.com/mixmastamyk/fr/blob/f96df8ed7210a033b9e711bbed768d4116213bfb/fr/linux.py#L219-L252
etcher-be/epab
epab/utils/_timeit.py
timeit
def timeit(func): """ Simple decorator to time functions :param func: function to decorate :type func: callable :return: wrapped function :rtype: callable """ @wraps(func) def _wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) elapsed = time.time() - start LOGGER.info('%s took %s seconds to complete', func.__name__, round(elapsed, 2)) return result return _wrapper
python
def timeit(func): """ Simple decorator to time functions :param func: function to decorate :type func: callable :return: wrapped function :rtype: callable """ @wraps(func) def _wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) elapsed = time.time() - start LOGGER.info('%s took %s seconds to complete', func.__name__, round(elapsed, 2)) return result return _wrapper
[ "def", "timeit", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "_wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "start", "=", "time", ".", "time", "(", ")", "result", "=", "func", "(", "*", "args", ",", "*", "*...
Simple decorator to time functions :param func: function to decorate :type func: callable :return: wrapped function :rtype: callable
[ "Simple", "decorator", "to", "time", "functions" ]
train
https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/utils/_timeit.py#L12-L32
Synerty/peek-plugin-base
peek_plugin_base/worker/CeleryDbConn.py
setConnStringForWindows
def setConnStringForWindows(): """ Set Conn String for Windiws Windows has a different way of forking processes, which causes the @worker_process_init.connect signal not to work in "CeleryDbConnInit" """ global _dbConnectString from peek_platform.file_config.PeekFileConfigABC import PeekFileConfigABC from peek_platform.file_config.PeekFileConfigSqlAlchemyMixin import \ PeekFileConfigSqlAlchemyMixin from peek_platform import PeekPlatformConfig class _WorkerTaskConfigMixin(PeekFileConfigABC, PeekFileConfigSqlAlchemyMixin): pass PeekPlatformConfig.componentName = peekWorkerName _dbConnectString = _WorkerTaskConfigMixin().dbConnectString
python
def setConnStringForWindows(): """ Set Conn String for Windiws Windows has a different way of forking processes, which causes the @worker_process_init.connect signal not to work in "CeleryDbConnInit" """ global _dbConnectString from peek_platform.file_config.PeekFileConfigABC import PeekFileConfigABC from peek_platform.file_config.PeekFileConfigSqlAlchemyMixin import \ PeekFileConfigSqlAlchemyMixin from peek_platform import PeekPlatformConfig class _WorkerTaskConfigMixin(PeekFileConfigABC, PeekFileConfigSqlAlchemyMixin): pass PeekPlatformConfig.componentName = peekWorkerName _dbConnectString = _WorkerTaskConfigMixin().dbConnectString
[ "def", "setConnStringForWindows", "(", ")", ":", "global", "_dbConnectString", "from", "peek_platform", ".", "file_config", ".", "PeekFileConfigABC", "import", "PeekFileConfigABC", "from", "peek_platform", ".", "file_config", ".", "PeekFileConfigSqlAlchemyMixin", "import", ...
Set Conn String for Windiws Windows has a different way of forking processes, which causes the @worker_process_init.connect signal not to work in "CeleryDbConnInit"
[ "Set", "Conn", "String", "for", "Windiws" ]
train
https://github.com/Synerty/peek-plugin-base/blob/276101d028e1ee0678af514c761b74cce5a5cda9/peek_plugin_base/worker/CeleryDbConn.py#L20-L40
Synerty/peek-plugin-base
peek_plugin_base/worker/CeleryDbConn.py
prefetchDeclarativeIds
def prefetchDeclarativeIds(Declarative, count) -> Optional[Iterable[int]]: """ Prefetch Declarative IDs This function prefetches a chunk of IDs from a database sequence. Doing this allows us to preallocate the IDs before an insert, which significantly speeds up : * Orm inserts, especially those using inheritance * When we need the ID to assign it to a related object that we're also inserting. :param Declarative: The SQLAlchemy declarative class. (The class that inherits from DeclarativeBase) :param count: The number of IDs to prefetch :return: An iterable that dispenses the new IDs """ return _commonPrefetchDeclarativeIds( getDbEngine(), _sequenceMutex, Declarative, count )
python
def prefetchDeclarativeIds(Declarative, count) -> Optional[Iterable[int]]: """ Prefetch Declarative IDs This function prefetches a chunk of IDs from a database sequence. Doing this allows us to preallocate the IDs before an insert, which significantly speeds up : * Orm inserts, especially those using inheritance * When we need the ID to assign it to a related object that we're also inserting. :param Declarative: The SQLAlchemy declarative class. (The class that inherits from DeclarativeBase) :param count: The number of IDs to prefetch :return: An iterable that dispenses the new IDs """ return _commonPrefetchDeclarativeIds( getDbEngine(), _sequenceMutex, Declarative, count )
[ "def", "prefetchDeclarativeIds", "(", "Declarative", ",", "count", ")", "->", "Optional", "[", "Iterable", "[", "int", "]", "]", ":", "return", "_commonPrefetchDeclarativeIds", "(", "getDbEngine", "(", ")", ",", "_sequenceMutex", ",", "Declarative", ",", "count"...
Prefetch Declarative IDs This function prefetches a chunk of IDs from a database sequence. Doing this allows us to preallocate the IDs before an insert, which significantly speeds up : * Orm inserts, especially those using inheritance * When we need the ID to assign it to a related object that we're also inserting. :param Declarative: The SQLAlchemy declarative class. (The class that inherits from DeclarativeBase) :param count: The number of IDs to prefetch :return: An iterable that dispenses the new IDs
[ "Prefetch", "Declarative", "IDs" ]
train
https://github.com/Synerty/peek-plugin-base/blob/276101d028e1ee0678af514c761b74cce5a5cda9/peek_plugin_base/worker/CeleryDbConn.py#L83-L102
benley/butcher
butcher/rubygems.py
install_gem
def install_gem(gemname, version=None, conservative=True, ri=False, rdoc=False, development=False, format_executable=False, force=False, gem_source=None): """Install a ruby gem.""" cmdline = ['gem', 'install'] if conservative: cmdline.append('--conservative') if ri: cmdline.append('--ri') else: cmdline.append('--no-ri') if rdoc: cmdline.append('--rdoc') else: cmdline.append('--no-rdoc') if development: cmdline.append('--development') if format_executable: cmdline.append('--format-executable') if force: cmdline.append('--force') if version: cmdline.extend(['--version', version]) cmdline.extend(['--clear-sources', '--source', gem_source or RubyGems().gem_source]) cmdline.append(gemname) msg = 'Installing ruby gem: %s' % gemname if version: msg += ' Version requested: %s' % version log.debug(msg) try: subprocess.check_output(cmdline, shell=False) except (OSError, subprocess.CalledProcessError) as err: raise error.ButcherError( 'Gem install failed. Error was: %s. Output: %s' % ( err, err.output))
python
def install_gem(gemname, version=None, conservative=True, ri=False, rdoc=False, development=False, format_executable=False, force=False, gem_source=None): """Install a ruby gem.""" cmdline = ['gem', 'install'] if conservative: cmdline.append('--conservative') if ri: cmdline.append('--ri') else: cmdline.append('--no-ri') if rdoc: cmdline.append('--rdoc') else: cmdline.append('--no-rdoc') if development: cmdline.append('--development') if format_executable: cmdline.append('--format-executable') if force: cmdline.append('--force') if version: cmdline.extend(['--version', version]) cmdline.extend(['--clear-sources', '--source', gem_source or RubyGems().gem_source]) cmdline.append(gemname) msg = 'Installing ruby gem: %s' % gemname if version: msg += ' Version requested: %s' % version log.debug(msg) try: subprocess.check_output(cmdline, shell=False) except (OSError, subprocess.CalledProcessError) as err: raise error.ButcherError( 'Gem install failed. Error was: %s. Output: %s' % ( err, err.output))
[ "def", "install_gem", "(", "gemname", ",", "version", "=", "None", ",", "conservative", "=", "True", ",", "ri", "=", "False", ",", "rdoc", "=", "False", ",", "development", "=", "False", ",", "format_executable", "=", "False", ",", "force", "=", "False",...
Install a ruby gem.
[ "Install", "a", "ruby", "gem", "." ]
train
https://github.com/benley/butcher/blob/8b18828ea040af56b7835beab5fd03eab23cc9ee/butcher/rubygems.py#L58-L96
benley/butcher
butcher/rubygems.py
is_installed
def is_installed(gemname, version=None): """Check if a gem is installed.""" cmdline = ['gem', 'list', '-i', gemname] if version: cmdline.extend(['-v', version]) try: subprocess.check_output(cmdline, shell=False) return True except (OSError, subprocess.CalledProcessError) as err: if err.returncode == 1: return False else: raise error.ButcherError( 'Failure running gem. Error was: %s. Output: %s', err, err.output)
python
def is_installed(gemname, version=None): """Check if a gem is installed.""" cmdline = ['gem', 'list', '-i', gemname] if version: cmdline.extend(['-v', version]) try: subprocess.check_output(cmdline, shell=False) return True except (OSError, subprocess.CalledProcessError) as err: if err.returncode == 1: return False else: raise error.ButcherError( 'Failure running gem. Error was: %s. Output: %s', err, err.output)
[ "def", "is_installed", "(", "gemname", ",", "version", "=", "None", ")", ":", "cmdline", "=", "[", "'gem'", ",", "'list'", ",", "'-i'", ",", "gemname", "]", "if", "version", ":", "cmdline", ".", "extend", "(", "[", "'-v'", ",", "version", "]", ")", ...
Check if a gem is installed.
[ "Check", "if", "a", "gem", "is", "installed", "." ]
train
https://github.com/benley/butcher/blob/8b18828ea040af56b7835beab5fd03eab23cc9ee/butcher/rubygems.py#L99-L113
ajyoon/blur
blur/markov/node.py
Node.merge_links_from
def merge_links_from(self, other_node, merge_same_value_targets=False): """ Merge links from another node with ``self.link_list``. Copy links from another node, merging when copied links point to a node which this already links to. Args: other_node (Node): The node to merge links from merge_same_value_targets (bool): Whether or not to merge links whose targets have the same value (but are not necessarily the same ``Node``). If False, links will only be merged when ``link_in_other.target == link_in_self.target``. If True, links will be merged when ``link_in_other.target.value == link_in_self.target.value`` Returns: None Example: >>> node_1 = Node('One') >>> node_2 = Node('Two') >>> node_1.add_link(node_1, 1) >>> node_1.add_link(node_2, 3) >>> node_2.add_link(node_1, 4) >>> node_1.merge_links_from(node_2) >>> print(node_1) node.Node instance with value One with 2 links: 0: 5 --> One 1: 3 --> Two """ for other_link in other_node.link_list: for existing_link in self.link_list: if merge_same_value_targets: if other_link.target.value == existing_link.target.value: existing_link.weight += other_link.weight break else: if other_link.target == existing_link.target: existing_link.weight += other_link.weight break else: self.add_link(other_link.target, other_link.weight)
python
def merge_links_from(self, other_node, merge_same_value_targets=False): """ Merge links from another node with ``self.link_list``. Copy links from another node, merging when copied links point to a node which this already links to. Args: other_node (Node): The node to merge links from merge_same_value_targets (bool): Whether or not to merge links whose targets have the same value (but are not necessarily the same ``Node``). If False, links will only be merged when ``link_in_other.target == link_in_self.target``. If True, links will be merged when ``link_in_other.target.value == link_in_self.target.value`` Returns: None Example: >>> node_1 = Node('One') >>> node_2 = Node('Two') >>> node_1.add_link(node_1, 1) >>> node_1.add_link(node_2, 3) >>> node_2.add_link(node_1, 4) >>> node_1.merge_links_from(node_2) >>> print(node_1) node.Node instance with value One with 2 links: 0: 5 --> One 1: 3 --> Two """ for other_link in other_node.link_list: for existing_link in self.link_list: if merge_same_value_targets: if other_link.target.value == existing_link.target.value: existing_link.weight += other_link.weight break else: if other_link.target == existing_link.target: existing_link.weight += other_link.weight break else: self.add_link(other_link.target, other_link.weight)
[ "def", "merge_links_from", "(", "self", ",", "other_node", ",", "merge_same_value_targets", "=", "False", ")", ":", "for", "other_link", "in", "other_node", ".", "link_list", ":", "for", "existing_link", "in", "self", ".", "link_list", ":", "if", "merge_same_val...
Merge links from another node with ``self.link_list``. Copy links from another node, merging when copied links point to a node which this already links to. Args: other_node (Node): The node to merge links from merge_same_value_targets (bool): Whether or not to merge links whose targets have the same value (but are not necessarily the same ``Node``). If False, links will only be merged when ``link_in_other.target == link_in_self.target``. If True, links will be merged when ``link_in_other.target.value == link_in_self.target.value`` Returns: None Example: >>> node_1 = Node('One') >>> node_2 = Node('Two') >>> node_1.add_link(node_1, 1) >>> node_1.add_link(node_2, 3) >>> node_2.add_link(node_1, 4) >>> node_1.merge_links_from(node_2) >>> print(node_1) node.Node instance with value One with 2 links: 0: 5 --> One 1: 3 --> Two
[ "Merge", "links", "from", "another", "node", "with", "self", ".", "link_list", "." ]
train
https://github.com/ajyoon/blur/blob/25fcf083af112bb003956a7a7e1c6ff7d8fef279/blur/markov/node.py#L66-L107
ajyoon/blur
blur/markov/node.py
Node.find_link
def find_link(self, target_node): """ Find the link that points to ``target_node`` if it exists. If no link in ``self`` points to ``target_node``, return None Args: target_node (Node): The node to look for in ``self.link_list`` Returns: Link: An existing link pointing to ``target_node`` if found None: If no such link exists Example: >>> node_1 = Node('One') >>> node_2 = Node('Two') >>> node_1.add_link(node_2, 1) >>> link_1 = node_1.link_list[0] >>> found_link = node_1.find_link(node_2) >>> found_link == link_1 True """ try: return next(l for l in self.link_list if l.target == target_node) except StopIteration: return None
python
def find_link(self, target_node): """ Find the link that points to ``target_node`` if it exists. If no link in ``self`` points to ``target_node``, return None Args: target_node (Node): The node to look for in ``self.link_list`` Returns: Link: An existing link pointing to ``target_node`` if found None: If no such link exists Example: >>> node_1 = Node('One') >>> node_2 = Node('Two') >>> node_1.add_link(node_2, 1) >>> link_1 = node_1.link_list[0] >>> found_link = node_1.find_link(node_2) >>> found_link == link_1 True """ try: return next(l for l in self.link_list if l.target == target_node) except StopIteration: return None
[ "def", "find_link", "(", "self", ",", "target_node", ")", ":", "try", ":", "return", "next", "(", "l", "for", "l", "in", "self", ".", "link_list", "if", "l", ".", "target", "==", "target_node", ")", "except", "StopIteration", ":", "return", "None" ]
Find the link that points to ``target_node`` if it exists. If no link in ``self`` points to ``target_node``, return None Args: target_node (Node): The node to look for in ``self.link_list`` Returns: Link: An existing link pointing to ``target_node`` if found None: If no such link exists Example: >>> node_1 = Node('One') >>> node_2 = Node('Two') >>> node_1.add_link(node_2, 1) >>> link_1 = node_1.link_list[0] >>> found_link = node_1.find_link(node_2) >>> found_link == link_1 True
[ "Find", "the", "link", "that", "points", "to", "target_node", "if", "it", "exists", "." ]
train
https://github.com/ajyoon/blur/blob/25fcf083af112bb003956a7a7e1c6ff7d8fef279/blur/markov/node.py#L109-L135
ajyoon/blur
blur/markov/node.py
Node.add_link
def add_link(self, targets, weight): """ Add link(s) pointing to ``targets``. If a link already exists pointing to a target, just add ``weight`` to that link's weight Args: targets (Node or list[Node]): node or nodes to link to weight (int or float): weight for the new link(s) Returns: None Example: >>> node_1 = Node('One') >>> node_2 = Node('Two') >>> node_1.add_link(node_2, 1) >>> new_link = node_1.link_list[0] >>> print(new_link) node.Link instance pointing to node with value "Two" with weight 1 """ # Generalize targets to a list to simplify code if not isinstance(targets, list): target_list = [targets] else: target_list = targets for target in target_list: # Check to see if self already has a link to target for existing_link in self.link_list: if existing_link.target == target: existing_link.weight += weight break else: self.link_list.append(Link(target, weight))
python
def add_link(self, targets, weight): """ Add link(s) pointing to ``targets``. If a link already exists pointing to a target, just add ``weight`` to that link's weight Args: targets (Node or list[Node]): node or nodes to link to weight (int or float): weight for the new link(s) Returns: None Example: >>> node_1 = Node('One') >>> node_2 = Node('Two') >>> node_1.add_link(node_2, 1) >>> new_link = node_1.link_list[0] >>> print(new_link) node.Link instance pointing to node with value "Two" with weight 1 """ # Generalize targets to a list to simplify code if not isinstance(targets, list): target_list = [targets] else: target_list = targets for target in target_list: # Check to see if self already has a link to target for existing_link in self.link_list: if existing_link.target == target: existing_link.weight += weight break else: self.link_list.append(Link(target, weight))
[ "def", "add_link", "(", "self", ",", "targets", ",", "weight", ")", ":", "# Generalize targets to a list to simplify code", "if", "not", "isinstance", "(", "targets", ",", "list", ")", ":", "target_list", "=", "[", "targets", "]", "else", ":", "target_list", "...
Add link(s) pointing to ``targets``. If a link already exists pointing to a target, just add ``weight`` to that link's weight Args: targets (Node or list[Node]): node or nodes to link to weight (int or float): weight for the new link(s) Returns: None Example: >>> node_1 = Node('One') >>> node_2 = Node('Two') >>> node_1.add_link(node_2, 1) >>> new_link = node_1.link_list[0] >>> print(new_link) node.Link instance pointing to node with value "Two" with weight 1
[ "Add", "link", "(", "s", ")", "pointing", "to", "targets", "." ]
train
https://github.com/ajyoon/blur/blob/25fcf083af112bb003956a7a7e1c6ff7d8fef279/blur/markov/node.py#L137-L171
ajyoon/blur
blur/markov/node.py
Node.add_link_to_self
def add_link_to_self(self, source, weight): """ Create and add a ``Link`` from a source node to ``self``. Args: source (Node): The node that will own the new ``Link`` pointing to ``self`` weight (int or float): The weight of the newly created ``Link`` Returns: None Example: >>> node_1 = Node('One') >>> node_2 = Node('Two') >>> node_1.add_link_to_self(node_2, 5) >>> new_link = node_2.link_list[0] >>> print('{} {}'.format(new_link.target.value, new_link.weight)) One 5 >>> print(new_link) node.Link instance pointing to node with value "One" with weight 5 """ # Generalize source to a list to simplify code if not isinstance(source, list): source = [source] for source_node in source: source_node.add_link(self, weight=weight)
python
def add_link_to_self(self, source, weight): """ Create and add a ``Link`` from a source node to ``self``. Args: source (Node): The node that will own the new ``Link`` pointing to ``self`` weight (int or float): The weight of the newly created ``Link`` Returns: None Example: >>> node_1 = Node('One') >>> node_2 = Node('Two') >>> node_1.add_link_to_self(node_2, 5) >>> new_link = node_2.link_list[0] >>> print('{} {}'.format(new_link.target.value, new_link.weight)) One 5 >>> print(new_link) node.Link instance pointing to node with value "One" with weight 5 """ # Generalize source to a list to simplify code if not isinstance(source, list): source = [source] for source_node in source: source_node.add_link(self, weight=weight)
[ "def", "add_link_to_self", "(", "self", ",", "source", ",", "weight", ")", ":", "# Generalize source to a list to simplify code", "if", "not", "isinstance", "(", "source", ",", "list", ")", ":", "source", "=", "[", "source", "]", "for", "source_node", "in", "s...
Create and add a ``Link`` from a source node to ``self``. Args: source (Node): The node that will own the new ``Link`` pointing to ``self`` weight (int or float): The weight of the newly created ``Link`` Returns: None Example: >>> node_1 = Node('One') >>> node_2 = Node('Two') >>> node_1.add_link_to_self(node_2, 5) >>> new_link = node_2.link_list[0] >>> print('{} {}'.format(new_link.target.value, new_link.weight)) One 5 >>> print(new_link) node.Link instance pointing to node with value "One" with weight 5
[ "Create", "and", "add", "a", "Link", "from", "a", "source", "node", "to", "self", "." ]
train
https://github.com/ajyoon/blur/blob/25fcf083af112bb003956a7a7e1c6ff7d8fef279/blur/markov/node.py#L173-L198
ajyoon/blur
blur/markov/node.py
Node.add_reciprocal_link
def add_reciprocal_link(self, target, weight): """ Add links pointing in either direction between ``self`` and ``target``. This creates a ``Link`` from ``self`` to ``target`` and a ``Link`` from ``target`` to ``self`` of equal weight. If ``target`` is a list of ``Node`` 's, repeat this for each one. Args: target (Node or list[Node]): weight (int or float): Returns: None Example: >>> node_1 = Node('One') >>> node_2 = Node('Two') >>> node_1.add_reciprocal_link(node_2, 5) >>> new_link_1 = node_1.link_list[0] >>> new_link_2 = node_2.link_list[0] >>> print(new_link_1) node.Link instance pointing to node with value "Two" with weight 5 >>> print(new_link_2) node.Link instance pointing to node with value "One" with weight 5 """ # Generalize ``target`` to a list if not isinstance(target, list): target_list = [target] else: target_list = target for t in target_list: self.add_link(t, weight) t.add_link(self, weight)
python
def add_reciprocal_link(self, target, weight): """ Add links pointing in either direction between ``self`` and ``target``. This creates a ``Link`` from ``self`` to ``target`` and a ``Link`` from ``target`` to ``self`` of equal weight. If ``target`` is a list of ``Node`` 's, repeat this for each one. Args: target (Node or list[Node]): weight (int or float): Returns: None Example: >>> node_1 = Node('One') >>> node_2 = Node('Two') >>> node_1.add_reciprocal_link(node_2, 5) >>> new_link_1 = node_1.link_list[0] >>> new_link_2 = node_2.link_list[0] >>> print(new_link_1) node.Link instance pointing to node with value "Two" with weight 5 >>> print(new_link_2) node.Link instance pointing to node with value "One" with weight 5 """ # Generalize ``target`` to a list if not isinstance(target, list): target_list = [target] else: target_list = target for t in target_list: self.add_link(t, weight) t.add_link(self, weight)
[ "def", "add_reciprocal_link", "(", "self", ",", "target", ",", "weight", ")", ":", "# Generalize ``target`` to a list", "if", "not", "isinstance", "(", "target", ",", "list", ")", ":", "target_list", "=", "[", "target", "]", "else", ":", "target_list", "=", ...
Add links pointing in either direction between ``self`` and ``target``. This creates a ``Link`` from ``self`` to ``target`` and a ``Link`` from ``target`` to ``self`` of equal weight. If ``target`` is a list of ``Node`` 's, repeat this for each one. Args: target (Node or list[Node]): weight (int or float): Returns: None Example: >>> node_1 = Node('One') >>> node_2 = Node('Two') >>> node_1.add_reciprocal_link(node_2, 5) >>> new_link_1 = node_1.link_list[0] >>> new_link_2 = node_2.link_list[0] >>> print(new_link_1) node.Link instance pointing to node with value "Two" with weight 5 >>> print(new_link_2) node.Link instance pointing to node with value "One" with weight 5
[ "Add", "links", "pointing", "in", "either", "direction", "between", "self", "and", "target", "." ]
train
https://github.com/ajyoon/blur/blob/25fcf083af112bb003956a7a7e1c6ff7d8fef279/blur/markov/node.py#L200-L232
ajyoon/blur
blur/markov/node.py
Node.remove_links_to_self
def remove_links_to_self(self): """ Remove any link in ``self.link_list`` whose ``target`` is ``self``. Returns: None Example: >>> node_1 = Node('One') >>> node_1.add_link(node_1, 5) >>> node_1.remove_links_to_self() >>> len(node_1.link_list) 0 """ self.link_list = [link for link in self.link_list if link.target != self]
python
def remove_links_to_self(self): """ Remove any link in ``self.link_list`` whose ``target`` is ``self``. Returns: None Example: >>> node_1 = Node('One') >>> node_1.add_link(node_1, 5) >>> node_1.remove_links_to_self() >>> len(node_1.link_list) 0 """ self.link_list = [link for link in self.link_list if link.target != self]
[ "def", "remove_links_to_self", "(", "self", ")", ":", "self", ".", "link_list", "=", "[", "link", "for", "link", "in", "self", ".", "link_list", "if", "link", ".", "target", "!=", "self", "]" ]
Remove any link in ``self.link_list`` whose ``target`` is ``self``. Returns: None Example: >>> node_1 = Node('One') >>> node_1.add_link(node_1, 5) >>> node_1.remove_links_to_self() >>> len(node_1.link_list) 0
[ "Remove", "any", "link", "in", "self", ".", "link_list", "whose", "target", "is", "self", "." ]
train
https://github.com/ajyoon/blur/blob/25fcf083af112bb003956a7a7e1c6ff7d8fef279/blur/markov/node.py#L234-L248
Aluriak/ACCC
accc/compiler/compiler.py
Compiler.compile
def compile(self, source_code, post_treatment=''.join): """Compile given source code. Return object code, modified by given post treatment. """ # read structure structure = self._structure(source_code) values = self._struct_to_values(structure, source_code) # create object code, translated in targeted language obj_code = langspec.translated( structure, values, self.target_lang_spec ) # apply post treatment and return return obj_code if post_treatment is None else post_treatment(obj_code)
python
def compile(self, source_code, post_treatment=''.join): """Compile given source code. Return object code, modified by given post treatment. """ # read structure structure = self._structure(source_code) values = self._struct_to_values(structure, source_code) # create object code, translated in targeted language obj_code = langspec.translated( structure, values, self.target_lang_spec ) # apply post treatment and return return obj_code if post_treatment is None else post_treatment(obj_code)
[ "def", "compile", "(", "self", ",", "source_code", ",", "post_treatment", "=", "''", ".", "join", ")", ":", "# read structure", "structure", "=", "self", ".", "_structure", "(", "source_code", ")", "values", "=", "self", ".", "_struct_to_values", "(", "struc...
Compile given source code. Return object code, modified by given post treatment.
[ "Compile", "given", "source", "code", ".", "Return", "object", "code", "modified", "by", "given", "post", "treatment", "." ]
train
https://github.com/Aluriak/ACCC/blob/9092f985bef7ed784264c86bc19c980f4ce2309f/accc/compiler/compiler.py#L121-L134
Aluriak/ACCC
accc/compiler/compiler.py
Compiler._initialize_tables
def _initialize_tables(self): """Create tables for structure and values, word->vocabulary""" # structure table self.table_struct, self.idnt_struct_size = self._create_struct_table() # values table self.table_values, self.idnt_values_size = self._create_values_table()
python
def _initialize_tables(self): """Create tables for structure and values, word->vocabulary""" # structure table self.table_struct, self.idnt_struct_size = self._create_struct_table() # values table self.table_values, self.idnt_values_size = self._create_values_table()
[ "def", "_initialize_tables", "(", "self", ")", ":", "# structure table", "self", ".", "table_struct", ",", "self", ".", "idnt_struct_size", "=", "self", ".", "_create_struct_table", "(", ")", "# values table", "self", ".", "table_values", ",", "self", ".", "idnt...
Create tables for structure and values, word->vocabulary
[ "Create", "tables", "for", "structure", "and", "values", "word", "-", ">", "vocabulary" ]
train
https://github.com/Aluriak/ACCC/blob/9092f985bef7ed784264c86bc19c980f4ce2309f/accc/compiler/compiler.py#L138-L143
Aluriak/ACCC
accc/compiler/compiler.py
Compiler._structure
def _structure(self, source_code): """return structure in ACDP format.""" # define cutter as a per block reader def cutter(seq, block_size): for index in range(0, len(seq), block_size): lexem = seq[index:index+block_size] if len(lexem) == block_size: yield self.table_struct[seq[index:index+block_size]] return tuple(cutter(source_code, self.idnt_struct_size))
python
def _structure(self, source_code): """return structure in ACDP format.""" # define cutter as a per block reader def cutter(seq, block_size): for index in range(0, len(seq), block_size): lexem = seq[index:index+block_size] if len(lexem) == block_size: yield self.table_struct[seq[index:index+block_size]] return tuple(cutter(source_code, self.idnt_struct_size))
[ "def", "_structure", "(", "self", ",", "source_code", ")", ":", "# define cutter as a per block reader", "def", "cutter", "(", "seq", ",", "block_size", ")", ":", "for", "index", "in", "range", "(", "0", ",", "len", "(", "seq", ")", ",", "block_size", ")",...
return structure in ACDP format.
[ "return", "structure", "in", "ACDP", "format", "." ]
train
https://github.com/Aluriak/ACCC/blob/9092f985bef7ed784264c86bc19c980f4ce2309f/accc/compiler/compiler.py#L150-L158
Aluriak/ACCC
accc/compiler/compiler.py
Compiler._next_lexem
def _next_lexem(self, lexem_type, source_code, source_code_size): """Return next readable lexem of given type in source_code. If no value can be found, the neutral_value will be used""" # define reader as a lexem extractor def reader(seq, block_size): identificator = '' for char in source_code: if len(identificator) == self.idnt_values_size[lexem_type]: yield self.table_values[lexem_type][identificator] identificator = '' identificator += char lexem_reader = reader(source_code, self.idnt_values_size) lexem = None time_out = 0 while lexem == None and time_out < 2*source_code_size: lexem = next(lexem_reader) time_out += 1 # here we have found a lexem return lexem
python
def _next_lexem(self, lexem_type, source_code, source_code_size): """Return next readable lexem of given type in source_code. If no value can be found, the neutral_value will be used""" # define reader as a lexem extractor def reader(seq, block_size): identificator = '' for char in source_code: if len(identificator) == self.idnt_values_size[lexem_type]: yield self.table_values[lexem_type][identificator] identificator = '' identificator += char lexem_reader = reader(source_code, self.idnt_values_size) lexem = None time_out = 0 while lexem == None and time_out < 2*source_code_size: lexem = next(lexem_reader) time_out += 1 # here we have found a lexem return lexem
[ "def", "_next_lexem", "(", "self", ",", "lexem_type", ",", "source_code", ",", "source_code_size", ")", ":", "# define reader as a lexem extractor", "def", "reader", "(", "seq", ",", "block_size", ")", ":", "identificator", "=", "''", "for", "char", "in", "sourc...
Return next readable lexem of given type in source_code. If no value can be found, the neutral_value will be used
[ "Return", "next", "readable", "lexem", "of", "given", "type", "in", "source_code", ".", "If", "no", "value", "can", "be", "found", "the", "neutral_value", "will", "be", "used" ]
train
https://github.com/Aluriak/ACCC/blob/9092f985bef7ed784264c86bc19c980f4ce2309f/accc/compiler/compiler.py#L160-L178
Aluriak/ACCC
accc/compiler/compiler.py
Compiler._next_condition_lexems
def _next_condition_lexems(self, source_code, source_code_size): """Return condition lexem readed in source_code""" # find three lexems lexems = tuple(( self._next_lexem(LEXEM_TYPE_COMPARISON, source_code, source_code_size), self._next_lexem(LEXEM_TYPE_OPERATOR , source_code, source_code_size), self._next_lexem(LEXEM_TYPE_COMPARISON, source_code, source_code_size) )) # verify integrity if None in lexems: # one of the condition lexem was not found in source code return None else: # all lexems are valid return ' '.join(lexems)
python
def _next_condition_lexems(self, source_code, source_code_size): """Return condition lexem readed in source_code""" # find three lexems lexems = tuple(( self._next_lexem(LEXEM_TYPE_COMPARISON, source_code, source_code_size), self._next_lexem(LEXEM_TYPE_OPERATOR , source_code, source_code_size), self._next_lexem(LEXEM_TYPE_COMPARISON, source_code, source_code_size) )) # verify integrity if None in lexems: # one of the condition lexem was not found in source code return None else: # all lexems are valid return ' '.join(lexems)
[ "def", "_next_condition_lexems", "(", "self", ",", "source_code", ",", "source_code_size", ")", ":", "# find three lexems", "lexems", "=", "tuple", "(", "(", "self", ".", "_next_lexem", "(", "LEXEM_TYPE_COMPARISON", ",", "source_code", ",", "source_code_size", ")", ...
Return condition lexem readed in source_code
[ "Return", "condition", "lexem", "readed", "in", "source_code" ]
train
https://github.com/Aluriak/ACCC/blob/9092f985bef7ed784264c86bc19c980f4ce2309f/accc/compiler/compiler.py#L180-L192
Aluriak/ACCC
accc/compiler/compiler.py
Compiler._string_to_int
def _string_to_int(self, s): """Read an integer in s, in Little Indian. """ base = len(self.alphabet) return sum((self._letter_to_int(l) * base**lsb for lsb, l in enumerate(s) ))
python
def _string_to_int(self, s): """Read an integer in s, in Little Indian. """ base = len(self.alphabet) return sum((self._letter_to_int(l) * base**lsb for lsb, l in enumerate(s) ))
[ "def", "_string_to_int", "(", "self", ",", "s", ")", ":", "base", "=", "len", "(", "self", ".", "alphabet", ")", "return", "sum", "(", "(", "self", ".", "_letter_to_int", "(", "l", ")", "*", "base", "**", "lsb", "for", "lsb", ",", "l", "in", "enu...
Read an integer in s, in Little Indian.
[ "Read", "an", "integer", "in", "s", "in", "Little", "Indian", "." ]
train
https://github.com/Aluriak/ACCC/blob/9092f985bef7ed784264c86bc19c980f4ce2309f/accc/compiler/compiler.py#L196-L201
Aluriak/ACCC
accc/compiler/compiler.py
Compiler._struct_to_values
def _struct_to_values(self, structure, source_code): """Return list of values readed in source_code, according to given structure. """ # iterate on source code until all values are finded # if a value is not foundable, # (ie its identificator is not in source code) # it will be replaced by associated neutral value iter_source_code = itertools.cycle(source_code) values = [] for lexem_type in (l for l in structure if l is not 'D'): if lexem_type is LEXEM_TYPE_CONDITION: new_value = self._next_condition_lexems( iter_source_code, len(source_code) ) else: new_value = self._next_lexem( lexem_type, iter_source_code, len(source_code) ) # if values is unvalid: # association with the right neutral value if new_value is None: if lexem_type in (LEXEM_TYPE_PREDICAT, LEXEM_TYPE_CONDITION): new_value = self.neutral_value_condition else: new_value = self.neutral_value_action values.append(new_value) return values
python
def _struct_to_values(self, structure, source_code): """Return list of values readed in source_code, according to given structure. """ # iterate on source code until all values are finded # if a value is not foundable, # (ie its identificator is not in source code) # it will be replaced by associated neutral value iter_source_code = itertools.cycle(source_code) values = [] for lexem_type in (l for l in structure if l is not 'D'): if lexem_type is LEXEM_TYPE_CONDITION: new_value = self._next_condition_lexems( iter_source_code, len(source_code) ) else: new_value = self._next_lexem( lexem_type, iter_source_code, len(source_code) ) # if values is unvalid: # association with the right neutral value if new_value is None: if lexem_type in (LEXEM_TYPE_PREDICAT, LEXEM_TYPE_CONDITION): new_value = self.neutral_value_condition else: new_value = self.neutral_value_action values.append(new_value) return values
[ "def", "_struct_to_values", "(", "self", ",", "structure", ",", "source_code", ")", ":", "# iterate on source code until all values are finded", "# if a value is not foundable, ", "# (ie its identificator is not in source code)", "# it will be replaced by associated neutral value", "...
Return list of values readed in source_code, according to given structure.
[ "Return", "list", "of", "values", "readed", "in", "source_code", "according", "to", "given", "structure", "." ]
train
https://github.com/Aluriak/ACCC/blob/9092f985bef7ed784264c86bc19c980f4ce2309f/accc/compiler/compiler.py#L220-L248
Aluriak/ACCC
accc/compiler/compiler.py
Compiler._create_struct_table
def _create_struct_table(self): """Create table identificator->vocabulary, and return it with size of an identificator""" len_alph = len(self.alphabet) len_vocb = len(self.voc_structure) identificator_size = ceil(log(len_vocb, len_alph)) # create list of lexems num2alph = lambda x, n: self.alphabet[(x // len_alph**n) % len_alph] identificators = [[str(num2alph(x, n)) for n in range(identificator_size) ] for x in range(len_vocb) ] # initialize table and iterable identificators_table = {} zip_id_voc = zip_longest( identificators, self.voc_structure, fillvalue=None ) # create dict identificator:word for idt, word in zip_id_voc: identificators_table[''.join(idt)] = word return identificators_table, identificator_size
python
def _create_struct_table(self): """Create table identificator->vocabulary, and return it with size of an identificator""" len_alph = len(self.alphabet) len_vocb = len(self.voc_structure) identificator_size = ceil(log(len_vocb, len_alph)) # create list of lexems num2alph = lambda x, n: self.alphabet[(x // len_alph**n) % len_alph] identificators = [[str(num2alph(x, n)) for n in range(identificator_size) ] for x in range(len_vocb) ] # initialize table and iterable identificators_table = {} zip_id_voc = zip_longest( identificators, self.voc_structure, fillvalue=None ) # create dict identificator:word for idt, word in zip_id_voc: identificators_table[''.join(idt)] = word return identificators_table, identificator_size
[ "def", "_create_struct_table", "(", "self", ")", ":", "len_alph", "=", "len", "(", "self", ".", "alphabet", ")", "len_vocb", "=", "len", "(", "self", ".", "voc_structure", ")", "identificator_size", "=", "ceil", "(", "log", "(", "len_vocb", ",", "len_alph"...
Create table identificator->vocabulary, and return it with size of an identificator
[ "Create", "table", "identificator", "-", ">", "vocabulary", "and", "return", "it", "with", "size", "of", "an", "identificator" ]
train
https://github.com/Aluriak/ACCC/blob/9092f985bef7ed784264c86bc19c980f4ce2309f/accc/compiler/compiler.py#L256-L278
Aluriak/ACCC
accc/compiler/compiler.py
Compiler._create_values_table
def _create_values_table(self): """Create table lexem_type->{identificator->vocabulary}, and return it with sizes of an identificator as lexem_type->identificator_size""" # number of existing character, and returned dicts len_alph = len(self.alphabet) identificators_table = {k:{} for k in self.voc_values.keys()} identificators_sizes = {k:-1 for k in self.voc_values.keys()} for lexem_type, vocabulary in self.voc_values.items(): # find number of different values that can be found, # and size of an identificator. len_vocb = len(vocabulary) identificators_sizes[lexem_type] = ceil(log(len_vocb, len_alph)) # create list of possible identificators num2alph = lambda x, n: self.alphabet[(x // len_alph**n) % len_alph] identificators = [[str(num2alph(x, n)) for n in range(identificators_sizes[lexem_type]) ] # this list is an identificator for x in range(len_alph**identificators_sizes[lexem_type]) ] # this one is a list of identificator # initialize iterable zip_id_voc = zip_longest( identificators, vocabulary, fillvalue=None ) # create dict {identificator:word} for idt, voc in zip_id_voc: identificators_table[lexem_type][''.join(idt)] = voc # return all return identificators_table, identificators_sizes
python
def _create_values_table(self): """Create table lexem_type->{identificator->vocabulary}, and return it with sizes of an identificator as lexem_type->identificator_size""" # number of existing character, and returned dicts len_alph = len(self.alphabet) identificators_table = {k:{} for k in self.voc_values.keys()} identificators_sizes = {k:-1 for k in self.voc_values.keys()} for lexem_type, vocabulary in self.voc_values.items(): # find number of different values that can be found, # and size of an identificator. len_vocb = len(vocabulary) identificators_sizes[lexem_type] = ceil(log(len_vocb, len_alph)) # create list of possible identificators num2alph = lambda x, n: self.alphabet[(x // len_alph**n) % len_alph] identificators = [[str(num2alph(x, n)) for n in range(identificators_sizes[lexem_type]) ] # this list is an identificator for x in range(len_alph**identificators_sizes[lexem_type]) ] # this one is a list of identificator # initialize iterable zip_id_voc = zip_longest( identificators, vocabulary, fillvalue=None ) # create dict {identificator:word} for idt, voc in zip_id_voc: identificators_table[lexem_type][''.join(idt)] = voc # return all return identificators_table, identificators_sizes
[ "def", "_create_values_table", "(", "self", ")", ":", "# number of existing character, and returned dicts", "len_alph", "=", "len", "(", "self", ".", "alphabet", ")", "identificators_table", "=", "{", "k", ":", "{", "}", "for", "k", "in", "self", ".", "voc_value...
Create table lexem_type->{identificator->vocabulary}, and return it with sizes of an identificator as lexem_type->identificator_size
[ "Create", "table", "lexem_type", "-", ">", "{", "identificator", "-", ">", "vocabulary", "}", "and", "return", "it", "with", "sizes", "of", "an", "identificator", "as", "lexem_type", "-", ">", "identificator_size" ]
train
https://github.com/Aluriak/ACCC/blob/9092f985bef7ed784264c86bc19c980f4ce2309f/accc/compiler/compiler.py#L281-L311
Synerty/peek-plugin-base
peek_plugin_base/client/PeekPlatformDesktopHttpHookABC.py
PeekPlatformDesktopHttpHookABC.addDesktopResource
def addDesktopResource(self, pluginSubPath: bytes, resource: BasicResource) -> None: """ Add Site Resource Add a cusotom implementation of a served http resource. :param pluginSubPath: The resource path where you want to serve this resource. :param resource: The resource to serve. :return: None """ pluginSubPath = pluginSubPath.strip(b'/') self.__rootDesktopResource.putChild(pluginSubPath, resource)
python
def addDesktopResource(self, pluginSubPath: bytes, resource: BasicResource) -> None: """ Add Site Resource Add a cusotom implementation of a served http resource. :param pluginSubPath: The resource path where you want to serve this resource. :param resource: The resource to serve. :return: None """ pluginSubPath = pluginSubPath.strip(b'/') self.__rootDesktopResource.putChild(pluginSubPath, resource)
[ "def", "addDesktopResource", "(", "self", ",", "pluginSubPath", ":", "bytes", ",", "resource", ":", "BasicResource", ")", "->", "None", ":", "pluginSubPath", "=", "pluginSubPath", ".", "strip", "(", "b'/'", ")", "self", ".", "__rootDesktopResource", ".", "putC...
Add Site Resource Add a cusotom implementation of a served http resource. :param pluginSubPath: The resource path where you want to serve this resource. :param resource: The resource to serve. :return: None
[ "Add", "Site", "Resource" ]
train
https://github.com/Synerty/peek-plugin-base/blob/276101d028e1ee0678af514c761b74cce5a5cda9/peek_plugin_base/client/PeekPlatformDesktopHttpHookABC.py#L31-L42
TheOstrichIO/ostrichlib
ostrich/utils/path.py
check_arg_types
def check_arg_types(funcname, *args): """Raise TypeError if not all items of `args` are same string type.""" hasstr = hasbytes = False for arg in args: if isinstance(arg, str): hasstr = True elif isinstance(arg, bytes): hasbytes = True else: raise TypeError('{0}() argument must be str or bytes, not {1}' .format(funcname, arg.__class__.__name__)) if hasstr and hasbytes: raise TypeError("Can't mix strings and bytes in path components")
python
def check_arg_types(funcname, *args): """Raise TypeError if not all items of `args` are same string type.""" hasstr = hasbytes = False for arg in args: if isinstance(arg, str): hasstr = True elif isinstance(arg, bytes): hasbytes = True else: raise TypeError('{0}() argument must be str or bytes, not {1}' .format(funcname, arg.__class__.__name__)) if hasstr and hasbytes: raise TypeError("Can't mix strings and bytes in path components")
[ "def", "check_arg_types", "(", "funcname", ",", "*", "args", ")", ":", "hasstr", "=", "hasbytes", "=", "False", "for", "arg", "in", "args", ":", "if", "isinstance", "(", "arg", ",", "str", ")", ":", "hasstr", "=", "True", "elif", "isinstance", "(", "...
Raise TypeError if not all items of `args` are same string type.
[ "Raise", "TypeError", "if", "not", "all", "items", "of", "args", "are", "same", "string", "type", "." ]
train
https://github.com/TheOstrichIO/ostrichlib/blob/ed97634ccbfb8b5042e61fbd0ac9a27aef281bcb/ostrich/utils/path.py#L21-L33
TheOstrichIO/ostrichlib
ostrich/utils/path.py
posix_commonpath
def posix_commonpath(paths): """Given a sequence of POSIX path names, return the longest common sub-path.""" if not paths: raise ValueError('commonpath() arg is an empty sequence') check_arg_types('commonpath', *paths) if isinstance(paths[0], bytes): sep = b'/' curdir = b'.' else: sep = '/' curdir = '.' split_paths = [path.split(sep) for path in paths] try: isabs, = set(p[:1] == sep for p in paths) except ValueError: raise ValueError("Can't mix absolute and relative paths") split_paths = [[c for c in s if c and c != curdir] for s in split_paths] s_min = min(split_paths) s_max = max(split_paths) common = s_min for i, run_c in enumerate(s_min): if run_c != s_max[i]: common = s_min[:i] break prefix = sep if isabs else sep[:0] return prefix + sep.join(common)
python
def posix_commonpath(paths): """Given a sequence of POSIX path names, return the longest common sub-path.""" if not paths: raise ValueError('commonpath() arg is an empty sequence') check_arg_types('commonpath', *paths) if isinstance(paths[0], bytes): sep = b'/' curdir = b'.' else: sep = '/' curdir = '.' split_paths = [path.split(sep) for path in paths] try: isabs, = set(p[:1] == sep for p in paths) except ValueError: raise ValueError("Can't mix absolute and relative paths") split_paths = [[c for c in s if c and c != curdir] for s in split_paths] s_min = min(split_paths) s_max = max(split_paths) common = s_min for i, run_c in enumerate(s_min): if run_c != s_max[i]: common = s_min[:i] break prefix = sep if isabs else sep[:0] return prefix + sep.join(common)
[ "def", "posix_commonpath", "(", "paths", ")", ":", "if", "not", "paths", ":", "raise", "ValueError", "(", "'commonpath() arg is an empty sequence'", ")", "check_arg_types", "(", "'commonpath'", ",", "*", "paths", ")", "if", "isinstance", "(", "paths", "[", "0", ...
Given a sequence of POSIX path names, return the longest common sub-path.
[ "Given", "a", "sequence", "of", "POSIX", "path", "names", "return", "the", "longest", "common", "sub", "-", "path", "." ]
train
https://github.com/TheOstrichIO/ostrichlib/blob/ed97634ccbfb8b5042e61fbd0ac9a27aef281bcb/ostrich/utils/path.py#L36-L69
TheOstrichIO/ostrichlib
ostrich/utils/path.py
nt_commonpath
def nt_commonpath(paths): # pylint: disable=too-many-locals """Given a sequence of NT path names, return the longest common sub-path.""" from ntpath import splitdrive if not paths: raise ValueError('commonpath() arg is an empty sequence') check_arg_types('commonpath', *paths) if isinstance(paths[0], bytes): sep = b'\\' altsep = b'/' curdir = b'.' else: sep = '\\' altsep = '/' curdir = '.' drivesplits = [splitdrive(p.replace(altsep, sep).lower()) for p in paths] split_paths = [p.split(sep) for d, p in drivesplits] try: isabs, = set(p[:1] == sep for d, p in drivesplits) except ValueError: raise ValueError("Can't mix absolute and relative paths") # Check that all drive letters or UNC paths match. The check is made # only now otherwise type errors for mixing strings and bytes would not # be caught. if len(set(d for d, p in drivesplits)) != 1: raise ValueError("Paths don't have the same drive") drive, path = splitdrive(paths[0].replace(altsep, sep)) common = path.split(sep) common = [c for c in common if c and c != curdir] split_paths = [[c for c in s if c and c != curdir] for s in split_paths] s_min = min(split_paths) s_max = max(split_paths) for i, run_c in enumerate(s_min): if run_c != s_max[i]: common = common[:i] break else: common = common[:len(s_min)] prefix = drive + sep if isabs else drive return prefix + sep.join(common)
python
def nt_commonpath(paths): # pylint: disable=too-many-locals """Given a sequence of NT path names, return the longest common sub-path.""" from ntpath import splitdrive if not paths: raise ValueError('commonpath() arg is an empty sequence') check_arg_types('commonpath', *paths) if isinstance(paths[0], bytes): sep = b'\\' altsep = b'/' curdir = b'.' else: sep = '\\' altsep = '/' curdir = '.' drivesplits = [splitdrive(p.replace(altsep, sep).lower()) for p in paths] split_paths = [p.split(sep) for d, p in drivesplits] try: isabs, = set(p[:1] == sep for d, p in drivesplits) except ValueError: raise ValueError("Can't mix absolute and relative paths") # Check that all drive letters or UNC paths match. The check is made # only now otherwise type errors for mixing strings and bytes would not # be caught. if len(set(d for d, p in drivesplits)) != 1: raise ValueError("Paths don't have the same drive") drive, path = splitdrive(paths[0].replace(altsep, sep)) common = path.split(sep) common = [c for c in common if c and c != curdir] split_paths = [[c for c in s if c and c != curdir] for s in split_paths] s_min = min(split_paths) s_max = max(split_paths) for i, run_c in enumerate(s_min): if run_c != s_max[i]: common = common[:i] break else: common = common[:len(s_min)] prefix = drive + sep if isabs else drive return prefix + sep.join(common)
[ "def", "nt_commonpath", "(", "paths", ")", ":", "# pylint: disable=too-many-locals", "from", "ntpath", "import", "splitdrive", "if", "not", "paths", ":", "raise", "ValueError", "(", "'commonpath() arg is an empty sequence'", ")", "check_arg_types", "(", "'commonpath'", ...
Given a sequence of NT path names, return the longest common sub-path.
[ "Given", "a", "sequence", "of", "NT", "path", "names", "return", "the", "longest", "common", "sub", "-", "path", "." ]
train
https://github.com/TheOstrichIO/ostrichlib/blob/ed97634ccbfb8b5042e61fbd0ac9a27aef281bcb/ostrich/utils/path.py#L72-L121
larryng/narwal
narwal/things.py
Commentable.comments
def comments(self, limit=None): """GETs comments to this thing. :param limit: max number of comments to return """ return self._reddit._limit_get(self.permalink, limit=limit)[1]
python
def comments(self, limit=None): """GETs comments to this thing. :param limit: max number of comments to return """ return self._reddit._limit_get(self.permalink, limit=limit)[1]
[ "def", "comments", "(", "self", ",", "limit", "=", "None", ")", ":", "return", "self", ".", "_reddit", ".", "_limit_get", "(", "self", ".", "permalink", ",", "limit", "=", "limit", ")", "[", "1", "]" ]
GETs comments to this thing. :param limit: max number of comments to return
[ "GETs", "comments", "to", "this", "thing", ".", ":", "param", "limit", ":", "max", "number", "of", "comments", "to", "return" ]
train
https://github.com/larryng/narwal/blob/58c409a475c8ed865579a61d7010162ed8cef597/narwal/things.py#L171-L176
larryng/narwal
narwal/things.py
Commentable.distinguish
def distinguish(self, how=True): """Distinguishes this thing (POST). Calls :meth:`narwal.Reddit.distinguish`. :param how: either True, False, or 'admin' """ return self._reddit.distinguish(self.name, how=how)
python
def distinguish(self, how=True): """Distinguishes this thing (POST). Calls :meth:`narwal.Reddit.distinguish`. :param how: either True, False, or 'admin' """ return self._reddit.distinguish(self.name, how=how)
[ "def", "distinguish", "(", "self", ",", "how", "=", "True", ")", ":", "return", "self", ".", "_reddit", ".", "distinguish", "(", "self", ".", "name", ",", "how", "=", "how", ")" ]
Distinguishes this thing (POST). Calls :meth:`narwal.Reddit.distinguish`. :param how: either True, False, or 'admin'
[ "Distinguishes", "this", "thing", "(", "POST", ")", ".", "Calls", ":", "meth", ":", "narwal", ".", "Reddit", ".", "distinguish", ".", ":", "param", "how", ":", "either", "True", "False", "or", "admin" ]
train
https://github.com/larryng/narwal/blob/58c409a475c8ed865579a61d7010162ed8cef597/narwal/things.py#L178-L183
larryng/narwal
narwal/things.py
Listing.next_listing
def next_listing(self, limit=None): """GETs next :class:`Listing` directed to by this :class:`Listing`. Returns :class:`Listing` object. :param limit: max number of entries to get :raise UnsupportedError: raised when trying to load more comments """ if self.after: return self._reddit._limit_get(self._path, params={'after': self.after}, limit=limit or self._limit) elif self._has_literally_more: more = self[-1] data = dict( link_id=self[0].parent_id, id=more.name, children=','.join(more.children) ) j = self._reddit.post('api', 'morechildren', data=data) # since reddit is inconsistent here, we're hacking it to be # consistent so it'll work with _thingify d = j['json'] d['kind'] = 'Listing' d['data']['children'] = d['data']['things'] del d['data']['things'] return self._reddit._thingify(d, path=self._path) else: raise NoMoreError('no more items')
python
def next_listing(self, limit=None): """GETs next :class:`Listing` directed to by this :class:`Listing`. Returns :class:`Listing` object. :param limit: max number of entries to get :raise UnsupportedError: raised when trying to load more comments """ if self.after: return self._reddit._limit_get(self._path, params={'after': self.after}, limit=limit or self._limit) elif self._has_literally_more: more = self[-1] data = dict( link_id=self[0].parent_id, id=more.name, children=','.join(more.children) ) j = self._reddit.post('api', 'morechildren', data=data) # since reddit is inconsistent here, we're hacking it to be # consistent so it'll work with _thingify d = j['json'] d['kind'] = 'Listing' d['data']['children'] = d['data']['things'] del d['data']['things'] return self._reddit._thingify(d, path=self._path) else: raise NoMoreError('no more items')
[ "def", "next_listing", "(", "self", ",", "limit", "=", "None", ")", ":", "if", "self", ".", "after", ":", "return", "self", ".", "_reddit", ".", "_limit_get", "(", "self", ".", "_path", ",", "params", "=", "{", "'after'", ":", "self", ".", "after", ...
GETs next :class:`Listing` directed to by this :class:`Listing`. Returns :class:`Listing` object. :param limit: max number of entries to get :raise UnsupportedError: raised when trying to load more comments
[ "GETs", "next", ":", "class", ":", "Listing", "directed", "to", "by", "this", ":", "class", ":", "Listing", ".", "Returns", ":", "class", ":", "Listing", "object", ".", ":", "param", "limit", ":", "max", "number", "of", "entries", "to", "get", ":", "...
train
https://github.com/larryng/narwal/blob/58c409a475c8ed865579a61d7010162ed8cef597/narwal/things.py#L258-L282
larryng/narwal
narwal/things.py
Listing.prev_listing
def prev_listing(self, limit=None): """GETs previous :class:`Listing` directed to by this :class:`Listing`. Returns :class:`Listing` object. :param limit: max number of entries to get """ if self.before: return self._reddit._limit_get(self._path, eparams={'before': self.before}, limit=limit or self._limit) else: raise NoMoreError('no previous items')
python
def prev_listing(self, limit=None): """GETs previous :class:`Listing` directed to by this :class:`Listing`. Returns :class:`Listing` object. :param limit: max number of entries to get """ if self.before: return self._reddit._limit_get(self._path, eparams={'before': self.before}, limit=limit or self._limit) else: raise NoMoreError('no previous items')
[ "def", "prev_listing", "(", "self", ",", "limit", "=", "None", ")", ":", "if", "self", ".", "before", ":", "return", "self", ".", "_reddit", ".", "_limit_get", "(", "self", ".", "_path", ",", "eparams", "=", "{", "'before'", ":", "self", ".", "before...
GETs previous :class:`Listing` directed to by this :class:`Listing`. Returns :class:`Listing` object. :param limit: max number of entries to get
[ "GETs", "previous", ":", "class", ":", "Listing", "directed", "to", "by", "this", ":", "class", ":", "Listing", ".", "Returns", ":", "class", ":", "Listing", "object", ".", ":", "param", "limit", ":", "max", "number", "of", "entries", "to", "get" ]
train
https://github.com/larryng/narwal/blob/58c409a475c8ed865579a61d7010162ed8cef597/narwal/things.py#L284-L292
larryng/narwal
narwal/things.py
Subreddit.hot
def hot(self, limit=None): """GETs hot links from this subreddit. Calls :meth:`narwal.Reddit.hot`. :param limit: max number of links to return """ return self._reddit.hot(self.display_name, limit=limit)
python
def hot(self, limit=None): """GETs hot links from this subreddit. Calls :meth:`narwal.Reddit.hot`. :param limit: max number of links to return """ return self._reddit.hot(self.display_name, limit=limit)
[ "def", "hot", "(", "self", ",", "limit", "=", "None", ")", ":", "return", "self", ".", "_reddit", ".", "hot", "(", "self", ".", "display_name", ",", "limit", "=", "limit", ")" ]
GETs hot links from this subreddit. Calls :meth:`narwal.Reddit.hot`. :param limit: max number of links to return
[ "GETs", "hot", "links", "from", "this", "subreddit", ".", "Calls", ":", "meth", ":", "narwal", ".", "Reddit", ".", "hot", ".", ":", "param", "limit", ":", "max", "number", "of", "links", "to", "return" ]
train
https://github.com/larryng/narwal/blob/58c409a475c8ed865579a61d7010162ed8cef597/narwal/things.py#L421-L426
larryng/narwal
narwal/things.py
Subreddit.new
def new(self, limit=None): """GETs new links from this subreddit. Calls :meth:`narwal.Reddit.new`. :param limit: max number of links to return """ return self._reddit.new(self.display_name, limit=limit)
python
def new(self, limit=None): """GETs new links from this subreddit. Calls :meth:`narwal.Reddit.new`. :param limit: max number of links to return """ return self._reddit.new(self.display_name, limit=limit)
[ "def", "new", "(", "self", ",", "limit", "=", "None", ")", ":", "return", "self", ".", "_reddit", ".", "new", "(", "self", ".", "display_name", ",", "limit", "=", "limit", ")" ]
GETs new links from this subreddit. Calls :meth:`narwal.Reddit.new`. :param limit: max number of links to return
[ "GETs", "new", "links", "from", "this", "subreddit", ".", "Calls", ":", "meth", ":", "narwal", ".", "Reddit", ".", "new", ".", ":", "param", "limit", ":", "max", "number", "of", "links", "to", "return" ]
train
https://github.com/larryng/narwal/blob/58c409a475c8ed865579a61d7010162ed8cef597/narwal/things.py#L428-L433
larryng/narwal
narwal/things.py
Subreddit.top
def top(self, limit=None): """GETs top links from this subreddit. Calls :meth:`narwal.Reddit.top`. :param limit: max number of links to return """ return self._reddit.top(self.display_name, limit=limit)
python
def top(self, limit=None): """GETs top links from this subreddit. Calls :meth:`narwal.Reddit.top`. :param limit: max number of links to return """ return self._reddit.top(self.display_name, limit=limit)
[ "def", "top", "(", "self", ",", "limit", "=", "None", ")", ":", "return", "self", ".", "_reddit", ".", "top", "(", "self", ".", "display_name", ",", "limit", "=", "limit", ")" ]
GETs top links from this subreddit. Calls :meth:`narwal.Reddit.top`. :param limit: max number of links to return
[ "GETs", "top", "links", "from", "this", "subreddit", ".", "Calls", ":", "meth", ":", "narwal", ".", "Reddit", ".", "top", ".", ":", "param", "limit", ":", "max", "number", "of", "links", "to", "return" ]
train
https://github.com/larryng/narwal/blob/58c409a475c8ed865579a61d7010162ed8cef597/narwal/things.py#L435-L440
larryng/narwal
narwal/things.py
Subreddit.controversial
def controversial(self, limit=None): """GETs controversial links from this subreddit. Calls :meth:`narwal.Reddit.controversial`. :param limit: max number of links to return """ return self._reddit.controversial(self.display_name, limit=limit)
python
def controversial(self, limit=None): """GETs controversial links from this subreddit. Calls :meth:`narwal.Reddit.controversial`. :param limit: max number of links to return """ return self._reddit.controversial(self.display_name, limit=limit)
[ "def", "controversial", "(", "self", ",", "limit", "=", "None", ")", ":", "return", "self", ".", "_reddit", ".", "controversial", "(", "self", ".", "display_name", ",", "limit", "=", "limit", ")" ]
GETs controversial links from this subreddit. Calls :meth:`narwal.Reddit.controversial`. :param limit: max number of links to return
[ "GETs", "controversial", "links", "from", "this", "subreddit", ".", "Calls", ":", "meth", ":", "narwal", ".", "Reddit", ".", "controversial", ".", ":", "param", "limit", ":", "max", "number", "of", "links", "to", "return" ]
train
https://github.com/larryng/narwal/blob/58c409a475c8ed865579a61d7010162ed8cef597/narwal/things.py#L442-L447
larryng/narwal
narwal/things.py
Subreddit.comments
def comments(self, limit=None): """GETs newest comments from this subreddit. Calls :meth:`narwal.Reddit.comments`. :param limit: max number of links to return """ return self._reddit.comments(self.display_name, limit=limit)
python
def comments(self, limit=None): """GETs newest comments from this subreddit. Calls :meth:`narwal.Reddit.comments`. :param limit: max number of links to return """ return self._reddit.comments(self.display_name, limit=limit)
[ "def", "comments", "(", "self", ",", "limit", "=", "None", ")", ":", "return", "self", ".", "_reddit", ".", "comments", "(", "self", ".", "display_name", ",", "limit", "=", "limit", ")" ]
GETs newest comments from this subreddit. Calls :meth:`narwal.Reddit.comments`. :param limit: max number of links to return
[ "GETs", "newest", "comments", "from", "this", "subreddit", ".", "Calls", ":", "meth", ":", "narwal", ".", "Reddit", ".", "comments", ".", ":", "param", "limit", ":", "max", "number", "of", "links", "to", "return" ]
train
https://github.com/larryng/narwal/blob/58c409a475c8ed865579a61d7010162ed8cef597/narwal/things.py#L449-L454
larryng/narwal
narwal/things.py
Subreddit.submit_link
def submit_link(self, title, url): """Submit link to this subreddit (POST). Calls :meth:`narwal.Reddit.submit_link`. :param title: title of submission :param url: url submission links to """ return self._reddit.submit_link(self.display_name, title, url)
python
def submit_link(self, title, url): """Submit link to this subreddit (POST). Calls :meth:`narwal.Reddit.submit_link`. :param title: title of submission :param url: url submission links to """ return self._reddit.submit_link(self.display_name, title, url)
[ "def", "submit_link", "(", "self", ",", "title", ",", "url", ")", ":", "return", "self", ".", "_reddit", ".", "submit_link", "(", "self", ".", "display_name", ",", "title", ",", "url", ")" ]
Submit link to this subreddit (POST). Calls :meth:`narwal.Reddit.submit_link`. :param title: title of submission :param url: url submission links to
[ "Submit", "link", "to", "this", "subreddit", "(", "POST", ")", ".", "Calls", ":", "meth", ":", "narwal", ".", "Reddit", ".", "submit_link", ".", ":", "param", "title", ":", "title", "of", "submission", ":", "param", "url", ":", "url", "submission", "li...
train
https://github.com/larryng/narwal/blob/58c409a475c8ed865579a61d7010162ed8cef597/narwal/things.py#L466-L472
larryng/narwal
narwal/things.py
Subreddit.submit_text
def submit_text(self, title, text): """Submit self text submission to this subreddit (POST). Calls :meth:`narwal.Reddit.submit_text`. :param title: title of submission :param text: self text """ return self._reddit.submit_text(self.display_name, title, text)
python
def submit_text(self, title, text): """Submit self text submission to this subreddit (POST). Calls :meth:`narwal.Reddit.submit_text`. :param title: title of submission :param text: self text """ return self._reddit.submit_text(self.display_name, title, text)
[ "def", "submit_text", "(", "self", ",", "title", ",", "text", ")", ":", "return", "self", ".", "_reddit", ".", "submit_text", "(", "self", ".", "display_name", ",", "title", ",", "text", ")" ]
Submit self text submission to this subreddit (POST). Calls :meth:`narwal.Reddit.submit_text`. :param title: title of submission :param text: self text
[ "Submit", "self", "text", "submission", "to", "this", "subreddit", "(", "POST", ")", ".", "Calls", ":", "meth", ":", "narwal", ".", "Reddit", ".", "submit_text", ".", ":", "param", "title", ":", "title", "of", "submission", ":", "param", "text", ":", "...
train
https://github.com/larryng/narwal/blob/58c409a475c8ed865579a61d7010162ed8cef597/narwal/things.py#L474-L480
larryng/narwal
narwal/things.py
Subreddit.moderators
def moderators(self, limit=None): """GETs moderators for this subreddit. Calls :meth:`narwal.Reddit.moderators`. :param limit: max number of items to return """ return self._reddit.moderators(self.display_name, limit=limit)
python
def moderators(self, limit=None): """GETs moderators for this subreddit. Calls :meth:`narwal.Reddit.moderators`. :param limit: max number of items to return """ return self._reddit.moderators(self.display_name, limit=limit)
[ "def", "moderators", "(", "self", ",", "limit", "=", "None", ")", ":", "return", "self", ".", "_reddit", ".", "moderators", "(", "self", ".", "display_name", ",", "limit", "=", "limit", ")" ]
GETs moderators for this subreddit. Calls :meth:`narwal.Reddit.moderators`. :param limit: max number of items to return
[ "GETs", "moderators", "for", "this", "subreddit", ".", "Calls", ":", "meth", ":", "narwal", ".", "Reddit", ".", "moderators", ".", ":", "param", "limit", ":", "max", "number", "of", "items", "to", "return" ]
train
https://github.com/larryng/narwal/blob/58c409a475c8ed865579a61d7010162ed8cef597/narwal/things.py#L482-L487
larryng/narwal
narwal/things.py
Subreddit.flair
def flair(self, name, text, css_class): """Sets flair for `user` in this subreddit (POST). Calls :meth:`narwal.Reddit.flairlist`. :param name: name of the user :param text: flair text to assign :param css_class: CSS class to assign to flair text """ return self._reddit.flair(self.display_name, name, text, css_class)
python
def flair(self, name, text, css_class): """Sets flair for `user` in this subreddit (POST). Calls :meth:`narwal.Reddit.flairlist`. :param name: name of the user :param text: flair text to assign :param css_class: CSS class to assign to flair text """ return self._reddit.flair(self.display_name, name, text, css_class)
[ "def", "flair", "(", "self", ",", "name", ",", "text", ",", "css_class", ")", ":", "return", "self", ".", "_reddit", ".", "flair", "(", "self", ".", "display_name", ",", "name", ",", "text", ",", "css_class", ")" ]
Sets flair for `user` in this subreddit (POST). Calls :meth:`narwal.Reddit.flairlist`. :param name: name of the user :param text: flair text to assign :param css_class: CSS class to assign to flair text
[ "Sets", "flair", "for", "user", "in", "this", "subreddit", "(", "POST", ")", ".", "Calls", ":", "meth", ":", "narwal", ".", "Reddit", ".", "flairlist", ".", ":", "param", "name", ":", "name", "of", "the", "user", ":", "param", "text", ":", "flair", ...
train
https://github.com/larryng/narwal/blob/58c409a475c8ed865579a61d7010162ed8cef597/narwal/things.py#L489-L496
larryng/narwal
narwal/things.py
Subreddit.flairlist
def flairlist(self, limit=1000, after=None, before=None): """GETs flairlist for this subreddit. Calls :meth:`narwal.Reddit.flairlist`. :param limit: max number of items to return :param after: full id of user to return entries after :param before: full id of user to return entries *before* """ return self._reddit.flairlist(self.display_name, limit=limit, after=after, before=before)
python
def flairlist(self, limit=1000, after=None, before=None): """GETs flairlist for this subreddit. Calls :meth:`narwal.Reddit.flairlist`. :param limit: max number of items to return :param after: full id of user to return entries after :param before: full id of user to return entries *before* """ return self._reddit.flairlist(self.display_name, limit=limit, after=after, before=before)
[ "def", "flairlist", "(", "self", ",", "limit", "=", "1000", ",", "after", "=", "None", ",", "before", "=", "None", ")", ":", "return", "self", ".", "_reddit", ".", "flairlist", "(", "self", ".", "display_name", ",", "limit", "=", "limit", ",", "after...
GETs flairlist for this subreddit. Calls :meth:`narwal.Reddit.flairlist`. :param limit: max number of items to return :param after: full id of user to return entries after :param before: full id of user to return entries *before*
[ "GETs", "flairlist", "for", "this", "subreddit", ".", "Calls", ":", "meth", ":", "narwal", ".", "Reddit", ".", "flairlist", ".", ":", "param", "limit", ":", "max", "number", "of", "items", "to", "return", ":", "param", "after", ":", "full", "id", "of",...
train
https://github.com/larryng/narwal/blob/58c409a475c8ed865579a61d7010162ed8cef597/narwal/things.py#L498-L505
larryng/narwal
narwal/things.py
Subreddit.contributors
def contributors(self, limit=None): """GETs contributors for this subreddit. Calls :meth:`narwal.Reddit.contributors`. :param limit: max number of items to return """ return self._reddit.contributors(self.display_name, limit=limit)
python
def contributors(self, limit=None): """GETs contributors for this subreddit. Calls :meth:`narwal.Reddit.contributors`. :param limit: max number of items to return """ return self._reddit.contributors(self.display_name, limit=limit)
[ "def", "contributors", "(", "self", ",", "limit", "=", "None", ")", ":", "return", "self", ".", "_reddit", ".", "contributors", "(", "self", ".", "display_name", ",", "limit", "=", "limit", ")" ]
GETs contributors for this subreddit. Calls :meth:`narwal.Reddit.contributors`. :param limit: max number of items to return
[ "GETs", "contributors", "for", "this", "subreddit", ".", "Calls", ":", "meth", ":", "narwal", ".", "Reddit", ".", "contributors", ".", ":", "param", "limit", ":", "max", "number", "of", "items", "to", "return" ]
train
https://github.com/larryng/narwal/blob/58c409a475c8ed865579a61d7010162ed8cef597/narwal/things.py#L514-L519
larryng/narwal
narwal/things.py
Message.reply
def reply(self, text): """POSTs reply to message with own message. Returns posted message. URL: ``http://www.reddit.com/api/comment/`` :param text: body text of message """ data = { 'thing_id': self.name, 'id': '#commentreply_{0}'.format(self.name), 'text': text, } j = self._reddit.post('api', 'comment', data=data) try: return self._reddit._thingify(j['json']['data']['things'][0], path=self._path) except Exception: raise UnexpectedResponse(j)
python
def reply(self, text): """POSTs reply to message with own message. Returns posted message. URL: ``http://www.reddit.com/api/comment/`` :param text: body text of message """ data = { 'thing_id': self.name, 'id': '#commentreply_{0}'.format(self.name), 'text': text, } j = self._reddit.post('api', 'comment', data=data) try: return self._reddit._thingify(j['json']['data']['things'][0], path=self._path) except Exception: raise UnexpectedResponse(j)
[ "def", "reply", "(", "self", ",", "text", ")", ":", "data", "=", "{", "'thing_id'", ":", "self", ".", "name", ",", "'id'", ":", "'#commentreply_{0}'", ".", "format", "(", "self", ".", "name", ")", ",", "'text'", ":", "text", ",", "}", "j", "=", "...
POSTs reply to message with own message. Returns posted message. URL: ``http://www.reddit.com/api/comment/`` :param text: body text of message
[ "POSTs", "reply", "to", "message", "with", "own", "message", ".", "Returns", "posted", "message", ".", "URL", ":", "http", ":", "//", "www", ".", "reddit", ".", "com", "/", "api", "/", "comment", "/", ":", "param", "text", ":", "body", "text", "of", ...
train
https://github.com/larryng/narwal/blob/58c409a475c8ed865579a61d7010162ed8cef597/narwal/things.py#L555-L571
larryng/narwal
narwal/things.py
Account.overview
def overview(self, limit=None): """GETs overview of user's activities. Calls :meth:`narwal.Reddit.user_overview`. :param limit: max number of items to get """ return self._reddit.user_overview(self.name, limit=limit)
python
def overview(self, limit=None): """GETs overview of user's activities. Calls :meth:`narwal.Reddit.user_overview`. :param limit: max number of items to get """ return self._reddit.user_overview(self.name, limit=limit)
[ "def", "overview", "(", "self", ",", "limit", "=", "None", ")", ":", "return", "self", ".", "_reddit", ".", "user_overview", "(", "self", ".", "name", ",", "limit", "=", "limit", ")" ]
GETs overview of user's activities. Calls :meth:`narwal.Reddit.user_overview`. :param limit: max number of items to get
[ "GETs", "overview", "of", "user", "s", "activities", ".", "Calls", ":", "meth", ":", "narwal", ".", "Reddit", ".", "user_overview", ".", ":", "param", "limit", ":", "max", "number", "of", "items", "to", "get" ]
train
https://github.com/larryng/narwal/blob/58c409a475c8ed865579a61d7010162ed8cef597/narwal/things.py#L599-L604
larryng/narwal
narwal/things.py
Account.comments
def comments(self, limit=None): """GETs user's comments. Calls :meth:`narwal.Reddit.user_comments`. :param limit: max number of comments to get """ return self._reddit.user_comments(self.name, limit=limit)
python
def comments(self, limit=None): """GETs user's comments. Calls :meth:`narwal.Reddit.user_comments`. :param limit: max number of comments to get """ return self._reddit.user_comments(self.name, limit=limit)
[ "def", "comments", "(", "self", ",", "limit", "=", "None", ")", ":", "return", "self", ".", "_reddit", ".", "user_comments", "(", "self", ".", "name", ",", "limit", "=", "limit", ")" ]
GETs user's comments. Calls :meth:`narwal.Reddit.user_comments`. :param limit: max number of comments to get
[ "GETs", "user", "s", "comments", ".", "Calls", ":", "meth", ":", "narwal", ".", "Reddit", ".", "user_comments", ".", ":", "param", "limit", ":", "max", "number", "of", "comments", "to", "get" ]
train
https://github.com/larryng/narwal/blob/58c409a475c8ed865579a61d7010162ed8cef597/narwal/things.py#L606-L611
larryng/narwal
narwal/things.py
Account.submitted
def submitted(self, limit=None): """GETs user's submissions. Calls :meth:`narwal.Reddit.user_submitted`. :param limit: max number of submissions to get """ return self._reddit.user_submitted(self.name, limit=limit)
python
def submitted(self, limit=None): """GETs user's submissions. Calls :meth:`narwal.Reddit.user_submitted`. :param limit: max number of submissions to get """ return self._reddit.user_submitted(self.name, limit=limit)
[ "def", "submitted", "(", "self", ",", "limit", "=", "None", ")", ":", "return", "self", ".", "_reddit", ".", "user_submitted", "(", "self", ".", "name", ",", "limit", "=", "limit", ")" ]
GETs user's submissions. Calls :meth:`narwal.Reddit.user_submitted`. :param limit: max number of submissions to get
[ "GETs", "user", "s", "submissions", ".", "Calls", ":", "meth", ":", "narwal", ".", "Reddit", ".", "user_submitted", ".", ":", "param", "limit", ":", "max", "number", "of", "submissions", "to", "get" ]
train
https://github.com/larryng/narwal/blob/58c409a475c8ed865579a61d7010162ed8cef597/narwal/things.py#L613-L618
larryng/narwal
narwal/things.py
Account.message
def message(self, subject, text): """Compose a message to this user. Calls :meth:`narwal.Reddit.compose`. :param subject: subject of message :param text: body of message """ return self._reddit.compose(self.name, subject, text)
python
def message(self, subject, text): """Compose a message to this user. Calls :meth:`narwal.Reddit.compose`. :param subject: subject of message :param text: body of message """ return self._reddit.compose(self.name, subject, text)
[ "def", "message", "(", "self", ",", "subject", ",", "text", ")", ":", "return", "self", ".", "_reddit", ".", "compose", "(", "self", ".", "name", ",", "subject", ",", "text", ")" ]
Compose a message to this user. Calls :meth:`narwal.Reddit.compose`. :param subject: subject of message :param text: body of message
[ "Compose", "a", "message", "to", "this", "user", ".", "Calls", ":", "meth", ":", "narwal", ".", "Reddit", ".", "compose", ".", ":", "param", "subject", ":", "subject", "of", "message", ":", "param", "text", ":", "body", "of", "message" ]
train
https://github.com/larryng/narwal/blob/58c409a475c8ed865579a61d7010162ed8cef597/narwal/things.py#L625-L631
hangyan/shaw
shaw/decorator/checked-exception.py
catches
def catches(exc, handler=re_raise): ''' Function decorator. Used to decorate function that handles exception class exc. An optional exception handler can be passed as a second argument. This exception handler shall have the signature handler(exc, message, traceback). ''' if not __CHECKING__: return lambda f: f def wrap(f): def call(*args, **kwd): try: ID = exc_checker.set_attention(exc) res = f(*args, **kwd) exc_checker.remove_attention(exc, ID) return res # handle checked exception except exc, e: exc_checker.remove_attention(exc, ID) traceback = sys.exc_info()[2] return handler(exc, str(e), traceback.tb_next.tb_next) # re-raise unchecked exception but remove checked exeption info first except Exception, e: exc_checker.remove_attention(exc, ID) traceback = sys.exc_info()[2] raise e.__class__, e.args, traceback.tb_next.tb_next call.__name__ = f.__name__ return call return wrap
python
def catches(exc, handler=re_raise): ''' Function decorator. Used to decorate function that handles exception class exc. An optional exception handler can be passed as a second argument. This exception handler shall have the signature handler(exc, message, traceback). ''' if not __CHECKING__: return lambda f: f def wrap(f): def call(*args, **kwd): try: ID = exc_checker.set_attention(exc) res = f(*args, **kwd) exc_checker.remove_attention(exc, ID) return res # handle checked exception except exc, e: exc_checker.remove_attention(exc, ID) traceback = sys.exc_info()[2] return handler(exc, str(e), traceback.tb_next.tb_next) # re-raise unchecked exception but remove checked exeption info first except Exception, e: exc_checker.remove_attention(exc, ID) traceback = sys.exc_info()[2] raise e.__class__, e.args, traceback.tb_next.tb_next call.__name__ = f.__name__ return call return wrap
[ "def", "catches", "(", "exc", ",", "handler", "=", "re_raise", ")", ":", "if", "not", "__CHECKING__", ":", "return", "lambda", "f", ":", "f", "def", "wrap", "(", "f", ")", ":", "def", "call", "(", "*", "args", ",", "*", "*", "kwd", ")", ":", "t...
Function decorator. Used to decorate function that handles exception class exc. An optional exception handler can be passed as a second argument. This exception handler shall have the signature handler(exc, message, traceback).
[ "Function", "decorator", ".", "Used", "to", "decorate", "function", "that", "handles", "exception", "class", "exc", "." ]
train
https://github.com/hangyan/shaw/blob/63d01d35e225ba4edb9c61edaf351e1bc0e8fd15/shaw/decorator/checked-exception.py#L43-L73
hangyan/shaw
shaw/decorator/checked-exception.py
throws
def throws(exc): ''' throws(exc)(func) -> func' Function decorator. Used to decorate a function that raises exc. ''' if not __CHECKING__: return lambda f: f def wrap(f): def call(*args, **kwd): res = f(*args, **kwd) # raise UncheckedExceptionError if exc is not automatically # registered by a function decorated with @catches(exc); # otherwise do nothing exc_checker.throwing(exc) return res call.__name__ = f.__name__ return call return wrap
python
def throws(exc): ''' throws(exc)(func) -> func' Function decorator. Used to decorate a function that raises exc. ''' if not __CHECKING__: return lambda f: f def wrap(f): def call(*args, **kwd): res = f(*args, **kwd) # raise UncheckedExceptionError if exc is not automatically # registered by a function decorated with @catches(exc); # otherwise do nothing exc_checker.throwing(exc) return res call.__name__ = f.__name__ return call return wrap
[ "def", "throws", "(", "exc", ")", ":", "if", "not", "__CHECKING__", ":", "return", "lambda", "f", ":", "f", "def", "wrap", "(", "f", ")", ":", "def", "call", "(", "*", "args", ",", "*", "*", "kwd", ")", ":", "res", "=", "f", "(", "*", "args",...
throws(exc)(func) -> func' Function decorator. Used to decorate a function that raises exc.
[ "throws", "(", "exc", ")", "(", "func", ")", "-", ">", "func" ]
train
https://github.com/hangyan/shaw/blob/63d01d35e225ba4edb9c61edaf351e1bc0e8fd15/shaw/decorator/checked-exception.py#L76-L95
lokhman/pydbal
pydbal/threading.py
SafeConnection.locked
def locked(self): """Context generator for `with` statement, yields thread-safe connection. :return: thread-safe connection :rtype: pydbal.connection.Connection """ conn = self._get_connection() try: self._lock(conn) yield conn finally: self._unlock(conn)
python
def locked(self): """Context generator for `with` statement, yields thread-safe connection. :return: thread-safe connection :rtype: pydbal.connection.Connection """ conn = self._get_connection() try: self._lock(conn) yield conn finally: self._unlock(conn)
[ "def", "locked", "(", "self", ")", ":", "conn", "=", "self", ".", "_get_connection", "(", ")", "try", ":", "self", ".", "_lock", "(", "conn", ")", "yield", "conn", "finally", ":", "self", ".", "_unlock", "(", "conn", ")" ]
Context generator for `with` statement, yields thread-safe connection. :return: thread-safe connection :rtype: pydbal.connection.Connection
[ "Context", "generator", "for", "with", "statement", "yields", "thread", "-", "safe", "connection", "." ]
train
https://github.com/lokhman/pydbal/blob/53f396a2a18826e9fff178cd2c0636c1656cbaea/pydbal/threading.py#L75-L86
lokhman/pydbal
pydbal/threading.py
SafeConnection.query
def query(self, sql, *args, **kwargs): """Executes an SQL SELECT query and returns rows generator. :param sql: query to execute :param args: parameters iterable :param kwargs: parameters iterable :return: rows generator :rtype: generator """ with self.locked() as conn: for row in conn.query(sql, *args, **kwargs): yield row
python
def query(self, sql, *args, **kwargs): """Executes an SQL SELECT query and returns rows generator. :param sql: query to execute :param args: parameters iterable :param kwargs: parameters iterable :return: rows generator :rtype: generator """ with self.locked() as conn: for row in conn.query(sql, *args, **kwargs): yield row
[ "def", "query", "(", "self", ",", "sql", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "self", ".", "locked", "(", ")", "as", "conn", ":", "for", "row", "in", "conn", ".", "query", "(", "sql", ",", "*", "args", ",", "*", "*", ...
Executes an SQL SELECT query and returns rows generator. :param sql: query to execute :param args: parameters iterable :param kwargs: parameters iterable :return: rows generator :rtype: generator
[ "Executes", "an", "SQL", "SELECT", "query", "and", "returns", "rows", "generator", "." ]
train
https://github.com/lokhman/pydbal/blob/53f396a2a18826e9fff178cd2c0636c1656cbaea/pydbal/threading.py#L88-L99
lokhman/pydbal
pydbal/threading.py
SafeConnection.execute
def execute(self, sql, *args, **kwargs): """Executes an SQL INSERT/UPDATE/DELETE query with the given parameters and returns the number of affected rows. :param sql: statement to execute :param args: parameters iterable :param kwargs: parameters iterable :return: number of affected rows :rtype: int """ with self.locked() as conn: return conn.execute(sql, *args, **kwargs)
python
def execute(self, sql, *args, **kwargs): """Executes an SQL INSERT/UPDATE/DELETE query with the given parameters and returns the number of affected rows. :param sql: statement to execute :param args: parameters iterable :param kwargs: parameters iterable :return: number of affected rows :rtype: int """ with self.locked() as conn: return conn.execute(sql, *args, **kwargs)
[ "def", "execute", "(", "self", ",", "sql", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "self", ".", "locked", "(", ")", "as", "conn", ":", "return", "conn", ".", "execute", "(", "sql", ",", "*", "args", ",", "*", "*", "kwargs",...
Executes an SQL INSERT/UPDATE/DELETE query with the given parameters and returns the number of affected rows. :param sql: statement to execute :param args: parameters iterable :param kwargs: parameters iterable :return: number of affected rows :rtype: int
[ "Executes", "an", "SQL", "INSERT", "/", "UPDATE", "/", "DELETE", "query", "with", "the", "given", "parameters", "and", "returns", "the", "number", "of", "affected", "rows", "." ]
train
https://github.com/lokhman/pydbal/blob/53f396a2a18826e9fff178cd2c0636c1656cbaea/pydbal/threading.py#L101-L111
lokhman/pydbal
pydbal/threading.py
SafeConnection.fetch
def fetch(self, sql, *args, **kwargs): """Executes an SQL SELECT query and returns the first row or `None`. :param sql: statement to execute :param args: parameters iterable :param kwargs: parameters iterable :return: the first row or `None` """ with self.locked() as conn: return conn.query(sql, *args, **kwargs).fetch()
python
def fetch(self, sql, *args, **kwargs): """Executes an SQL SELECT query and returns the first row or `None`. :param sql: statement to execute :param args: parameters iterable :param kwargs: parameters iterable :return: the first row or `None` """ with self.locked() as conn: return conn.query(sql, *args, **kwargs).fetch()
[ "def", "fetch", "(", "self", ",", "sql", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "self", ".", "locked", "(", ")", "as", "conn", ":", "return", "conn", ".", "query", "(", "sql", ",", "*", "args", ",", "*", "*", "kwargs", "...
Executes an SQL SELECT query and returns the first row or `None`. :param sql: statement to execute :param args: parameters iterable :param kwargs: parameters iterable :return: the first row or `None`
[ "Executes", "an", "SQL", "SELECT", "query", "and", "returns", "the", "first", "row", "or", "None", "." ]
train
https://github.com/lokhman/pydbal/blob/53f396a2a18826e9fff178cd2c0636c1656cbaea/pydbal/threading.py#L113-L122
lokhman/pydbal
pydbal/threading.py
SafeConnection.fetch_all
def fetch_all(self, sql, *args, **kwargs): """Executes an SQL SELECT query and returns all selected rows. :param sql: statement to execute :param args: parameters iterable :param kwargs: parameters iterable :return: all selected rows :rtype: list """ with self.locked() as conn: return conn.query(sql, *args, **kwargs).fetch_all()
python
def fetch_all(self, sql, *args, **kwargs): """Executes an SQL SELECT query and returns all selected rows. :param sql: statement to execute :param args: parameters iterable :param kwargs: parameters iterable :return: all selected rows :rtype: list """ with self.locked() as conn: return conn.query(sql, *args, **kwargs).fetch_all()
[ "def", "fetch_all", "(", "self", ",", "sql", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "self", ".", "locked", "(", ")", "as", "conn", ":", "return", "conn", ".", "query", "(", "sql", ",", "*", "args", ",", "*", "*", "kwargs",...
Executes an SQL SELECT query and returns all selected rows. :param sql: statement to execute :param args: parameters iterable :param kwargs: parameters iterable :return: all selected rows :rtype: list
[ "Executes", "an", "SQL", "SELECT", "query", "and", "returns", "all", "selected", "rows", "." ]
train
https://github.com/lokhman/pydbal/blob/53f396a2a18826e9fff178cd2c0636c1656cbaea/pydbal/threading.py#L124-L134
lokhman/pydbal
pydbal/threading.py
SafeConnection.fetch_column
def fetch_column(self, sql, *args, **kwargs): """Executes an SQL SELECT query and returns the first column of the first row or `None`. :param sql: statement to execute :param args: parameters iterable :param kwargs: parameters iterable :return: the first row of the first column or `None` """ with self.locked() as conn: return conn.query(sql, *args, **kwargs).fetch_column()
python
def fetch_column(self, sql, *args, **kwargs): """Executes an SQL SELECT query and returns the first column of the first row or `None`. :param sql: statement to execute :param args: parameters iterable :param kwargs: parameters iterable :return: the first row of the first column or `None` """ with self.locked() as conn: return conn.query(sql, *args, **kwargs).fetch_column()
[ "def", "fetch_column", "(", "self", ",", "sql", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "self", ".", "locked", "(", ")", "as", "conn", ":", "return", "conn", ".", "query", "(", "sql", ",", "*", "args", ",", "*", "*", "kwarg...
Executes an SQL SELECT query and returns the first column of the first row or `None`. :param sql: statement to execute :param args: parameters iterable :param kwargs: parameters iterable :return: the first row of the first column or `None`
[ "Executes", "an", "SQL", "SELECT", "query", "and", "returns", "the", "first", "column", "of", "the", "first", "row", "or", "None", "." ]
train
https://github.com/lokhman/pydbal/blob/53f396a2a18826e9fff178cd2c0636c1656cbaea/pydbal/threading.py#L136-L145
lokhman/pydbal
pydbal/threading.py
SafeConnection.insert
def insert(self, table, values): """Inserts a table row with specified data. :param table: the expression of the table to insert data into, quoted or unquoted :param values: a dictionary containing column-value pairs :return: last inserted ID """ with self.locked() as conn: return conn.insert(table, values)
python
def insert(self, table, values): """Inserts a table row with specified data. :param table: the expression of the table to insert data into, quoted or unquoted :param values: a dictionary containing column-value pairs :return: last inserted ID """ with self.locked() as conn: return conn.insert(table, values)
[ "def", "insert", "(", "self", ",", "table", ",", "values", ")", ":", "with", "self", ".", "locked", "(", ")", "as", "conn", ":", "return", "conn", ".", "insert", "(", "table", ",", "values", ")" ]
Inserts a table row with specified data. :param table: the expression of the table to insert data into, quoted or unquoted :param values: a dictionary containing column-value pairs :return: last inserted ID
[ "Inserts", "a", "table", "row", "with", "specified", "data", "." ]
train
https://github.com/lokhman/pydbal/blob/53f396a2a18826e9fff178cd2c0636c1656cbaea/pydbal/threading.py#L161-L169
lokhman/pydbal
pydbal/threading.py
SafeConnection.update
def update(self, table, values, identifier): """Updates a table row with specified data by given identifier. :param table: the expression of the table to update quoted or unquoted :param values: a dictionary containing column-value pairs :param identifier: the update criteria; a dictionary containing column-value pairs :return: the number of affected rows :rtype: int """ with self.locked() as conn: return conn.update(table, values, identifier)
python
def update(self, table, values, identifier): """Updates a table row with specified data by given identifier. :param table: the expression of the table to update quoted or unquoted :param values: a dictionary containing column-value pairs :param identifier: the update criteria; a dictionary containing column-value pairs :return: the number of affected rows :rtype: int """ with self.locked() as conn: return conn.update(table, values, identifier)
[ "def", "update", "(", "self", ",", "table", ",", "values", ",", "identifier", ")", ":", "with", "self", ".", "locked", "(", ")", "as", "conn", ":", "return", "conn", ".", "update", "(", "table", ",", "values", ",", "identifier", ")" ]
Updates a table row with specified data by given identifier. :param table: the expression of the table to update quoted or unquoted :param values: a dictionary containing column-value pairs :param identifier: the update criteria; a dictionary containing column-value pairs :return: the number of affected rows :rtype: int
[ "Updates", "a", "table", "row", "with", "specified", "data", "by", "given", "identifier", "." ]
train
https://github.com/lokhman/pydbal/blob/53f396a2a18826e9fff178cd2c0636c1656cbaea/pydbal/threading.py#L171-L181
lokhman/pydbal
pydbal/threading.py
SafeConnection.delete
def delete(self, table, identifier): """Deletes a table row by given identifier. :param table: the expression of the table to update quoted or unquoted :param identifier: the delete criteria; a dictionary containing column-value pairs :return: the number of affected rows :rtype: int """ with self.locked() as conn: return conn.delete(table, identifier)
python
def delete(self, table, identifier): """Deletes a table row by given identifier. :param table: the expression of the table to update quoted or unquoted :param identifier: the delete criteria; a dictionary containing column-value pairs :return: the number of affected rows :rtype: int """ with self.locked() as conn: return conn.delete(table, identifier)
[ "def", "delete", "(", "self", ",", "table", ",", "identifier", ")", ":", "with", "self", ".", "locked", "(", ")", "as", "conn", ":", "return", "conn", ".", "delete", "(", "table", ",", "identifier", ")" ]
Deletes a table row by given identifier. :param table: the expression of the table to update quoted or unquoted :param identifier: the delete criteria; a dictionary containing column-value pairs :return: the number of affected rows :rtype: int
[ "Deletes", "a", "table", "row", "by", "given", "identifier", "." ]
train
https://github.com/lokhman/pydbal/blob/53f396a2a18826e9fff178cd2c0636c1656cbaea/pydbal/threading.py#L183-L192
duniter/duniter-python-api
duniterpy/helpers.py
ensure_bytes
def ensure_bytes(data: Union[str, bytes]) -> bytes: """ Convert data in bytes if data is a string :param data: Data :rtype bytes: """ if isinstance(data, str): return bytes(data, 'utf-8') return data
python
def ensure_bytes(data: Union[str, bytes]) -> bytes: """ Convert data in bytes if data is a string :param data: Data :rtype bytes: """ if isinstance(data, str): return bytes(data, 'utf-8') return data
[ "def", "ensure_bytes", "(", "data", ":", "Union", "[", "str", ",", "bytes", "]", ")", "->", "bytes", ":", "if", "isinstance", "(", "data", ",", "str", ")", ":", "return", "bytes", "(", "data", ",", "'utf-8'", ")", "return", "data" ]
Convert data in bytes if data is a string :param data: Data :rtype bytes:
[ "Convert", "data", "in", "bytes", "if", "data", "is", "a", "string" ]
train
https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/helpers.py#L5-L15
duniter/duniter-python-api
duniterpy/helpers.py
ensure_str
def ensure_str(data: Union[str, bytes]) -> str: """ Convert data in str if data are bytes :param data: Data :rtype str: """ if isinstance(data, bytes): return str(data, 'utf-8') return data
python
def ensure_str(data: Union[str, bytes]) -> str: """ Convert data in str if data are bytes :param data: Data :rtype str: """ if isinstance(data, bytes): return str(data, 'utf-8') return data
[ "def", "ensure_str", "(", "data", ":", "Union", "[", "str", ",", "bytes", "]", ")", "->", "str", ":", "if", "isinstance", "(", "data", ",", "bytes", ")", ":", "return", "str", "(", "data", ",", "'utf-8'", ")", "return", "data" ]
Convert data in str if data are bytes :param data: Data :rtype str:
[ "Convert", "data", "in", "str", "if", "data", "are", "bytes" ]
train
https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/helpers.py#L18-L28
duniter/duniter-python-api
duniterpy/helpers.py
xor_bytes
def xor_bytes(b1: bytes, b2: bytes) -> bytearray: """ Apply XOR operation on two bytes arguments :param b1: First bytes argument :param b2: Second bytes argument :rtype bytearray: """ result = bytearray() for i1, i2 in zip(b1, b2): result.append(i1 ^ i2) return result
python
def xor_bytes(b1: bytes, b2: bytes) -> bytearray: """ Apply XOR operation on two bytes arguments :param b1: First bytes argument :param b2: Second bytes argument :rtype bytearray: """ result = bytearray() for i1, i2 in zip(b1, b2): result.append(i1 ^ i2) return result
[ "def", "xor_bytes", "(", "b1", ":", "bytes", ",", "b2", ":", "bytes", ")", "->", "bytearray", ":", "result", "=", "bytearray", "(", ")", "for", "i1", ",", "i2", "in", "zip", "(", "b1", ",", "b2", ")", ":", "result", ".", "append", "(", "i1", "^...
Apply XOR operation on two bytes arguments :param b1: First bytes argument :param b2: Second bytes argument :rtype bytearray:
[ "Apply", "XOR", "operation", "on", "two", "bytes", "arguments" ]
train
https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/helpers.py#L31-L42
cohorte/cohorte-herald
python/herald/remote/herald_jabsorbrpc.py
JabsorbRpcDispatcher._simple_dispatch
def _simple_dispatch(self, name, params): """ Dispatch method """ # Normalize parameters if params: if isinstance(params, (list, tuple)): params = [jabsorb.from_jabsorb(param) for param in params] else: params = {key: jabsorb.from_jabsorb(value) for key, value in params.items()} # Dispatch like JSON-RPC return super(JabsorbRpcDispatcher, self)._simple_dispatch(name, params)
python
def _simple_dispatch(self, name, params): """ Dispatch method """ # Normalize parameters if params: if isinstance(params, (list, tuple)): params = [jabsorb.from_jabsorb(param) for param in params] else: params = {key: jabsorb.from_jabsorb(value) for key, value in params.items()} # Dispatch like JSON-RPC return super(JabsorbRpcDispatcher, self)._simple_dispatch(name, params)
[ "def", "_simple_dispatch", "(", "self", ",", "name", ",", "params", ")", ":", "# Normalize parameters", "if", "params", ":", "if", "isinstance", "(", "params", ",", "(", "list", ",", "tuple", ")", ")", ":", "params", "=", "[", "jabsorb", ".", "from_jabso...
Dispatch method
[ "Dispatch", "method" ]
train
https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/herald/remote/herald_jabsorbrpc.py#L84-L97
funkybob/knights-templater
knights/compiler.py
kompile
def kompile(src, raw=False, filename='<compiler>', loader=None, **kwargs): ''' Creates a new class based on the supplied template, and returnsit. class Template(object): def __call__(self, context): return ''.join(self._iterator(context)) def _iterator(self, context): return map(str, self._root(context) def _root(self, context): yield '' yield ... yield from self.head(context) Blocks create new methods, and add a 'yield from self.{block}(context)' to the current function ''' parser = Parser(src, loader=loader) parser.load_library('knights.tags') parser.load_library('knights.helpers') parser.build_method('_root') if parser.parent: # Remove _root from the method list parser.methods = [ method for method in parser.methods if method.name != '_root' ] klass = parser.build_class() # Wrap it in a module inst = ast.Module(body=[klass]) ast.fix_missing_locations(inst) if kwargs.get('astor', False): import astor print(astor.to_source(inst)) # Compile code to create class code = compile(inst, filename=filename, mode='exec', optimize=2) # Execute it and return the instance g = { '_': Helpers(parser.helpers), 'parent': parser.parent, 'ContextScope': ContextScope, } eval(code, g) klass = g['Template'] if raw: return klass return klass()
python
def kompile(src, raw=False, filename='<compiler>', loader=None, **kwargs): ''' Creates a new class based on the supplied template, and returnsit. class Template(object): def __call__(self, context): return ''.join(self._iterator(context)) def _iterator(self, context): return map(str, self._root(context) def _root(self, context): yield '' yield ... yield from self.head(context) Blocks create new methods, and add a 'yield from self.{block}(context)' to the current function ''' parser = Parser(src, loader=loader) parser.load_library('knights.tags') parser.load_library('knights.helpers') parser.build_method('_root') if parser.parent: # Remove _root from the method list parser.methods = [ method for method in parser.methods if method.name != '_root' ] klass = parser.build_class() # Wrap it in a module inst = ast.Module(body=[klass]) ast.fix_missing_locations(inst) if kwargs.get('astor', False): import astor print(astor.to_source(inst)) # Compile code to create class code = compile(inst, filename=filename, mode='exec', optimize=2) # Execute it and return the instance g = { '_': Helpers(parser.helpers), 'parent': parser.parent, 'ContextScope': ContextScope, } eval(code, g) klass = g['Template'] if raw: return klass return klass()
[ "def", "kompile", "(", "src", ",", "raw", "=", "False", ",", "filename", "=", "'<compiler>'", ",", "loader", "=", "None", ",", "*", "*", "kwargs", ")", ":", "parser", "=", "Parser", "(", "src", ",", "loader", "=", "loader", ")", "parser", ".", "loa...
Creates a new class based on the supplied template, and returnsit. class Template(object): def __call__(self, context): return ''.join(self._iterator(context)) def _iterator(self, context): return map(str, self._root(context) def _root(self, context): yield '' yield ... yield from self.head(context) Blocks create new methods, and add a 'yield from self.{block}(context)' to the current function
[ "Creates", "a", "new", "class", "based", "on", "the", "supplied", "template", "and", "returnsit", "." ]
train
https://github.com/funkybob/knights-templater/blob/b15cdbaae7d824d02f7f03ca04599ae94bb759dd/knights/compiler.py#L8-L66
joedborg/CoPing
CoPing/ping.py
calculate_checksum
def calculate_checksum(source_string): """ A port of the functionality of in_cksum() from ping.c Ideally this would act on the string as a series of 16-bit ints (host packed), but this works. Network data is big-endian, hosts are typically little-endian """ countTo = (int(len(source_string) / 2)) * 2 sum = 0 count = 0 # Handle bytes in pairs (decoding as short ints) loByte = 0 hiByte = 0 while count < countTo: if (sys.byteorder == "little"): loByte = source_string[count] hiByte = source_string[count + 1] else: loByte = source_string[count + 1] hiByte = source_string[count] sum = sum + (ord(hiByte) * 256 + ord(loByte)) count += 2 # Handle last byte if applicable (odd-number of bytes) # Endianness should be irrelevant in this case if countTo < len(source_string): # Check for odd length loByte = source_string[len(source_string) - 1] sum += ord(loByte) sum &= 0xffffffff # Truncate sum to 32 bits (a variance from ping.c, which # uses signed ints, but overflow is unlikely in ping) sum = (sum >> 16) + (sum & 0xffff) # Add high 16 bits to low 16 bits sum += (sum >> 16) # Add carry from above (if any) answer = ~sum & 0xffff # Invert and truncate to 16 bits answer = socket.htons(answer) return answer
python
def calculate_checksum(source_string): """ A port of the functionality of in_cksum() from ping.c Ideally this would act on the string as a series of 16-bit ints (host packed), but this works. Network data is big-endian, hosts are typically little-endian """ countTo = (int(len(source_string) / 2)) * 2 sum = 0 count = 0 # Handle bytes in pairs (decoding as short ints) loByte = 0 hiByte = 0 while count < countTo: if (sys.byteorder == "little"): loByte = source_string[count] hiByte = source_string[count + 1] else: loByte = source_string[count + 1] hiByte = source_string[count] sum = sum + (ord(hiByte) * 256 + ord(loByte)) count += 2 # Handle last byte if applicable (odd-number of bytes) # Endianness should be irrelevant in this case if countTo < len(source_string): # Check for odd length loByte = source_string[len(source_string) - 1] sum += ord(loByte) sum &= 0xffffffff # Truncate sum to 32 bits (a variance from ping.c, which # uses signed ints, but overflow is unlikely in ping) sum = (sum >> 16) + (sum & 0xffff) # Add high 16 bits to low 16 bits sum += (sum >> 16) # Add carry from above (if any) answer = ~sum & 0xffff # Invert and truncate to 16 bits answer = socket.htons(answer) return answer
[ "def", "calculate_checksum", "(", "source_string", ")", ":", "countTo", "=", "(", "int", "(", "len", "(", "source_string", ")", "/", "2", ")", ")", "*", "2", "sum", "=", "0", "count", "=", "0", "# Handle bytes in pairs (decoding as short ints)", "loByte", "=...
A port of the functionality of in_cksum() from ping.c Ideally this would act on the string as a series of 16-bit ints (host packed), but this works. Network data is big-endian, hosts are typically little-endian
[ "A", "port", "of", "the", "functionality", "of", "in_cksum", "()", "from", "ping", ".", "c", "Ideally", "this", "would", "act", "on", "the", "string", "as", "a", "series", "of", "16", "-", "bit", "ints", "(", "host", "packed", ")", "but", "this", "wo...
train
https://github.com/joedborg/CoPing/blob/2239729ee4107b999c1cba696d94f7d48ab73d36/CoPing/ping.py#L54-L92
joedborg/CoPing
CoPing/ping.py
Ping.signal_handler
def signal_handler(self, signum, frame): """ Handle print_exit via signals. """ self.print_exit() print("\n(Terminated with signal %d)\n" % (signum)) sys.exit(0)
python
def signal_handler(self, signum, frame): """ Handle print_exit via signals. """ self.print_exit() print("\n(Terminated with signal %d)\n" % (signum)) sys.exit(0)
[ "def", "signal_handler", "(", "self", ",", "signum", ",", "frame", ")", ":", "self", ".", "print_exit", "(", ")", "print", "(", "\"\\n(Terminated with signal %d)\\n\"", "%", "(", "signum", ")", ")", "sys", ".", "exit", "(", "0", ")" ]
Handle print_exit via signals.
[ "Handle", "print_exit", "via", "signals", "." ]
train
https://github.com/joedborg/CoPing/blob/2239729ee4107b999c1cba696d94f7d48ab73d36/CoPing/ping.py#L136-L142
joedborg/CoPing
CoPing/ping.py
Ping.header2dict
def header2dict(self, names, struct_format, data): """ Unpack the raw received IP and ICMP header information to a dict. """ unpacked_data = struct.unpack(struct_format, data) return dict(zip(names, unpacked_data))
python
def header2dict(self, names, struct_format, data): """ Unpack the raw received IP and ICMP header information to a dict. """ unpacked_data = struct.unpack(struct_format, data) return dict(zip(names, unpacked_data))
[ "def", "header2dict", "(", "self", ",", "names", ",", "struct_format", ",", "data", ")", ":", "unpacked_data", "=", "struct", ".", "unpack", "(", "struct_format", ",", "data", ")", "return", "dict", "(", "zip", "(", "names", ",", "unpacked_data", ")", ")...
Unpack the raw received IP and ICMP header information to a dict.
[ "Unpack", "the", "raw", "received", "IP", "and", "ICMP", "header", "information", "to", "a", "dict", "." ]
train
https://github.com/joedborg/CoPing/blob/2239729ee4107b999c1cba696d94f7d48ab73d36/CoPing/ping.py#L149-L154
joedborg/CoPing
CoPing/ping.py
Ping.do
def do(self): """ Send one ICMP ECHO_REQUEST and receive the response until self.timeout. """ try: # One could use UDP here, but it's obscure current_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname("icmp")) except socket.error as (errno, msg): if errno == 1: # Operation not permitted - Add more information to traceback etype, evalue, etb = sys.exc_info() evalue = etype( "%s - Note that ICMP messages can only be send from processes running as root." % evalue ) raise etype, evalue, etb raise # raise the original error send_time = self.send_one_ping(current_socket) if send_time == None: return self.send_count += 1 receive_time, packet_size, ip, ip_header, icmp_header = self.receive_one_ping(current_socket) current_socket.close() if receive_time: self.receive_count += 1 delay = (receive_time - send_time) * 1000.0 self.total_time += delay if self.min_time > delay: self.min_time = delay if self.max_time < delay: self.max_time = delay return PingSuccess(delay, ip, packet_size, ip_header, icmp_header) else: return PingTimeout(self.destination)
python
def do(self): """ Send one ICMP ECHO_REQUEST and receive the response until self.timeout. """ try: # One could use UDP here, but it's obscure current_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname("icmp")) except socket.error as (errno, msg): if errno == 1: # Operation not permitted - Add more information to traceback etype, evalue, etb = sys.exc_info() evalue = etype( "%s - Note that ICMP messages can only be send from processes running as root." % evalue ) raise etype, evalue, etb raise # raise the original error send_time = self.send_one_ping(current_socket) if send_time == None: return self.send_count += 1 receive_time, packet_size, ip, ip_header, icmp_header = self.receive_one_ping(current_socket) current_socket.close() if receive_time: self.receive_count += 1 delay = (receive_time - send_time) * 1000.0 self.total_time += delay if self.min_time > delay: self.min_time = delay if self.max_time < delay: self.max_time = delay return PingSuccess(delay, ip, packet_size, ip_header, icmp_header) else: return PingTimeout(self.destination)
[ "def", "do", "(", "self", ")", ":", "try", ":", "# One could use UDP here, but it's obscure", "current_socket", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_RAW", ",", "socket", ".", "getprotobyname", "(", "\"icmp\"", ...
Send one ICMP ECHO_REQUEST and receive the response until self.timeout.
[ "Send", "one", "ICMP", "ECHO_REQUEST", "and", "receive", "the", "response", "until", "self", ".", "timeout", "." ]
train
https://github.com/joedborg/CoPing/blob/2239729ee4107b999c1cba696d94f7d48ab73d36/CoPing/ping.py#L157-L192
joedborg/CoPing
CoPing/ping.py
Ping.send_one_ping
def send_one_ping(self, current_socket): """ Send one ICMP ECHO_REQUEST. """ # Header is type (8), code (8), checksum (16), id (16), sequence (16) checksum = 0 # Make a dummy header with a 0 checksum. header = struct.pack( "!BBHHH", ICMP_ECHO, 0, checksum, self.own_id, self.seq_number ) padBytes = [] startVal = 0x42 for i in range(startVal, startVal + (self.packet_size)): padBytes += [(i & 0xff)] # Keep chars in the 0-255 range data = bytes(padBytes) # Calculate the checksum on the data and the dummy header. checksum = calculate_checksum(header + data) # Checksum is in network order # Now that we have the right checksum, we put that in. It's just easier # to make up a new header than to stuff it into the dummy. header = struct.pack( "!BBHHH", ICMP_ECHO, 0, checksum, self.own_id, self.seq_number ) packet = header + data send_time = default_timer() try: current_socket.sendto(packet, (self.destination, 1)) # Port number is irrelevant for ICMP except socket.error as e: print("General failure (%s)" % (e.args[1])) current_socket.close() return return send_time
python
def send_one_ping(self, current_socket): """ Send one ICMP ECHO_REQUEST. """ # Header is type (8), code (8), checksum (16), id (16), sequence (16) checksum = 0 # Make a dummy header with a 0 checksum. header = struct.pack( "!BBHHH", ICMP_ECHO, 0, checksum, self.own_id, self.seq_number ) padBytes = [] startVal = 0x42 for i in range(startVal, startVal + (self.packet_size)): padBytes += [(i & 0xff)] # Keep chars in the 0-255 range data = bytes(padBytes) # Calculate the checksum on the data and the dummy header. checksum = calculate_checksum(header + data) # Checksum is in network order # Now that we have the right checksum, we put that in. It's just easier # to make up a new header than to stuff it into the dummy. header = struct.pack( "!BBHHH", ICMP_ECHO, 0, checksum, self.own_id, self.seq_number ) packet = header + data send_time = default_timer() try: current_socket.sendto(packet, (self.destination, 1)) # Port number is irrelevant for ICMP except socket.error as e: print("General failure (%s)" % (e.args[1])) current_socket.close() return return send_time
[ "def", "send_one_ping", "(", "self", ",", "current_socket", ")", ":", "# Header is type (8), code (8), checksum (16), id (16), sequence (16)", "checksum", "=", "0", "# Make a dummy header with a 0 checksum.", "header", "=", "struct", ".", "pack", "(", "\"!BBHHH\"", ",", "IC...
Send one ICMP ECHO_REQUEST.
[ "Send", "one", "ICMP", "ECHO_REQUEST", "." ]
train
https://github.com/joedborg/CoPing/blob/2239729ee4107b999c1cba696d94f7d48ab73d36/CoPing/ping.py#L194-L232
joedborg/CoPing
CoPing/ping.py
Ping.receive_one_ping
def receive_one_ping(self, current_socket): """ Receive the ping from the socket. timeout = in ms. """ timeout = self.timeout / 1000.0 while True: # Loop while waiting for packet or timeout select_start = default_timer() inputready, outputready, exceptready = select.select([current_socket], [], [], timeout) select_duration = (default_timer() - select_start) if inputready == []: # timeout return None, 0, 0, 0, 0 receive_time = default_timer() packet_data, address = current_socket.recvfrom(ICMP_MAX_RECV) icmp_header = self.header2dict( names=[ "type", "code", "checksum", "packet_id", "seq_number" ], struct_format="!BBHHH", data=packet_data[20:28] ) if icmp_header["packet_id"] == self.own_id: # Our packet ip_header = self.header2dict( names=[ "version", "type", "length", "id", "flags", "ttl", "protocol", "checksum", "src_ip", "dest_ip" ], struct_format="!BBHHHBBHII", data=packet_data[:20] ) packet_size = len(packet_data) - 28 ip = socket.inet_ntoa(struct.pack("!I", ip_header["src_ip"])) # XXX: Why not ip = address[0] ??? return receive_time, packet_size, ip, ip_header, icmp_header timeout = timeout - select_duration if timeout <= 0: return None, 0, 0, 0, 0
python
def receive_one_ping(self, current_socket): """ Receive the ping from the socket. timeout = in ms. """ timeout = self.timeout / 1000.0 while True: # Loop while waiting for packet or timeout select_start = default_timer() inputready, outputready, exceptready = select.select([current_socket], [], [], timeout) select_duration = (default_timer() - select_start) if inputready == []: # timeout return None, 0, 0, 0, 0 receive_time = default_timer() packet_data, address = current_socket.recvfrom(ICMP_MAX_RECV) icmp_header = self.header2dict( names=[ "type", "code", "checksum", "packet_id", "seq_number" ], struct_format="!BBHHH", data=packet_data[20:28] ) if icmp_header["packet_id"] == self.own_id: # Our packet ip_header = self.header2dict( names=[ "version", "type", "length", "id", "flags", "ttl", "protocol", "checksum", "src_ip", "dest_ip" ], struct_format="!BBHHHBBHII", data=packet_data[:20] ) packet_size = len(packet_data) - 28 ip = socket.inet_ntoa(struct.pack("!I", ip_header["src_ip"])) # XXX: Why not ip = address[0] ??? return receive_time, packet_size, ip, ip_header, icmp_header timeout = timeout - select_duration if timeout <= 0: return None, 0, 0, 0, 0
[ "def", "receive_one_ping", "(", "self", ",", "current_socket", ")", ":", "timeout", "=", "self", ".", "timeout", "/", "1000.0", "while", "True", ":", "# Loop while waiting for packet or timeout", "select_start", "=", "default_timer", "(", ")", "inputready", ",", "...
Receive the ping from the socket. timeout = in ms.
[ "Receive", "the", "ping", "from", "the", "socket", ".", "timeout", "=", "in", "ms", "." ]
train
https://github.com/joedborg/CoPing/blob/2239729ee4107b999c1cba696d94f7d48ab73d36/CoPing/ping.py#L234-L277
cohorte/cohorte-herald
python/snippets/herald_mqtt/mqtt.py
MQTTRouter.get_link
def get_link(self, peer): """ Retrieves the link to the given peer """ for access in peer.accesses: if access.type == 'mqtt': break else: # No MQTT access found return None # Get server access tuple server = (access.server.host, access.server.port) with self.__lock: try: # Get existing link return self._links[server] except KeyError: # Create a new link link = self._links[server] = MQTTLink(access) return link
python
def get_link(self, peer): """ Retrieves the link to the given peer """ for access in peer.accesses: if access.type == 'mqtt': break else: # No MQTT access found return None # Get server access tuple server = (access.server.host, access.server.port) with self.__lock: try: # Get existing link return self._links[server] except KeyError: # Create a new link link = self._links[server] = MQTTLink(access) return link
[ "def", "get_link", "(", "self", ",", "peer", ")", ":", "for", "access", "in", "peer", ".", "accesses", ":", "if", "access", ".", "type", "==", "'mqtt'", ":", "break", "else", ":", "# No MQTT access found", "return", "None", "# Get server access tuple", "serv...
Retrieves the link to the given peer
[ "Retrieves", "the", "link", "to", "the", "given", "peer" ]
train
https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/snippets/herald_mqtt/mqtt.py#L20-L42
Laufire/ec
ec/modules/helpers.py
exit
def exit(exit_code=0): r"""A function to support exiting from exit hooks. Could also be used to exit from the calling scripts in a thread safe manner. """ core.processExitHooks() if state.isExitHooked and not hasattr(sys, 'exitfunc'): # The function is called from the exit hook sys.stderr.flush() sys.stdout.flush() os._exit(exit_code) #pylint: disable=W0212 sys.exit(exit_code)
python
def exit(exit_code=0): r"""A function to support exiting from exit hooks. Could also be used to exit from the calling scripts in a thread safe manner. """ core.processExitHooks() if state.isExitHooked and not hasattr(sys, 'exitfunc'): # The function is called from the exit hook sys.stderr.flush() sys.stdout.flush() os._exit(exit_code) #pylint: disable=W0212 sys.exit(exit_code)
[ "def", "exit", "(", "exit_code", "=", "0", ")", ":", "core", ".", "processExitHooks", "(", ")", "if", "state", ".", "isExitHooked", "and", "not", "hasattr", "(", "sys", ",", "'exitfunc'", ")", ":", "# The function is called from the exit hook", "sys", ".", "...
r"""A function to support exiting from exit hooks. Could also be used to exit from the calling scripts in a thread safe manner.
[ "r", "A", "function", "to", "support", "exiting", "from", "exit", "hooks", "." ]
train
https://github.com/Laufire/ec/blob/63e84a1daef9234487d7de538e5da233a7d13071/ec/modules/helpers.py#L22-L34
Laufire/ec
ec/modules/helpers.py
getDigestableArgs
def getDigestableArgs(Argv): r"""Splits the given Argv into *Args and **KwArgs. """ first_kwarg_pos = 0 for arg in Argv: if KWARG_VALIDATOR.search(arg): break else: first_kwarg_pos += 1 for arg in Argv[first_kwarg_pos:]: # ensure that the kwargs are valid if not KWARG_VALIDATOR.search(arg): raise HandledException('Could not parse the arg "%s".' % arg) return Argv[:first_kwarg_pos], list2dict(Argv[first_kwarg_pos:])
python
def getDigestableArgs(Argv): r"""Splits the given Argv into *Args and **KwArgs. """ first_kwarg_pos = 0 for arg in Argv: if KWARG_VALIDATOR.search(arg): break else: first_kwarg_pos += 1 for arg in Argv[first_kwarg_pos:]: # ensure that the kwargs are valid if not KWARG_VALIDATOR.search(arg): raise HandledException('Could not parse the arg "%s".' % arg) return Argv[:first_kwarg_pos], list2dict(Argv[first_kwarg_pos:])
[ "def", "getDigestableArgs", "(", "Argv", ")", ":", "first_kwarg_pos", "=", "0", "for", "arg", "in", "Argv", ":", "if", "KWARG_VALIDATOR", ".", "search", "(", "arg", ")", ":", "break", "else", ":", "first_kwarg_pos", "+=", "1", "for", "arg", "in", "Argv",...
r"""Splits the given Argv into *Args and **KwArgs.
[ "r", "Splits", "the", "given", "Argv", "into", "*", "Args", "and", "**", "KwArgs", "." ]
train
https://github.com/Laufire/ec/blob/63e84a1daef9234487d7de538e5da233a7d13071/ec/modules/helpers.py#L58-L74
Laufire/ec
ec/modules/helpers.py
listMemberHelps
def listMemberHelps(TargetGroup): r"""Gets help on a group's children. """ Members = [] for Member in TargetGroup.Members.values(): # get unique children (by discarding aliases) if Member not in Members: Members.append(Member) Ret = [] for Member in Members: Config = Member.Config Ret.append(('%s%s' % (Config['name'], ', %s' % Config['alias'] if 'alias' in Config else ''), Config.get('desc', ''))) return Ret
python
def listMemberHelps(TargetGroup): r"""Gets help on a group's children. """ Members = [] for Member in TargetGroup.Members.values(): # get unique children (by discarding aliases) if Member not in Members: Members.append(Member) Ret = [] for Member in Members: Config = Member.Config Ret.append(('%s%s' % (Config['name'], ', %s' % Config['alias'] if 'alias' in Config else ''), Config.get('desc', ''))) return Ret
[ "def", "listMemberHelps", "(", "TargetGroup", ")", ":", "Members", "=", "[", "]", "for", "Member", "in", "TargetGroup", ".", "Members", ".", "values", "(", ")", ":", "# get unique children (by discarding aliases)", "if", "Member", "not", "in", "Members", ":", ...
r"""Gets help on a group's children.
[ "r", "Gets", "help", "on", "a", "group", "s", "children", "." ]
train
https://github.com/Laufire/ec/blob/63e84a1daef9234487d7de538e5da233a7d13071/ec/modules/helpers.py#L133-L148