repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
treycucco/bidon
bidon/db/access/data_access.py
Upsert.target_str
def target_str(self): """Returns the string representation of the target property.""" if isinstance(self.target, tuple): return "({})".format(", ".join(self.target)) else: return self.target
python
def target_str(self): """Returns the string representation of the target property.""" if isinstance(self.target, tuple): return "({})".format(", ".join(self.target)) else: return self.target
[ "def", "target_str", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "target", ",", "tuple", ")", ":", "return", "\"({})\"", ".", "format", "(", "\", \"", ".", "join", "(", "self", ".", "target", ")", ")", "else", ":", "return", "self", ...
Returns the string representation of the target property.
[ "Returns", "the", "string", "representation", "of", "the", "target", "property", "." ]
train
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/access/data_access.py#L409-L414
eddiejessup/cellulist
cellulist/cell_list.py
get_inters
def get_inters(r, L, R_cut): ''' Return points within a given cut-off of each other, in a periodic system. Uses a cell-list. Parameters ---------- r: array, shape (n, d) where d is one of (2, 3). A set of n point coordinates. Coordinates are assumed to lie in [-L / 2, L / 2...
python
def get_inters(r, L, R_cut): ''' Return points within a given cut-off of each other, in a periodic system. Uses a cell-list. Parameters ---------- r: array, shape (n, d) where d is one of (2, 3). A set of n point coordinates. Coordinates are assumed to lie in [-L / 2, L / 2...
[ "def", "get_inters", "(", "r", ",", "L", ",", "R_cut", ")", ":", "if", "r", ".", "shape", "[", "1", "]", "==", "2", ":", "_cell_list", ".", "cell_list_2d", ".", "make_inters", "(", "r", ".", "T", ",", "L", ",", "R_cut", ")", "elif", "r", ".", ...
Return points within a given cut-off of each other, in a periodic system. Uses a cell-list. Parameters ---------- r: array, shape (n, d) where d is one of (2, 3). A set of n point coordinates. Coordinates are assumed to lie in [-L / 2, L / 2]. L: float. Bounds of the sy...
[ "Return", "points", "within", "a", "given", "cut", "-", "off", "of", "each", "other", "in", "a", "periodic", "system", "." ]
train
https://github.com/eddiejessup/cellulist/blob/44a790829274be3b8ce78abc6b4969e593d29f71/cellulist/cell_list.py#L9-L46
eddiejessup/cellulist
cellulist/cell_list.py
get_inters_direct
def get_inters_direct(r, L, R_cut): ''' Return points within a given cut-off of each other, in a periodic system. Uses a direct algorithm, which may be very slow for large numbers of points. Parameters ---------- r: array, shape (n, d) where d is one of (2, 3). A set of n point...
python
def get_inters_direct(r, L, R_cut): ''' Return points within a given cut-off of each other, in a periodic system. Uses a direct algorithm, which may be very slow for large numbers of points. Parameters ---------- r: array, shape (n, d) where d is one of (2, 3). A set of n point...
[ "def", "get_inters_direct", "(", "r", ",", "L", ",", "R_cut", ")", ":", "_cell_list", ".", "cell_list_direct", ".", "make_inters", "(", "r", ".", "T", ",", "L", ",", "R_cut", ")", "return", "_parse_inters", "(", ")" ]
Return points within a given cut-off of each other, in a periodic system. Uses a direct algorithm, which may be very slow for large numbers of points. Parameters ---------- r: array, shape (n, d) where d is one of (2, 3). A set of n point coordinates. Coordinates are assumed to...
[ "Return", "points", "within", "a", "given", "cut", "-", "off", "of", "each", "other", "in", "a", "periodic", "system", "." ]
train
https://github.com/eddiejessup/cellulist/blob/44a790829274be3b8ce78abc6b4969e593d29f71/cellulist/cell_list.py#L49-L80
anti1869/sunhead
src/sunhead/serializers/json.py
JSONSerializer.json_serial
def json_serial(cls, obj): """JSON serializer for objects not serializable by default json code""" if isinstance(obj, datetime): serial = obj.isoformat() elif issubclass(obj.__class__, enum.Enum): serial = obj.value elif isinstance(obj, timedelta): ...
python
def json_serial(cls, obj): """JSON serializer for objects not serializable by default json code""" if isinstance(obj, datetime): serial = obj.isoformat() elif issubclass(obj.__class__, enum.Enum): serial = obj.value elif isinstance(obj, timedelta): ...
[ "def", "json_serial", "(", "cls", ",", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "datetime", ")", ":", "serial", "=", "obj", ".", "isoformat", "(", ")", "elif", "issubclass", "(", "obj", ".", "__class__", ",", "enum", ".", "Enum", ")", ...
JSON serializer for objects not serializable by default json code
[ "JSON", "serializer", "for", "objects", "not", "serializable", "by", "default", "json", "code" ]
train
https://github.com/anti1869/sunhead/blob/5117ec797a38eb82d955241d20547d125efe80f3/src/sunhead/serializers/json.py#L34-L57
sci-bots/mpm
mpm/hooks.py
on_plugin_install
def on_plugin_install(plugin_directory, ostream=sys.stdout): ''' Run ``on_plugin_install`` script for specified plugin directory (if available). **TODO** Add support for Linux, OSX. Parameters ---------- plugin_directory : str File system to plugin directory. ostream :file-like...
python
def on_plugin_install(plugin_directory, ostream=sys.stdout): ''' Run ``on_plugin_install`` script for specified plugin directory (if available). **TODO** Add support for Linux, OSX. Parameters ---------- plugin_directory : str File system to plugin directory. ostream :file-like...
[ "def", "on_plugin_install", "(", "plugin_directory", ",", "ostream", "=", "sys", ".", "stdout", ")", ":", "current_directory", "=", "os", ".", "getcwd", "(", ")", "plugin_directory", "=", "ph", ".", "path", "(", "plugin_directory", ")", ".", "realpath", "(",...
Run ``on_plugin_install`` script for specified plugin directory (if available). **TODO** Add support for Linux, OSX. Parameters ---------- plugin_directory : str File system to plugin directory. ostream :file-like Output stream for status messages (default: ``sys.stdout``).
[ "Run", "on_plugin_install", "script", "for", "specified", "plugin", "directory", "(", "if", "available", ")", "." ]
train
https://github.com/sci-bots/mpm/blob/a69651cda4b37ee6b17df4fe0809249e7f4dc536/mpm/hooks.py#L12-L53
redodo/formats
formats/api.py
register
def register(type, parser, composer, **meta): """Registers a parser and composer of a format. You can use this method to overwrite existing formats. :param type: The unique name of the format :param parser: The method to parse data as the format :param composer: The method to compose data as the f...
python
def register(type, parser, composer, **meta): """Registers a parser and composer of a format. You can use this method to overwrite existing formats. :param type: The unique name of the format :param parser: The method to parse data as the format :param composer: The method to compose data as the f...
[ "def", "register", "(", "type", ",", "parser", ",", "composer", ",", "*", "*", "meta", ")", ":", "return", "default_bank", ".", "register", "(", "type", ",", "parser", ",", "composer", ",", "*", "*", "meta", ")" ]
Registers a parser and composer of a format. You can use this method to overwrite existing formats. :param type: The unique name of the format :param parser: The method to parse data as the format :param composer: The method to compose data as the format :param meta: The extra information associat...
[ "Registers", "a", "parser", "and", "composer", "of", "a", "format", "." ]
train
https://github.com/redodo/formats/blob/5bc7a79a2c93ef895534edbbf83f1efe2f62e081/formats/api.py#L21-L31
sys-git/certifiable
certifiable/cli_impl/core/certify_number.py
cli_certify_core_number
def cli_certify_core_number( config, min_value, max_value, value, ): """Console script for certify_number""" verbose = config['verbose'] if verbose: click.echo(Back.GREEN + Fore.BLACK + "ACTION: certify-int") def parser(v): # Attempt a json/pickle decode: try: v ...
python
def cli_certify_core_number( config, min_value, max_value, value, ): """Console script for certify_number""" verbose = config['verbose'] if verbose: click.echo(Back.GREEN + Fore.BLACK + "ACTION: certify-int") def parser(v): # Attempt a json/pickle decode: try: v ...
[ "def", "cli_certify_core_number", "(", "config", ",", "min_value", ",", "max_value", ",", "value", ",", ")", ":", "verbose", "=", "config", "[", "'verbose'", "]", "if", "verbose", ":", "click", ".", "echo", "(", "Back", ".", "GREEN", "+", "Fore", ".", ...
Console script for certify_number
[ "Console", "script", "for", "certify_number" ]
train
https://github.com/sys-git/certifiable/blob/a3c33c0d4f3ac2c53be9eded3fae633fa5f697f8/certifiable/cli_impl/core/certify_number.py#L24-L68
alexhayes/django-toolkit
django_toolkit/url/resolve.py
resolve_url
def resolve_url(url, desktop_user_agent=None, mobile_user_agent=None): """ Url Resolver Given a url a list of resolved urls is returned for desktop and mobile user agents """ if not desktop_user_agent: desktop_user_agent = DESKTOP_USER_AGENT if not mobile_user_agent: mobile_user_...
python
def resolve_url(url, desktop_user_agent=None, mobile_user_agent=None): """ Url Resolver Given a url a list of resolved urls is returned for desktop and mobile user agents """ if not desktop_user_agent: desktop_user_agent = DESKTOP_USER_AGENT if not mobile_user_agent: mobile_user_...
[ "def", "resolve_url", "(", "url", ",", "desktop_user_agent", "=", "None", ",", "mobile_user_agent", "=", "None", ")", ":", "if", "not", "desktop_user_agent", ":", "desktop_user_agent", "=", "DESKTOP_USER_AGENT", "if", "not", "mobile_user_agent", ":", "mobile_user_ag...
Url Resolver Given a url a list of resolved urls is returned for desktop and mobile user agents
[ "Url", "Resolver", "Given", "a", "url", "a", "list", "of", "resolved", "urls", "is", "returned", "for", "desktop", "and", "mobile", "user", "agents" ]
train
https://github.com/alexhayes/django-toolkit/blob/b64106392fad596defc915b8235fe6e1d0013b5b/django_toolkit/url/resolve.py#L22-L51
jorgeecardona/dynect
dynect/__init__.py
DynectAuth.token
def token(self): " Get token when needed." if hasattr(self, '_token'): return getattr(self, '_token') # Json formatted auth. data = json.dumps({'customer_name': self.customer, 'user_name': self.username, 'password': self...
python
def token(self): " Get token when needed." if hasattr(self, '_token'): return getattr(self, '_token') # Json formatted auth. data = json.dumps({'customer_name': self.customer, 'user_name': self.username, 'password': self...
[ "def", "token", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'_token'", ")", ":", "return", "getattr", "(", "self", ",", "'_token'", ")", "# Json formatted auth.", "data", "=", "json", ".", "dumps", "(", "{", "'customer_name'", ":", "self",...
Get token when needed.
[ "Get", "token", "when", "needed", "." ]
train
https://github.com/jorgeecardona/dynect/blob/d2cd85bc510f00108a3a5bfe515f45daae15a482/dynect/__init__.py#L27-L62
jorgeecardona/dynect
dynect/__init__.py
DynectAuth.parse_error
def parse_error(self, response): " Parse authentication errors." # Check invalid credentials. if self.check_error(response, 'failure', 'INVALID_DATA'): raise self.CredentialsError( self.response_message(response, 'ERROR'))
python
def parse_error(self, response): " Parse authentication errors." # Check invalid credentials. if self.check_error(response, 'failure', 'INVALID_DATA'): raise self.CredentialsError( self.response_message(response, 'ERROR'))
[ "def", "parse_error", "(", "self", ",", "response", ")", ":", "# Check invalid credentials.", "if", "self", ".", "check_error", "(", "response", ",", "'failure'", ",", "'INVALID_DATA'", ")", ":", "raise", "self", ".", "CredentialsError", "(", "self", ".", "res...
Parse authentication errors.
[ "Parse", "authentication", "errors", "." ]
train
https://github.com/jorgeecardona/dynect/blob/d2cd85bc510f00108a3a5bfe515f45daae15a482/dynect/__init__.py#L64-L70
jorgeecardona/dynect
dynect/__init__.py
DynectAuth.check_error
def check_error(self, response, status, err_cd): " Check an error in the response." if 'status' not in response: return False if response['status'] != status: return False if 'msgs' not in response: return False if not isinstance(response['...
python
def check_error(self, response, status, err_cd): " Check an error in the response." if 'status' not in response: return False if response['status'] != status: return False if 'msgs' not in response: return False if not isinstance(response['...
[ "def", "check_error", "(", "self", ",", "response", ",", "status", ",", "err_cd", ")", ":", "if", "'status'", "not", "in", "response", ":", "return", "False", "if", "response", "[", "'status'", "]", "!=", "status", ":", "return", "False", "if", "'msgs'",...
Check an error in the response.
[ "Check", "an", "error", "in", "the", "response", "." ]
train
https://github.com/jorgeecardona/dynect/blob/d2cd85bc510f00108a3a5bfe515f45daae15a482/dynect/__init__.py#L72-L95
jorgeecardona/dynect
dynect/__init__.py
Dynect.hook_response
def hook_response(self, response): " Detect any failure." # Decode content with json. response._content = json.loads(response.content) return response
python
def hook_response(self, response): " Detect any failure." # Decode content with json. response._content = json.loads(response.content) return response
[ "def", "hook_response", "(", "self", ",", "response", ")", ":", "# Decode content with json.", "response", ".", "_content", "=", "json", ".", "loads", "(", "response", ".", "content", ")", "return", "response" ]
Detect any failure.
[ "Detect", "any", "failure", "." ]
train
https://github.com/jorgeecardona/dynect/blob/d2cd85bc510f00108a3a5bfe515f45daae15a482/dynect/__init__.py#L173-L177
jorgeecardona/dynect
dynect/__init__.py
Dynect.check_errors
def check_errors(self, response): " Check some common errors." # Read content. content = response.content if 'status' not in content: raise self.GeneralError('We expect a status field.') # Return the decoded content if status is success. if content['status'...
python
def check_errors(self, response): " Check some common errors." # Read content. content = response.content if 'status' not in content: raise self.GeneralError('We expect a status field.') # Return the decoded content if status is success. if content['status'...
[ "def", "check_errors", "(", "self", ",", "response", ")", ":", "# Read content.", "content", "=", "response", ".", "content", "if", "'status'", "not", "in", "content", ":", "raise", "self", ".", "GeneralError", "(", "'We expect a status field.'", ")", "# Return ...
Check some common errors.
[ "Check", "some", "common", "errors", "." ]
train
https://github.com/jorgeecardona/dynect/blob/d2cd85bc510f00108a3a5bfe515f45daae15a482/dynect/__init__.py#L199-L239
jorgeecardona/dynect
dynect/__init__.py
Dynect.add_address
def add_address(self, fqdn, address, ttl=0): " Add a new address to a domain." data = {'rdata': {'address': address}, 'ttl': str(ttl)} # Make request. response = self.post('/REST/ARecord/%s/%s' % ( self.zone, fqdn), data=data) return Address(self, data=response.con...
python
def add_address(self, fqdn, address, ttl=0): " Add a new address to a domain." data = {'rdata': {'address': address}, 'ttl': str(ttl)} # Make request. response = self.post('/REST/ARecord/%s/%s' % ( self.zone, fqdn), data=data) return Address(self, data=response.con...
[ "def", "add_address", "(", "self", ",", "fqdn", ",", "address", ",", "ttl", "=", "0", ")", ":", "data", "=", "{", "'rdata'", ":", "{", "'address'", ":", "address", "}", ",", "'ttl'", ":", "str", "(", "ttl", ")", "}", "# Make request.", "response", ...
Add a new address to a domain.
[ "Add", "a", "new", "address", "to", "a", "domain", "." ]
train
https://github.com/jorgeecardona/dynect/blob/d2cd85bc510f00108a3a5bfe515f45daae15a482/dynect/__init__.py#L242-L251
jorgeecardona/dynect
dynect/__init__.py
Dynect.publish
def publish(self): " Publish last changes." # Publish changes. response = self.put('/REST/Zone/%s' % ( self.zone, ), data={'publish': True}) return response.content['data']['serial']
python
def publish(self): " Publish last changes." # Publish changes. response = self.put('/REST/Zone/%s' % ( self.zone, ), data={'publish': True}) return response.content['data']['serial']
[ "def", "publish", "(", "self", ")", ":", "# Publish changes.", "response", "=", "self", ".", "put", "(", "'/REST/Zone/%s'", "%", "(", "self", ".", "zone", ",", ")", ",", "data", "=", "{", "'publish'", ":", "True", "}", ")", "return", "response", ".", ...
Publish last changes.
[ "Publish", "last", "changes", "." ]
train
https://github.com/jorgeecardona/dynect/blob/d2cd85bc510f00108a3a5bfe515f45daae15a482/dynect/__init__.py#L254-L261
jorgeecardona/dynect
dynect/__init__.py
Dynect.list_address
def list_address(self, domain): " Get the list of addresses of a single domain." try: response = self.get('/REST/ARecord/%s/%s' % ( self.zone, domain)) except self.NotFoundError: return [] # Return a generator with the addresses. addresse...
python
def list_address(self, domain): " Get the list of addresses of a single domain." try: response = self.get('/REST/ARecord/%s/%s' % ( self.zone, domain)) except self.NotFoundError: return [] # Return a generator with the addresses. addresse...
[ "def", "list_address", "(", "self", ",", "domain", ")", ":", "try", ":", "response", "=", "self", ".", "get", "(", "'/REST/ARecord/%s/%s'", "%", "(", "self", ".", "zone", ",", "domain", ")", ")", "except", "self", ".", "NotFoundError", ":", "return", "...
Get the list of addresses of a single domain.
[ "Get", "the", "list", "of", "addresses", "of", "a", "single", "domain", "." ]
train
https://github.com/jorgeecardona/dynect/blob/d2cd85bc510f00108a3a5bfe515f45daae15a482/dynect/__init__.py#L264-L275
jorgeecardona/dynect
dynect/__init__.py
Dynect.remove_address
def remove_address(self, fqdn, address): " Remove an address of a domain." # Get a list of addresses. for record in self.list_address(fqdn): if record.address == address: record.delete() break
python
def remove_address(self, fqdn, address): " Remove an address of a domain." # Get a list of addresses. for record in self.list_address(fqdn): if record.address == address: record.delete() break
[ "def", "remove_address", "(", "self", ",", "fqdn", ",", "address", ")", ":", "# Get a list of addresses.", "for", "record", "in", "self", ".", "list_address", "(", "fqdn", ")", ":", "if", "record", ".", "address", "==", "address", ":", "record", ".", "dele...
Remove an address of a domain.
[ "Remove", "an", "address", "of", "a", "domain", "." ]
train
https://github.com/jorgeecardona/dynect/blob/d2cd85bc510f00108a3a5bfe515f45daae15a482/dynect/__init__.py#L277-L284
jorgeecardona/dynect
dynect/__init__.py
Node.delete
def delete(self): " Delete the address." response = self.dyn.delete(self.delete_url) return response.content['job_id']
python
def delete(self): " Delete the address." response = self.dyn.delete(self.delete_url) return response.content['job_id']
[ "def", "delete", "(", "self", ")", ":", "response", "=", "self", ".", "dyn", ".", "delete", "(", "self", ".", "delete_url", ")", "return", "response", ".", "content", "[", "'job_id'", "]" ]
Delete the address.
[ "Delete", "the", "address", "." ]
train
https://github.com/jorgeecardona/dynect/blob/d2cd85bc510f00108a3a5bfe515f45daae15a482/dynect/__init__.py#L314-L317
jorgeecardona/dynect
dynect/__init__.py
DynectRecord.delete
def delete(self): " Delete the record." response = self.dyn.delete(self.url) return response.content['job_id']
python
def delete(self): " Delete the record." response = self.dyn.delete(self.url) return response.content['job_id']
[ "def", "delete", "(", "self", ")", ":", "response", "=", "self", ".", "dyn", ".", "delete", "(", "self", ".", "url", ")", "return", "response", ".", "content", "[", "'job_id'", "]" ]
Delete the record.
[ "Delete", "the", "record", "." ]
train
https://github.com/jorgeecardona/dynect/blob/d2cd85bc510f00108a3a5bfe515f45daae15a482/dynect/__init__.py#L348-L352
KnowledgeLinks/rdfframework
rdfframework/connections/connmanager.py
make_tstore_conn
def make_tstore_conn(params, **kwargs): """ Returns a triplestore connection args: attr_name: The name the connection will be assigned in the config manager params: The paramaters of the connection kwargs: log_level: logging level to use """ ...
python
def make_tstore_conn(params, **kwargs): """ Returns a triplestore connection args: attr_name: The name the connection will be assigned in the config manager params: The paramaters of the connection kwargs: log_level: logging level to use """ ...
[ "def", "make_tstore_conn", "(", "params", ",", "*", "*", "kwargs", ")", ":", "log", ".", "setLevel", "(", "params", ".", "get", "(", "'log_level'", ",", "__LOG_LEVEL__", ")", ")", "log", ".", "debug", "(", "\"\\n%s\"", ",", "params", ")", "params", "."...
Returns a triplestore connection args: attr_name: The name the connection will be assigned in the config manager params: The paramaters of the connection kwargs: log_level: logging level to use
[ "Returns", "a", "triplestore", "connection" ]
train
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/connections/connmanager.py#L264-L283
KnowledgeLinks/rdfframework
rdfframework/connections/connmanager.py
setup_conn
def setup_conn(**kwargs): """ returns a triplestore conncection based on the kwargs. Order of preceedence is as follows: kwargs['conn'] kwargs['tstore_def'] kwargs['triplestore_url'] kwargs['rdflib'] RdfConfigManager.data_tstore RdfConfigManager.TRIPLESTORE_URL ...
python
def setup_conn(**kwargs): """ returns a triplestore conncection based on the kwargs. Order of preceedence is as follows: kwargs['conn'] kwargs['tstore_def'] kwargs['triplestore_url'] kwargs['rdflib'] RdfConfigManager.data_tstore RdfConfigManager.TRIPLESTORE_URL ...
[ "def", "setup_conn", "(", "*", "*", "kwargs", ")", ":", "from", "rdfframework", ".", "configuration", "import", "RdfConfigManager", "if", "kwargs", ".", "get", "(", "\"conn\"", ")", ":", "conn", "=", "kwargs", "[", "'conn'", "]", "elif", "kwargs", ".", "...
returns a triplestore conncection based on the kwargs. Order of preceedence is as follows: kwargs['conn'] kwargs['tstore_def'] kwargs['triplestore_url'] kwargs['rdflib'] RdfConfigManager.data_tstore RdfConfigManager.TRIPLESTORE_URL kwargs: conn: establish...
[ "returns", "a", "triplestore", "conncection", "based", "on", "the", "kwargs", ".", "Order", "of", "preceedence", "is", "as", "follows", ":", "kwargs", "[", "conn", "]", "kwargs", "[", "tstore_def", "]", "kwargs", "[", "triplestore_url", "]", "kwargs", "[", ...
train
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/connections/connmanager.py#L285-L322
KnowledgeLinks/rdfframework
rdfframework/connections/connmanager.py
ConnManager.set_conn
def set_conn(self, **kwargs): """ takes a connection and creates the connection """ # log = logging.getLogger("%s.%s" % (self.log, inspect.stack()[0][3])) log.setLevel(kwargs.get('log_level',self.log_level)) conn_name = kwargs.get("name") if not conn_name: raise Nam...
python
def set_conn(self, **kwargs): """ takes a connection and creates the connection """ # log = logging.getLogger("%s.%s" % (self.log, inspect.stack()[0][3])) log.setLevel(kwargs.get('log_level',self.log_level)) conn_name = kwargs.get("name") if not conn_name: raise Nam...
[ "def", "set_conn", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# log = logging.getLogger(\"%s.%s\" % (self.log, inspect.stack()[0][3]))", "log", ".", "setLevel", "(", "kwargs", ".", "get", "(", "'log_level'", ",", "self", ".", "log_level", ")", ")", "conn_nam...
takes a connection and creates the connection
[ "takes", "a", "connection", "and", "creates", "the", "connection" ]
train
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/connections/connmanager.py#L106-L132
KnowledgeLinks/rdfframework
rdfframework/connections/connmanager.py
ConnManager.get
def get(self, conn_name, default=None, **kwargs): """ returns the specified connection args: conn_name: the name of the connection """ if isinstance(conn_name, RdfwConnections): return conn_name try: return self.conns[conn_name] excep...
python
def get(self, conn_name, default=None, **kwargs): """ returns the specified connection args: conn_name: the name of the connection """ if isinstance(conn_name, RdfwConnections): return conn_name try: return self.conns[conn_name] excep...
[ "def", "get", "(", "self", ",", "conn_name", ",", "default", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "conn_name", ",", "RdfwConnections", ")", ":", "return", "conn_name", "try", ":", "return", "self", ".", "conns", "[",...
returns the specified connection args: conn_name: the name of the connection
[ "returns", "the", "specified", "connection" ]
train
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/connections/connmanager.py#L135-L149
KnowledgeLinks/rdfframework
rdfframework/connections/connmanager.py
ConnManager.load
def load(self, conn_list, **kwargs): """ Takes a list of connections and sets them in the manager args: conn_list: list of connection defitions """ for conn in conn_list: conn['delay_check'] = kwargs.get('delay_check', False) self.set_conn(**conn) ...
python
def load(self, conn_list, **kwargs): """ Takes a list of connections and sets them in the manager args: conn_list: list of connection defitions """ for conn in conn_list: conn['delay_check'] = kwargs.get('delay_check', False) self.set_conn(**conn) ...
[ "def", "load", "(", "self", ",", "conn_list", ",", "*", "*", "kwargs", ")", ":", "for", "conn", "in", "conn_list", ":", "conn", "[", "'delay_check'", "]", "=", "kwargs", ".", "get", "(", "'delay_check'", ",", "False", ")", "self", ".", "set_conn", "(...
Takes a list of connections and sets them in the manager args: conn_list: list of connection defitions
[ "Takes", "a", "list", "of", "connections", "and", "sets", "them", "in", "the", "manager" ]
train
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/connections/connmanager.py#L151-L164
KnowledgeLinks/rdfframework
rdfframework/connections/connmanager.py
ConnManager.failing
def failing(self): """ Tests to see if all connections are working returns: dictionary of all failing connections """ log_levels = {key: conn.log_level for key, conn in self.conns.items() if hasattr(conn, 'log_level')} for key in log_levels: ...
python
def failing(self): """ Tests to see if all connections are working returns: dictionary of all failing connections """ log_levels = {key: conn.log_level for key, conn in self.conns.items() if hasattr(conn, 'log_level')} for key in log_levels: ...
[ "def", "failing", "(", "self", ")", ":", "log_levels", "=", "{", "key", ":", "conn", ".", "log_level", "for", "key", ",", "conn", "in", "self", ".", "conns", ".", "items", "(", ")", "if", "hasattr", "(", "conn", ",", "'log_level'", ")", "}", "for",...
Tests to see if all connections are working returns: dictionary of all failing connections
[ "Tests", "to", "see", "if", "all", "connections", "are", "working" ]
train
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/connections/connmanager.py#L167-L181
KnowledgeLinks/rdfframework
rdfframework/connections/connmanager.py
ConnManager.wait_for_conns
def wait_for_conns(self, timeout=60, start_delay=0, interval=5, **kwargs): ''' delays unitil all connections are working args: timeout: number of seconds to try to connecting. Error out when timeout is reached start_delay: number of seconds to...
python
def wait_for_conns(self, timeout=60, start_delay=0, interval=5, **kwargs): ''' delays unitil all connections are working args: timeout: number of seconds to try to connecting. Error out when timeout is reached start_delay: number of seconds to...
[ "def", "wait_for_conns", "(", "self", ",", "timeout", "=", "60", ",", "start_delay", "=", "0", ",", "interval", "=", "5", ",", "*", "*", "kwargs", ")", ":", "log", ".", "setLevel", "(", "kwargs", ".", "get", "(", "'log_level'", ",", "self", ".", "l...
delays unitil all connections are working args: timeout: number of seconds to try to connecting. Error out when timeout is reached start_delay: number of seconds to wait before checking status interval: number of seconds to wait betwee...
[ "delays", "unitil", "all", "connections", "are", "working" ]
train
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/connections/connmanager.py#L183-L233
KnowledgeLinks/rdfframework
rdfframework/connections/connmanager.py
ConnManager.active
def active(self): """ returns a dictionary of connections set as active. """ return {key: value for key, value in self.conns.items() if value.active}
python
def active(self): """ returns a dictionary of connections set as active. """ return {key: value for key, value in self.conns.items() if value.active}
[ "def", "active", "(", "self", ")", ":", "return", "{", "key", ":", "value", "for", "key", ",", "value", "in", "self", ".", "conns", ".", "items", "(", ")", "if", "value", ".", "active", "}" ]
returns a dictionary of connections set as active.
[ "returns", "a", "dictionary", "of", "connections", "set", "as", "active", "." ]
train
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/connections/connmanager.py#L258-L262
lehins/python-wepay
wepay/calls/subscription_plan.py
SubscriptionPlan.__create
def __create(self, account_id, name, short_description, amount, period, **kwargs): """Call documentation: `/subscription_plan/create <https://www.wepay.com/developer/reference/subscription_plan#create>`_, plus extra keyword parameters: :keyword str access_token:...
python
def __create(self, account_id, name, short_description, amount, period, **kwargs): """Call documentation: `/subscription_plan/create <https://www.wepay.com/developer/reference/subscription_plan#create>`_, plus extra keyword parameters: :keyword str access_token:...
[ "def", "__create", "(", "self", ",", "account_id", ",", "name", ",", "short_description", ",", "amount", ",", "period", ",", "*", "*", "kwargs", ")", ":", "params", "=", "{", "'account_id'", ":", "account_id", ",", "'name'", ":", "name", ",", "'short_des...
Call documentation: `/subscription_plan/create <https://www.wepay.com/developer/reference/subscription_plan#create>`_, plus extra keyword parameters: :keyword str access_token: will be used instead of instance's ``access_token``, with ``batch_mode=True`` will set `authorizati...
[ "Call", "documentation", ":", "/", "subscription_plan", "/", "create", "<https", ":", "//", "www", ".", "wepay", ".", "com", "/", "developer", "/", "reference", "/", "subscription_plan#create", ">", "_", "plus", "extra", "keyword", "parameters", ":", ":", "k...
train
https://github.com/lehins/python-wepay/blob/414d25a1a8d0ecb22a3ddd1f16c60b805bb52a1f/wepay/calls/subscription_plan.py#L57-L84
lehins/python-wepay
wepay/calls/subscription_plan.py
SubscriptionPlan.__delete
def __delete(self, subscription_plan_id, **kwargs): """Call documentation: `/subscription_plan/delete <https://www.wepay.com/developer/reference/subscription_plan#delete>`_, plus extra keyword parameters: :keyword str access_token: will be used instead of instance's `...
python
def __delete(self, subscription_plan_id, **kwargs): """Call documentation: `/subscription_plan/delete <https://www.wepay.com/developer/reference/subscription_plan#delete>`_, plus extra keyword parameters: :keyword str access_token: will be used instead of instance's `...
[ "def", "__delete", "(", "self", ",", "subscription_plan_id", ",", "*", "*", "kwargs", ")", ":", "params", "=", "{", "'subscription_plan_id'", ":", "subscription_plan_id", "}", "return", "self", ".", "make_call", "(", "self", ".", "__delete", ",", "params", "...
Call documentation: `/subscription_plan/delete <https://www.wepay.com/developer/reference/subscription_plan#delete>`_, plus extra keyword parameters: :keyword str access_token: will be used instead of instance's ``access_token``, with ``batch_mode=True`` will set `authorizati...
[ "Call", "documentation", ":", "/", "subscription_plan", "/", "delete", "<https", ":", "//", "www", ".", "wepay", ".", "com", "/", "developer", "/", "reference", "/", "subscription_plan#delete", ">", "_", "plus", "extra", "keyword", "parameters", ":", ":", "k...
train
https://github.com/lehins/python-wepay/blob/414d25a1a8d0ecb22a3ddd1f16c60b805bb52a1f/wepay/calls/subscription_plan.py#L92-L114
lehins/python-wepay
wepay/calls/subscription_plan.py
SubscriptionPlan.__get_button
def __get_button(self, account_id, button_type, **kwargs): """Call documentation: `/subscription_plan/get_button <https://www.wepay.com/developer/reference/subscription_plan#get_button>`_, plus extra keyword parameters: :keyword str access_token: will be used instead of instance...
python
def __get_button(self, account_id, button_type, **kwargs): """Call documentation: `/subscription_plan/get_button <https://www.wepay.com/developer/reference/subscription_plan#get_button>`_, plus extra keyword parameters: :keyword str access_token: will be used instead of instance...
[ "def", "__get_button", "(", "self", ",", "account_id", ",", "button_type", ",", "*", "*", "kwargs", ")", ":", "params", "=", "{", "'account_id'", ":", "account_id", ",", "'button_type'", ":", "button_type", "}", "return", "self", ".", "make_call", "(", "se...
Call documentation: `/subscription_plan/get_button <https://www.wepay.com/developer/reference/subscription_plan#get_button>`_, plus extra keyword parameters: :keyword str access_token: will be used instead of instance's ``access_token``, with ``batch_mode=True`` will set `aut...
[ "Call", "documentation", ":", "/", "subscription_plan", "/", "get_button", "<https", ":", "//", "www", ".", "wepay", ".", "com", "/", "developer", "/", "reference", "/", "subscription_plan#get_button", ">", "_", "plus", "extra", "keyword", "parameters", ":", "...
train
https://github.com/lehins/python-wepay/blob/414d25a1a8d0ecb22a3ddd1f16c60b805bb52a1f/wepay/calls/subscription_plan.py#L118-L141
lehins/python-wepay
wepay/calls/subscription_plan.py
SubscriptionPlan.__modify
def __modify(self, subscription_plan_id, **kwargs): """Call documentation: `/subscription_plan/modify <https://www.wepay.com/developer/reference/subscription_plan#modify>`_, plus extra keyword parameters: :keyword str access_token: will be used instead of instance's `...
python
def __modify(self, subscription_plan_id, **kwargs): """Call documentation: `/subscription_plan/modify <https://www.wepay.com/developer/reference/subscription_plan#modify>`_, plus extra keyword parameters: :keyword str access_token: will be used instead of instance's `...
[ "def", "__modify", "(", "self", ",", "subscription_plan_id", ",", "*", "*", "kwargs", ")", ":", "params", "=", "{", "'subscription_plan_id'", ":", "subscription_plan_id", "}", "return", "self", ".", "make_call", "(", "self", ".", "__modify", ",", "params", "...
Call documentation: `/subscription_plan/modify <https://www.wepay.com/developer/reference/subscription_plan#modify>`_, plus extra keyword parameters: :keyword str access_token: will be used instead of instance's ``access_token``, with ``batch_mode=True`` will set `authorizati...
[ "Call", "documentation", ":", "/", "subscription_plan", "/", "modify", "<https", ":", "//", "www", ".", "wepay", ".", "com", "/", "developer", "/", "reference", "/", "subscription_plan#modify", ">", "_", "plus", "extra", "keyword", "parameters", ":", ":", "k...
train
https://github.com/lehins/python-wepay/blob/414d25a1a8d0ecb22a3ddd1f16c60b805bb52a1f/wepay/calls/subscription_plan.py#L148-L170
UT-ET/offer
offer/offerCLI.py
main
def main(): """Host a file.""" description = """Host a file on the LAN.""" argParser = _argparse.ArgumentParser(description=description) argParser.add_argument('file', help='File to host') argParser.add_argument('-p', '--port', help='Port to us...
python
def main(): """Host a file.""" description = """Host a file on the LAN.""" argParser = _argparse.ArgumentParser(description=description) argParser.add_argument('file', help='File to host') argParser.add_argument('-p', '--port', help='Port to us...
[ "def", "main", "(", ")", ":", "description", "=", "\"\"\"Host a file on the LAN.\"\"\"", "argParser", "=", "_argparse", ".", "ArgumentParser", "(", "description", "=", "description", ")", "argParser", ".", "add_argument", "(", "'file'", ",", "help", "=", "'File to...
Host a file.
[ "Host", "a", "file", "." ]
train
https://github.com/UT-ET/offer/blob/8dee15337b60999040feb3529333b871fb5e258f/offer/offerCLI.py#L88-L151
UT-ET/offer
offer/offerCLI.py
FileHTTPServerHandler.send_head
def send_head(self): """Common code for GET and HEAD commands. This sends the response code and MIME headers. Return value is either a file object (which has to be copied to the outputfile by the caller unless the command was HEAD, and must be closed by the caller under all cir...
python
def send_head(self): """Common code for GET and HEAD commands. This sends the response code and MIME headers. Return value is either a file object (which has to be copied to the outputfile by the caller unless the command was HEAD, and must be closed by the caller under all cir...
[ "def", "send_head", "(", "self", ")", ":", "offerredPath", "=", "self", ".", "absFilePath", "f", "=", "None", "fName", "=", "_path", ".", "basename", "(", "offerredPath", ")", "urlPath", "=", "_U2", ".", "unquote", "(", "self", ".", "path", ")", "if", ...
Common code for GET and HEAD commands. This sends the response code and MIME headers. Return value is either a file object (which has to be copied to the outputfile by the caller unless the command was HEAD, and must be closed by the caller under all circumstances), or None, in...
[ "Common", "code", "for", "GET", "and", "HEAD", "commands", "." ]
train
https://github.com/UT-ET/offer/blob/8dee15337b60999040feb3529333b871fb5e258f/offer/offerCLI.py#L32-L73
daknuett/py_register_machine2
machines/small.py
small_register_machine
def small_register_machine(rom_size = 50, ram_size = 200, flash_size = 500): """ An unprogrammend Register Machine with * one OutputRegister to ``sys.stdout`` (``out0``) * 15 General Purpose Register (``r0 - r14``) returns : ``(Processor, ROM, RAM, Flash)`` """ rom = memory.ROM(rom_size) ram = memory.RAM(ram...
python
def small_register_machine(rom_size = 50, ram_size = 200, flash_size = 500): """ An unprogrammend Register Machine with * one OutputRegister to ``sys.stdout`` (``out0``) * 15 General Purpose Register (``r0 - r14``) returns : ``(Processor, ROM, RAM, Flash)`` """ rom = memory.ROM(rom_size) ram = memory.RAM(ram...
[ "def", "small_register_machine", "(", "rom_size", "=", "50", ",", "ram_size", "=", "200", ",", "flash_size", "=", "500", ")", ":", "rom", "=", "memory", ".", "ROM", "(", "rom_size", ")", "ram", "=", "memory", ".", "RAM", "(", "ram_size", ")", "flash", ...
An unprogrammend Register Machine with * one OutputRegister to ``sys.stdout`` (``out0``) * 15 General Purpose Register (``r0 - r14``) returns : ``(Processor, ROM, RAM, Flash)``
[ "An", "unprogrammend", "Register", "Machine", "with" ]
train
https://github.com/daknuett/py_register_machine2/blob/599c53cd7576297d0d7a53344ed5d9aa98acc751/machines/small.py#L12-L54
svasilev94/GraphLibrary
graphlibrary/digraph.py
DiGraph.add_vertex
def add_vertex(self, vertex, **attr): """ Add vertex and update vertex attributes """ self.vertices[vertex] = [] if attr: self.nodes[vertex] = attr self.pred[vertex] = [] self.succ[vertex] = []
python
def add_vertex(self, vertex, **attr): """ Add vertex and update vertex attributes """ self.vertices[vertex] = [] if attr: self.nodes[vertex] = attr self.pred[vertex] = [] self.succ[vertex] = []
[ "def", "add_vertex", "(", "self", ",", "vertex", ",", "*", "*", "attr", ")", ":", "self", ".", "vertices", "[", "vertex", "]", "=", "[", "]", "if", "attr", ":", "self", ".", "nodes", "[", "vertex", "]", "=", "attr", "self", ".", "pred", "[", "v...
Add vertex and update vertex attributes
[ "Add", "vertex", "and", "update", "vertex", "attributes" ]
train
https://github.com/svasilev94/GraphLibrary/blob/bf979a80bdea17eeb25955f0c119ca8f711ef62b/graphlibrary/digraph.py#L25-L33
svasilev94/GraphLibrary
graphlibrary/digraph.py
DiGraph.add_edge
def add_edge(self, u, v, **attr): """ Add an edge from u to v and update edge attributes """ if u not in self.vertices: self.vertices[u] = [] self.pred[u] = [] self.succ[u] = [] if v not in self.vertices: self.vertices[v] =...
python
def add_edge(self, u, v, **attr): """ Add an edge from u to v and update edge attributes """ if u not in self.vertices: self.vertices[u] = [] self.pred[u] = [] self.succ[u] = [] if v not in self.vertices: self.vertices[v] =...
[ "def", "add_edge", "(", "self", ",", "u", ",", "v", ",", "*", "*", "attr", ")", ":", "if", "u", "not", "in", "self", ".", "vertices", ":", "self", ".", "vertices", "[", "u", "]", "=", "[", "]", "self", ".", "pred", "[", "u", "]", "=", "[", ...
Add an edge from u to v and update edge attributes
[ "Add", "an", "edge", "from", "u", "to", "v", "and", "update", "edge", "attributes" ]
train
https://github.com/svasilev94/GraphLibrary/blob/bf979a80bdea17eeb25955f0c119ca8f711ef62b/graphlibrary/digraph.py#L35-L52
svasilev94/GraphLibrary
graphlibrary/digraph.py
DiGraph.remove_vertex
def remove_vertex(self, vertex): """ Remove vertex from G """ try: self.vertices.pop(vertex) self.succ.pop(vertex) except KeyError: raise GraphInsertError("Vertex %s doesn't exist." % (vertex,)) if vertex in self.nodes: ...
python
def remove_vertex(self, vertex): """ Remove vertex from G """ try: self.vertices.pop(vertex) self.succ.pop(vertex) except KeyError: raise GraphInsertError("Vertex %s doesn't exist." % (vertex,)) if vertex in self.nodes: ...
[ "def", "remove_vertex", "(", "self", ",", "vertex", ")", ":", "try", ":", "self", ".", "vertices", ".", "pop", "(", "vertex", ")", "self", ".", "succ", ".", "pop", "(", "vertex", ")", "except", "KeyError", ":", "raise", "GraphInsertError", "(", "\"Vert...
Remove vertex from G
[ "Remove", "vertex", "from", "G" ]
train
https://github.com/svasilev94/GraphLibrary/blob/bf979a80bdea17eeb25955f0c119ca8f711ef62b/graphlibrary/digraph.py#L54-L79
svasilev94/GraphLibrary
graphlibrary/digraph.py
DiGraph.has_successor
def has_successor(self, u, v): """ Check if vertex u has successor v """ if u not in self.vertices: raise GraphInsertError("Vertex %s doesn't exist." % (u,)) return (u in self.succ and v in self.succ[u])
python
def has_successor(self, u, v): """ Check if vertex u has successor v """ if u not in self.vertices: raise GraphInsertError("Vertex %s doesn't exist." % (u,)) return (u in self.succ and v in self.succ[u])
[ "def", "has_successor", "(", "self", ",", "u", ",", "v", ")", ":", "if", "u", "not", "in", "self", ".", "vertices", ":", "raise", "GraphInsertError", "(", "\"Vertex %s doesn't exist.\"", "%", "(", "u", ",", ")", ")", "return", "(", "u", "in", "self", ...
Check if vertex u has successor v
[ "Check", "if", "vertex", "u", "has", "successor", "v" ]
train
https://github.com/svasilev94/GraphLibrary/blob/bf979a80bdea17eeb25955f0c119ca8f711ef62b/graphlibrary/digraph.py#L99-L105
svasilev94/GraphLibrary
graphlibrary/digraph.py
DiGraph.has_predecessor
def has_predecessor(self, u, v): """ Check if vertex u has predecessor v """ if u not in self.vertices: raise GraphInsertError("Vertex %s doesn't exist." % (u,)) return(u in self.pred and v in self.pred[u])
python
def has_predecessor(self, u, v): """ Check if vertex u has predecessor v """ if u not in self.vertices: raise GraphInsertError("Vertex %s doesn't exist." % (u,)) return(u in self.pred and v in self.pred[u])
[ "def", "has_predecessor", "(", "self", ",", "u", ",", "v", ")", ":", "if", "u", "not", "in", "self", ".", "vertices", ":", "raise", "GraphInsertError", "(", "\"Vertex %s doesn't exist.\"", "%", "(", "u", ",", ")", ")", "return", "(", "u", "in", "self",...
Check if vertex u has predecessor v
[ "Check", "if", "vertex", "u", "has", "predecessor", "v" ]
train
https://github.com/svasilev94/GraphLibrary/blob/bf979a80bdea17eeb25955f0c119ca8f711ef62b/graphlibrary/digraph.py#L107-L113
evetrivia/thanatos
thanatos/questions/base.py
Question.format_question
def format_question(self, correct_answer, possible_wrong_answers, question, add_images_to_question=False): """ Takes a set of values and converts it to the standard format expected as a return from self.ask(). :param correct_answer: A tuple of the answer key and text to be shown. :type ...
python
def format_question(self, correct_answer, possible_wrong_answers, question, add_images_to_question=False): """ Takes a set of values and converts it to the standard format expected as a return from self.ask(). :param correct_answer: A tuple of the answer key and text to be shown. :type ...
[ "def", "format_question", "(", "self", ",", "correct_answer", ",", "possible_wrong_answers", ",", "question", ",", "add_images_to_question", "=", "False", ")", ":", "# Lets randomly select some wrong answers", "wrong_answers", "=", "random", ".", "sample", "(", "possibl...
Takes a set of values and converts it to the standard format expected as a return from self.ask(). :param correct_answer: A tuple of the answer key and text to be shown. :type correct_answer: tuple :param possible_wrong_answers: A list of tuples, each tuple being being (id, dis...
[ "Takes", "a", "set", "of", "values", "and", "converts", "it", "to", "the", "standard", "format", "expected", "as", "a", "return", "from", "self", ".", "ask", "()", "." ]
train
https://github.com/evetrivia/thanatos/blob/664c12a8ccf4d27ab0e06e0969bbb6381f74789c/thanatos/questions/base.py#L38-L74
evetrivia/thanatos
thanatos/questions/base.py
Question.convert_choices_to_dict
def convert_choices_to_dict(choices): """ Takes a list of tuples and converts it to a list of dictionaries of where each dictionary has a value and text key. This is the expected format of question choices to be returned by self.ask() :param convert_choices_to_dict: :type conver...
python
def convert_choices_to_dict(choices): """ Takes a list of tuples and converts it to a list of dictionaries of where each dictionary has a value and text key. This is the expected format of question choices to be returned by self.ask() :param convert_choices_to_dict: :type conver...
[ "def", "convert_choices_to_dict", "(", "choices", ")", ":", "formatted_choices", "=", "[", "]", "for", "x", "in", "choices", ":", "formatted_choices", ".", "append", "(", "{", "'value'", ":", "x", "[", "0", "]", ",", "'text'", ":", "x", "[", "1", "]", ...
Takes a list of tuples and converts it to a list of dictionaries of where each dictionary has a value and text key. This is the expected format of question choices to be returned by self.ask() :param convert_choices_to_dict: :type convert_choices_to_dict: list :return: ...
[ "Takes", "a", "list", "of", "tuples", "and", "converts", "it", "to", "a", "list", "of", "dictionaries", "of", "where", "each", "dictionary", "has", "a", "value", "and", "text", "key", ".", "This", "is", "the", "expected", "format", "of", "question", "cho...
train
https://github.com/evetrivia/thanatos/blob/664c12a8ccf4d27ab0e06e0969bbb6381f74789c/thanatos/questions/base.py#L77-L97
nickmilon/Hellas
Hellas/Thebes.py
format_header
def format_header(frmt, return_len=False): """creates a header string from a new style format string useful when printing dictionaries :param str frmt: a new style format string :returns: a table header string assumptions for frmt specs: - all have a separator = '|' and include a key size form...
python
def format_header(frmt, return_len=False): """creates a header string from a new style format string useful when printing dictionaries :param str frmt: a new style format string :returns: a table header string assumptions for frmt specs: - all have a separator = '|' and include a key size form...
[ "def", "format_header", "(", "frmt", ",", "return_len", "=", "False", ")", ":", "names", "=", "re", ".", "sub", "(", "\"{(.*?):.*?}\"", ",", "r\"\\1\"", ",", "frmt", ")", "names", "=", "[", "i", "for", "i", "in", "names", ".", "split", "(", "\"|\"", ...
creates a header string from a new style format string useful when printing dictionaries :param str frmt: a new style format string :returns: a table header string assumptions for frmt specs: - all have a separator = '|' and include a key size format directive i.e.: '{key:size}' - no other...
[ "creates", "a", "header", "string", "from", "a", "new", "style", "format", "string", "useful", "when", "printing", "dictionaries" ]
train
https://github.com/nickmilon/Hellas/blob/542e4778692fbec90753942946f20100412ec9ee/Hellas/Thebes.py#L11-L40
nickmilon/Hellas
Hellas/Thebes.py
chunks_str_frame
def chunks_str_frame(a_str, n=None, center=True): """places a frame around a string :Parameters: - a_str: string to frame - n: number of chars in each line - center: center string in frame if True and n > len(str) :Example: >>> print(chunks_str_frame('the quick brown fox', 4...
python
def chunks_str_frame(a_str, n=None, center=True): """places a frame around a string :Parameters: - a_str: string to frame - n: number of chars in each line - center: center string in frame if True and n > len(str) :Example: >>> print(chunks_str_frame('the quick brown fox', 4...
[ "def", "chunks_str_frame", "(", "a_str", ",", "n", "=", "None", ",", "center", "=", "True", ")", ":", "if", "n", "is", "None", ":", "n", "=", "len", "(", "a_str", ")", "elif", "n", ">", "len", "(", "a_str", ")", "and", "center", "is", "True", "...
places a frame around a string :Parameters: - a_str: string to frame - n: number of chars in each line - center: center string in frame if True and n > len(str) :Example: >>> print(chunks_str_frame('the quick brown fox', 44)) ╔════════════════════════════════════════════...
[ "places", "a", "frame", "around", "a", "string", ":", "Parameters", ":", "-", "a_str", ":", "string", "to", "frame", "-", "n", ":", "number", "of", "chars", "in", "each", "line", "-", "center", ":", "center", "string", "in", "frame", "if", "True", "a...
train
https://github.com/nickmilon/Hellas/blob/542e4778692fbec90753942946f20100412ec9ee/Hellas/Thebes.py#L43-L68
nickmilon/Hellas
Hellas/Thebes.py
MacAddress.mac_expand
def mac_expand(cls, mac, upper=True, lower=False): """expands a compressed mac addres str ie (AC8674075628) to mac address (AC:86:74:07:56:28) also makes it lower/upper case""" mac = ":".join(["".join(i) for i in zip(mac[::2], mac[1::2])]) return mac.upper() if upper else mac.lower() if lower el...
python
def mac_expand(cls, mac, upper=True, lower=False): """expands a compressed mac addres str ie (AC8674075628) to mac address (AC:86:74:07:56:28) also makes it lower/upper case""" mac = ":".join(["".join(i) for i in zip(mac[::2], mac[1::2])]) return mac.upper() if upper else mac.lower() if lower el...
[ "def", "mac_expand", "(", "cls", ",", "mac", ",", "upper", "=", "True", ",", "lower", "=", "False", ")", ":", "mac", "=", "\":\"", ".", "join", "(", "[", "\"\"", ".", "join", "(", "i", ")", "for", "i", "in", "zip", "(", "mac", "[", ":", ":", ...
expands a compressed mac addres str ie (AC8674075628) to mac address (AC:86:74:07:56:28) also makes it lower/upper case
[ "expands", "a", "compressed", "mac", "addres", "str", "ie", "(", "AC8674075628", ")", "to", "mac", "address", "(", "AC", ":", "86", ":", "74", ":", "07", ":", "56", ":", "28", ")", "also", "makes", "it", "lower", "/", "upper", "case" ]
train
https://github.com/nickmilon/Hellas/blob/542e4778692fbec90753942946f20100412ec9ee/Hellas/Thebes.py#L99-L102
Tinche/django-bower-cache
registry/admin.py
ClonedRepoAdmin.save_form
def save_form(self, request, form, change): """Here we pluck out the data to create a new cloned repo. Form is an instance of NewRepoForm. """ name = form.cleaned_data['name'] origin_url = form.cleaned_data['origin_url'] res = ClonedRepo(name=name, origin=origin_url) ...
python
def save_form(self, request, form, change): """Here we pluck out the data to create a new cloned repo. Form is an instance of NewRepoForm. """ name = form.cleaned_data['name'] origin_url = form.cleaned_data['origin_url'] res = ClonedRepo(name=name, origin=origin_url) ...
[ "def", "save_form", "(", "self", ",", "request", ",", "form", ",", "change", ")", ":", "name", "=", "form", ".", "cleaned_data", "[", "'name'", "]", "origin_url", "=", "form", ".", "cleaned_data", "[", "'origin_url'", "]", "res", "=", "ClonedRepo", "(", ...
Here we pluck out the data to create a new cloned repo. Form is an instance of NewRepoForm.
[ "Here", "we", "pluck", "out", "the", "data", "to", "create", "a", "new", "cloned", "repo", "." ]
train
https://github.com/Tinche/django-bower-cache/blob/5245b2ee80c33c09d85ce0bf8f047825d9df2118/registry/admin.py#L65-L76
Tinche/django-bower-cache
registry/admin.py
ClonedRepoAdmin.add_view
def add_view(self, request, **kwargs): """A custom add_view, to catch exceptions from 'save_model'. Just to be clear, this is very filthy. """ try: return super(ClonedRepoAdmin, self).add_view(request, **kwargs) except ValidationError: # Rerender the f...
python
def add_view(self, request, **kwargs): """A custom add_view, to catch exceptions from 'save_model'. Just to be clear, this is very filthy. """ try: return super(ClonedRepoAdmin, self).add_view(request, **kwargs) except ValidationError: # Rerender the f...
[ "def", "add_view", "(", "self", ",", "request", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "super", "(", "ClonedRepoAdmin", ",", "self", ")", ".", "add_view", "(", "request", ",", "*", "*", "kwargs", ")", "except", "ValidationError", ":",...
A custom add_view, to catch exceptions from 'save_model'. Just to be clear, this is very filthy.
[ "A", "custom", "add_view", "to", "catch", "exceptions", "from", "save_model", "." ]
train
https://github.com/Tinche/django-bower-cache/blob/5245b2ee80c33c09d85ce0bf8f047825d9df2118/registry/admin.py#L82-L91
Tinche/django-bower-cache
registry/admin.py
ClonedRepoAdmin.git_pull_view
def git_pull_view(self, request, repo_name): """Perform a git pull and redirect back to the repo.""" LOG.info("Pull requested for %s." % repo_name) repo = get_object_or_404(self.model, name=repo_name) repo.pull() self.message_user(request, "Repo %s successfully updated." % repo_n...
python
def git_pull_view(self, request, repo_name): """Perform a git pull and redirect back to the repo.""" LOG.info("Pull requested for %s." % repo_name) repo = get_object_or_404(self.model, name=repo_name) repo.pull() self.message_user(request, "Repo %s successfully updated." % repo_n...
[ "def", "git_pull_view", "(", "self", ",", "request", ",", "repo_name", ")", ":", "LOG", ".", "info", "(", "\"Pull requested for %s.\"", "%", "repo_name", ")", "repo", "=", "get_object_or_404", "(", "self", ".", "model", ",", "name", "=", "repo_name", ")", ...
Perform a git pull and redirect back to the repo.
[ "Perform", "a", "git", "pull", "and", "redirect", "back", "to", "the", "repo", "." ]
train
https://github.com/Tinche/django-bower-cache/blob/5245b2ee80c33c09d85ce0bf8f047825d9df2118/registry/admin.py#L102-L109
Tinche/django-bower-cache
registry/admin.py
ClonedRepoAdmin.update_all_view
def update_all_view(self, request): """Update all repositories and redirect back to the repo list.""" LOG.info("Total update requested.") total_count = errors = 0 for repo in self.model.objects.all(): total_count += 1 try: repo.pull() e...
python
def update_all_view(self, request): """Update all repositories and redirect back to the repo list.""" LOG.info("Total update requested.") total_count = errors = 0 for repo in self.model.objects.all(): total_count += 1 try: repo.pull() e...
[ "def", "update_all_view", "(", "self", ",", "request", ")", ":", "LOG", ".", "info", "(", "\"Total update requested.\"", ")", "total_count", "=", "errors", "=", "0", "for", "repo", "in", "self", ".", "model", ".", "objects", ".", "all", "(", ")", ":", ...
Update all repositories and redirect back to the repo list.
[ "Update", "all", "repositories", "and", "redirect", "back", "to", "the", "repo", "list", "." ]
train
https://github.com/Tinche/django-bower-cache/blob/5245b2ee80c33c09d85ce0bf8f047825d9df2118/registry/admin.py#L111-L125
Tinche/django-bower-cache
registry/admin.py
NewRepoForm.clean
def clean(self): """Validate the new repo form. Might perform a request to upstream Bower.""" cleaned_data = super(NewRepoForm, self).clean() origin_url = cleaned_data['origin_url'] origin_source = cleaned_data['origin_source'] if origin_source == 'origin_url' and not...
python
def clean(self): """Validate the new repo form. Might perform a request to upstream Bower.""" cleaned_data = super(NewRepoForm, self).clean() origin_url = cleaned_data['origin_url'] origin_source = cleaned_data['origin_source'] if origin_source == 'origin_url' and not...
[ "def", "clean", "(", "self", ")", ":", "cleaned_data", "=", "super", "(", "NewRepoForm", ",", "self", ")", ".", "clean", "(", ")", "origin_url", "=", "cleaned_data", "[", "'origin_url'", "]", "origin_source", "=", "cleaned_data", "[", "'origin_source'", "]",...
Validate the new repo form. Might perform a request to upstream Bower.
[ "Validate", "the", "new", "repo", "form", "." ]
train
https://github.com/Tinche/django-bower-cache/blob/5245b2ee80c33c09d85ce0bf8f047825d9df2118/registry/admin.py#L137-L168
s-ball/i18nparse
i18nparse/i18nparse.py
activate
def activate(lang=None): """Activate a translation for lang. If lang is None, then the language of locale.getdefaultlocale() is used. If the translation file does not exist, the original messages will be used. """ if lang is None: lang = locale.getlocale()[0] tr = gettext.translation("argparse", os...
python
def activate(lang=None): """Activate a translation for lang. If lang is None, then the language of locale.getdefaultlocale() is used. If the translation file does not exist, the original messages will be used. """ if lang is None: lang = locale.getlocale()[0] tr = gettext.translation("argparse", os...
[ "def", "activate", "(", "lang", "=", "None", ")", ":", "if", "lang", "is", "None", ":", "lang", "=", "locale", ".", "getlocale", "(", ")", "[", "0", "]", "tr", "=", "gettext", ".", "translation", "(", "\"argparse\"", ",", "os", ".", "path", ".", ...
Activate a translation for lang. If lang is None, then the language of locale.getdefaultlocale() is used. If the translation file does not exist, the original messages will be used.
[ "Activate", "a", "translation", "for", "lang", "." ]
train
https://github.com/s-ball/i18nparse/blob/cc70cbf31903caf45ebfdcb62a57744b6fe9d0df/i18nparse/i18nparse.py#L11-L22
geertj/looping
lib/looping/pyside.py
PySideEventLoop.run
def run(self): """Run until there are no more events. This only looks at events scheduled through the event loop. """ self._stop = False while not self._stop: have_sources = self._timers or self._readers or self._writers if not self._processor.pending and ...
python
def run(self): """Run until there are no more events. This only looks at events scheduled through the event loop. """ self._stop = False while not self._stop: have_sources = self._timers or self._readers or self._writers if not self._processor.pending and ...
[ "def", "run", "(", "self", ")", ":", "self", ".", "_stop", "=", "False", "while", "not", "self", ".", "_stop", ":", "have_sources", "=", "self", ".", "_timers", "or", "self", ".", "_readers", "or", "self", ".", "_writers", "if", "not", "self", ".", ...
Run until there are no more events. This only looks at events scheduled through the event loop.
[ "Run", "until", "there", "are", "no", "more", "events", ".", "This", "only", "looks", "at", "events", "scheduled", "through", "the", "event", "loop", "." ]
train
https://github.com/geertj/looping/blob/b60303714685aede18b37c0d80f8f55175ad7a65/lib/looping/pyside.py#L97-L111
gdelnegro/django-translation-server
translation_server/management/commands/upload_csv.py
Command.__import_csv
def __import_csv(self): """ file format: header Código WMLB|Código WMHT|WMLB EN|WMLB PT|WMHT EN|WMHT PT|Nome do Campo|Tipo do Campo|Contexto|Local de Uso primary_tag|auxiliary_tag|text_en|text_pt_br|auxiliary_text_en|auxiliary_text_pt_br|Nome do Campo|Tipo do Campo|Contexto|Local...
python
def __import_csv(self): """ file format: header Código WMLB|Código WMHT|WMLB EN|WMLB PT|WMHT EN|WMHT PT|Nome do Campo|Tipo do Campo|Contexto|Local de Uso primary_tag|auxiliary_tag|text_en|text_pt_br|auxiliary_text_en|auxiliary_text_pt_br|Nome do Campo|Tipo do Campo|Contexto|Local...
[ "def", "__import_csv", "(", "self", ")", ":", "# valids = re.sub(r\"[^A-Za-z]+\", '', my_string)", "# if \"código\" in line, then it's header, ignore it", "# type = re.sub(r\"[^A-Za-z]+\", '', line[0])", "# auxiliary_type = re.sub(r\"[^A-Za-z]+\", '', line[1])", "import", "sys", "import", ...
file format: header Código WMLB|Código WMHT|WMLB EN|WMLB PT|WMHT EN|WMHT PT|Nome do Campo|Tipo do Campo|Contexto|Local de Uso primary_tag|auxiliary_tag|text_en|text_pt_br|auxiliary_text_en|auxiliary_text_pt_br|Nome do Campo|Tipo do Campo|Contexto|Local de Uso 0|1|2|3|4|5|6|7|8|9
[ "file", "format", ":", "header", "Código", "WMLB|Código", "WMHT|WMLB", "EN|WMLB", "PT|WMHT", "EN|WMHT", "PT|Nome", "do", "Campo|Tipo", "do", "Campo|Contexto|Local", "de", "Uso", "primary_tag|auxiliary_tag|text_en|text_pt_br|auxiliary_text_en|auxiliary_text_pt_br|Nome", "do", "C...
train
https://github.com/gdelnegro/django-translation-server/blob/0f9de98d1cb07a42e1d323e20a384074ad28da57/translation_server/management/commands/upload_csv.py#L36-L97
edeposit/edeposit.amqp.harvester
src/edeposit/amqp/harvester/structures.py
Author.to_namedtuple
def to_namedtuple(self): """ Convert class to namedtuple. Note: This method is neccessary for AMQP communication. Returns: namedtuple: Representation of the class as simple structure. """ keys = filter(lambda x: not x.startswith("_"), self.__dict...
python
def to_namedtuple(self): """ Convert class to namedtuple. Note: This method is neccessary for AMQP communication. Returns: namedtuple: Representation of the class as simple structure. """ keys = filter(lambda x: not x.startswith("_"), self.__dict...
[ "def", "to_namedtuple", "(", "self", ")", ":", "keys", "=", "filter", "(", "lambda", "x", ":", "not", "x", ".", "startswith", "(", "\"_\"", ")", ",", "self", ".", "__dict__", ")", "opt_nt", "=", "namedtuple", "(", "self", ".", "__class__", ".", "__na...
Convert class to namedtuple. Note: This method is neccessary for AMQP communication. Returns: namedtuple: Representation of the class as simple structure.
[ "Convert", "class", "to", "namedtuple", "." ]
train
https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/structures.py#L26-L40
edeposit/edeposit.amqp.harvester
src/edeposit/amqp/harvester/structures.py
Publication.to_namedtuple
def to_namedtuple(self): """ Convert class and all subclasses (:class:`Author`, :class:`Optionals`) to namedtuple. Note: This method is neccessary for AMQP communication. Returns: namedtuple: Representation of the class as simple structure. """ ...
python
def to_namedtuple(self): """ Convert class and all subclasses (:class:`Author`, :class:`Optionals`) to namedtuple. Note: This method is neccessary for AMQP communication. Returns: namedtuple: Representation of the class as simple structure. """ ...
[ "def", "to_namedtuple", "(", "self", ")", ":", "keys", "=", "filter", "(", "lambda", "x", ":", "not", "x", ".", "startswith", "(", "\"_\"", ")", ",", "self", ".", "__dict__", ")", "opt_nt", "=", "namedtuple", "(", "self", ".", "__class__", ".", "__na...
Convert class and all subclasses (:class:`Author`, :class:`Optionals`) to namedtuple. Note: This method is neccessary for AMQP communication. Returns: namedtuple: Representation of the class as simple structure.
[ "Convert", "class", "and", "all", "subclasses", "(", ":", "class", ":", "Author", ":", "class", ":", "Optionals", ")", "to", "namedtuple", "." ]
train
https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/structures.py#L147-L176
edeposit/edeposit.amqp.harvester
src/edeposit/amqp/harvester/structures.py
Publication._get_hash
def _get_hash(self): """ Create hash of the class. Hash should be unique for given ebook, so ISBN is main component of the hash if provided. Returns: str: Hash. """ if self.optionals and self.optionals.ISBN: isbn = self.optionals.ISBN.rep...
python
def _get_hash(self): """ Create hash of the class. Hash should be unique for given ebook, so ISBN is main component of the hash if provided. Returns: str: Hash. """ if self.optionals and self.optionals.ISBN: isbn = self.optionals.ISBN.rep...
[ "def", "_get_hash", "(", "self", ")", ":", "if", "self", ".", "optionals", "and", "self", ".", "optionals", ".", "ISBN", ":", "isbn", "=", "self", ".", "optionals", ".", "ISBN", ".", "replace", "(", "\"-\"", ",", "\"\"", ")", "if", "len", "(", "isb...
Create hash of the class. Hash should be unique for given ebook, so ISBN is main component of the hash if provided. Returns: str: Hash.
[ "Create", "hash", "of", "the", "class", "." ]
train
https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/structures.py#L178-L199
kmedian/luriegold
luriegold/luriegold_func.py
luriegold
def luriegold(R): """Lurie-Goldberg Algorithm to adjust a correlation matrix to be semipositive definite Philip M. Lurie and Matthew S. Goldberg (1998), An Approximate Method for Sampling Correlated Random Variables from Partially-Specified Distributions, Management Science, Vol 44, No. 2, Fe...
python
def luriegold(R): """Lurie-Goldberg Algorithm to adjust a correlation matrix to be semipositive definite Philip M. Lurie and Matthew S. Goldberg (1998), An Approximate Method for Sampling Correlated Random Variables from Partially-Specified Distributions, Management Science, Vol 44, No. 2, Fe...
[ "def", "luriegold", "(", "R", ")", ":", "# subfunctions", "def", "xtotril", "(", "x", ",", "idx", ",", "mat", ")", ":", "\"\"\"Create 'L' lower triangular matrix.\"\"\"", "mat", "[", "idx", "]", "=", "x", "return", "mat", "def", "xtocorr", "(", "x", ",", ...
Lurie-Goldberg Algorithm to adjust a correlation matrix to be semipositive definite Philip M. Lurie and Matthew S. Goldberg (1998), An Approximate Method for Sampling Correlated Random Variables from Partially-Specified Distributions, Management Science, Vol 44, No. 2, February 1998, pp 20...
[ "Lurie", "-", "Goldberg", "Algorithm", "to", "adjust", "a", "correlation", "matrix", "to", "be", "semipositive", "definite" ]
train
https://github.com/kmedian/luriegold/blob/9aa77fb3f7277e44973b472cc81aa15bbe171414/luriegold/luriegold_func.py#L6-L68
aksas/pypo4sel
core/pypo4sel/core/webdrivers.py
get_driver
def get_driver(browser='firefox', args=None): """ :param browser: :param args: :rtype: RemoteDriver :return: """ if browser not in BROWSER_MAPPING.keys(): raise RuntimeError("unknown browser %s. allowed: %s" % (browser, ", ".join(BROWSER_MAPPING.keys()))) driver_cls = BROWSER_MAP...
python
def get_driver(browser='firefox', args=None): """ :param browser: :param args: :rtype: RemoteDriver :return: """ if browser not in BROWSER_MAPPING.keys(): raise RuntimeError("unknown browser %s. allowed: %s" % (browser, ", ".join(BROWSER_MAPPING.keys()))) driver_cls = BROWSER_MAP...
[ "def", "get_driver", "(", "browser", "=", "'firefox'", ",", "args", "=", "None", ")", ":", "if", "browser", "not", "in", "BROWSER_MAPPING", ".", "keys", "(", ")", ":", "raise", "RuntimeError", "(", "\"unknown browser %s. allowed: %s\"", "%", "(", "browser", ...
:param browser: :param args: :rtype: RemoteDriver :return:
[ ":", "param", "browser", ":", ":", "param", "args", ":", ":", "rtype", ":", "RemoteDriver", ":", "return", ":" ]
train
https://github.com/aksas/pypo4sel/blob/935b5f9bfa6682aefdef8a43ebcbcf274dec752c/core/pypo4sel/core/webdrivers.py#L123-L140
calvinku96/labreporthelper
labreporthelper/manage.py
generate_datasets_list
def generate_datasets_list(settings, argv): """ generate datasets list to activate args: settings: dictionary from settings file argv: list from sys.argv """ datasets_string_list = settings["DATASETS_LIST"] datasets_list = [] if len(argv) == 2: ...
python
def generate_datasets_list(settings, argv): """ generate datasets list to activate args: settings: dictionary from settings file argv: list from sys.argv """ datasets_string_list = settings["DATASETS_LIST"] datasets_list = [] if len(argv) == 2: ...
[ "def", "generate_datasets_list", "(", "settings", ",", "argv", ")", ":", "datasets_string_list", "=", "settings", "[", "\"DATASETS_LIST\"", "]", "datasets_list", "=", "[", "]", "if", "len", "(", "argv", ")", "==", "2", ":", "try", ":", "datasets_items", "=",...
generate datasets list to activate args: settings: dictionary from settings file argv: list from sys.argv
[ "generate", "datasets", "list", "to", "activate" ]
train
https://github.com/calvinku96/labreporthelper/blob/4d436241f389c02eb188c313190df62ab28c3763/labreporthelper/manage.py#L15-L54
calvinku96/labreporthelper
labreporthelper/manage.py
manage
def manage(settingspath, root_dir, argv): """ Manage all processes """ # add settings.json to environment variables os.environ[ENV_VAR_SETTINGS] = settingspath # add root_dir os.environ[ENV_VAR_ROOT_DIR] = root_dir # get datasets list with open(settingspath) as settings_file: ...
python
def manage(settingspath, root_dir, argv): """ Manage all processes """ # add settings.json to environment variables os.environ[ENV_VAR_SETTINGS] = settingspath # add root_dir os.environ[ENV_VAR_ROOT_DIR] = root_dir # get datasets list with open(settingspath) as settings_file: ...
[ "def", "manage", "(", "settingspath", ",", "root_dir", ",", "argv", ")", ":", "# add settings.json to environment variables", "os", ".", "environ", "[", "ENV_VAR_SETTINGS", "]", "=", "settingspath", "# add root_dir", "os", ".", "environ", "[", "ENV_VAR_ROOT_DIR", "]...
Manage all processes
[ "Manage", "all", "processes" ]
train
https://github.com/calvinku96/labreporthelper/blob/4d436241f389c02eb188c313190df62ab28c3763/labreporthelper/manage.py#L95-L115
shaypal5/utilp
utilp/func/_path.py
is_pathname_valid
def is_pathname_valid(pathname: str) -> bool: """Checks if the given path name is valid. Returns ------- `True` if the passed pathname is a valid pathname for the current OS; `False` otherwise. """ # If this pathname is either not a string or is but is empty, this pathname # is invalid....
python
def is_pathname_valid(pathname: str) -> bool: """Checks if the given path name is valid. Returns ------- `True` if the passed pathname is a valid pathname for the current OS; `False` otherwise. """ # If this pathname is either not a string or is but is empty, this pathname # is invalid....
[ "def", "is_pathname_valid", "(", "pathname", ":", "str", ")", "->", "bool", ":", "# If this pathname is either not a string or is but is empty, this pathname", "# is invalid.", "try", ":", "if", "not", "isinstance", "(", "pathname", ",", "str", ")", "or", "not", "path...
Checks if the given path name is valid. Returns ------- `True` if the passed pathname is a valid pathname for the current OS; `False` otherwise.
[ "Checks", "if", "the", "given", "path", "name", "is", "valid", "." ]
train
https://github.com/shaypal5/utilp/blob/932abaf8ccfd06557632b7dbebc7775da1de8430/utilp/func/_path.py#L25-L91
shaypal5/utilp
utilp/func/_path.py
is_path_creatable
def is_path_creatable(pathname: str) -> bool: """Checks whether the given path is creatable. Returns ------- `True` if the current user has sufficient permissions to create the passed pathname; `False` otherwise. """ # Parent directory of the passed path. If empty, we substitute the current...
python
def is_path_creatable(pathname: str) -> bool: """Checks whether the given path is creatable. Returns ------- `True` if the current user has sufficient permissions to create the passed pathname; `False` otherwise. """ # Parent directory of the passed path. If empty, we substitute the current...
[ "def", "is_path_creatable", "(", "pathname", ":", "str", ")", "->", "bool", ":", "# Parent directory of the passed path. If empty, we substitute the current", "# working directory (CWD) instead.", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "pathname", ")", "o...
Checks whether the given path is creatable. Returns ------- `True` if the current user has sufficient permissions to create the passed pathname; `False` otherwise.
[ "Checks", "whether", "the", "given", "path", "is", "creatable", "." ]
train
https://github.com/shaypal5/utilp/blob/932abaf8ccfd06557632b7dbebc7775da1de8430/utilp/func/_path.py#L98-L109
shaypal5/utilp
utilp/func/_path.py
path_exists_or_creatable
def path_exists_or_creatable(pathname: str) -> bool: """Checks whether the given path exists or is creatable. This function is guaranteed to _never_ raise exceptions. Returns ------- `True` if the passed pathname is a valid pathname for the current OS _and_ either currently exists or is hypoth...
python
def path_exists_or_creatable(pathname: str) -> bool: """Checks whether the given path exists or is creatable. This function is guaranteed to _never_ raise exceptions. Returns ------- `True` if the passed pathname is a valid pathname for the current OS _and_ either currently exists or is hypoth...
[ "def", "path_exists_or_creatable", "(", "pathname", ":", "str", ")", "->", "bool", ":", "try", ":", "# To prevent \"os\" module calls from raising undesirable exceptions on", "# invalid pathnames, is_pathname_valid() is explicitly called first.", "return", "is_pathname_valid", "(", ...
Checks whether the given path exists or is creatable. This function is guaranteed to _never_ raise exceptions. Returns ------- `True` if the passed pathname is a valid pathname for the current OS _and_ either currently exists or is hypothetically creatable; `False` otherwise.
[ "Checks", "whether", "the", "given", "path", "exists", "or", "is", "creatable", "." ]
train
https://github.com/shaypal5/utilp/blob/932abaf8ccfd06557632b7dbebc7775da1de8430/utilp/func/_path.py#L112-L132
shaypal5/utilp
utilp/func/_path.py
is_path_sibling_creatable
def is_path_sibling_creatable(pathname: str) -> bool: """Checks whether current user can create siblings of the given path. Returns ------- `True` if the current user has sufficient permissions to create siblings (i.e., arbitrary files in the parent directory) of the passed pathname; `False` ot...
python
def is_path_sibling_creatable(pathname: str) -> bool: """Checks whether current user can create siblings of the given path. Returns ------- `True` if the current user has sufficient permissions to create siblings (i.e., arbitrary files in the parent directory) of the passed pathname; `False` ot...
[ "def", "is_path_sibling_creatable", "(", "pathname", ":", "str", ")", "->", "bool", ":", "# Parent directory of the passed path. If empty, we substitute the current", "# working directory (CWD) instead.", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "pathname", "...
Checks whether current user can create siblings of the given path. Returns ------- `True` if the current user has sufficient permissions to create siblings (i.e., arbitrary files in the parent directory) of the passed pathname; `False` otherwise.
[ "Checks", "whether", "current", "user", "can", "create", "siblings", "of", "the", "given", "path", "." ]
train
https://github.com/shaypal5/utilp/blob/932abaf8ccfd06557632b7dbebc7775da1de8430/utilp/func/_path.py#L135-L158
shaypal5/utilp
utilp/func/_path.py
path_exists_or_creatable_portable
def path_exists_or_creatable_portable(pathname: str) -> bool: """OS-portable check for whether current path exists or is creatable. This function is guaranteed to _never_ raise exceptions. Returns ------ `True` if the passed pathname is a valid pathname on the current OS _and_ either currently...
python
def path_exists_or_creatable_portable(pathname: str) -> bool: """OS-portable check for whether current path exists or is creatable. This function is guaranteed to _never_ raise exceptions. Returns ------ `True` if the passed pathname is a valid pathname on the current OS _and_ either currently...
[ "def", "path_exists_or_creatable_portable", "(", "pathname", ":", "str", ")", "->", "bool", ":", "try", ":", "# To prevent \"os\" module calls from raising undesirable exceptions on", "# invalid pathnames, is_pathname_valid() is explicitly called first.", "return", "is_pathname_valid",...
OS-portable check for whether current path exists or is creatable. This function is guaranteed to _never_ raise exceptions. Returns ------ `True` if the passed pathname is a valid pathname on the current OS _and_ either currently exists or is hypothetically creatable in a cross-platform manner...
[ "OS", "-", "portable", "check", "for", "whether", "current", "path", "exists", "or", "is", "creatable", "." ]
train
https://github.com/shaypal5/utilp/blob/932abaf8ccfd06557632b7dbebc7775da1de8430/utilp/func/_path.py#L161-L182
d0c0nnor/jocelyn
src/jocelyn/__init__.py
Q
def Q(name): """Gets a variable from the current sketch. Processing has a number of methods and variables with the same name, 'mousePressed' for example. This allows us to disambiguate. Also casts numeric values as floats to make it easier to translate code from pde to python. """ retval =...
python
def Q(name): """Gets a variable from the current sketch. Processing has a number of methods and variables with the same name, 'mousePressed' for example. This allows us to disambiguate. Also casts numeric values as floats to make it easier to translate code from pde to python. """ retval =...
[ "def", "Q", "(", "name", ")", ":", "retval", "=", "PApplet", ".", "getDeclaredField", "(", "name", ")", ".", "get", "(", "Sketch", ".", "get_instance", "(", ")", ")", "if", "isinstance", "(", "retval", ",", "(", "long", ",", "int", ")", ")", ":", ...
Gets a variable from the current sketch. Processing has a number of methods and variables with the same name, 'mousePressed' for example. This allows us to disambiguate. Also casts numeric values as floats to make it easier to translate code from pde to python.
[ "Gets", "a", "variable", "from", "the", "current", "sketch", ".", "Processing", "has", "a", "number", "of", "methods", "and", "variables", "with", "the", "same", "name", "mousePressed", "for", "example", ".", "This", "allows", "us", "to", "disambiguate", "."...
train
https://github.com/d0c0nnor/jocelyn/blob/a9bb73ab89d7488cec1b1bcd6d612f7a56d9b01c/src/jocelyn/__init__.py#L150-L163
d0c0nnor/jocelyn
src/jocelyn/__init__.py
Sketch.run_sketch
def run_sketch(self): """ Initialises the underlying PApplet and creates a frame ( using ``create_frame`` if required ) to display it in. """ Sketch.instance = self self.init() frame = self.create_frame() if frame: frame.add(self) ...
python
def run_sketch(self): """ Initialises the underlying PApplet and creates a frame ( using ``create_frame`` if required ) to display it in. """ Sketch.instance = self self.init() frame = self.create_frame() if frame: frame.add(self) ...
[ "def", "run_sketch", "(", "self", ")", ":", "Sketch", ".", "instance", "=", "self", "self", ".", "init", "(", ")", "frame", "=", "self", ".", "create_frame", "(", ")", "if", "frame", ":", "frame", ".", "add", "(", "self", ")", "frame", ".", "pack",...
Initialises the underlying PApplet and creates a frame ( using ``create_frame`` if required ) to display it in.
[ "Initialises", "the", "underlying", "PApplet", "and", "creates", "a", "frame", "(", "using", "create_frame", "if", "required", ")", "to", "display", "it", "in", "." ]
train
https://github.com/d0c0nnor/jocelyn/blob/a9bb73ab89d7488cec1b1bcd6d612f7a56d9b01c/src/jocelyn/__init__.py#L71-L83
edeposit/edeposit.amqp.harvester
src/edeposit/amqp/harvester/autoparser/conf_reader.py
_get_source
def _get_source(link): """ Return source of the `link` whether it is filename or url. Args: link (str): Filename or URL. Returns: str: Content. Raises: UserWarning: When the `link` couldn't be resolved. """ if link.startswith("http://") or link.startswith("https://...
python
def _get_source(link): """ Return source of the `link` whether it is filename or url. Args: link (str): Filename or URL. Returns: str: Content. Raises: UserWarning: When the `link` couldn't be resolved. """ if link.startswith("http://") or link.startswith("https://...
[ "def", "_get_source", "(", "link", ")", ":", "if", "link", ".", "startswith", "(", "\"http://\"", ")", "or", "link", ".", "startswith", "(", "\"https://\"", ")", ":", "down", "=", "httpkie", ".", "Downloader", "(", ")", "return", "down", ".", "download",...
Return source of the `link` whether it is filename or url. Args: link (str): Filename or URL. Returns: str: Content. Raises: UserWarning: When the `link` couldn't be resolved.
[ "Return", "source", "of", "the", "link", "whether", "it", "is", "filename", "or", "url", "." ]
train
https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/autoparser/conf_reader.py#L18-L39
edeposit/edeposit.amqp.harvester
src/edeposit/amqp/harvester/autoparser/conf_reader.py
_process_config_item
def _process_config_item(item, dirname): """ Process one item from the configuration file, which contains multiple items saved as dictionary. This function reads additional data from the config and do some replacements - for example, if you specify url, it will download data from this url and s...
python
def _process_config_item(item, dirname): """ Process one item from the configuration file, which contains multiple items saved as dictionary. This function reads additional data from the config and do some replacements - for example, if you specify url, it will download data from this url and s...
[ "def", "_process_config_item", "(", "item", ",", "dirname", ")", ":", "item", "=", "copy", ".", "deepcopy", "(", "item", ")", "html", "=", "item", ".", "get", "(", "\"html\"", ",", "None", ")", "if", "not", "html", ":", "raise", "UserWarning", "(", "...
Process one item from the configuration file, which contains multiple items saved as dictionary. This function reads additional data from the config and do some replacements - for example, if you specify url, it will download data from this url and so on. Args: item (dict): Item, which wil...
[ "Process", "one", "item", "from", "the", "configuration", "file", "which", "contains", "multiple", "items", "saved", "as", "dictionary", "." ]
train
https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/autoparser/conf_reader.py#L42-L89
edeposit/edeposit.amqp.harvester
src/edeposit/amqp/harvester/autoparser/conf_reader.py
read_config
def read_config(file_name): """ Read YAML file with configuration and pointers to example data. Args: file_name (str): Name of the file, where the configuration is stored. Returns: dict: Parsed and processed data (see :func:`_process_config_item`). Example YAML file:: html...
python
def read_config(file_name): """ Read YAML file with configuration and pointers to example data. Args: file_name (str): Name of the file, where the configuration is stored. Returns: dict: Parsed and processed data (see :func:`_process_config_item`). Example YAML file:: html...
[ "def", "read_config", "(", "file_name", ")", ":", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "file_name", ")", ")", "dirname", "=", "os", ".", "path", ".", "relpath", "(", "dirname", ")", "# create...
Read YAML file with configuration and pointers to example data. Args: file_name (str): Name of the file, where the configuration is stored. Returns: dict: Parsed and processed data (see :func:`_process_config_item`). Example YAML file:: html: simple_xml.xml first: ...
[ "Read", "YAML", "file", "with", "configuration", "and", "pointers", "to", "example", "data", "." ]
train
https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/autoparser/conf_reader.py#L92-L136
andrewjsledge/django-hash-filter
django_hash_filter/templatetags/hash_filter.py
hash
def hash(value, arg): """ Returns a hex-digest of the passed in value for the hash algorithm given. """ arg = str(arg).lower() if sys.version_info >= (3,0): value = value.encode("utf-8") if not arg in get_available_hashes(): raise TemplateSyntaxError("The %s hash algorithm does n...
python
def hash(value, arg): """ Returns a hex-digest of the passed in value for the hash algorithm given. """ arg = str(arg).lower() if sys.version_info >= (3,0): value = value.encode("utf-8") if not arg in get_available_hashes(): raise TemplateSyntaxError("The %s hash algorithm does n...
[ "def", "hash", "(", "value", ",", "arg", ")", ":", "arg", "=", "str", "(", "arg", ")", ".", "lower", "(", ")", "if", "sys", ".", "version_info", ">=", "(", "3", ",", "0", ")", ":", "value", "=", "value", ".", "encode", "(", "\"utf-8\"", ")", ...
Returns a hex-digest of the passed in value for the hash algorithm given.
[ "Returns", "a", "hex", "-", "digest", "of", "the", "passed", "in", "value", "for", "the", "hash", "algorithm", "given", "." ]
train
https://github.com/andrewjsledge/django-hash-filter/blob/ea90b2903938e0733d3abfafed308a8d041d9fe7/django_hash_filter/templatetags/hash_filter.py#L13-L27
tBaxter/django-fretboard
fretboard/templatetags/paginator.py
paginator
def paginator(context, adjacent_pages=2): """ To be used in conjunction with the object_list generic view. Adds pagination context variables for use in displaying first, adjacent and last page links in addition to those created by the object_list generic view. """ current_page = context.ge...
python
def paginator(context, adjacent_pages=2): """ To be used in conjunction with the object_list generic view. Adds pagination context variables for use in displaying first, adjacent and last page links in addition to those created by the object_list generic view. """ current_page = context.ge...
[ "def", "paginator", "(", "context", ",", "adjacent_pages", "=", "2", ")", ":", "current_page", "=", "context", ".", "get", "(", "'page'", ")", "paginator", "=", "context", ".", "get", "(", "'paginator'", ")", "if", "not", "paginator", ":", "return", "pag...
To be used in conjunction with the object_list generic view. Adds pagination context variables for use in displaying first, adjacent and last page links in addition to those created by the object_list generic view.
[ "To", "be", "used", "in", "conjunction", "with", "the", "object_list", "generic", "view", ".", "Adds", "pagination", "context", "variables", "for", "use", "in", "displaying", "first", "adjacent", "and", "last", "page", "links", "in", "addition", "to", "those",...
train
https://github.com/tBaxter/django-fretboard/blob/3c3f9557089821283f315a07f3e5a57a2725ab3b/fretboard/templatetags/paginator.py#L7-L41
genericclient/genericclient-base
genericclient_base/utils.py
parse_link
def parse_link(value): """Return a list of parsed link headers proxies. i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg" :rtype: list """ links = [] replace_chars = ' \'"' value = value.strip(replace_chars) if not value...
python
def parse_link(value): """Return a list of parsed link headers proxies. i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg" :rtype: list """ links = [] replace_chars = ' \'"' value = value.strip(replace_chars) if not value...
[ "def", "parse_link", "(", "value", ")", ":", "links", "=", "[", "]", "replace_chars", "=", "' \\'\"'", "value", "=", "value", ".", "strip", "(", "replace_chars", ")", "if", "not", "value", ":", "return", "links", "for", "val", "in", "re", ".", "split",...
Return a list of parsed link headers proxies. i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg" :rtype: list
[ "Return", "a", "list", "of", "parsed", "link", "headers", "proxies", ".", "i", ".", "e", ".", "Link", ":", "<http", ":", "/", "...", "/", "front", ".", "jpeg", ">", ";", "rel", "=", "front", ";", "type", "=", "image", "/", "jpeg", "<http", ":", ...
train
https://github.com/genericclient/genericclient-base/blob/193f7c879c40decaf03504af633f593b88e4abc5/genericclient_base/utils.py#L25-L57
genericclient/genericclient-base
genericclient_base/utils.py
parse_headers_link
def parse_headers_link(headers): """Returns the parsed header links of the response, if any.""" header = CaseInsensitiveDict(headers).get('link') l = {} if header: links = parse_link(header) for link in links: key = link.get('rel') or link.get('url') l[key] = ...
python
def parse_headers_link(headers): """Returns the parsed header links of the response, if any.""" header = CaseInsensitiveDict(headers).get('link') l = {} if header: links = parse_link(header) for link in links: key = link.get('rel') or link.get('url') l[key] = ...
[ "def", "parse_headers_link", "(", "headers", ")", ":", "header", "=", "CaseInsensitiveDict", "(", "headers", ")", ".", "get", "(", "'link'", ")", "l", "=", "{", "}", "if", "header", ":", "links", "=", "parse_link", "(", "header", ")", "for", "link", "i...
Returns the parsed header links of the response, if any.
[ "Returns", "the", "parsed", "header", "links", "of", "the", "response", "if", "any", "." ]
train
https://github.com/genericclient/genericclient-base/blob/193f7c879c40decaf03504af633f593b88e4abc5/genericclient_base/utils.py#L60-L74
zyga/python-phablet
phablet.py
main
def main(args=None): """ Phablet command line user interface This function implements the phablet command line tool """ parser = argparse.ArgumentParser( description=_("Run a command on Ubuntu Phablet"), epilog=""" This tool will start ssh on your connected Ubuntu Touch devi...
python
def main(args=None): """ Phablet command line user interface This function implements the phablet command line tool """ parser = argparse.ArgumentParser( description=_("Run a command on Ubuntu Phablet"), epilog=""" This tool will start ssh on your connected Ubuntu Touch devi...
[ "def", "main", "(", "args", "=", "None", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "_", "(", "\"Run a command on Ubuntu Phablet\"", ")", ",", "epilog", "=", "\"\"\"\n This tool will start ssh on your connected Ubuntu Tou...
Phablet command line user interface This function implements the phablet command line tool
[ "Phablet", "command", "line", "user", "interface" ]
train
https://github.com/zyga/python-phablet/blob/c281045dfb8b55dd2888e1efe9631f72ffc77ac8/phablet.py#L524-L595
zyga/python-phablet
phablet.py
Phablet.run
def run(self, cmd, timeout=None, key=None): """ Run a command on the phablet device using ssh :param cmd: a list of strings to execute as a command :param timeout: a timeout (in seconds) for device discovery :param key: a path to a public ssh ...
python
def run(self, cmd, timeout=None, key=None): """ Run a command on the phablet device using ssh :param cmd: a list of strings to execute as a command :param timeout: a timeout (in seconds) for device discovery :param key: a path to a public ssh ...
[ "def", "run", "(", "self", ",", "cmd", ",", "timeout", "=", "None", ",", "key", "=", "None", ")", ":", "if", "not", "isinstance", "(", "cmd", ",", "list", ")", ":", "raise", "TypeError", "(", "\"cmd needs to be a list\"", ")", "if", "not", "all", "("...
Run a command on the phablet device using ssh :param cmd: a list of strings to execute as a command :param timeout: a timeout (in seconds) for device discovery :param key: a path to a public ssh key to use for connection :returns: the exit...
[ "Run", "a", "command", "on", "the", "phablet", "device", "using", "ssh" ]
train
https://github.com/zyga/python-phablet/blob/c281045dfb8b55dd2888e1efe9631f72ffc77ac8/phablet.py#L165-L187
zyga/python-phablet
phablet.py
Phablet.connect
def connect(self, timeout=None, key=None): """ Perform one-time setup procedure. :param timeout: a timeout (in seconds) for device discovery :param key: a path to a public ssh key to use for connection This method will allow you to execute :meth:`cmdline...
python
def connect(self, timeout=None, key=None): """ Perform one-time setup procedure. :param timeout: a timeout (in seconds) for device discovery :param key: a path to a public ssh key to use for connection This method will allow you to execute :meth:`cmdline...
[ "def", "connect", "(", "self", ",", "timeout", "=", "None", ",", "key", "=", "None", ")", ":", "if", "self", ".", "port", "is", "not", "None", ":", "return", "self", ".", "_wait_for_device", "(", "timeout", ")", "self", ".", "_setup_port_forwarding", "...
Perform one-time setup procedure. :param timeout: a timeout (in seconds) for device discovery :param key: a path to a public ssh key to use for connection This method will allow you to execute :meth:`cmdline()` repeatedly without incurring the extra overhead of ...
[ "Perform", "one", "-", "time", "setup", "procedure", "." ]
train
https://github.com/zyga/python-phablet/blob/c281045dfb8b55dd2888e1efe9631f72ffc77ac8/phablet.py#L189-L213
zyga/python-phablet
phablet.py
Phablet.ssh_cmdline
def ssh_cmdline(self, cmd): """ Get argument list for meth:`subprocess.Popen()` to run ssh. :param cmd: a list of arguments to pass to ssh :returns: argument list to pass as the first argument to subprocess.Popen() .. note:: you must call :me...
python
def ssh_cmdline(self, cmd): """ Get argument list for meth:`subprocess.Popen()` to run ssh. :param cmd: a list of arguments to pass to ssh :returns: argument list to pass as the first argument to subprocess.Popen() .. note:: you must call :me...
[ "def", "ssh_cmdline", "(", "self", ",", "cmd", ")", ":", "if", "not", "isinstance", "(", "cmd", ",", "list", ")", ":", "raise", "TypeError", "(", "\"cmd needs to be a list\"", ")", "if", "not", "all", "(", "isinstance", "(", "item", ",", "str", ")", "f...
Get argument list for meth:`subprocess.Popen()` to run ssh. :param cmd: a list of arguments to pass to ssh :returns: argument list to pass as the first argument to subprocess.Popen() .. note:: you must call :meth:`connect()` at least once before ...
[ "Get", "argument", "list", "for", "meth", ":", "subprocess", ".", "Popen", "()", "to", "run", "ssh", "." ]
train
https://github.com/zyga/python-phablet/blob/c281045dfb8b55dd2888e1efe9631f72ffc77ac8/phablet.py#L215-L249
zyga/python-phablet
phablet.py
Phablet.rsync_cmdline
def rsync_cmdline(self, src, dest, *rsync_options): """ Get argument list for meth:`subprocess.Popen()` to run rsync. :param src: source file or directory :param dest: destination file or directory :param rsync_options: any additional argument...
python
def rsync_cmdline(self, src, dest, *rsync_options): """ Get argument list for meth:`subprocess.Popen()` to run rsync. :param src: source file or directory :param dest: destination file or directory :param rsync_options: any additional argument...
[ "def", "rsync_cmdline", "(", "self", ",", "src", ",", "dest", ",", "*", "rsync_options", ")", ":", "if", "not", "all", "(", "isinstance", "(", "item", ",", "str", ")", "for", "item", "in", "rsync_options", ")", ":", "raise", "TypeError", "(", "\"cmd ne...
Get argument list for meth:`subprocess.Popen()` to run rsync. :param src: source file or directory :param dest: destination file or directory :param rsync_options: any additional arguments to pass to rsync, useful if you want to pass '-a' ...
[ "Get", "argument", "list", "for", "meth", ":", "subprocess", ".", "Popen", "()", "to", "run", "rsync", "." ]
train
https://github.com/zyga/python-phablet/blob/c281045dfb8b55dd2888e1efe9631f72ffc77ac8/phablet.py#L253-L291
zyga/python-phablet
phablet.py
Phablet.push
def push(self, src, dest, timeout=None, key=None): """ Push (synchronize) some data onto the phablet device :param src: source file or directory :param dest: destination file or directory :param timeout: a timeout (in seconds) for device disco...
python
def push(self, src, dest, timeout=None, key=None): """ Push (synchronize) some data onto the phablet device :param src: source file or directory :param dest: destination file or directory :param timeout: a timeout (in seconds) for device disco...
[ "def", "push", "(", "self", ",", "src", ",", "dest", ",", "timeout", "=", "None", ",", "key", "=", "None", ")", ":", "self", ".", "connect", "(", "timeout", ",", "key", ")", "_logger", ".", "info", "(", "\"Pushing %r to %r\"", ",", "src", ",", "des...
Push (synchronize) some data onto the phablet device :param src: source file or directory :param dest: destination file or directory :param timeout: a timeout (in seconds) for device discovery :param key: a path to a public ssh key to use ...
[ "Push", "(", "synchronize", ")", "some", "data", "onto", "the", "phablet", "device" ]
train
https://github.com/zyga/python-phablet/blob/c281045dfb8b55dd2888e1efe9631f72ffc77ac8/phablet.py#L293-L311
kodexlab/reliure
reliure/options.py
Option.FromType
def FromType(name, otype): """ ValueOption subclasses factory, creates a convenient option to store data from a given Type. attribute precedence : * ``|attrs| > 0`` (``multi`` and ``uniq`` are implicit) => NotImplementedError * ``uniq`` (``multi`` is implicit) => NotImp...
python
def FromType(name, otype): """ ValueOption subclasses factory, creates a convenient option to store data from a given Type. attribute precedence : * ``|attrs| > 0`` (``multi`` and ``uniq`` are implicit) => NotImplementedError * ``uniq`` (``multi`` is implicit) => NotImp...
[ "def", "FromType", "(", "name", ",", "otype", ")", ":", "if", "otype", ".", "attrs", "is", "not", "None", "and", "len", "(", "otype", ".", "attrs", ")", ":", "raise", "NotImplementedError", "(", "\"for otype, options can't have attributs\"", ")", "#return Vect...
ValueOption subclasses factory, creates a convenient option to store data from a given Type. attribute precedence : * ``|attrs| > 0`` (``multi`` and ``uniq`` are implicit) => NotImplementedError * ``uniq`` (``multi`` is implicit) => NotImplementedError * ``multi`` and `...
[ "ValueOption", "subclasses", "factory", "creates", "a", "convenient", "option", "to", "store", "data", "from", "a", "given", "Type", "." ]
train
https://github.com/kodexlab/reliure/blob/0450c7a9254c5c003162738458bbe0c49e777ba5/reliure/options.py#L24-L50
kodexlab/reliure
reliure/options.py
Option.set
def set(self, value, parse=False): """ Set the value of the option. One can also set the 'value' property: >>> opt = ValueOption("oname", Numeric(default=1,help="an option exemple")) >>> opt.value = 12 :param value: the new value """ self.value ...
python
def set(self, value, parse=False): """ Set the value of the option. One can also set the 'value' property: >>> opt = ValueOption("oname", Numeric(default=1,help="an option exemple")) >>> opt.value = 12 :param value: the new value """ self.value ...
[ "def", "set", "(", "self", ",", "value", ",", "parse", "=", "False", ")", ":", "self", ".", "value", "=", "self", ".", "parse", "(", "value", ")", "if", "parse", "else", "value" ]
Set the value of the option. One can also set the 'value' property: >>> opt = ValueOption("oname", Numeric(default=1,help="an option exemple")) >>> opt.value = 12 :param value: the new value
[ "Set", "the", "value", "of", "the", "option", ".", "One", "can", "also", "set", "the", "value", "property", ":" ]
train
https://github.com/kodexlab/reliure/blob/0450c7a9254c5c003162738458bbe0c49e777ba5/reliure/options.py#L142-L152
kodexlab/reliure
reliure/options.py
Option.as_dict
def as_dict(self): """ returns a dictionary view of the option :returns: the option converted in a dict :rtype: dict """ opt_info = {} opt_info["type"] = "value" opt_info["name"] = self.name opt_info["value"] = self.value opt_info["otype"]...
python
def as_dict(self): """ returns a dictionary view of the option :returns: the option converted in a dict :rtype: dict """ opt_info = {} opt_info["type"] = "value" opt_info["name"] = self.name opt_info["value"] = self.value opt_info["otype"]...
[ "def", "as_dict", "(", "self", ")", ":", "opt_info", "=", "{", "}", "opt_info", "[", "\"type\"", "]", "=", "\"value\"", "opt_info", "[", "\"name\"", "]", "=", "self", ".", "name", "opt_info", "[", "\"value\"", "]", "=", "self", ".", "value", "opt_info"...
returns a dictionary view of the option :returns: the option converted in a dict :rtype: dict
[ "returns", "a", "dictionary", "view", "of", "the", "option", ":", "returns", ":", "the", "option", "converted", "in", "a", "dict", ":", "rtype", ":", "dict" ]
train
https://github.com/kodexlab/reliure/blob/0450c7a9254c5c003162738458bbe0c49e777ba5/reliure/options.py#L154-L166
heikomuller/sco-datastore
scodata/datastore.py
ObjectStore.upsert_object_property
def upsert_object_property(self, identifier, properties, ignore_constraints=False): """Manipulate an object's property set. Inserts or updates properties in given dictionary. If a property key does not exist in the object's property set it is created. If the value is None an existing property is...
python
def upsert_object_property(self, identifier, properties, ignore_constraints=False): """Manipulate an object's property set. Inserts or updates properties in given dictionary. If a property key does not exist in the object's property set it is created. If the value is None an existing property is...
[ "def", "upsert_object_property", "(", "self", ",", "identifier", ",", "properties", ",", "ignore_constraints", "=", "False", ")", ":", "# Retrieve the object with the gievn identifier. This is a (sub-)class", "# of ObjectHandle", "obj", "=", "self", ".", "get_object", "(", ...
Manipulate an object's property set. Inserts or updates properties in given dictionary. If a property key does not exist in the object's property set it is created. If the value is None an existing property is deleted. Existing object properties that are not present in the given propert...
[ "Manipulate", "an", "object", "s", "property", "set", ".", "Inserts", "or", "updates", "properties", "in", "given", "dictionary", ".", "If", "a", "property", "key", "does", "not", "exist", "in", "the", "object", "s", "property", "set", "it", "is", "created...
train
https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/datastore.py#L334-L386
heikomuller/sco-datastore
scodata/datastore.py
MongoDBStore.delete_object
def delete_object(self, identifier, erase=False): """Delete the entry with given identifier in the database. Returns the handle for the deleted object or None if object identifier is unknown. If the read-only property of the object is set to true a ValueError is raised. Paramet...
python
def delete_object(self, identifier, erase=False): """Delete the entry with given identifier in the database. Returns the handle for the deleted object or None if object identifier is unknown. If the read-only property of the object is set to true a ValueError is raised. Paramet...
[ "def", "delete_object", "(", "self", ",", "identifier", ",", "erase", "=", "False", ")", ":", "# Get object to ensure that it exists.", "db_object", "=", "self", ".", "get_object", "(", "identifier", ")", "# Set active flag to False if object exists.", "if", "db_object"...
Delete the entry with given identifier in the database. Returns the handle for the deleted object or None if object identifier is unknown. If the read-only property of the object is set to true a ValueError is raised. Parameters ---------- identifier : string ...
[ "Delete", "the", "entry", "with", "given", "identifier", "in", "the", "database", ".", "Returns", "the", "handle", "for", "the", "deleted", "object", "or", "None", "if", "object", "identifier", "is", "unknown", "." ]
train
https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/datastore.py#L418-L454
heikomuller/sco-datastore
scodata/datastore.py
MongoDBStore.get_object
def get_object(self, identifier, include_inactive=False): """Retrieve object with given identifier from the database. Parameters ---------- identifier : string Unique object identifier include_inactive : Boolean Flag indicating whether inactive (i.e., del...
python
def get_object(self, identifier, include_inactive=False): """Retrieve object with given identifier from the database. Parameters ---------- identifier : string Unique object identifier include_inactive : Boolean Flag indicating whether inactive (i.e., del...
[ "def", "get_object", "(", "self", ",", "identifier", ",", "include_inactive", "=", "False", ")", ":", "# Find all objects with given identifier. The result size is expected", "# to be zero or one", "query", "=", "{", "'_id'", ":", "identifier", "}", "if", "not", "includ...
Retrieve object with given identifier from the database. Parameters ---------- identifier : string Unique object identifier include_inactive : Boolean Flag indicating whether inactive (i.e., deleted) object should be included in the search (i.e., retu...
[ "Retrieve", "object", "with", "given", "identifier", "from", "the", "database", "." ]
train
https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/datastore.py#L488-L515
heikomuller/sco-datastore
scodata/datastore.py
MongoDBStore.insert_object
def insert_object(self, db_object): """Create new entry in the database. Parameters ---------- db_object : (Sub-class of)ObjectHandle """ # Create object using the to_dict() method. obj = self.to_dict(db_object) obj['active'] = True self.collecti...
python
def insert_object(self, db_object): """Create new entry in the database. Parameters ---------- db_object : (Sub-class of)ObjectHandle """ # Create object using the to_dict() method. obj = self.to_dict(db_object) obj['active'] = True self.collecti...
[ "def", "insert_object", "(", "self", ",", "db_object", ")", ":", "# Create object using the to_dict() method.", "obj", "=", "self", ".", "to_dict", "(", "db_object", ")", "obj", "[", "'active'", "]", "=", "True", "self", ".", "collection", ".", "insert_one", ...
Create new entry in the database. Parameters ---------- db_object : (Sub-class of)ObjectHandle
[ "Create", "new", "entry", "in", "the", "database", "." ]
train
https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/datastore.py#L517-L527
heikomuller/sco-datastore
scodata/datastore.py
MongoDBStore.list_objects
def list_objects(self, query=None, limit=-1, offset=-1): """List of all objects in the database. Optinal parameter limit and offset for pagination. A dictionary of key,value-pairs can be given as addictional query condition for document properties. Parameters ---------- ...
python
def list_objects(self, query=None, limit=-1, offset=-1): """List of all objects in the database. Optinal parameter limit and offset for pagination. A dictionary of key,value-pairs can be given as addictional query condition for document properties. Parameters ---------- ...
[ "def", "list_objects", "(", "self", ",", "query", "=", "None", ",", "limit", "=", "-", "1", ",", "offset", "=", "-", "1", ")", ":", "result", "=", "[", "]", "# Build the document query", "doc", "=", "{", "'active'", ":", "True", "}", "if", "not", "...
List of all objects in the database. Optinal parameter limit and offset for pagination. A dictionary of key,value-pairs can be given as addictional query condition for document properties. Parameters ---------- query : Dictionary Filter objects by property-value pair...
[ "List", "of", "all", "objects", "in", "the", "database", ".", "Optinal", "parameter", "limit", "and", "offset", "for", "pagination", ".", "A", "dictionary", "of", "key", "value", "-", "pairs", "can", "be", "given", "as", "addictional", "query", "condition", ...
train
https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/datastore.py#L529-L565
heikomuller/sco-datastore
scodata/datastore.py
MongoDBStore.replace_object
def replace_object(self, db_object): """Update an existing object (identified by the object identifier) with the given modified object. Parameters ---------- db_object : (Sub-class of)ObjectHandle Replacement object """ # To enable provenance traces o...
python
def replace_object(self, db_object): """Update an existing object (identified by the object identifier) with the given modified object. Parameters ---------- db_object : (Sub-class of)ObjectHandle Replacement object """ # To enable provenance traces o...
[ "def", "replace_object", "(", "self", ",", "db_object", ")", ":", "# To enable provenance traces objects are not actually deleted from the", "# database. Instead, their active flag is set to False.", "obj", "=", "self", ".", "to_dict", "(", "db_object", ")", "obj", "[", "'act...
Update an existing object (identified by the object identifier) with the given modified object. Parameters ---------- db_object : (Sub-class of)ObjectHandle Replacement object
[ "Update", "an", "existing", "object", "(", "identified", "by", "the", "object", "identifier", ")", "with", "the", "given", "modified", "object", "." ]
train
https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/datastore.py#L567-L580
heikomuller/sco-datastore
scodata/datastore.py
MongoDBStore.to_dict
def to_dict(self, db_obj): """Create a Json-like dictionary for objects managed by this object store. Parameters ---------- db_obj : (Sub-class of)ObjectHandle Returns ------- (JSON) Json-like object, i.e., dictionary. """ # B...
python
def to_dict(self, db_obj): """Create a Json-like dictionary for objects managed by this object store. Parameters ---------- db_obj : (Sub-class of)ObjectHandle Returns ------- (JSON) Json-like object, i.e., dictionary. """ # B...
[ "def", "to_dict", "(", "self", ",", "db_obj", ")", ":", "# Base Json serialization for database objects", "return", "{", "'_id'", ":", "db_obj", ".", "identifier", ",", "'timestamp'", ":", "str", "(", "db_obj", ".", "timestamp", ".", "isoformat", "(", ")", ")"...
Create a Json-like dictionary for objects managed by this object store. Parameters ---------- db_obj : (Sub-class of)ObjectHandle Returns ------- (JSON) Json-like object, i.e., dictionary.
[ "Create", "a", "Json", "-", "like", "dictionary", "for", "objects", "managed", "by", "this", "object", "store", "." ]
train
https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/datastore.py#L582-L599
praekeltfoundation/seed-service-rating
ratings/tasks.py
SendInviteMessage.compile_msg_payload
def compile_msg_payload(self, invite): """ Determine recipient, message content, return it as a dict that can be Posted to the message sender """ self.l.info("Compiling the outbound message payload") update_invite = False # Determine the recipient address if "to_...
python
def compile_msg_payload(self, invite): """ Determine recipient, message content, return it as a dict that can be Posted to the message sender """ self.l.info("Compiling the outbound message payload") update_invite = False # Determine the recipient address if "to_...
[ "def", "compile_msg_payload", "(", "self", ",", "invite", ")", ":", "self", ".", "l", ".", "info", "(", "\"Compiling the outbound message payload\"", ")", "update_invite", "=", "False", "# Determine the recipient address", "if", "\"to_addr\"", "in", "invite", ".", "...
Determine recipient, message content, return it as a dict that can be Posted to the message sender
[ "Determine", "recipient", "message", "content", "return", "it", "as", "a", "dict", "that", "can", "be", "Posted", "to", "the", "message", "sender" ]
train
https://github.com/praekeltfoundation/seed-service-rating/blob/73f7974a5bcb6e1f32a756be5274b200084c2670/ratings/tasks.py#L60-L100
praekeltfoundation/seed-service-rating
ratings/tasks.py
SendInviteMessage.send_message
def send_message(self, payload): """ Create a post request to the message sender """ self.l.info("Creating outbound message request") result = ms_client.create_outbound(payload) self.l.info("Created outbound message request") return result
python
def send_message(self, payload): """ Create a post request to the message sender """ self.l.info("Creating outbound message request") result = ms_client.create_outbound(payload) self.l.info("Created outbound message request") return result
[ "def", "send_message", "(", "self", ",", "payload", ")", ":", "self", ".", "l", ".", "info", "(", "\"Creating outbound message request\"", ")", "result", "=", "ms_client", ".", "create_outbound", "(", "payload", ")", "self", ".", "l", ".", "info", "(", "\"...
Create a post request to the message sender
[ "Create", "a", "post", "request", "to", "the", "message", "sender" ]
train
https://github.com/praekeltfoundation/seed-service-rating/blob/73f7974a5bcb6e1f32a756be5274b200084c2670/ratings/tasks.py#L102-L108
praekeltfoundation/seed-service-rating
ratings/tasks.py
SendInviteMessage.run
def run(self, invite_id, **kwargs): """ Sends a message about service rating to invitee """ self.l = self.get_logger(**kwargs) self.l.info("Looking up the invite") invite = Invite.objects.get(id=invite_id) msg_payload = self.compile_msg_payload(invite) result = se...
python
def run(self, invite_id, **kwargs): """ Sends a message about service rating to invitee """ self.l = self.get_logger(**kwargs) self.l.info("Looking up the invite") invite = Invite.objects.get(id=invite_id) msg_payload = self.compile_msg_payload(invite) result = se...
[ "def", "run", "(", "self", ",", "invite_id", ",", "*", "*", "kwargs", ")", ":", "self", ".", "l", "=", "self", ".", "get_logger", "(", "*", "*", "kwargs", ")", "self", ".", "l", ".", "info", "(", "\"Looking up the invite\"", ")", "invite", "=", "In...
Sends a message about service rating to invitee
[ "Sends", "a", "message", "about", "service", "rating", "to", "invitee" ]
train
https://github.com/praekeltfoundation/seed-service-rating/blob/73f7974a5bcb6e1f32a756be5274b200084c2670/ratings/tasks.py#L110-L121
praekelt/vumi-http-api
vumi_http_api/concurrency_limiter.py
ConcurrencyLimiter.start
def start(self): """ Start a concurrent operation. If we are below the limit, we increment the concurrency count and fire the deferred we return. If not, we add the deferred to the waiters list and return it unfired. """ # While the implemetation matches the desc...
python
def start(self): """ Start a concurrent operation. If we are below the limit, we increment the concurrency count and fire the deferred we return. If not, we add the deferred to the waiters list and return it unfired. """ # While the implemetation matches the desc...
[ "def", "start", "(", "self", ")", ":", "# While the implemetation matches the description in the docstring", "# conceptually, it always adds a new waiter and then calls", "# _check_concurrent() to handle the various cases.", "if", "self", ".", "_limit", "<", "0", ":", "# Special case...
Start a concurrent operation. If we are below the limit, we increment the concurrency count and fire the deferred we return. If not, we add the deferred to the waiters list and return it unfired.
[ "Start", "a", "concurrent", "operation", "." ]
train
https://github.com/praekelt/vumi-http-api/blob/0d7cf1cb71794c93272c19095cf8c37f4c250a59/vumi_http_api/concurrency_limiter.py#L69-L88
praekelt/vumi-http-api
vumi_http_api/concurrency_limiter.py
ConcurrencyLimitManager.start
def start(self, key): """ Start a concurrent operation. This gets the concurrency limiter for the given key (creating it if necessary) and starts a concurrent operation on it. """ start_d = self._get_limiter(key).start() self._cleanup_limiter(key) return ...
python
def start(self, key): """ Start a concurrent operation. This gets the concurrency limiter for the given key (creating it if necessary) and starts a concurrent operation on it. """ start_d = self._get_limiter(key).start() self._cleanup_limiter(key) return ...
[ "def", "start", "(", "self", ",", "key", ")", ":", "start_d", "=", "self", ".", "_get_limiter", "(", "key", ")", ".", "start", "(", ")", "self", ".", "_cleanup_limiter", "(", "key", ")", "return", "start_d" ]
Start a concurrent operation. This gets the concurrency limiter for the given key (creating it if necessary) and starts a concurrent operation on it.
[ "Start", "a", "concurrent", "operation", "." ]
train
https://github.com/praekelt/vumi-http-api/blob/0d7cf1cb71794c93272c19095cf8c37f4c250a59/vumi_http_api/concurrency_limiter.py#L132-L141
praekelt/vumi-http-api
vumi_http_api/concurrency_limiter.py
ConcurrencyLimitManager.stop
def stop(self, key): """ Stop a concurrent operation. This gets the concurrency limiter for the given key (creating it if necessary) and stops a concurrent operation on it. If the concurrency limiter is empty, it is deleted. """ self._get_limiter(key).stop() ...
python
def stop(self, key): """ Stop a concurrent operation. This gets the concurrency limiter for the given key (creating it if necessary) and stops a concurrent operation on it. If the concurrency limiter is empty, it is deleted. """ self._get_limiter(key).stop() ...
[ "def", "stop", "(", "self", ",", "key", ")", ":", "self", ".", "_get_limiter", "(", "key", ")", ".", "stop", "(", ")", "self", ".", "_cleanup_limiter", "(", "key", ")" ]
Stop a concurrent operation. This gets the concurrency limiter for the given key (creating it if necessary) and stops a concurrent operation on it. If the concurrency limiter is empty, it is deleted.
[ "Stop", "a", "concurrent", "operation", "." ]
train
https://github.com/praekelt/vumi-http-api/blob/0d7cf1cb71794c93272c19095cf8c37f4c250a59/vumi_http_api/concurrency_limiter.py#L143-L152
minhhoit/yacms
yacms/core/templatetags/yacms_tags.py
fields_for
def fields_for(context, form, template="includes/form_fields.html"): """ Renders fields for a form with an optional template choice. """ context["form_for_fields"] = form return get_template(template).render(context)
python
def fields_for(context, form, template="includes/form_fields.html"): """ Renders fields for a form with an optional template choice. """ context["form_for_fields"] = form return get_template(template).render(context)
[ "def", "fields_for", "(", "context", ",", "form", ",", "template", "=", "\"includes/form_fields.html\"", ")", ":", "context", "[", "\"form_for_fields\"", "]", "=", "form", "return", "get_template", "(", "template", ")", ".", "render", "(", "context", ")" ]
Renders fields for a form with an optional template choice.
[ "Renders", "fields", "for", "a", "form", "with", "an", "optional", "template", "choice", "." ]
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/templatetags/yacms_tags.py#L104-L109
minhhoit/yacms
yacms/core/templatetags/yacms_tags.py
sort_by
def sort_by(items, attr): """ General sort filter - sorts by either attribute or key. """ def key_func(item): try: return getattr(item, attr) except AttributeError: try: return item[attr] except TypeError: getattr(item, ...
python
def sort_by(items, attr): """ General sort filter - sorts by either attribute or key. """ def key_func(item): try: return getattr(item, attr) except AttributeError: try: return item[attr] except TypeError: getattr(item, ...
[ "def", "sort_by", "(", "items", ",", "attr", ")", ":", "def", "key_func", "(", "item", ")", ":", "try", ":", "return", "getattr", "(", "item", ",", "attr", ")", "except", "AttributeError", ":", "try", ":", "return", "item", "[", "attr", "]", "except"...
General sort filter - sorts by either attribute or key.
[ "General", "sort", "filter", "-", "sorts", "by", "either", "attribute", "or", "key", "." ]
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/templatetags/yacms_tags.py#L121-L133
minhhoit/yacms
yacms/core/templatetags/yacms_tags.py
ifinstalled
def ifinstalled(parser, token): """ Old-style ``if`` tag that renders contents if the given app is installed. The main use case is: {% ifinstalled app_name %} {% include "app_name/template.html" %} {% endifinstalled %} so we need to manually pull out all tokens if the app isn't install...
python
def ifinstalled(parser, token): """ Old-style ``if`` tag that renders contents if the given app is installed. The main use case is: {% ifinstalled app_name %} {% include "app_name/template.html" %} {% endifinstalled %} so we need to manually pull out all tokens if the app isn't install...
[ "def", "ifinstalled", "(", "parser", ",", "token", ")", ":", "try", ":", "tag", ",", "app", "=", "token", ".", "split_contents", "(", ")", "except", "ValueError", ":", "raise", "TemplateSyntaxError", "(", "\"ifinstalled should be in the form: \"", "\"{% ifinstalle...
Old-style ``if`` tag that renders contents if the given app is installed. The main use case is: {% ifinstalled app_name %} {% include "app_name/template.html" %} {% endifinstalled %} so we need to manually pull out all tokens if the app isn't installed, since if we used a normal ``if`` tag wit...
[ "Old", "-", "style", "if", "tag", "that", "renders", "contents", "if", "the", "given", "app", "is", "installed", ".", "The", "main", "use", "case", "is", ":" ]
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/templatetags/yacms_tags.py#L149-L188
minhhoit/yacms
yacms/core/templatetags/yacms_tags.py
gravatar_url
def gravatar_url(email, size=32): """ Return the full URL for a Gravatar given an email hash. """ bits = (md5(email.lower().encode("utf-8")).hexdigest(), size) return "//www.gravatar.com/avatar/%s?s=%s&d=identicon&r=PG" % bits
python
def gravatar_url(email, size=32): """ Return the full URL for a Gravatar given an email hash. """ bits = (md5(email.lower().encode("utf-8")).hexdigest(), size) return "//www.gravatar.com/avatar/%s?s=%s&d=identicon&r=PG" % bits
[ "def", "gravatar_url", "(", "email", ",", "size", "=", "32", ")", ":", "bits", "=", "(", "md5", "(", "email", ".", "lower", "(", ")", ".", "encode", "(", "\"utf-8\"", ")", ")", ".", "hexdigest", "(", ")", ",", "size", ")", "return", "\"//www.gravat...
Return the full URL for a Gravatar given an email hash.
[ "Return", "the", "full", "URL", "for", "a", "Gravatar", "given", "an", "email", "hash", "." ]
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/templatetags/yacms_tags.py#L203-L208
minhhoit/yacms
yacms/core/templatetags/yacms_tags.py
metablock
def metablock(parsed): """ Remove HTML tags, entities and superfluous characters from meta blocks. """ parsed = " ".join(parsed.replace("\n", "").split()).replace(" ,", ",") return escape(strip_tags(decode_entities(parsed)))
python
def metablock(parsed): """ Remove HTML tags, entities and superfluous characters from meta blocks. """ parsed = " ".join(parsed.replace("\n", "").split()).replace(" ,", ",") return escape(strip_tags(decode_entities(parsed)))
[ "def", "metablock", "(", "parsed", ")", ":", "parsed", "=", "\" \"", ".", "join", "(", "parsed", ".", "replace", "(", "\"\\n\"", ",", "\"\"", ")", ".", "split", "(", ")", ")", ".", "replace", "(", "\" ,\"", ",", "\",\"", ")", "return", "escape", "(...
Remove HTML tags, entities and superfluous characters from meta blocks.
[ "Remove", "HTML", "tags", "entities", "and", "superfluous", "characters", "from", "meta", "blocks", "." ]
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/templatetags/yacms_tags.py#L212-L218