id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
244,400
rameshg87/pyremotevbox
pyremotevbox/ZSI/parse.py
ParsedSoap.Parse
def Parse(self, how): '''Parse the message. ''' if type(how) == types.ClassType: how = how.typecode return how.parse(self.body_root, self)
python
def Parse(self, how): '''Parse the message. ''' if type(how) == types.ClassType: how = how.typecode return how.parse(self.body_root, self)
[ "def", "Parse", "(", "self", ",", "how", ")", ":", "if", "type", "(", "how", ")", "==", "types", ".", "ClassType", ":", "how", "=", "how", ".", "typecode", "return", "how", ".", "parse", "(", "self", ".", "body_root", ",", "self", ")" ]
Parse the message.
[ "Parse", "the", "message", "." ]
123dffff27da57c8faa3ac1dd4c68b1cf4558b1a
https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/parse.py#L322-L326
244,401
rameshg87/pyremotevbox
pyremotevbox/ZSI/parse.py
ParsedSoap.WhatActorsArePresent
def WhatActorsArePresent(self): '''Return a list of URI's of all the actor attributes found in the header. The special actor "next" is ignored. ''' results = [] for E in self.header_elements: a = _find_actor(E) if a not in [ None, SOAP.ACTOR_NEXT ]: results.append(a) return results
python
def WhatActorsArePresent(self): '''Return a list of URI's of all the actor attributes found in the header. The special actor "next" is ignored. ''' results = [] for E in self.header_elements: a = _find_actor(E) if a not in [ None, SOAP.ACTOR_NEXT ]: results.append(a) return results
[ "def", "WhatActorsArePresent", "(", "self", ")", ":", "results", "=", "[", "]", "for", "E", "in", "self", ".", "header_elements", ":", "a", "=", "_find_actor", "(", "E", ")", "if", "a", "not", "in", "[", "None", ",", "SOAP", ".", "ACTOR_NEXT", "]", ":", "results", ".", "append", "(", "a", ")", "return", "results" ]
Return a list of URI's of all the actor attributes found in the header. The special actor "next" is ignored.
[ "Return", "a", "list", "of", "URI", "s", "of", "all", "the", "actor", "attributes", "found", "in", "the", "header", ".", "The", "special", "actor", "next", "is", "ignored", "." ]
123dffff27da57c8faa3ac1dd4c68b1cf4558b1a
https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/parse.py#L335-L343
244,402
magland/vdomr
vdomr/vdom.py
VDOM._repr_html_
def _repr_html_(self): """ Return HTML representation of VDOM object. HTML escaping is performed wherever necessary. """ # Use StringIO to avoid a large number of memory allocations with string concat with io.StringIO() as out: out.write('<{tag}'.format(tag=escape(self.tag_name))) if self.style: # Important values are in double quotes - cgi.escape only escapes double quotes, not single quotes! out.write(' style="{css}"'.format( css=escape(self._to_inline_css(self.style)))) for k, v in self.attributes.items(): k2 = k if k2 == 'class_': k2 = 'class' # Important values are in double quotes - cgi.escape only escapes double quotes, not single quotes! if isinstance(v, string_types): out.write(' {key}="{value}"'.format( key=escape(k2), value=escape(v))) if isinstance(v, bool) and v: out.write(' {key}'.format(key=escape(k2))) out.write('>') for c in self.children: if isinstance(c, string_types): out.write(escape(safe_unicode(c))) else: out.write(c._repr_html_()) out.write('</{tag}>'.format(tag=escape(self.tag_name))) return out.getvalue()
python
def _repr_html_(self): """ Return HTML representation of VDOM object. HTML escaping is performed wherever necessary. """ # Use StringIO to avoid a large number of memory allocations with string concat with io.StringIO() as out: out.write('<{tag}'.format(tag=escape(self.tag_name))) if self.style: # Important values are in double quotes - cgi.escape only escapes double quotes, not single quotes! out.write(' style="{css}"'.format( css=escape(self._to_inline_css(self.style)))) for k, v in self.attributes.items(): k2 = k if k2 == 'class_': k2 = 'class' # Important values are in double quotes - cgi.escape only escapes double quotes, not single quotes! if isinstance(v, string_types): out.write(' {key}="{value}"'.format( key=escape(k2), value=escape(v))) if isinstance(v, bool) and v: out.write(' {key}'.format(key=escape(k2))) out.write('>') for c in self.children: if isinstance(c, string_types): out.write(escape(safe_unicode(c))) else: out.write(c._repr_html_()) out.write('</{tag}>'.format(tag=escape(self.tag_name))) return out.getvalue()
[ "def", "_repr_html_", "(", "self", ")", ":", "# Use StringIO to avoid a large number of memory allocations with string concat", "with", "io", ".", "StringIO", "(", ")", "as", "out", ":", "out", ".", "write", "(", "'<{tag}'", ".", "format", "(", "tag", "=", "escape", "(", "self", ".", "tag_name", ")", ")", ")", "if", "self", ".", "style", ":", "# Important values are in double quotes - cgi.escape only escapes double quotes, not single quotes!", "out", ".", "write", "(", "' style=\"{css}\"'", ".", "format", "(", "css", "=", "escape", "(", "self", ".", "_to_inline_css", "(", "self", ".", "style", ")", ")", ")", ")", "for", "k", ",", "v", "in", "self", ".", "attributes", ".", "items", "(", ")", ":", "k2", "=", "k", "if", "k2", "==", "'class_'", ":", "k2", "=", "'class'", "# Important values are in double quotes - cgi.escape only escapes double quotes, not single quotes!", "if", "isinstance", "(", "v", ",", "string_types", ")", ":", "out", ".", "write", "(", "' {key}=\"{value}\"'", ".", "format", "(", "key", "=", "escape", "(", "k2", ")", ",", "value", "=", "escape", "(", "v", ")", ")", ")", "if", "isinstance", "(", "v", ",", "bool", ")", "and", "v", ":", "out", ".", "write", "(", "' {key}'", ".", "format", "(", "key", "=", "escape", "(", "k2", ")", ")", ")", "out", ".", "write", "(", "'>'", ")", "for", "c", "in", "self", ".", "children", ":", "if", "isinstance", "(", "c", ",", "string_types", ")", ":", "out", ".", "write", "(", "escape", "(", "safe_unicode", "(", "c", ")", ")", ")", "else", ":", "out", ".", "write", "(", "c", ".", "_repr_html_", "(", ")", ")", "out", ".", "write", "(", "'</{tag}>'", ".", "format", "(", "tag", "=", "escape", "(", "self", ".", "tag_name", ")", ")", ")", "return", "out", ".", "getvalue", "(", ")" ]
Return HTML representation of VDOM object. HTML escaping is performed wherever necessary.
[ "Return", "HTML", "representation", "of", "VDOM", "object", ".", "HTML", "escaping", "is", "performed", "wherever", "necessary", "." ]
89f62611689a596ca49d9e080f3a7e9cf58b71b6
https://github.com/magland/vdomr/blob/89f62611689a596ca49d9e080f3a7e9cf58b71b6/vdomr/vdom.py#L31-L64
244,403
pybel/pybel-artifactory
src/pybel_artifactory/deploy.py
_deploy_helper
def _deploy_helper(filename, module_name, get_module, get_today_fn, hash_check=True, auth=None): """Deploys a file to the Artifactory BEL namespace cache :param str filename: The physical path :param str module_name: The name of the module to deploy to :param tuple[str] auth: A pair of (str username, str password) to give to the auth keyword of the constructor of :class:`artifactory.ArtifactoryPath`. Defaults to the result of :func:`get_arty_auth`. :return: The resource path, if it was deployed successfully, else none. :rtype: Optional[str] """ path = ArtifactoryPath( get_module(module_name), auth=get_arty_auth() if auth is None else auth ) path.mkdir(exist_ok=True) if hash_check: deployed_semantic_hashes = { get_bel_resource_hash(subpath.as_posix()) for subpath in path } semantic_hash = get_bel_resource_hash(filename) if semantic_hash in deployed_semantic_hashes: return # Don't deploy if it's already uploaded target = path / get_today_fn(module_name) target.deploy_file(filename) log.info('deployed %s', module_name) return target.as_posix()
python
def _deploy_helper(filename, module_name, get_module, get_today_fn, hash_check=True, auth=None): """Deploys a file to the Artifactory BEL namespace cache :param str filename: The physical path :param str module_name: The name of the module to deploy to :param tuple[str] auth: A pair of (str username, str password) to give to the auth keyword of the constructor of :class:`artifactory.ArtifactoryPath`. Defaults to the result of :func:`get_arty_auth`. :return: The resource path, if it was deployed successfully, else none. :rtype: Optional[str] """ path = ArtifactoryPath( get_module(module_name), auth=get_arty_auth() if auth is None else auth ) path.mkdir(exist_ok=True) if hash_check: deployed_semantic_hashes = { get_bel_resource_hash(subpath.as_posix()) for subpath in path } semantic_hash = get_bel_resource_hash(filename) if semantic_hash in deployed_semantic_hashes: return # Don't deploy if it's already uploaded target = path / get_today_fn(module_name) target.deploy_file(filename) log.info('deployed %s', module_name) return target.as_posix()
[ "def", "_deploy_helper", "(", "filename", ",", "module_name", ",", "get_module", ",", "get_today_fn", ",", "hash_check", "=", "True", ",", "auth", "=", "None", ")", ":", "path", "=", "ArtifactoryPath", "(", "get_module", "(", "module_name", ")", ",", "auth", "=", "get_arty_auth", "(", ")", "if", "auth", "is", "None", "else", "auth", ")", "path", ".", "mkdir", "(", "exist_ok", "=", "True", ")", "if", "hash_check", ":", "deployed_semantic_hashes", "=", "{", "get_bel_resource_hash", "(", "subpath", ".", "as_posix", "(", ")", ")", "for", "subpath", "in", "path", "}", "semantic_hash", "=", "get_bel_resource_hash", "(", "filename", ")", "if", "semantic_hash", "in", "deployed_semantic_hashes", ":", "return", "# Don't deploy if it's already uploaded", "target", "=", "path", "/", "get_today_fn", "(", "module_name", ")", "target", ".", "deploy_file", "(", "filename", ")", "log", ".", "info", "(", "'deployed %s'", ",", "module_name", ")", "return", "target", ".", "as_posix", "(", ")" ]
Deploys a file to the Artifactory BEL namespace cache :param str filename: The physical path :param str module_name: The name of the module to deploy to :param tuple[str] auth: A pair of (str username, str password) to give to the auth keyword of the constructor of :class:`artifactory.ArtifactoryPath`. Defaults to the result of :func:`get_arty_auth`. :return: The resource path, if it was deployed successfully, else none. :rtype: Optional[str]
[ "Deploys", "a", "file", "to", "the", "Artifactory", "BEL", "namespace", "cache" ]
720107780a59be2ef08885290dfa519b1da62871
https://github.com/pybel/pybel-artifactory/blob/720107780a59be2ef08885290dfa519b1da62871/src/pybel_artifactory/deploy.py#L37-L69
244,404
pybel/pybel-artifactory
src/pybel_artifactory/deploy.py
deploy_namespace
def deploy_namespace(filename, module_name, hash_check=True, auth=None): """Deploy a file to the Artifactory BEL namespace cache. :param str filename: The physical path :param str module_name: The name of the module to deploy to :param bool hash_check: Ensure the hash is unique before deploying :param tuple[str] auth: A pair of (str username, str password) to give to the auth keyword of the constructor of :class:`artifactory.ArtifactoryPath`. Defaults to the result of :func:`get_arty_auth`. :return: The resource path, if it was deployed successfully, else none. :rtype: Optional[str] """ return _deploy_helper( filename, module_name, get_namespace_module_url, get_namespace_today, hash_check=hash_check, auth=auth )
python
def deploy_namespace(filename, module_name, hash_check=True, auth=None): """Deploy a file to the Artifactory BEL namespace cache. :param str filename: The physical path :param str module_name: The name of the module to deploy to :param bool hash_check: Ensure the hash is unique before deploying :param tuple[str] auth: A pair of (str username, str password) to give to the auth keyword of the constructor of :class:`artifactory.ArtifactoryPath`. Defaults to the result of :func:`get_arty_auth`. :return: The resource path, if it was deployed successfully, else none. :rtype: Optional[str] """ return _deploy_helper( filename, module_name, get_namespace_module_url, get_namespace_today, hash_check=hash_check, auth=auth )
[ "def", "deploy_namespace", "(", "filename", ",", "module_name", ",", "hash_check", "=", "True", ",", "auth", "=", "None", ")", ":", "return", "_deploy_helper", "(", "filename", ",", "module_name", ",", "get_namespace_module_url", ",", "get_namespace_today", ",", "hash_check", "=", "hash_check", ",", "auth", "=", "auth", ")" ]
Deploy a file to the Artifactory BEL namespace cache. :param str filename: The physical path :param str module_name: The name of the module to deploy to :param bool hash_check: Ensure the hash is unique before deploying :param tuple[str] auth: A pair of (str username, str password) to give to the auth keyword of the constructor of :class:`artifactory.ArtifactoryPath`. Defaults to the result of :func:`get_arty_auth`. :return: The resource path, if it was deployed successfully, else none. :rtype: Optional[str]
[ "Deploy", "a", "file", "to", "the", "Artifactory", "BEL", "namespace", "cache", "." ]
720107780a59be2ef08885290dfa519b1da62871
https://github.com/pybel/pybel-artifactory/blob/720107780a59be2ef08885290dfa519b1da62871/src/pybel_artifactory/deploy.py#L72-L90
244,405
pybel/pybel-artifactory
src/pybel_artifactory/deploy.py
deploy_annotation
def deploy_annotation(filename, module_name, hash_check=True, auth=None): """Deploy a file to the Artifactory BEL annotation cache. :param str filename: The physical file path :param str module_name: The name of the module to deploy to :param bool hash_check: Ensure the hash is unique before deploying :param tuple[str] auth: A pair of (str username, str password) to give to the auth keyword of the constructor of :class:`artifactory.ArtifactoryPath`. Defaults to the result of :func:`get_arty_auth`. :return: The resource path, if it was deployed successfully, else none. :rtype: Optional[str] """ return _deploy_helper( filename, module_name, get_annotation_module_url, get_annotation_today, hash_check=hash_check, auth=auth )
python
def deploy_annotation(filename, module_name, hash_check=True, auth=None): """Deploy a file to the Artifactory BEL annotation cache. :param str filename: The physical file path :param str module_name: The name of the module to deploy to :param bool hash_check: Ensure the hash is unique before deploying :param tuple[str] auth: A pair of (str username, str password) to give to the auth keyword of the constructor of :class:`artifactory.ArtifactoryPath`. Defaults to the result of :func:`get_arty_auth`. :return: The resource path, if it was deployed successfully, else none. :rtype: Optional[str] """ return _deploy_helper( filename, module_name, get_annotation_module_url, get_annotation_today, hash_check=hash_check, auth=auth )
[ "def", "deploy_annotation", "(", "filename", ",", "module_name", ",", "hash_check", "=", "True", ",", "auth", "=", "None", ")", ":", "return", "_deploy_helper", "(", "filename", ",", "module_name", ",", "get_annotation_module_url", ",", "get_annotation_today", ",", "hash_check", "=", "hash_check", ",", "auth", "=", "auth", ")" ]
Deploy a file to the Artifactory BEL annotation cache. :param str filename: The physical file path :param str module_name: The name of the module to deploy to :param bool hash_check: Ensure the hash is unique before deploying :param tuple[str] auth: A pair of (str username, str password) to give to the auth keyword of the constructor of :class:`artifactory.ArtifactoryPath`. Defaults to the result of :func:`get_arty_auth`. :return: The resource path, if it was deployed successfully, else none. :rtype: Optional[str]
[ "Deploy", "a", "file", "to", "the", "Artifactory", "BEL", "annotation", "cache", "." ]
720107780a59be2ef08885290dfa519b1da62871
https://github.com/pybel/pybel-artifactory/blob/720107780a59be2ef08885290dfa519b1da62871/src/pybel_artifactory/deploy.py#L93-L111
244,406
pybel/pybel-artifactory
src/pybel_artifactory/deploy.py
deploy_knowledge
def deploy_knowledge(filename, module_name, auth=None): """Deploy a file to the Artifactory BEL knowledge cache. :param str filename: The physical file path :param str module_name: The name of the module to deploy to :param tuple[str] auth: A pair of (str username, str password) to give to the auth keyword of the constructor of :class:`artifactory.ArtifactoryPath`. Defaults to the result of :func:`get_arty_auth`. :return: The resource path, if it was deployed successfully, else none. :rtype: Optional[str] """ return _deploy_helper( filename, module_name, get_knowledge_module_url, get_knowledge_today, hash_check=False, auth=auth )
python
def deploy_knowledge(filename, module_name, auth=None): """Deploy a file to the Artifactory BEL knowledge cache. :param str filename: The physical file path :param str module_name: The name of the module to deploy to :param tuple[str] auth: A pair of (str username, str password) to give to the auth keyword of the constructor of :class:`artifactory.ArtifactoryPath`. Defaults to the result of :func:`get_arty_auth`. :return: The resource path, if it was deployed successfully, else none. :rtype: Optional[str] """ return _deploy_helper( filename, module_name, get_knowledge_module_url, get_knowledge_today, hash_check=False, auth=auth )
[ "def", "deploy_knowledge", "(", "filename", ",", "module_name", ",", "auth", "=", "None", ")", ":", "return", "_deploy_helper", "(", "filename", ",", "module_name", ",", "get_knowledge_module_url", ",", "get_knowledge_today", ",", "hash_check", "=", "False", ",", "auth", "=", "auth", ")" ]
Deploy a file to the Artifactory BEL knowledge cache. :param str filename: The physical file path :param str module_name: The name of the module to deploy to :param tuple[str] auth: A pair of (str username, str password) to give to the auth keyword of the constructor of :class:`artifactory.ArtifactoryPath`. Defaults to the result of :func:`get_arty_auth`. :return: The resource path, if it was deployed successfully, else none. :rtype: Optional[str]
[ "Deploy", "a", "file", "to", "the", "Artifactory", "BEL", "knowledge", "cache", "." ]
720107780a59be2ef08885290dfa519b1da62871
https://github.com/pybel/pybel-artifactory/blob/720107780a59be2ef08885290dfa519b1da62871/src/pybel_artifactory/deploy.py#L114-L131
244,407
pybel/pybel-artifactory
src/pybel_artifactory/deploy.py
deploy_directory
def deploy_directory(directory, auth=None): """Deploy all files in a given directory. :param str directory: the path to a directory :param tuple[str] auth: A pair of (str username, str password) to give to the auth keyword of the constructor of :class:`artifactory.ArtifactoryPath`. Defaults to the result of :func:`get_arty_auth`. """ for file in os.listdir(directory): full_path = os.path.join(directory, file) if file.endswith(BELANNO_EXTENSION): name = file[:-len(BELANNO_EXTENSION)] log.info('deploying annotation %s', full_path) deploy_annotation(full_path, name, auth=auth) elif file.endswith(BELNS_EXTENSION): name = file[:-len(BELNS_EXTENSION)] log.info('deploying namespace %s', full_path) deploy_namespace(full_path, name, auth=auth) elif file.endswith(BEL_EXTENSION): name = file[:-len(BEL_EXTENSION)] log.info('deploying knowledge %s', full_path) deploy_knowledge(full_path, name, auth=auth) else: log.debug('not deploying %s', full_path)
python
def deploy_directory(directory, auth=None): """Deploy all files in a given directory. :param str directory: the path to a directory :param tuple[str] auth: A pair of (str username, str password) to give to the auth keyword of the constructor of :class:`artifactory.ArtifactoryPath`. Defaults to the result of :func:`get_arty_auth`. """ for file in os.listdir(directory): full_path = os.path.join(directory, file) if file.endswith(BELANNO_EXTENSION): name = file[:-len(BELANNO_EXTENSION)] log.info('deploying annotation %s', full_path) deploy_annotation(full_path, name, auth=auth) elif file.endswith(BELNS_EXTENSION): name = file[:-len(BELNS_EXTENSION)] log.info('deploying namespace %s', full_path) deploy_namespace(full_path, name, auth=auth) elif file.endswith(BEL_EXTENSION): name = file[:-len(BEL_EXTENSION)] log.info('deploying knowledge %s', full_path) deploy_knowledge(full_path, name, auth=auth) else: log.debug('not deploying %s', full_path)
[ "def", "deploy_directory", "(", "directory", ",", "auth", "=", "None", ")", ":", "for", "file", "in", "os", ".", "listdir", "(", "directory", ")", ":", "full_path", "=", "os", ".", "path", ".", "join", "(", "directory", ",", "file", ")", "if", "file", ".", "endswith", "(", "BELANNO_EXTENSION", ")", ":", "name", "=", "file", "[", ":", "-", "len", "(", "BELANNO_EXTENSION", ")", "]", "log", ".", "info", "(", "'deploying annotation %s'", ",", "full_path", ")", "deploy_annotation", "(", "full_path", ",", "name", ",", "auth", "=", "auth", ")", "elif", "file", ".", "endswith", "(", "BELNS_EXTENSION", ")", ":", "name", "=", "file", "[", ":", "-", "len", "(", "BELNS_EXTENSION", ")", "]", "log", ".", "info", "(", "'deploying namespace %s'", ",", "full_path", ")", "deploy_namespace", "(", "full_path", ",", "name", ",", "auth", "=", "auth", ")", "elif", "file", ".", "endswith", "(", "BEL_EXTENSION", ")", ":", "name", "=", "file", "[", ":", "-", "len", "(", "BEL_EXTENSION", ")", "]", "log", ".", "info", "(", "'deploying knowledge %s'", ",", "full_path", ")", "deploy_knowledge", "(", "full_path", ",", "name", ",", "auth", "=", "auth", ")", "else", ":", "log", ".", "debug", "(", "'not deploying %s'", ",", "full_path", ")" ]
Deploy all files in a given directory. :param str directory: the path to a directory :param tuple[str] auth: A pair of (str username, str password) to give to the auth keyword of the constructor of :class:`artifactory.ArtifactoryPath`. Defaults to the result of :func:`get_arty_auth`.
[ "Deploy", "all", "files", "in", "a", "given", "directory", "." ]
720107780a59be2ef08885290dfa519b1da62871
https://github.com/pybel/pybel-artifactory/blob/720107780a59be2ef08885290dfa519b1da62871/src/pybel_artifactory/deploy.py#L134-L160
244,408
mbr/unleash
unleash/git.py
export_tree
def export_tree(lookup, tree, path): """Exports the given tree object to path. :param lookup: Function to retrieve objects for SHA1 hashes. :param tree: Tree to export. :param path: Output path. """ FILE_PERM = S_IRWXU | S_IRWXG | S_IRWXO for name, mode, hexsha in tree.iteritems(): dest = os.path.join(path, name) if S_ISGITLINK(mode): log.error('Ignored submodule {}; submodules are not yet supported.' .format(name)) # raise ValueError('Does not support submodules') elif S_ISDIR(mode): os.mkdir(dest) os.chmod(dest, 0o0755) export_tree(lookup, lookup(hexsha), dest) elif S_ISLNK(mode): os.symlink(lookup(hexsha).data, dest) elif S_ISREG(mode): with open(dest, 'wb') as out: for chunk in lookup(hexsha).chunked: out.write(chunk) os.chmod(dest, mode & FILE_PERM) else: raise ValueError('Cannot deal with mode of {:o} from {}'.format( mode, name))
python
def export_tree(lookup, tree, path): """Exports the given tree object to path. :param lookup: Function to retrieve objects for SHA1 hashes. :param tree: Tree to export. :param path: Output path. """ FILE_PERM = S_IRWXU | S_IRWXG | S_IRWXO for name, mode, hexsha in tree.iteritems(): dest = os.path.join(path, name) if S_ISGITLINK(mode): log.error('Ignored submodule {}; submodules are not yet supported.' .format(name)) # raise ValueError('Does not support submodules') elif S_ISDIR(mode): os.mkdir(dest) os.chmod(dest, 0o0755) export_tree(lookup, lookup(hexsha), dest) elif S_ISLNK(mode): os.symlink(lookup(hexsha).data, dest) elif S_ISREG(mode): with open(dest, 'wb') as out: for chunk in lookup(hexsha).chunked: out.write(chunk) os.chmod(dest, mode & FILE_PERM) else: raise ValueError('Cannot deal with mode of {:o} from {}'.format( mode, name))
[ "def", "export_tree", "(", "lookup", ",", "tree", ",", "path", ")", ":", "FILE_PERM", "=", "S_IRWXU", "|", "S_IRWXG", "|", "S_IRWXO", "for", "name", ",", "mode", ",", "hexsha", "in", "tree", ".", "iteritems", "(", ")", ":", "dest", "=", "os", ".", "path", ".", "join", "(", "path", ",", "name", ")", "if", "S_ISGITLINK", "(", "mode", ")", ":", "log", ".", "error", "(", "'Ignored submodule {}; submodules are not yet supported.'", ".", "format", "(", "name", ")", ")", "# raise ValueError('Does not support submodules')", "elif", "S_ISDIR", "(", "mode", ")", ":", "os", ".", "mkdir", "(", "dest", ")", "os", ".", "chmod", "(", "dest", ",", "0o0755", ")", "export_tree", "(", "lookup", ",", "lookup", "(", "hexsha", ")", ",", "dest", ")", "elif", "S_ISLNK", "(", "mode", ")", ":", "os", ".", "symlink", "(", "lookup", "(", "hexsha", ")", ".", "data", ",", "dest", ")", "elif", "S_ISREG", "(", "mode", ")", ":", "with", "open", "(", "dest", ",", "'wb'", ")", "as", "out", ":", "for", "chunk", "in", "lookup", "(", "hexsha", ")", ".", "chunked", ":", "out", ".", "write", "(", "chunk", ")", "os", ".", "chmod", "(", "dest", ",", "mode", "&", "FILE_PERM", ")", "else", ":", "raise", "ValueError", "(", "'Cannot deal with mode of {:o} from {}'", ".", "format", "(", "mode", ",", "name", ")", ")" ]
Exports the given tree object to path. :param lookup: Function to retrieve objects for SHA1 hashes. :param tree: Tree to export. :param path: Output path.
[ "Exports", "the", "given", "tree", "object", "to", "path", "." ]
f36c6e6600868bc054f5b8d4cf1c03ea8eb8da4c
https://github.com/mbr/unleash/blob/f36c6e6600868bc054f5b8d4cf1c03ea8eb8da4c/unleash/git.py#L17-L46
244,409
jspricke/python-abook
abook.py
abook2vcf
def abook2vcf(): """Command line tool to convert from Abook to vCard""" from argparse import ArgumentParser, FileType from os.path import expanduser from sys import stdout parser = ArgumentParser(description='Converter from Abook to vCard syntax.') parser.add_argument('infile', nargs='?', default=expanduser('~/.abook/addressbook'), help='The Abook file to process (default: ~/.abook/addressbook)') parser.add_argument('outfile', nargs='?', type=FileType('w'), default=stdout, help='Output vCard file (default: stdout)') args = parser.parse_args() args.outfile.write(Abook(args.infile).to_vcf())
python
def abook2vcf(): """Command line tool to convert from Abook to vCard""" from argparse import ArgumentParser, FileType from os.path import expanduser from sys import stdout parser = ArgumentParser(description='Converter from Abook to vCard syntax.') parser.add_argument('infile', nargs='?', default=expanduser('~/.abook/addressbook'), help='The Abook file to process (default: ~/.abook/addressbook)') parser.add_argument('outfile', nargs='?', type=FileType('w'), default=stdout, help='Output vCard file (default: stdout)') args = parser.parse_args() args.outfile.write(Abook(args.infile).to_vcf())
[ "def", "abook2vcf", "(", ")", ":", "from", "argparse", "import", "ArgumentParser", ",", "FileType", "from", "os", ".", "path", "import", "expanduser", "from", "sys", "import", "stdout", "parser", "=", "ArgumentParser", "(", "description", "=", "'Converter from Abook to vCard syntax.'", ")", "parser", ".", "add_argument", "(", "'infile'", ",", "nargs", "=", "'?'", ",", "default", "=", "expanduser", "(", "'~/.abook/addressbook'", ")", ",", "help", "=", "'The Abook file to process (default: ~/.abook/addressbook)'", ")", "parser", ".", "add_argument", "(", "'outfile'", ",", "nargs", "=", "'?'", ",", "type", "=", "FileType", "(", "'w'", ")", ",", "default", "=", "stdout", ",", "help", "=", "'Output vCard file (default: stdout)'", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "args", ".", "outfile", ".", "write", "(", "Abook", "(", "args", ".", "infile", ")", ".", "to_vcf", "(", ")", ")" ]
Command line tool to convert from Abook to vCard
[ "Command", "line", "tool", "to", "convert", "from", "Abook", "to", "vCard" ]
cc58ad998303ce9a8b347a3317158c8f7cd0529f
https://github.com/jspricke/python-abook/blob/cc58ad998303ce9a8b347a3317158c8f7cd0529f/abook.py#L328-L341
244,410
jspricke/python-abook
abook.py
vcf2abook
def vcf2abook(): """Command line tool to convert from vCard to Abook""" from argparse import ArgumentParser, FileType from sys import stdin parser = ArgumentParser(description='Converter from vCard to Abook syntax.') parser.add_argument('infile', nargs='?', type=FileType('r'), default=stdin, help='Input vCard file (default: stdin)') parser.add_argument('outfile', nargs='?', default=expanduser('~/.abook/addressbook'), help='Output Abook file (default: ~/.abook/addressbook)') args = parser.parse_args() Abook.abook_file(args.infile, args.outfile)
python
def vcf2abook(): """Command line tool to convert from vCard to Abook""" from argparse import ArgumentParser, FileType from sys import stdin parser = ArgumentParser(description='Converter from vCard to Abook syntax.') parser.add_argument('infile', nargs='?', type=FileType('r'), default=stdin, help='Input vCard file (default: stdin)') parser.add_argument('outfile', nargs='?', default=expanduser('~/.abook/addressbook'), help='Output Abook file (default: ~/.abook/addressbook)') args = parser.parse_args() Abook.abook_file(args.infile, args.outfile)
[ "def", "vcf2abook", "(", ")", ":", "from", "argparse", "import", "ArgumentParser", ",", "FileType", "from", "sys", "import", "stdin", "parser", "=", "ArgumentParser", "(", "description", "=", "'Converter from vCard to Abook syntax.'", ")", "parser", ".", "add_argument", "(", "'infile'", ",", "nargs", "=", "'?'", ",", "type", "=", "FileType", "(", "'r'", ")", ",", "default", "=", "stdin", ",", "help", "=", "'Input vCard file (default: stdin)'", ")", "parser", ".", "add_argument", "(", "'outfile'", ",", "nargs", "=", "'?'", ",", "default", "=", "expanduser", "(", "'~/.abook/addressbook'", ")", ",", "help", "=", "'Output Abook file (default: ~/.abook/addressbook)'", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "Abook", ".", "abook_file", "(", "args", ".", "infile", ",", "args", ".", "outfile", ")" ]
Command line tool to convert from vCard to Abook
[ "Command", "line", "tool", "to", "convert", "from", "vCard", "to", "Abook" ]
cc58ad998303ce9a8b347a3317158c8f7cd0529f
https://github.com/jspricke/python-abook/blob/cc58ad998303ce9a8b347a3317158c8f7cd0529f/abook.py#L344-L356
244,411
jspricke/python-abook
abook.py
Abook._update
def _update(self): """ Update internal state.""" with self._lock: if getmtime(self._filename) > self._last_modified: self._last_modified = getmtime(self._filename) self._book = ConfigParser(default_section='format') self._book.read(self._filename)
python
def _update(self): """ Update internal state.""" with self._lock: if getmtime(self._filename) > self._last_modified: self._last_modified = getmtime(self._filename) self._book = ConfigParser(default_section='format') self._book.read(self._filename)
[ "def", "_update", "(", "self", ")", ":", "with", "self", ".", "_lock", ":", "if", "getmtime", "(", "self", ".", "_filename", ")", ">", "self", ".", "_last_modified", ":", "self", ".", "_last_modified", "=", "getmtime", "(", "self", ".", "_filename", ")", "self", ".", "_book", "=", "ConfigParser", "(", "default_section", "=", "'format'", ")", "self", ".", "_book", ".", "read", "(", "self", ".", "_filename", ")" ]
Update internal state.
[ "Update", "internal", "state", "." ]
cc58ad998303ce9a8b347a3317158c8f7cd0529f
https://github.com/jspricke/python-abook/blob/cc58ad998303ce9a8b347a3317158c8f7cd0529f/abook.py#L42-L48
244,412
jspricke/python-abook
abook.py
Abook._gen_addr
def _gen_addr(entry): """Generates a vCard Address object""" return Address(street=entry.get('address', ''), extended=entry.get('address2', ''), city=entry.get('city', ''), region=entry.get('state', ''), code=entry.get('zip', ''), country=entry.get('country', ''))
python
def _gen_addr(entry): """Generates a vCard Address object""" return Address(street=entry.get('address', ''), extended=entry.get('address2', ''), city=entry.get('city', ''), region=entry.get('state', ''), code=entry.get('zip', ''), country=entry.get('country', ''))
[ "def", "_gen_addr", "(", "entry", ")", ":", "return", "Address", "(", "street", "=", "entry", ".", "get", "(", "'address'", ",", "''", ")", ",", "extended", "=", "entry", ".", "get", "(", "'address2'", ",", "''", ")", ",", "city", "=", "entry", ".", "get", "(", "'city'", ",", "''", ")", ",", "region", "=", "entry", ".", "get", "(", "'state'", ",", "''", ")", ",", "code", "=", "entry", ".", "get", "(", "'zip'", ",", "''", ")", ",", "country", "=", "entry", ".", "get", "(", "'country'", ",", "''", ")", ")" ]
Generates a vCard Address object
[ "Generates", "a", "vCard", "Address", "object" ]
cc58ad998303ce9a8b347a3317158c8f7cd0529f
https://github.com/jspricke/python-abook/blob/cc58ad998303ce9a8b347a3317158c8f7cd0529f/abook.py#L125-L132
244,413
jspricke/python-abook
abook.py
Abook._add_photo
def _add_photo(self, card, name): """Tries to load a photo and add it to the vCard""" try: photo_file = join(dirname(self._filename), 'photo/%s.jpeg' % name) jpeg = open(photo_file, 'rb').read() photo = card.add('photo') photo.type_param = 'jpeg' photo.encoding_param = 'b' photo.value = jpeg except IOError: pass
python
def _add_photo(self, card, name): """Tries to load a photo and add it to the vCard""" try: photo_file = join(dirname(self._filename), 'photo/%s.jpeg' % name) jpeg = open(photo_file, 'rb').read() photo = card.add('photo') photo.type_param = 'jpeg' photo.encoding_param = 'b' photo.value = jpeg except IOError: pass
[ "def", "_add_photo", "(", "self", ",", "card", ",", "name", ")", ":", "try", ":", "photo_file", "=", "join", "(", "dirname", "(", "self", ".", "_filename", ")", ",", "'photo/%s.jpeg'", "%", "name", ")", "jpeg", "=", "open", "(", "photo_file", ",", "'rb'", ")", ".", "read", "(", ")", "photo", "=", "card", ".", "add", "(", "'photo'", ")", "photo", ".", "type_param", "=", "'jpeg'", "photo", ".", "encoding_param", "=", "'b'", "photo", ".", "value", "=", "jpeg", "except", "IOError", ":", "pass" ]
Tries to load a photo and add it to the vCard
[ "Tries", "to", "load", "a", "photo", "and", "add", "it", "to", "the", "vCard" ]
cc58ad998303ce9a8b347a3317158c8f7cd0529f
https://github.com/jspricke/python-abook/blob/cc58ad998303ce9a8b347a3317158c8f7cd0529f/abook.py#L134-L144
244,414
jspricke/python-abook
abook.py
Abook._to_vcard
def _to_vcard(self, entry): """Return a vCard of the Abook entry""" card = vCard() card.add('uid').value = Abook._gen_uid(entry) card.add('fn').value = entry['name'] card.add('n').value = Abook._gen_name(entry['name']) if 'email' in entry: for email in entry['email'].split(','): card.add('email').value = email addr_comps = ['address', 'address2', 'city', 'country', 'zip', 'country'] if any(comp in entry for comp in addr_comps): card.add('adr').value = Abook._gen_addr(entry) if 'other' in entry: tel = card.add('tel') tel.value = entry['other'] if 'phone' in entry: tel = card.add('tel') tel.type_param = 'home' tel.value = entry['phone'] if 'workphone' in entry: tel = card.add('tel') tel.type_param = 'work' tel.value = entry['workphone'] if 'mobile' in entry: tel = card.add('tel') tel.type_param = 'cell' tel.value = entry['mobile'] if 'nick' in entry: card.add('nickname').value = entry['nick'] if 'url' in entry: card.add('url').value = entry['url'] if 'notes' in entry: card.add('note').value = entry['notes'] self._add_photo(card, entry['name']) return card
python
def _to_vcard(self, entry): """Return a vCard of the Abook entry""" card = vCard() card.add('uid').value = Abook._gen_uid(entry) card.add('fn').value = entry['name'] card.add('n').value = Abook._gen_name(entry['name']) if 'email' in entry: for email in entry['email'].split(','): card.add('email').value = email addr_comps = ['address', 'address2', 'city', 'country', 'zip', 'country'] if any(comp in entry for comp in addr_comps): card.add('adr').value = Abook._gen_addr(entry) if 'other' in entry: tel = card.add('tel') tel.value = entry['other'] if 'phone' in entry: tel = card.add('tel') tel.type_param = 'home' tel.value = entry['phone'] if 'workphone' in entry: tel = card.add('tel') tel.type_param = 'work' tel.value = entry['workphone'] if 'mobile' in entry: tel = card.add('tel') tel.type_param = 'cell' tel.value = entry['mobile'] if 'nick' in entry: card.add('nickname').value = entry['nick'] if 'url' in entry: card.add('url').value = entry['url'] if 'notes' in entry: card.add('note').value = entry['notes'] self._add_photo(card, entry['name']) return card
[ "def", "_to_vcard", "(", "self", ",", "entry", ")", ":", "card", "=", "vCard", "(", ")", "card", ".", "add", "(", "'uid'", ")", ".", "value", "=", "Abook", ".", "_gen_uid", "(", "entry", ")", "card", ".", "add", "(", "'fn'", ")", ".", "value", "=", "entry", "[", "'name'", "]", "card", ".", "add", "(", "'n'", ")", ".", "value", "=", "Abook", ".", "_gen_name", "(", "entry", "[", "'name'", "]", ")", "if", "'email'", "in", "entry", ":", "for", "email", "in", "entry", "[", "'email'", "]", ".", "split", "(", "','", ")", ":", "card", ".", "add", "(", "'email'", ")", ".", "value", "=", "email", "addr_comps", "=", "[", "'address'", ",", "'address2'", ",", "'city'", ",", "'country'", ",", "'zip'", ",", "'country'", "]", "if", "any", "(", "comp", "in", "entry", "for", "comp", "in", "addr_comps", ")", ":", "card", ".", "add", "(", "'adr'", ")", ".", "value", "=", "Abook", ".", "_gen_addr", "(", "entry", ")", "if", "'other'", "in", "entry", ":", "tel", "=", "card", ".", "add", "(", "'tel'", ")", "tel", ".", "value", "=", "entry", "[", "'other'", "]", "if", "'phone'", "in", "entry", ":", "tel", "=", "card", ".", "add", "(", "'tel'", ")", "tel", ".", "type_param", "=", "'home'", "tel", ".", "value", "=", "entry", "[", "'phone'", "]", "if", "'workphone'", "in", "entry", ":", "tel", "=", "card", ".", "add", "(", "'tel'", ")", "tel", ".", "type_param", "=", "'work'", "tel", ".", "value", "=", "entry", "[", "'workphone'", "]", "if", "'mobile'", "in", "entry", ":", "tel", "=", "card", ".", "add", "(", "'tel'", ")", "tel", ".", "type_param", "=", "'cell'", "tel", ".", "value", "=", "entry", "[", "'mobile'", "]", "if", "'nick'", "in", "entry", ":", "card", ".", "add", "(", "'nickname'", ")", ".", "value", "=", "entry", "[", "'nick'", "]", "if", "'url'", "in", "entry", ":", "card", ".", "add", "(", "'url'", ")", ".", "value", "=", "entry", "[", "'url'", "]", "if", "'notes'", "in", "entry", ":", "card", ".", "add", "(", "'note'", ")", ".", "value", "=", "entry", "[", "'notes'", "]", "self", ".", "_add_photo", "(", "card", ",", "entry", "[", "'name'", "]", ")", "return", "card" ]
Return a vCard of the Abook entry
[ "Return", "a", "vCard", "of", "the", "Abook", "entry" ]
cc58ad998303ce9a8b347a3317158c8f7cd0529f
https://github.com/jspricke/python-abook/blob/cc58ad998303ce9a8b347a3317158c8f7cd0529f/abook.py#L146-L192
244,415
jspricke/python-abook
abook.py
Abook.to_vcards
def to_vcards(self): """Return a list of vCards""" self._update() return [self._to_vcard(self._book[entry]) for entry in self._book.sections()]
python
def to_vcards(self): """Return a list of vCards""" self._update() return [self._to_vcard(self._book[entry]) for entry in self._book.sections()]
[ "def", "to_vcards", "(", "self", ")", ":", "self", ".", "_update", "(", ")", "return", "[", "self", ".", "_to_vcard", "(", "self", ".", "_book", "[", "entry", "]", ")", "for", "entry", "in", "self", ".", "_book", ".", "sections", "(", ")", "]" ]
Return a list of vCards
[ "Return", "a", "list", "of", "vCards" ]
cc58ad998303ce9a8b347a3317158c8f7cd0529f
https://github.com/jspricke/python-abook/blob/cc58ad998303ce9a8b347a3317158c8f7cd0529f/abook.py#L214-L217
244,416
jspricke/python-abook
abook.py
Abook._conv_adr
def _conv_adr(adr, entry): """Converts to Abook address format""" if adr.value.street: entry['address'] = adr.value.street if adr.value.extended: entry['address2'] = adr.value.extended if adr.value.city: entry['city'] = adr.value.city if adr.value.region: entry['state'] = adr.value.region if adr.value.code and adr.value.code != '0': entry['zip'] = adr.value.code if adr.value.country: entry['country'] = adr.value.country
python
def _conv_adr(adr, entry): """Converts to Abook address format""" if adr.value.street: entry['address'] = adr.value.street if adr.value.extended: entry['address2'] = adr.value.extended if adr.value.city: entry['city'] = adr.value.city if adr.value.region: entry['state'] = adr.value.region if adr.value.code and adr.value.code != '0': entry['zip'] = adr.value.code if adr.value.country: entry['country'] = adr.value.country
[ "def", "_conv_adr", "(", "adr", ",", "entry", ")", ":", "if", "adr", ".", "value", ".", "street", ":", "entry", "[", "'address'", "]", "=", "adr", ".", "value", ".", "street", "if", "adr", ".", "value", ".", "extended", ":", "entry", "[", "'address2'", "]", "=", "adr", ".", "value", ".", "extended", "if", "adr", ".", "value", ".", "city", ":", "entry", "[", "'city'", "]", "=", "adr", ".", "value", ".", "city", "if", "adr", ".", "value", ".", "region", ":", "entry", "[", "'state'", "]", "=", "adr", ".", "value", ".", "region", "if", "adr", ".", "value", ".", "code", "and", "adr", ".", "value", ".", "code", "!=", "'0'", ":", "entry", "[", "'zip'", "]", "=", "adr", ".", "value", ".", "code", "if", "adr", ".", "value", ".", "country", ":", "entry", "[", "'country'", "]", "=", "adr", ".", "value", ".", "country" ]
Converts to Abook address format
[ "Converts", "to", "Abook", "address", "format" ]
cc58ad998303ce9a8b347a3317158c8f7cd0529f
https://github.com/jspricke/python-abook/blob/cc58ad998303ce9a8b347a3317158c8f7cd0529f/abook.py#L254-L267
244,417
jspricke/python-abook
abook.py
Abook._conv_tel_list
def _conv_tel_list(tel_list, entry): """Converts to Abook phone types""" for tel in tel_list: if not hasattr(tel, 'TYPE_param'): entry['other'] = tel.value elif tel.TYPE_param.lower() == 'home': entry['phone'] = tel.value elif tel.TYPE_param.lower() == 'work': entry['workphone'] = tel.value elif tel.TYPE_param.lower() == 'cell': entry['mobile'] = tel.value
python
def _conv_tel_list(tel_list, entry): """Converts to Abook phone types""" for tel in tel_list: if not hasattr(tel, 'TYPE_param'): entry['other'] = tel.value elif tel.TYPE_param.lower() == 'home': entry['phone'] = tel.value elif tel.TYPE_param.lower() == 'work': entry['workphone'] = tel.value elif tel.TYPE_param.lower() == 'cell': entry['mobile'] = tel.value
[ "def", "_conv_tel_list", "(", "tel_list", ",", "entry", ")", ":", "for", "tel", "in", "tel_list", ":", "if", "not", "hasattr", "(", "tel", ",", "'TYPE_param'", ")", ":", "entry", "[", "'other'", "]", "=", "tel", ".", "value", "elif", "tel", ".", "TYPE_param", ".", "lower", "(", ")", "==", "'home'", ":", "entry", "[", "'phone'", "]", "=", "tel", ".", "value", "elif", "tel", ".", "TYPE_param", ".", "lower", "(", ")", "==", "'work'", ":", "entry", "[", "'workphone'", "]", "=", "tel", ".", "value", "elif", "tel", ".", "TYPE_param", ".", "lower", "(", ")", "==", "'cell'", ":", "entry", "[", "'mobile'", "]", "=", "tel", ".", "value" ]
Converts to Abook phone types
[ "Converts", "to", "Abook", "phone", "types" ]
cc58ad998303ce9a8b347a3317158c8f7cd0529f
https://github.com/jspricke/python-abook/blob/cc58ad998303ce9a8b347a3317158c8f7cd0529f/abook.py#L270-L280
244,418
jspricke/python-abook
abook.py
Abook.to_abook
def to_abook(card, section, book, bookfile=None): """Converts a vCard to Abook""" book[section] = {} book[section]['name'] = card.fn.value if hasattr(card, 'email'): book[section]['email'] = ','.join([e.value for e in card.email_list]) if hasattr(card, 'adr'): Abook._conv_adr(card.adr, book[section]) if hasattr(card, 'tel_list'): Abook._conv_tel_list(card.tel_list, book[section]) if hasattr(card, 'nickname') and card.nickname.value: book[section]['nick'] = card.nickname.value if hasattr(card, 'url') and card.url.value: book[section]['url'] = card.url.value if hasattr(card, 'note') and card.note.value: book[section]['notes'] = card.note.value if hasattr(card, 'photo') and bookfile: try: photo_file = join(dirname(bookfile), 'photo/%s.%s' % (card.fn.value, card.photo.TYPE_param)) open(photo_file, 'wb').write(card.photo.value) except IOError: pass
python
def to_abook(card, section, book, bookfile=None): """Converts a vCard to Abook""" book[section] = {} book[section]['name'] = card.fn.value if hasattr(card, 'email'): book[section]['email'] = ','.join([e.value for e in card.email_list]) if hasattr(card, 'adr'): Abook._conv_adr(card.adr, book[section]) if hasattr(card, 'tel_list'): Abook._conv_tel_list(card.tel_list, book[section]) if hasattr(card, 'nickname') and card.nickname.value: book[section]['nick'] = card.nickname.value if hasattr(card, 'url') and card.url.value: book[section]['url'] = card.url.value if hasattr(card, 'note') and card.note.value: book[section]['notes'] = card.note.value if hasattr(card, 'photo') and bookfile: try: photo_file = join(dirname(bookfile), 'photo/%s.%s' % (card.fn.value, card.photo.TYPE_param)) open(photo_file, 'wb').write(card.photo.value) except IOError: pass
[ "def", "to_abook", "(", "card", ",", "section", ",", "book", ",", "bookfile", "=", "None", ")", ":", "book", "[", "section", "]", "=", "{", "}", "book", "[", "section", "]", "[", "'name'", "]", "=", "card", ".", "fn", ".", "value", "if", "hasattr", "(", "card", ",", "'email'", ")", ":", "book", "[", "section", "]", "[", "'email'", "]", "=", "','", ".", "join", "(", "[", "e", ".", "value", "for", "e", "in", "card", ".", "email_list", "]", ")", "if", "hasattr", "(", "card", ",", "'adr'", ")", ":", "Abook", ".", "_conv_adr", "(", "card", ".", "adr", ",", "book", "[", "section", "]", ")", "if", "hasattr", "(", "card", ",", "'tel_list'", ")", ":", "Abook", ".", "_conv_tel_list", "(", "card", ".", "tel_list", ",", "book", "[", "section", "]", ")", "if", "hasattr", "(", "card", ",", "'nickname'", ")", "and", "card", ".", "nickname", ".", "value", ":", "book", "[", "section", "]", "[", "'nick'", "]", "=", "card", ".", "nickname", ".", "value", "if", "hasattr", "(", "card", ",", "'url'", ")", "and", "card", ".", "url", ".", "value", ":", "book", "[", "section", "]", "[", "'url'", "]", "=", "card", ".", "url", ".", "value", "if", "hasattr", "(", "card", ",", "'note'", ")", "and", "card", ".", "note", ".", "value", ":", "book", "[", "section", "]", "[", "'notes'", "]", "=", "card", ".", "note", ".", "value", "if", "hasattr", "(", "card", ",", "'photo'", ")", "and", "bookfile", ":", "try", ":", "photo_file", "=", "join", "(", "dirname", "(", "bookfile", ")", ",", "'photo/%s.%s'", "%", "(", "card", ".", "fn", ".", "value", ",", "card", ".", "photo", ".", "TYPE_param", ")", ")", "open", "(", "photo_file", ",", "'wb'", ")", ".", "write", "(", "card", ".", "photo", ".", "value", ")", "except", "IOError", ":", "pass" ]
Converts a vCard to Abook
[ "Converts", "a", "vCard", "to", "Abook" ]
cc58ad998303ce9a8b347a3317158c8f7cd0529f
https://github.com/jspricke/python-abook/blob/cc58ad998303ce9a8b347a3317158c8f7cd0529f/abook.py#L283-L311
244,419
jspricke/python-abook
abook.py
Abook.abook_file
def abook_file(vcard, bookfile): """Write a new Abook file with the given vcards""" book = ConfigParser(default_section='format') book['format'] = {} book['format']['program'] = 'abook' book['format']['version'] = '0.6.1' for (i, card) in enumerate(readComponents(vcard.read())): Abook.to_abook(card, str(i), book, bookfile) with open(bookfile, 'w') as fp: book.write(fp, False)
python
def abook_file(vcard, bookfile): """Write a new Abook file with the given vcards""" book = ConfigParser(default_section='format') book['format'] = {} book['format']['program'] = 'abook' book['format']['version'] = '0.6.1' for (i, card) in enumerate(readComponents(vcard.read())): Abook.to_abook(card, str(i), book, bookfile) with open(bookfile, 'w') as fp: book.write(fp, False)
[ "def", "abook_file", "(", "vcard", ",", "bookfile", ")", ":", "book", "=", "ConfigParser", "(", "default_section", "=", "'format'", ")", "book", "[", "'format'", "]", "=", "{", "}", "book", "[", "'format'", "]", "[", "'program'", "]", "=", "'abook'", "book", "[", "'format'", "]", "[", "'version'", "]", "=", "'0.6.1'", "for", "(", "i", ",", "card", ")", "in", "enumerate", "(", "readComponents", "(", "vcard", ".", "read", "(", ")", ")", ")", ":", "Abook", ".", "to_abook", "(", "card", ",", "str", "(", "i", ")", ",", "book", ",", "bookfile", ")", "with", "open", "(", "bookfile", ",", "'w'", ")", "as", "fp", ":", "book", ".", "write", "(", "fp", ",", "False", ")" ]
Write a new Abook file with the given vcards
[ "Write", "a", "new", "Abook", "file", "with", "the", "given", "vcards" ]
cc58ad998303ce9a8b347a3317158c8f7cd0529f
https://github.com/jspricke/python-abook/blob/cc58ad998303ce9a8b347a3317158c8f7cd0529f/abook.py#L314-L325
244,420
collectiveacuity/labPack
labpack/compilers/filters.py
positional_filter
def positional_filter(positional_filters, title=''): ''' a method to construct a conditional filter function to test positional arguments :param positional_filters: dictionary or list of dictionaries with query criteria :param title: string with name of function to use instead :return: callable for filter_function NOTE: query criteria architecture each item in the path filters argument must be a dictionary which is composed of integer-value key names that represent the index value of the positional segment to test and key values with the dictionary of conditional operators used to test the string value in the indexed field of the record. eg. positional_filters = [ { 0: { 'must_contain': [ '^lab' ] } } ] this example filter looks at the first segment of each key string in the collection for a string value which starts with the characters 'lab'. as a result, it will match both the following: lab/unittests/1473719695.2165067.json 'laboratory20160912.json' NOTE: the filter function uses a query filters list structure to represent the disjunctive normal form of a logical expression. a record is added to the results list if any query criteria dictionary in the list evaluates to true. within each query criteria dictionary, all declared conditional operators must evaluate to true. in this way, the positional_filters represents a boolean OR operator and each criteria dictionary inside the list represents a boolean AND operator between all keys in the dictionary. each query criteria uses the architecture of query declaration in the jsonModel.query method NOTE: function function will lazy load a dictionary input positional_filters: [ { 0: { conditional operators }, 1: { conditional_operators }, ... } ] conditional operators: "byte_data": false, "discrete_values": [ "" ], "excluded_values": [ "" ], 'equal_to': '', "greater_than": "", "less_than": "", "max_length": 0, "max_value": "", "min_length": 0, "min_value": "", "must_contain": [ "" ], "must_not_contain": [ "" ], "contains_either": [ "" ] ''' # define help text if not title: title = 'positional_filter' filter_arg = '%s(positional_filters=[...])' % title # construct path_filter model filter_schema = { 'schema': { 'byte_data': False, 'discrete_values': [ '' ], 'excluded_values': [ '' ], 'equal_to': '', 'greater_than': '', 'less_than': '', 'max_length': 0, 'max_value': '', 'min_length': 0, 'min_value': '', 'must_contain': [ '' ], 'must_not_contain': [ '' ], 'contains_either': [ '' ] }, 'components': { '.discrete_values': { 'required_field': False }, '.excluded_values': { 'required_field': False }, '.must_contain': { 'required_field': False }, '.must_not_contain': { 'required_field': False }, '.contains_either': { 'required_field': False } } } from jsonmodel.validators import jsonModel filter_model = jsonModel(filter_schema) # lazy load path dictionary if isinstance(positional_filters, dict): positional_filters = [ positional_filters ] # validate input if not isinstance(positional_filters, list): raise TypeError('%s must be a list.' % filter_arg) for i in range(len(positional_filters)): if not isinstance(positional_filters[i], dict): raise TypeError('%s item %s must be a dictionary.' % (filter_arg, i)) for key, value in positional_filters[i].items(): _key_name = '%s : {...}' % key if not isinstance(key, int): raise TypeError('%s key name must be an int.' % filter_arg.replace('...', _key_name)) elif not isinstance(value, dict): raise TypeError('%s key value must be a dictionary' % filter_arg.replace('...', _key_name)) filter_model.validate(value) # construct segment value model segment_schema = { 'schema': { 'segment_value': 'string' } } segment_model = jsonModel(segment_schema) # construct filter function def filter_function(*args): max_index = len(args) - 1 for filter in positional_filters: criteria_match = True for key, value in filter.items(): if key > max_index: criteria_match = False break segment_criteria = { '.segment_value': value } segment_data = { 'segment_value': args[key] } if not segment_model.query(segment_criteria, segment_data): criteria_match = False break if criteria_match: return True return False return filter_function
python
def positional_filter(positional_filters, title=''): ''' a method to construct a conditional filter function to test positional arguments :param positional_filters: dictionary or list of dictionaries with query criteria :param title: string with name of function to use instead :return: callable for filter_function NOTE: query criteria architecture each item in the path filters argument must be a dictionary which is composed of integer-value key names that represent the index value of the positional segment to test and key values with the dictionary of conditional operators used to test the string value in the indexed field of the record. eg. positional_filters = [ { 0: { 'must_contain': [ '^lab' ] } } ] this example filter looks at the first segment of each key string in the collection for a string value which starts with the characters 'lab'. as a result, it will match both the following: lab/unittests/1473719695.2165067.json 'laboratory20160912.json' NOTE: the filter function uses a query filters list structure to represent the disjunctive normal form of a logical expression. a record is added to the results list if any query criteria dictionary in the list evaluates to true. within each query criteria dictionary, all declared conditional operators must evaluate to true. in this way, the positional_filters represents a boolean OR operator and each criteria dictionary inside the list represents a boolean AND operator between all keys in the dictionary. each query criteria uses the architecture of query declaration in the jsonModel.query method NOTE: function function will lazy load a dictionary input positional_filters: [ { 0: { conditional operators }, 1: { conditional_operators }, ... } ] conditional operators: "byte_data": false, "discrete_values": [ "" ], "excluded_values": [ "" ], 'equal_to': '', "greater_than": "", "less_than": "", "max_length": 0, "max_value": "", "min_length": 0, "min_value": "", "must_contain": [ "" ], "must_not_contain": [ "" ], "contains_either": [ "" ] ''' # define help text if not title: title = 'positional_filter' filter_arg = '%s(positional_filters=[...])' % title # construct path_filter model filter_schema = { 'schema': { 'byte_data': False, 'discrete_values': [ '' ], 'excluded_values': [ '' ], 'equal_to': '', 'greater_than': '', 'less_than': '', 'max_length': 0, 'max_value': '', 'min_length': 0, 'min_value': '', 'must_contain': [ '' ], 'must_not_contain': [ '' ], 'contains_either': [ '' ] }, 'components': { '.discrete_values': { 'required_field': False }, '.excluded_values': { 'required_field': False }, '.must_contain': { 'required_field': False }, '.must_not_contain': { 'required_field': False }, '.contains_either': { 'required_field': False } } } from jsonmodel.validators import jsonModel filter_model = jsonModel(filter_schema) # lazy load path dictionary if isinstance(positional_filters, dict): positional_filters = [ positional_filters ] # validate input if not isinstance(positional_filters, list): raise TypeError('%s must be a list.' % filter_arg) for i in range(len(positional_filters)): if not isinstance(positional_filters[i], dict): raise TypeError('%s item %s must be a dictionary.' % (filter_arg, i)) for key, value in positional_filters[i].items(): _key_name = '%s : {...}' % key if not isinstance(key, int): raise TypeError('%s key name must be an int.' % filter_arg.replace('...', _key_name)) elif not isinstance(value, dict): raise TypeError('%s key value must be a dictionary' % filter_arg.replace('...', _key_name)) filter_model.validate(value) # construct segment value model segment_schema = { 'schema': { 'segment_value': 'string' } } segment_model = jsonModel(segment_schema) # construct filter function def filter_function(*args): max_index = len(args) - 1 for filter in positional_filters: criteria_match = True for key, value in filter.items(): if key > max_index: criteria_match = False break segment_criteria = { '.segment_value': value } segment_data = { 'segment_value': args[key] } if not segment_model.query(segment_criteria, segment_data): criteria_match = False break if criteria_match: return True return False return filter_function
[ "def", "positional_filter", "(", "positional_filters", ",", "title", "=", "''", ")", ":", "# define help text ", "if", "not", "title", ":", "title", "=", "'positional_filter'", "filter_arg", "=", "'%s(positional_filters=[...])'", "%", "title", "# construct path_filter model", "filter_schema", "=", "{", "'schema'", ":", "{", "'byte_data'", ":", "False", ",", "'discrete_values'", ":", "[", "''", "]", ",", "'excluded_values'", ":", "[", "''", "]", ",", "'equal_to'", ":", "''", ",", "'greater_than'", ":", "''", ",", "'less_than'", ":", "''", ",", "'max_length'", ":", "0", ",", "'max_value'", ":", "''", ",", "'min_length'", ":", "0", ",", "'min_value'", ":", "''", ",", "'must_contain'", ":", "[", "''", "]", ",", "'must_not_contain'", ":", "[", "''", "]", ",", "'contains_either'", ":", "[", "''", "]", "}", ",", "'components'", ":", "{", "'.discrete_values'", ":", "{", "'required_field'", ":", "False", "}", ",", "'.excluded_values'", ":", "{", "'required_field'", ":", "False", "}", ",", "'.must_contain'", ":", "{", "'required_field'", ":", "False", "}", ",", "'.must_not_contain'", ":", "{", "'required_field'", ":", "False", "}", ",", "'.contains_either'", ":", "{", "'required_field'", ":", "False", "}", "}", "}", "from", "jsonmodel", ".", "validators", "import", "jsonModel", "filter_model", "=", "jsonModel", "(", "filter_schema", ")", "# lazy load path dictionary", "if", "isinstance", "(", "positional_filters", ",", "dict", ")", ":", "positional_filters", "=", "[", "positional_filters", "]", "# validate input", "if", "not", "isinstance", "(", "positional_filters", ",", "list", ")", ":", "raise", "TypeError", "(", "'%s must be a list.'", "%", "filter_arg", ")", "for", "i", "in", "range", "(", "len", "(", "positional_filters", ")", ")", ":", "if", "not", "isinstance", "(", "positional_filters", "[", "i", "]", ",", "dict", ")", ":", "raise", "TypeError", "(", "'%s item %s must be a dictionary.'", "%", "(", "filter_arg", ",", "i", ")", ")", "for", "key", ",", "value", "in", "positional_filters", "[", "i", "]", ".", "items", "(", ")", ":", "_key_name", "=", "'%s : {...}'", "%", "key", "if", "not", "isinstance", "(", "key", ",", "int", ")", ":", "raise", "TypeError", "(", "'%s key name must be an int.'", "%", "filter_arg", ".", "replace", "(", "'...'", ",", "_key_name", ")", ")", "elif", "not", "isinstance", "(", "value", ",", "dict", ")", ":", "raise", "TypeError", "(", "'%s key value must be a dictionary'", "%", "filter_arg", ".", "replace", "(", "'...'", ",", "_key_name", ")", ")", "filter_model", ".", "validate", "(", "value", ")", "# construct segment value model", "segment_schema", "=", "{", "'schema'", ":", "{", "'segment_value'", ":", "'string'", "}", "}", "segment_model", "=", "jsonModel", "(", "segment_schema", ")", "# construct filter function", "def", "filter_function", "(", "*", "args", ")", ":", "max_index", "=", "len", "(", "args", ")", "-", "1", "for", "filter", "in", "positional_filters", ":", "criteria_match", "=", "True", "for", "key", ",", "value", "in", "filter", ".", "items", "(", ")", ":", "if", "key", ">", "max_index", ":", "criteria_match", "=", "False", "break", "segment_criteria", "=", "{", "'.segment_value'", ":", "value", "}", "segment_data", "=", "{", "'segment_value'", ":", "args", "[", "key", "]", "}", "if", "not", "segment_model", ".", "query", "(", "segment_criteria", ",", "segment_data", ")", ":", "criteria_match", "=", "False", "break", "if", "criteria_match", ":", "return", "True", "return", "False", "return", "filter_function" ]
a method to construct a conditional filter function to test positional arguments :param positional_filters: dictionary or list of dictionaries with query criteria :param title: string with name of function to use instead :return: callable for filter_function NOTE: query criteria architecture each item in the path filters argument must be a dictionary which is composed of integer-value key names that represent the index value of the positional segment to test and key values with the dictionary of conditional operators used to test the string value in the indexed field of the record. eg. positional_filters = [ { 0: { 'must_contain': [ '^lab' ] } } ] this example filter looks at the first segment of each key string in the collection for a string value which starts with the characters 'lab'. as a result, it will match both the following: lab/unittests/1473719695.2165067.json 'laboratory20160912.json' NOTE: the filter function uses a query filters list structure to represent the disjunctive normal form of a logical expression. a record is added to the results list if any query criteria dictionary in the list evaluates to true. within each query criteria dictionary, all declared conditional operators must evaluate to true. in this way, the positional_filters represents a boolean OR operator and each criteria dictionary inside the list represents a boolean AND operator between all keys in the dictionary. each query criteria uses the architecture of query declaration in the jsonModel.query method NOTE: function function will lazy load a dictionary input positional_filters: [ { 0: { conditional operators }, 1: { conditional_operators }, ... } ] conditional operators: "byte_data": false, "discrete_values": [ "" ], "excluded_values": [ "" ], 'equal_to': '', "greater_than": "", "less_than": "", "max_length": 0, "max_value": "", "min_length": 0, "min_value": "", "must_contain": [ "" ], "must_not_contain": [ "" ], "contains_either": [ "" ]
[ "a", "method", "to", "construct", "a", "conditional", "filter", "function", "to", "test", "positional", "arguments" ]
52949ece35e72e3cc308f54d9ffa6bfbd96805b8
https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/compilers/filters.py#L6-L148
244,421
PSU-OIT-ARC/django-local-settings
local_settings/loader.py
Loader.load_and_check
def load_and_check(self, base_settings, prompt=None): """Load settings and check them. Loads the settings from ``base_settings``, then checks them. Returns: (merged settings, True) on success (None, False) on failure """ checker = Checker(self.file_name, self.section, self.registry, self.strategy_type, prompt) settings = self.load(base_settings) if checker.check(settings): return settings, True return None, False
python
def load_and_check(self, base_settings, prompt=None): """Load settings and check them. Loads the settings from ``base_settings``, then checks them. Returns: (merged settings, True) on success (None, False) on failure """ checker = Checker(self.file_name, self.section, self.registry, self.strategy_type, prompt) settings = self.load(base_settings) if checker.check(settings): return settings, True return None, False
[ "def", "load_and_check", "(", "self", ",", "base_settings", ",", "prompt", "=", "None", ")", ":", "checker", "=", "Checker", "(", "self", ".", "file_name", ",", "self", ".", "section", ",", "self", ".", "registry", ",", "self", ".", "strategy_type", ",", "prompt", ")", "settings", "=", "self", ".", "load", "(", "base_settings", ")", "if", "checker", ".", "check", "(", "settings", ")", ":", "return", "settings", ",", "True", "return", "None", ",", "False" ]
Load settings and check them. Loads the settings from ``base_settings``, then checks them. Returns: (merged settings, True) on success (None, False) on failure
[ "Load", "settings", "and", "check", "them", "." ]
758810fbd9411c2046a187afcac6532155cac694
https://github.com/PSU-OIT-ARC/django-local-settings/blob/758810fbd9411c2046a187afcac6532155cac694/local_settings/loader.py#L20-L34
244,422
PSU-OIT-ARC/django-local-settings
local_settings/loader.py
Loader.load
def load(self, base_settings): """Merge local settings from file with ``base_settings``. Returns a new settings dict containing the base settings and the loaded settings. Includes: - base settings - settings from extended file(s), if any - settings from file """ is_valid_key = lambda k: k.isupper() and not k.startswith('_') # Base settings, including `LocalSetting`s, loaded from the # Django settings module. valid_keys = (k for k in base_settings if is_valid_key(k)) base_settings = DottedAccessDict((k, base_settings[k]) for k in valid_keys) # Settings read from the settings file; values are unprocessed. settings_from_file = self.strategy.read_file(self.file_name, self.section) settings_from_file.pop('extends', None) # The fully resolved settings. settings = Settings(base_settings) settings_names = [] settings_not_decoded = set() for name, value in settings_from_file.items(): for prefix in ('PREPEND.', 'APPEND.', 'SWAP.'): if name.startswith(prefix): name = name[len(prefix):] name = '{prefix}({name})'.format(**locals()) break settings_names.append(name) # Attempt to decode raw values. Errors in decoding at this # stage are ignored. try: value = self.strategy.decode_value(value) except ValueError: settings_not_decoded.add(name) settings.set_dotted(name, value) # See if this setting corresponds to a `LocalSetting`. If # so, note that the `LocalSetting` has a value by putting it # in the registry. This also makes it easy to retrieve the # `LocalSetting` later so its value can be set. current_value = base_settings.get_dotted(name, None) if isinstance(current_value, LocalSetting): self.registry[current_value] = name # Interpolate values of settings read from file. When a setting # that couldn't be decoded previously is encountered, its post- # interpolation value will be decoded. for name in settings_names: value = settings.get_dotted(name) value, _ = self._interpolate_values(value, settings) if name in settings_not_decoded: value = self.strategy.decode_value(value) settings.set_dotted(name, value) # Interpolate base settings. self._interpolate_values(settings, settings) self._interpolate_keys(settings, settings) self._prepend_extras(settings, settings.pop('PREPEND', None)) self._append_extras(settings, settings.pop('APPEND', None)) self._swap_list_items(settings, settings.pop('SWAP', None)) self._import_from_string(settings, settings.pop('IMPORT_FROM_STRING', None)) for local_setting, name in self.registry.items(): local_setting.value = settings.get_dotted(name) return settings
python
def load(self, base_settings): """Merge local settings from file with ``base_settings``. Returns a new settings dict containing the base settings and the loaded settings. Includes: - base settings - settings from extended file(s), if any - settings from file """ is_valid_key = lambda k: k.isupper() and not k.startswith('_') # Base settings, including `LocalSetting`s, loaded from the # Django settings module. valid_keys = (k for k in base_settings if is_valid_key(k)) base_settings = DottedAccessDict((k, base_settings[k]) for k in valid_keys) # Settings read from the settings file; values are unprocessed. settings_from_file = self.strategy.read_file(self.file_name, self.section) settings_from_file.pop('extends', None) # The fully resolved settings. settings = Settings(base_settings) settings_names = [] settings_not_decoded = set() for name, value in settings_from_file.items(): for prefix in ('PREPEND.', 'APPEND.', 'SWAP.'): if name.startswith(prefix): name = name[len(prefix):] name = '{prefix}({name})'.format(**locals()) break settings_names.append(name) # Attempt to decode raw values. Errors in decoding at this # stage are ignored. try: value = self.strategy.decode_value(value) except ValueError: settings_not_decoded.add(name) settings.set_dotted(name, value) # See if this setting corresponds to a `LocalSetting`. If # so, note that the `LocalSetting` has a value by putting it # in the registry. This also makes it easy to retrieve the # `LocalSetting` later so its value can be set. current_value = base_settings.get_dotted(name, None) if isinstance(current_value, LocalSetting): self.registry[current_value] = name # Interpolate values of settings read from file. When a setting # that couldn't be decoded previously is encountered, its post- # interpolation value will be decoded. for name in settings_names: value = settings.get_dotted(name) value, _ = self._interpolate_values(value, settings) if name in settings_not_decoded: value = self.strategy.decode_value(value) settings.set_dotted(name, value) # Interpolate base settings. self._interpolate_values(settings, settings) self._interpolate_keys(settings, settings) self._prepend_extras(settings, settings.pop('PREPEND', None)) self._append_extras(settings, settings.pop('APPEND', None)) self._swap_list_items(settings, settings.pop('SWAP', None)) self._import_from_string(settings, settings.pop('IMPORT_FROM_STRING', None)) for local_setting, name in self.registry.items(): local_setting.value = settings.get_dotted(name) return settings
[ "def", "load", "(", "self", ",", "base_settings", ")", ":", "is_valid_key", "=", "lambda", "k", ":", "k", ".", "isupper", "(", ")", "and", "not", "k", ".", "startswith", "(", "'_'", ")", "# Base settings, including `LocalSetting`s, loaded from the", "# Django settings module.", "valid_keys", "=", "(", "k", "for", "k", "in", "base_settings", "if", "is_valid_key", "(", "k", ")", ")", "base_settings", "=", "DottedAccessDict", "(", "(", "k", ",", "base_settings", "[", "k", "]", ")", "for", "k", "in", "valid_keys", ")", "# Settings read from the settings file; values are unprocessed.", "settings_from_file", "=", "self", ".", "strategy", ".", "read_file", "(", "self", ".", "file_name", ",", "self", ".", "section", ")", "settings_from_file", ".", "pop", "(", "'extends'", ",", "None", ")", "# The fully resolved settings.", "settings", "=", "Settings", "(", "base_settings", ")", "settings_names", "=", "[", "]", "settings_not_decoded", "=", "set", "(", ")", "for", "name", ",", "value", "in", "settings_from_file", ".", "items", "(", ")", ":", "for", "prefix", "in", "(", "'PREPEND.'", ",", "'APPEND.'", ",", "'SWAP.'", ")", ":", "if", "name", ".", "startswith", "(", "prefix", ")", ":", "name", "=", "name", "[", "len", "(", "prefix", ")", ":", "]", "name", "=", "'{prefix}({name})'", ".", "format", "(", "*", "*", "locals", "(", ")", ")", "break", "settings_names", ".", "append", "(", "name", ")", "# Attempt to decode raw values. Errors in decoding at this", "# stage are ignored.", "try", ":", "value", "=", "self", ".", "strategy", ".", "decode_value", "(", "value", ")", "except", "ValueError", ":", "settings_not_decoded", ".", "add", "(", "name", ")", "settings", ".", "set_dotted", "(", "name", ",", "value", ")", "# See if this setting corresponds to a `LocalSetting`. If", "# so, note that the `LocalSetting` has a value by putting it", "# in the registry. This also makes it easy to retrieve the", "# `LocalSetting` later so its value can be set.", "current_value", "=", "base_settings", ".", "get_dotted", "(", "name", ",", "None", ")", "if", "isinstance", "(", "current_value", ",", "LocalSetting", ")", ":", "self", ".", "registry", "[", "current_value", "]", "=", "name", "# Interpolate values of settings read from file. When a setting", "# that couldn't be decoded previously is encountered, its post-", "# interpolation value will be decoded.", "for", "name", "in", "settings_names", ":", "value", "=", "settings", ".", "get_dotted", "(", "name", ")", "value", ",", "_", "=", "self", ".", "_interpolate_values", "(", "value", ",", "settings", ")", "if", "name", "in", "settings_not_decoded", ":", "value", "=", "self", ".", "strategy", ".", "decode_value", "(", "value", ")", "settings", ".", "set_dotted", "(", "name", ",", "value", ")", "# Interpolate base settings.", "self", ".", "_interpolate_values", "(", "settings", ",", "settings", ")", "self", ".", "_interpolate_keys", "(", "settings", ",", "settings", ")", "self", ".", "_prepend_extras", "(", "settings", ",", "settings", ".", "pop", "(", "'PREPEND'", ",", "None", ")", ")", "self", ".", "_append_extras", "(", "settings", ",", "settings", ".", "pop", "(", "'APPEND'", ",", "None", ")", ")", "self", ".", "_swap_list_items", "(", "settings", ",", "settings", ".", "pop", "(", "'SWAP'", ",", "None", ")", ")", "self", ".", "_import_from_string", "(", "settings", ",", "settings", ".", "pop", "(", "'IMPORT_FROM_STRING'", ",", "None", ")", ")", "for", "local_setting", ",", "name", "in", "self", ".", "registry", ".", "items", "(", ")", ":", "local_setting", ".", "value", "=", "settings", ".", "get_dotted", "(", "name", ")", "return", "settings" ]
Merge local settings from file with ``base_settings``. Returns a new settings dict containing the base settings and the loaded settings. Includes: - base settings - settings from extended file(s), if any - settings from file
[ "Merge", "local", "settings", "from", "file", "with", "base_settings", "." ]
758810fbd9411c2046a187afcac6532155cac694
https://github.com/PSU-OIT-ARC/django-local-settings/blob/758810fbd9411c2046a187afcac6532155cac694/local_settings/loader.py#L36-L113
244,423
PSU-OIT-ARC/django-local-settings
local_settings/loader.py
Loader._inject
def _inject(self, value, settings): """Inject ``settings`` into ``value``. Go through ``value`` looking for ``{{NAME}}`` groups and replace each group with the value of the named item from ``settings``. Args: value (str): The value to inject settings into settings: An object that provides the dotted access interface Returns: (str, bool): The new value and whether the new value is different from the original value """ assert isinstance(value, string_types), 'Expected str; got {0.__class__}'.format(value) begin, end = '{{', '}}' if begin not in value: return value, False new_value = value begin_pos, end_pos = 0, None len_begin, len_end = len(begin), len(end) len_value = len(new_value) while begin_pos < len_value: # Find next {{. begin_pos = new_value.find(begin, begin_pos) if begin_pos == -1: break # Save everything before {{. before = new_value[:begin_pos] # Find }} after {{. begin_pos += len_begin end_pos = new_value.find(end, begin_pos) if end_pos == -1: raise ValueError('Unmatched {begin}...{end} in {value}'.format(**locals())) # Get name between {{ and }}, ignoring leading and trailing # whitespace. name = new_value[begin_pos:end_pos] name = name.strip() if not name: raise ValueError('Empty name in {value}'.format(**locals())) # Save everything after }}. after_pos = end_pos + len_end try: after = new_value[after_pos:] except IndexError: # Reached end of value. after = '' # Retrieve string value for named setting (the "injection # value"). try: injection_value = settings.get_dotted(name) except KeyError: raise KeyError('{name} not found in {settings}'.format(**locals())) if not isinstance(injection_value, string_types): injection_value = self.strategy.encode_value(injection_value) # Combine before, inject value, and after to get the new # value. new_value = ''.join((before, injection_value, after)) # Continue after injected value. begin_pos = len(before) + len(injection_value) len_value = len(new_value) return new_value, (new_value != value)
python
def _inject(self, value, settings): """Inject ``settings`` into ``value``. Go through ``value`` looking for ``{{NAME}}`` groups and replace each group with the value of the named item from ``settings``. Args: value (str): The value to inject settings into settings: An object that provides the dotted access interface Returns: (str, bool): The new value and whether the new value is different from the original value """ assert isinstance(value, string_types), 'Expected str; got {0.__class__}'.format(value) begin, end = '{{', '}}' if begin not in value: return value, False new_value = value begin_pos, end_pos = 0, None len_begin, len_end = len(begin), len(end) len_value = len(new_value) while begin_pos < len_value: # Find next {{. begin_pos = new_value.find(begin, begin_pos) if begin_pos == -1: break # Save everything before {{. before = new_value[:begin_pos] # Find }} after {{. begin_pos += len_begin end_pos = new_value.find(end, begin_pos) if end_pos == -1: raise ValueError('Unmatched {begin}...{end} in {value}'.format(**locals())) # Get name between {{ and }}, ignoring leading and trailing # whitespace. name = new_value[begin_pos:end_pos] name = name.strip() if not name: raise ValueError('Empty name in {value}'.format(**locals())) # Save everything after }}. after_pos = end_pos + len_end try: after = new_value[after_pos:] except IndexError: # Reached end of value. after = '' # Retrieve string value for named setting (the "injection # value"). try: injection_value = settings.get_dotted(name) except KeyError: raise KeyError('{name} not found in {settings}'.format(**locals())) if not isinstance(injection_value, string_types): injection_value = self.strategy.encode_value(injection_value) # Combine before, inject value, and after to get the new # value. new_value = ''.join((before, injection_value, after)) # Continue after injected value. begin_pos = len(before) + len(injection_value) len_value = len(new_value) return new_value, (new_value != value)
[ "def", "_inject", "(", "self", ",", "value", ",", "settings", ")", ":", "assert", "isinstance", "(", "value", ",", "string_types", ")", ",", "'Expected str; got {0.__class__}'", ".", "format", "(", "value", ")", "begin", ",", "end", "=", "'{{'", ",", "'}}'", "if", "begin", "not", "in", "value", ":", "return", "value", ",", "False", "new_value", "=", "value", "begin_pos", ",", "end_pos", "=", "0", ",", "None", "len_begin", ",", "len_end", "=", "len", "(", "begin", ")", ",", "len", "(", "end", ")", "len_value", "=", "len", "(", "new_value", ")", "while", "begin_pos", "<", "len_value", ":", "# Find next {{.", "begin_pos", "=", "new_value", ".", "find", "(", "begin", ",", "begin_pos", ")", "if", "begin_pos", "==", "-", "1", ":", "break", "# Save everything before {{.", "before", "=", "new_value", "[", ":", "begin_pos", "]", "# Find }} after {{.", "begin_pos", "+=", "len_begin", "end_pos", "=", "new_value", ".", "find", "(", "end", ",", "begin_pos", ")", "if", "end_pos", "==", "-", "1", ":", "raise", "ValueError", "(", "'Unmatched {begin}...{end} in {value}'", ".", "format", "(", "*", "*", "locals", "(", ")", ")", ")", "# Get name between {{ and }}, ignoring leading and trailing", "# whitespace.", "name", "=", "new_value", "[", "begin_pos", ":", "end_pos", "]", "name", "=", "name", ".", "strip", "(", ")", "if", "not", "name", ":", "raise", "ValueError", "(", "'Empty name in {value}'", ".", "format", "(", "*", "*", "locals", "(", ")", ")", ")", "# Save everything after }}.", "after_pos", "=", "end_pos", "+", "len_end", "try", ":", "after", "=", "new_value", "[", "after_pos", ":", "]", "except", "IndexError", ":", "# Reached end of value.", "after", "=", "''", "# Retrieve string value for named setting (the \"injection", "# value\").", "try", ":", "injection_value", "=", "settings", ".", "get_dotted", "(", "name", ")", "except", "KeyError", ":", "raise", "KeyError", "(", "'{name} not found in {settings}'", ".", "format", "(", "*", "*", "locals", "(", ")", ")", ")", "if", "not", "isinstance", "(", "injection_value", ",", "string_types", ")", ":", "injection_value", "=", "self", ".", "strategy", ".", "encode_value", "(", "injection_value", ")", "# Combine before, inject value, and after to get the new", "# value.", "new_value", "=", "''", ".", "join", "(", "(", "before", ",", "injection_value", ",", "after", ")", ")", "# Continue after injected value.", "begin_pos", "=", "len", "(", "before", ")", "+", "len", "(", "injection_value", ")", "len_value", "=", "len", "(", "new_value", ")", "return", "new_value", ",", "(", "new_value", "!=", "value", ")" ]
Inject ``settings`` into ``value``. Go through ``value`` looking for ``{{NAME}}`` groups and replace each group with the value of the named item from ``settings``. Args: value (str): The value to inject settings into settings: An object that provides the dotted access interface Returns: (str, bool): The new value and whether the new value is different from the original value
[ "Inject", "settings", "into", "value", "." ]
758810fbd9411c2046a187afcac6532155cac694
https://github.com/PSU-OIT-ARC/django-local-settings/blob/758810fbd9411c2046a187afcac6532155cac694/local_settings/loader.py#L208-L285
244,424
rosenbrockc/acorn
acorn/utility.py
_get_reporoot
def _get_reporoot(): """Returns the absolute path to the repo root directory on the current system. """ from os import path import acorn medpath = path.abspath(acorn.__file__) return path.dirname(path.dirname(medpath))
python
def _get_reporoot(): """Returns the absolute path to the repo root directory on the current system. """ from os import path import acorn medpath = path.abspath(acorn.__file__) return path.dirname(path.dirname(medpath))
[ "def", "_get_reporoot", "(", ")", ":", "from", "os", "import", "path", "import", "acorn", "medpath", "=", "path", ".", "abspath", "(", "acorn", ".", "__file__", ")", "return", "path", ".", "dirname", "(", "path", ".", "dirname", "(", "medpath", ")", ")" ]
Returns the absolute path to the repo root directory on the current system.
[ "Returns", "the", "absolute", "path", "to", "the", "repo", "root", "directory", "on", "the", "current", "system", "." ]
9a44d1a1ad8bfc2c54a6b56d9efe54433a797820
https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/utility.py#L3-L10
244,425
babab/pycommand
pycommand/pycommand.py
run_and_exit
def run_and_exit(command_class): '''A shortcut for reading from sys.argv and exiting the interpreter''' cmd = command_class(sys.argv[1:]) if cmd.error: print('error: {0}'.format(cmd.error)) sys.exit(1) else: sys.exit(cmd.run())
python
def run_and_exit(command_class): '''A shortcut for reading from sys.argv and exiting the interpreter''' cmd = command_class(sys.argv[1:]) if cmd.error: print('error: {0}'.format(cmd.error)) sys.exit(1) else: sys.exit(cmd.run())
[ "def", "run_and_exit", "(", "command_class", ")", ":", "cmd", "=", "command_class", "(", "sys", ".", "argv", "[", "1", ":", "]", ")", "if", "cmd", ".", "error", ":", "print", "(", "'error: {0}'", ".", "format", "(", "cmd", ".", "error", ")", ")", "sys", ".", "exit", "(", "1", ")", "else", ":", "sys", ".", "exit", "(", "cmd", ".", "run", "(", ")", ")" ]
A shortcut for reading from sys.argv and exiting the interpreter
[ "A", "shortcut", "for", "reading", "from", "sys", ".", "argv", "and", "exiting", "the", "interpreter" ]
07237cd3a624e7b5688edca17ae38bf8b28b74d4
https://github.com/babab/pycommand/blob/07237cd3a624e7b5688edca17ae38bf8b28b74d4/pycommand/pycommand.py#L216-L223
244,426
babab/pycommand
pycommand/pycommand.py
CommandBase.registerParentFlag
def registerParentFlag(self, optionName, value): '''Register a flag of a parent command :Parameters: - `optionName`: String. Name of option - `value`: Mixed. Value of parsed flag` ''' self.parentFlags.update({optionName: value}) return self
python
def registerParentFlag(self, optionName, value): '''Register a flag of a parent command :Parameters: - `optionName`: String. Name of option - `value`: Mixed. Value of parsed flag` ''' self.parentFlags.update({optionName: value}) return self
[ "def", "registerParentFlag", "(", "self", ",", "optionName", ",", "value", ")", ":", "self", ".", "parentFlags", ".", "update", "(", "{", "optionName", ":", "value", "}", ")", "return", "self" ]
Register a flag of a parent command :Parameters: - `optionName`: String. Name of option - `value`: Mixed. Value of parsed flag`
[ "Register", "a", "flag", "of", "a", "parent", "command" ]
07237cd3a624e7b5688edca17ae38bf8b28b74d4
https://github.com/babab/pycommand/blob/07237cd3a624e7b5688edca17ae38bf8b28b74d4/pycommand/pycommand.py#L205-L213
244,427
radjkarl/fancyTools
fancytools/math/radialAverage.py
radialAverage
def radialAverage(arr, center=None): """ radial average a 2darray around a center if no center is given, take middle """ # taken from # http://stackoverflow.com/questions/21242011/most-efficient-way-to-calculate-radial-profile s0, s1 = arr.shape[:2] if center is None: center = s0/2, s1/2 y, x = np.indices((s0, s1)) r = np.sqrt((x - center[0])**2 + (y - center[1])**2) r = r.astype(np.int) tbin = np.bincount(r.ravel(), arr.ravel()) nr = np.bincount(r.ravel()) radialprofile = tbin/ nr return radialprofile
python
def radialAverage(arr, center=None): """ radial average a 2darray around a center if no center is given, take middle """ # taken from # http://stackoverflow.com/questions/21242011/most-efficient-way-to-calculate-radial-profile s0, s1 = arr.shape[:2] if center is None: center = s0/2, s1/2 y, x = np.indices((s0, s1)) r = np.sqrt((x - center[0])**2 + (y - center[1])**2) r = r.astype(np.int) tbin = np.bincount(r.ravel(), arr.ravel()) nr = np.bincount(r.ravel()) radialprofile = tbin/ nr return radialprofile
[ "def", "radialAverage", "(", "arr", ",", "center", "=", "None", ")", ":", "# taken from", "# http://stackoverflow.com/questions/21242011/most-efficient-way-to-calculate-radial-profile", "s0", ",", "s1", "=", "arr", ".", "shape", "[", ":", "2", "]", "if", "center", "is", "None", ":", "center", "=", "s0", "/", "2", ",", "s1", "/", "2", "y", ",", "x", "=", "np", ".", "indices", "(", "(", "s0", ",", "s1", ")", ")", "r", "=", "np", ".", "sqrt", "(", "(", "x", "-", "center", "[", "0", "]", ")", "**", "2", "+", "(", "y", "-", "center", "[", "1", "]", ")", "**", "2", ")", "r", "=", "r", ".", "astype", "(", "np", ".", "int", ")", "tbin", "=", "np", ".", "bincount", "(", "r", ".", "ravel", "(", ")", ",", "arr", ".", "ravel", "(", ")", ")", "nr", "=", "np", ".", "bincount", "(", "r", ".", "ravel", "(", ")", ")", "radialprofile", "=", "tbin", "/", "nr", "return", "radialprofile" ]
radial average a 2darray around a center if no center is given, take middle
[ "radial", "average", "a", "2darray", "around", "a", "center", "if", "no", "center", "is", "given", "take", "middle" ]
4c4d961003dc4ed6e46429a0c24f7e2bb52caa8b
https://github.com/radjkarl/fancyTools/blob/4c4d961003dc4ed6e46429a0c24f7e2bb52caa8b/fancytools/math/radialAverage.py#L6-L22
244,428
tomi77/python-t77-date
t77_date/tz.py
_convert
def _convert(value, tzto, defaulttz): """Convert datetime.datetime object between timezones""" if not isinstance(value, datetime): raise ValueError('value must be a datetime.datetime object') if value.tzinfo is None: value = value.replace(tzinfo=defaulttz) return value.astimezone(tzto)
python
def _convert(value, tzto, defaulttz): """Convert datetime.datetime object between timezones""" if not isinstance(value, datetime): raise ValueError('value must be a datetime.datetime object') if value.tzinfo is None: value = value.replace(tzinfo=defaulttz) return value.astimezone(tzto)
[ "def", "_convert", "(", "value", ",", "tzto", ",", "defaulttz", ")", ":", "if", "not", "isinstance", "(", "value", ",", "datetime", ")", ":", "raise", "ValueError", "(", "'value must be a datetime.datetime object'", ")", "if", "value", ".", "tzinfo", "is", "None", ":", "value", "=", "value", ".", "replace", "(", "tzinfo", "=", "defaulttz", ")", "return", "value", ".", "astimezone", "(", "tzto", ")" ]
Convert datetime.datetime object between timezones
[ "Convert", "datetime", ".", "datetime", "object", "between", "timezones" ]
b4b12ce6a02884fb62460f6b9068e7fa28979fce
https://github.com/tomi77/python-t77-date/blob/b4b12ce6a02884fb62460f6b9068e7fa28979fce/t77_date/tz.py#L9-L17
244,429
tomi77/python-t77-date
t77_date/tz.py
to_local
def to_local(value, defaulttz=None): """Convert datetime.datetime time to local time zone If value doesn't have tzinfo, then defaulttz is set. Default value of defaulttz is UTC. """ if defaulttz is None: defaulttz = tzutc() return _convert(value, tzlocal(), defaulttz)
python
def to_local(value, defaulttz=None): """Convert datetime.datetime time to local time zone If value doesn't have tzinfo, then defaulttz is set. Default value of defaulttz is UTC. """ if defaulttz is None: defaulttz = tzutc() return _convert(value, tzlocal(), defaulttz)
[ "def", "to_local", "(", "value", ",", "defaulttz", "=", "None", ")", ":", "if", "defaulttz", "is", "None", ":", "defaulttz", "=", "tzutc", "(", ")", "return", "_convert", "(", "value", ",", "tzlocal", "(", ")", ",", "defaulttz", ")" ]
Convert datetime.datetime time to local time zone If value doesn't have tzinfo, then defaulttz is set. Default value of defaulttz is UTC.
[ "Convert", "datetime", ".", "datetime", "time", "to", "local", "time", "zone" ]
b4b12ce6a02884fb62460f6b9068e7fa28979fce
https://github.com/tomi77/python-t77-date/blob/b4b12ce6a02884fb62460f6b9068e7fa28979fce/t77_date/tz.py#L20-L28
244,430
tomi77/python-t77-date
t77_date/tz.py
to_utc
def to_utc(value, defaulttz=None): """Convert datetime.datetime time to UTC If value doesn't have tzinfo, then defaulttz is set. Default value of defaulttz is local time zone. """ if defaulttz is None: defaulttz = tzlocal() return _convert(value, tzutc(), defaulttz)
python
def to_utc(value, defaulttz=None): """Convert datetime.datetime time to UTC If value doesn't have tzinfo, then defaulttz is set. Default value of defaulttz is local time zone. """ if defaulttz is None: defaulttz = tzlocal() return _convert(value, tzutc(), defaulttz)
[ "def", "to_utc", "(", "value", ",", "defaulttz", "=", "None", ")", ":", "if", "defaulttz", "is", "None", ":", "defaulttz", "=", "tzlocal", "(", ")", "return", "_convert", "(", "value", ",", "tzutc", "(", ")", ",", "defaulttz", ")" ]
Convert datetime.datetime time to UTC If value doesn't have tzinfo, then defaulttz is set. Default value of defaulttz is local time zone.
[ "Convert", "datetime", ".", "datetime", "time", "to", "UTC" ]
b4b12ce6a02884fb62460f6b9068e7fa28979fce
https://github.com/tomi77/python-t77-date/blob/b4b12ce6a02884fb62460f6b9068e7fa28979fce/t77_date/tz.py#L31-L39
244,431
jasonfharris/sysexecute
sysexecute/common.py
prettyPrintDictionary
def prettyPrintDictionary(d): '''Pretty print a dictionary as simple keys and values''' maxKeyLength = 0 maxValueLength = 0 for key, value in d.iteritems(): maxKeyLength = max(maxKeyLength, len(key)) maxValueLength = max(maxValueLength, len(key)) for key in sorted(d.keys()): print ("%"+str(maxKeyLength)+"s : %-" + str(maxValueLength)+ "s") % (key,d[key])
python
def prettyPrintDictionary(d): '''Pretty print a dictionary as simple keys and values''' maxKeyLength = 0 maxValueLength = 0 for key, value in d.iteritems(): maxKeyLength = max(maxKeyLength, len(key)) maxValueLength = max(maxValueLength, len(key)) for key in sorted(d.keys()): print ("%"+str(maxKeyLength)+"s : %-" + str(maxValueLength)+ "s") % (key,d[key])
[ "def", "prettyPrintDictionary", "(", "d", ")", ":", "maxKeyLength", "=", "0", "maxValueLength", "=", "0", "for", "key", ",", "value", "in", "d", ".", "iteritems", "(", ")", ":", "maxKeyLength", "=", "max", "(", "maxKeyLength", ",", "len", "(", "key", ")", ")", "maxValueLength", "=", "max", "(", "maxValueLength", ",", "len", "(", "key", ")", ")", "for", "key", "in", "sorted", "(", "d", ".", "keys", "(", ")", ")", ":", "print", "(", "\"%\"", "+", "str", "(", "maxKeyLength", ")", "+", "\"s : %-\"", "+", "str", "(", "maxValueLength", ")", "+", "\"s\"", ")", "%", "(", "key", ",", "d", "[", "key", "]", ")" ]
Pretty print a dictionary as simple keys and values
[ "Pretty", "print", "a", "dictionary", "as", "simple", "keys", "and", "values" ]
5fb0639364fa91452da93f99220bf622351d0b7a
https://github.com/jasonfharris/sysexecute/blob/5fb0639364fa91452da93f99220bf622351d0b7a/sysexecute/common.py#L49-L57
244,432
noirbizarre/minibench
minibench/benchmark.py
Benchmark.label
def label(self): '''A human readable label''' if self.__doc__ and self.__doc__.strip(): return self.__doc__.strip().splitlines()[0] return humanize(self.__class__.__name__)
python
def label(self): '''A human readable label''' if self.__doc__ and self.__doc__.strip(): return self.__doc__.strip().splitlines()[0] return humanize(self.__class__.__name__)
[ "def", "label", "(", "self", ")", ":", "if", "self", ".", "__doc__", "and", "self", ".", "__doc__", ".", "strip", "(", ")", ":", "return", "self", ".", "__doc__", ".", "strip", "(", ")", ".", "splitlines", "(", ")", "[", "0", "]", "return", "humanize", "(", "self", ".", "__class__", ".", "__name__", ")" ]
A human readable label
[ "A", "human", "readable", "label" ]
a1ac66dc075181c62bb3c0d3a26beb5c46d5f4ab
https://github.com/noirbizarre/minibench/blob/a1ac66dc075181c62bb3c0d3a26beb5c46d5f4ab/minibench/benchmark.py#L55-L59
244,433
noirbizarre/minibench
minibench/benchmark.py
Benchmark.label_for
def label_for(self, name): '''Get a human readable label for a method given its name''' method = getattr(self, name) if method.__doc__ and method.__doc__.strip(): return method.__doc__.strip().splitlines()[0] return humanize(name.replace(self._prefix, ''))
python
def label_for(self, name): '''Get a human readable label for a method given its name''' method = getattr(self, name) if method.__doc__ and method.__doc__.strip(): return method.__doc__.strip().splitlines()[0] return humanize(name.replace(self._prefix, ''))
[ "def", "label_for", "(", "self", ",", "name", ")", ":", "method", "=", "getattr", "(", "self", ",", "name", ")", "if", "method", ".", "__doc__", "and", "method", ".", "__doc__", ".", "strip", "(", ")", ":", "return", "method", ".", "__doc__", ".", "strip", "(", ")", ".", "splitlines", "(", ")", "[", "0", "]", "return", "humanize", "(", "name", ".", "replace", "(", "self", ".", "_prefix", ",", "''", ")", ")" ]
Get a human readable label for a method given its name
[ "Get", "a", "human", "readable", "label", "for", "a", "method", "given", "its", "name" ]
a1ac66dc075181c62bb3c0d3a26beb5c46d5f4ab
https://github.com/noirbizarre/minibench/blob/a1ac66dc075181c62bb3c0d3a26beb5c46d5f4ab/minibench/benchmark.py#L61-L66
244,434
noirbizarre/minibench
minibench/benchmark.py
Benchmark.run
def run(self): ''' Collect all tests to run and run them. Each method will be run :attr:`Benchmark.times`. ''' tests = self._collect() if not tests: return self.times self.before_class() for test in tests: func = getattr(self, test) results = self.results[test] = Result() self._before(self, test) self.before() for i in range(self.times): self._before_each(self, test, i) result = self._run_one(func) results.total += result.duration if result.success: results.has_success = True else: results.has_errors = True self._after_each(self, test, i) if self.debug and not result.success: results.error = result.result break self.after() self._after(self, test) self.after_class()
python
def run(self): ''' Collect all tests to run and run them. Each method will be run :attr:`Benchmark.times`. ''' tests = self._collect() if not tests: return self.times self.before_class() for test in tests: func = getattr(self, test) results = self.results[test] = Result() self._before(self, test) self.before() for i in range(self.times): self._before_each(self, test, i) result = self._run_one(func) results.total += result.duration if result.success: results.has_success = True else: results.has_errors = True self._after_each(self, test, i) if self.debug and not result.success: results.error = result.result break self.after() self._after(self, test) self.after_class()
[ "def", "run", "(", "self", ")", ":", "tests", "=", "self", ".", "_collect", "(", ")", "if", "not", "tests", ":", "return", "self", ".", "times", "self", ".", "before_class", "(", ")", "for", "test", "in", "tests", ":", "func", "=", "getattr", "(", "self", ",", "test", ")", "results", "=", "self", ".", "results", "[", "test", "]", "=", "Result", "(", ")", "self", ".", "_before", "(", "self", ",", "test", ")", "self", ".", "before", "(", ")", "for", "i", "in", "range", "(", "self", ".", "times", ")", ":", "self", ".", "_before_each", "(", "self", ",", "test", ",", "i", ")", "result", "=", "self", ".", "_run_one", "(", "func", ")", "results", ".", "total", "+=", "result", ".", "duration", "if", "result", ".", "success", ":", "results", ".", "has_success", "=", "True", "else", ":", "results", ".", "has_errors", "=", "True", "self", ".", "_after_each", "(", "self", ",", "test", ",", "i", ")", "if", "self", ".", "debug", "and", "not", "result", ".", "success", ":", "results", ".", "error", "=", "result", ".", "result", "break", "self", ".", "after", "(", ")", "self", ".", "_after", "(", "self", ",", "test", ")", "self", ".", "after_class", "(", ")" ]
Collect all tests to run and run them. Each method will be run :attr:`Benchmark.times`.
[ "Collect", "all", "tests", "to", "run", "and", "run", "them", "." ]
a1ac66dc075181c62bb3c0d3a26beb5c46d5f4ab
https://github.com/noirbizarre/minibench/blob/a1ac66dc075181c62bb3c0d3a26beb5c46d5f4ab/minibench/benchmark.py#L111-L145
244,435
GemHQ/round-py
round/__init__.py
Context.authorizer
def authorizer(self, schemes, resource, action, request_args): """Construct the Authorization header for a request. Args: schemes (list of str): Authentication schemes supported for the requested action. resource (str): Object upon which an action is being performed. action (str): Action being performed. request_args (list of str): Arguments passed to the action call. Returns: (str, str) A tuple of the auth scheme satisfied, and the credential for the Authorization header or empty strings if none could be satisfied. """ if not schemes: return u'', u'' for scheme in schemes: if scheme in self.schemes and self.has_auth_params(scheme): cred = Context.format_auth_params(self.schemes[scheme][u'params']) if hasattr(self, 'mfa_token'): cred = '{}, mfa_token="{}"'.format(cred, self.mfa_token) return scheme, cred raise AuthenticationError(self, schemes)
python
def authorizer(self, schemes, resource, action, request_args): """Construct the Authorization header for a request. Args: schemes (list of str): Authentication schemes supported for the requested action. resource (str): Object upon which an action is being performed. action (str): Action being performed. request_args (list of str): Arguments passed to the action call. Returns: (str, str) A tuple of the auth scheme satisfied, and the credential for the Authorization header or empty strings if none could be satisfied. """ if not schemes: return u'', u'' for scheme in schemes: if scheme in self.schemes and self.has_auth_params(scheme): cred = Context.format_auth_params(self.schemes[scheme][u'params']) if hasattr(self, 'mfa_token'): cred = '{}, mfa_token="{}"'.format(cred, self.mfa_token) return scheme, cred raise AuthenticationError(self, schemes)
[ "def", "authorizer", "(", "self", ",", "schemes", ",", "resource", ",", "action", ",", "request_args", ")", ":", "if", "not", "schemes", ":", "return", "u''", ",", "u''", "for", "scheme", "in", "schemes", ":", "if", "scheme", "in", "self", ".", "schemes", "and", "self", ".", "has_auth_params", "(", "scheme", ")", ":", "cred", "=", "Context", ".", "format_auth_params", "(", "self", ".", "schemes", "[", "scheme", "]", "[", "u'params'", "]", ")", "if", "hasattr", "(", "self", ",", "'mfa_token'", ")", ":", "cred", "=", "'{}, mfa_token=\"{}\"'", ".", "format", "(", "cred", ",", "self", ".", "mfa_token", ")", "return", "scheme", ",", "cred", "raise", "AuthenticationError", "(", "self", ",", "schemes", ")" ]
Construct the Authorization header for a request. Args: schemes (list of str): Authentication schemes supported for the requested action. resource (str): Object upon which an action is being performed. action (str): Action being performed. request_args (list of str): Arguments passed to the action call. Returns: (str, str) A tuple of the auth scheme satisfied, and the credential for the Authorization header or empty strings if none could be satisfied.
[ "Construct", "the", "Authorization", "header", "for", "a", "request", "." ]
d0838f849cd260b1eb5df67ed3c6f2fe56c91c21
https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/__init__.py#L65-L89
244,436
GemHQ/round-py
round/__init__.py
Context.authorize
def authorize(self, scheme, **params): """Store credentials required to satisfy a given auth scheme. Args: scheme (str): The name of the Authentication scheme. **params: parameters for the specified scheme. Returns: True if parameters are set successfully (note that this doesn't mean the credentials are valid) False if the scheme specified is not supported """ if scheme not in self.schemes: return False for field, value in iteritems(params): setattr(self, field, value) if field in self.schemes[scheme][u'params'].keys() and value: self.schemes[scheme][u'params'][field] = value return True
python
def authorize(self, scheme, **params): """Store credentials required to satisfy a given auth scheme. Args: scheme (str): The name of the Authentication scheme. **params: parameters for the specified scheme. Returns: True if parameters are set successfully (note that this doesn't mean the credentials are valid) False if the scheme specified is not supported """ if scheme not in self.schemes: return False for field, value in iteritems(params): setattr(self, field, value) if field in self.schemes[scheme][u'params'].keys() and value: self.schemes[scheme][u'params'][field] = value return True
[ "def", "authorize", "(", "self", ",", "scheme", ",", "*", "*", "params", ")", ":", "if", "scheme", "not", "in", "self", ".", "schemes", ":", "return", "False", "for", "field", ",", "value", "in", "iteritems", "(", "params", ")", ":", "setattr", "(", "self", ",", "field", ",", "value", ")", "if", "field", "in", "self", ".", "schemes", "[", "scheme", "]", "[", "u'params'", "]", ".", "keys", "(", ")", "and", "value", ":", "self", ".", "schemes", "[", "scheme", "]", "[", "u'params'", "]", "[", "field", "]", "=", "value", "return", "True" ]
Store credentials required to satisfy a given auth scheme. Args: scheme (str): The name of the Authentication scheme. **params: parameters for the specified scheme. Returns: True if parameters are set successfully (note that this doesn't mean the credentials are valid) False if the scheme specified is not supported
[ "Store", "credentials", "required", "to", "satisfy", "a", "given", "auth", "scheme", "." ]
d0838f849cd260b1eb5df67ed3c6f2fe56c91c21
https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/__init__.py#L91-L111
244,437
GemHQ/round-py
round/__init__.py
Context.has_auth_params
def has_auth_params(self, scheme): """Check whether all information required for a given auth scheme have been supplied. Args: scheme (str): Name of the authentication scheme to check. One of Gem-Identify, Gem-Device, Gem-Application Returns: True if all required parameters for the specified scheme are present or False otherwise. """ for k, v in iteritems(self.schemes[scheme][u'params']): if not v: return False return True
python
def has_auth_params(self, scheme): """Check whether all information required for a given auth scheme have been supplied. Args: scheme (str): Name of the authentication scheme to check. One of Gem-Identify, Gem-Device, Gem-Application Returns: True if all required parameters for the specified scheme are present or False otherwise. """ for k, v in iteritems(self.schemes[scheme][u'params']): if not v: return False return True
[ "def", "has_auth_params", "(", "self", ",", "scheme", ")", ":", "for", "k", ",", "v", "in", "iteritems", "(", "self", ".", "schemes", "[", "scheme", "]", "[", "u'params'", "]", ")", ":", "if", "not", "v", ":", "return", "False", "return", "True" ]
Check whether all information required for a given auth scheme have been supplied. Args: scheme (str): Name of the authentication scheme to check. One of Gem-Identify, Gem-Device, Gem-Application Returns: True if all required parameters for the specified scheme are present or False otherwise.
[ "Check", "whether", "all", "information", "required", "for", "a", "given", "auth", "scheme", "have", "been", "supplied", "." ]
d0838f849cd260b1eb5df67ed3c6f2fe56c91c21
https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/__init__.py#L113-L127
244,438
GemHQ/round-py
round/__init__.py
Context.format_auth_params
def format_auth_params(params): """Generate the format expected by HTTP Headers from parameters. Args: params (dict): {key: value} to convert to key=value Returns: A formatted header string. """ parts = [] for (key, value) in params.items(): if value: parts.append('{}="{}"'.format(key, value)) return ", ".join(parts)
python
def format_auth_params(params): """Generate the format expected by HTTP Headers from parameters. Args: params (dict): {key: value} to convert to key=value Returns: A formatted header string. """ parts = [] for (key, value) in params.items(): if value: parts.append('{}="{}"'.format(key, value)) return ", ".join(parts)
[ "def", "format_auth_params", "(", "params", ")", ":", "parts", "=", "[", "]", "for", "(", "key", ",", "value", ")", "in", "params", ".", "items", "(", ")", ":", "if", "value", ":", "parts", ".", "append", "(", "'{}=\"{}\"'", ".", "format", "(", "key", ",", "value", ")", ")", "return", "\", \"", ".", "join", "(", "parts", ")" ]
Generate the format expected by HTTP Headers from parameters. Args: params (dict): {key: value} to convert to key=value Returns: A formatted header string.
[ "Generate", "the", "format", "expected", "by", "HTTP", "Headers", "from", "parameters", "." ]
d0838f849cd260b1eb5df67ed3c6f2fe56c91c21
https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/__init__.py#L130-L143
244,439
lambdalisue/django-roughpages
src/roughpages/backends/__init__.py
get_backend
def get_backend(backend_class=None): """ Get backend instance If no `backend_class` is specified, the backend class is determined from the value of `settings.ROUGHPAGES_BACKEND`. `backend_class` can be a class object or dots separated python import path Returns: backend instance """ cache_name = '_backend_instance' if not hasattr(get_backend, cache_name): backend_class = backend_class or settings.ROUGHPAGES_BACKEND if isinstance(backend_class, basestring): module_path, class_name = backend_class.rsplit(".", 1) module = import_module(module_path) backend_class = getattr(module, class_name) setattr(get_backend, cache_name, backend_class()) return getattr(get_backend, cache_name)
python
def get_backend(backend_class=None): """ Get backend instance If no `backend_class` is specified, the backend class is determined from the value of `settings.ROUGHPAGES_BACKEND`. `backend_class` can be a class object or dots separated python import path Returns: backend instance """ cache_name = '_backend_instance' if not hasattr(get_backend, cache_name): backend_class = backend_class or settings.ROUGHPAGES_BACKEND if isinstance(backend_class, basestring): module_path, class_name = backend_class.rsplit(".", 1) module = import_module(module_path) backend_class = getattr(module, class_name) setattr(get_backend, cache_name, backend_class()) return getattr(get_backend, cache_name)
[ "def", "get_backend", "(", "backend_class", "=", "None", ")", ":", "cache_name", "=", "'_backend_instance'", "if", "not", "hasattr", "(", "get_backend", ",", "cache_name", ")", ":", "backend_class", "=", "backend_class", "or", "settings", ".", "ROUGHPAGES_BACKEND", "if", "isinstance", "(", "backend_class", ",", "basestring", ")", ":", "module_path", ",", "class_name", "=", "backend_class", ".", "rsplit", "(", "\".\"", ",", "1", ")", "module", "=", "import_module", "(", "module_path", ")", "backend_class", "=", "getattr", "(", "module", ",", "class_name", ")", "setattr", "(", "get_backend", ",", "cache_name", ",", "backend_class", "(", ")", ")", "return", "getattr", "(", "get_backend", ",", "cache_name", ")" ]
Get backend instance If no `backend_class` is specified, the backend class is determined from the value of `settings.ROUGHPAGES_BACKEND`. `backend_class` can be a class object or dots separated python import path Returns: backend instance
[ "Get", "backend", "instance" ]
f6a2724ece729c5deced2c2546d172561ef785ec
https://github.com/lambdalisue/django-roughpages/blob/f6a2724ece729c5deced2c2546d172561ef785ec/src/roughpages/backends/__init__.py#L9-L28
244,440
jayferg/faderport
faderport.py
find_faderport_input_name
def find_faderport_input_name(number=0): """ Find the MIDI input name for a connected FaderPort. NOTE! Untested for more than one FaderPort attached. :param number: 0 unless you've got more than one FaderPort attached. In which case 0 is the first, 1 is the second etc :return: Port name or None """ ins = [i for i in mido.get_input_names() if i.lower().startswith('faderport')] if 0 <= number < len(ins): return ins[number] else: return None
python
def find_faderport_input_name(number=0): """ Find the MIDI input name for a connected FaderPort. NOTE! Untested for more than one FaderPort attached. :param number: 0 unless you've got more than one FaderPort attached. In which case 0 is the first, 1 is the second etc :return: Port name or None """ ins = [i for i in mido.get_input_names() if i.lower().startswith('faderport')] if 0 <= number < len(ins): return ins[number] else: return None
[ "def", "find_faderport_input_name", "(", "number", "=", "0", ")", ":", "ins", "=", "[", "i", "for", "i", "in", "mido", ".", "get_input_names", "(", ")", "if", "i", ".", "lower", "(", ")", ".", "startswith", "(", "'faderport'", ")", "]", "if", "0", "<=", "number", "<", "len", "(", "ins", ")", ":", "return", "ins", "[", "number", "]", "else", ":", "return", "None" ]
Find the MIDI input name for a connected FaderPort. NOTE! Untested for more than one FaderPort attached. :param number: 0 unless you've got more than one FaderPort attached. In which case 0 is the first, 1 is the second etc :return: Port name or None
[ "Find", "the", "MIDI", "input", "name", "for", "a", "connected", "FaderPort", "." ]
53152797f3dedd0fa56d66068313f5484e469a68
https://github.com/jayferg/faderport/blob/53152797f3dedd0fa56d66068313f5484e469a68/faderport.py#L354-L367
244,441
jayferg/faderport
faderport.py
find_faderport_output_name
def find_faderport_output_name(number=0): """ Find the MIDI output name for a connected FaderPort. NOTE! Untested for more than one FaderPort attached. :param number: 0 unless you've got more than one FaderPort attached. In which case 0 is the first, 1 is the second etc :return: Port name or None """ outs = [i for i in mido.get_output_names() if i.lower().startswith('faderport')] if 0 <= number < len(outs): return outs[number] else: return None
python
def find_faderport_output_name(number=0): """ Find the MIDI output name for a connected FaderPort. NOTE! Untested for more than one FaderPort attached. :param number: 0 unless you've got more than one FaderPort attached. In which case 0 is the first, 1 is the second etc :return: Port name or None """ outs = [i for i in mido.get_output_names() if i.lower().startswith('faderport')] if 0 <= number < len(outs): return outs[number] else: return None
[ "def", "find_faderport_output_name", "(", "number", "=", "0", ")", ":", "outs", "=", "[", "i", "for", "i", "in", "mido", ".", "get_output_names", "(", ")", "if", "i", ".", "lower", "(", ")", ".", "startswith", "(", "'faderport'", ")", "]", "if", "0", "<=", "number", "<", "len", "(", "outs", ")", ":", "return", "outs", "[", "number", "]", "else", ":", "return", "None" ]
Find the MIDI output name for a connected FaderPort. NOTE! Untested for more than one FaderPort attached. :param number: 0 unless you've got more than one FaderPort attached. In which case 0 is the first, 1 is the second etc :return: Port name or None
[ "Find", "the", "MIDI", "output", "name", "for", "a", "connected", "FaderPort", "." ]
53152797f3dedd0fa56d66068313f5484e469a68
https://github.com/jayferg/faderport/blob/53152797f3dedd0fa56d66068313f5484e469a68/faderport.py#L370-L383
244,442
jayferg/faderport
faderport.py
FaderPort._message_callback
def _message_callback(self, msg): """Callback function to handle incoming MIDI messages.""" if msg.type == 'polytouch': button = button_from_press(msg.note) if button: self.on_button(button, msg.value != 0) elif msg.note == 127: self.on_fader_touch(msg.value != 0) elif msg.type == 'control_change' and msg.control == 0: self._msb = msg.value elif msg.type == 'control_change' and msg.control == 32: self._fader = (self._msb << 7 | msg.value) >> 4 self.on_fader(self._fader) elif msg.type == 'pitchwheel': self.on_rotary(1 if msg.pitch < 0 else -1) else: print('Unhandled:', msg)
python
def _message_callback(self, msg): """Callback function to handle incoming MIDI messages.""" if msg.type == 'polytouch': button = button_from_press(msg.note) if button: self.on_button(button, msg.value != 0) elif msg.note == 127: self.on_fader_touch(msg.value != 0) elif msg.type == 'control_change' and msg.control == 0: self._msb = msg.value elif msg.type == 'control_change' and msg.control == 32: self._fader = (self._msb << 7 | msg.value) >> 4 self.on_fader(self._fader) elif msg.type == 'pitchwheel': self.on_rotary(1 if msg.pitch < 0 else -1) else: print('Unhandled:', msg)
[ "def", "_message_callback", "(", "self", ",", "msg", ")", ":", "if", "msg", ".", "type", "==", "'polytouch'", ":", "button", "=", "button_from_press", "(", "msg", ".", "note", ")", "if", "button", ":", "self", ".", "on_button", "(", "button", ",", "msg", ".", "value", "!=", "0", ")", "elif", "msg", ".", "note", "==", "127", ":", "self", ".", "on_fader_touch", "(", "msg", ".", "value", "!=", "0", ")", "elif", "msg", ".", "type", "==", "'control_change'", "and", "msg", ".", "control", "==", "0", ":", "self", ".", "_msb", "=", "msg", ".", "value", "elif", "msg", ".", "type", "==", "'control_change'", "and", "msg", ".", "control", "==", "32", ":", "self", ".", "_fader", "=", "(", "self", ".", "_msb", "<<", "7", "|", "msg", ".", "value", ")", ">>", "4", "self", ".", "on_fader", "(", "self", ".", "_fader", ")", "elif", "msg", ".", "type", "==", "'pitchwheel'", ":", "self", ".", "on_rotary", "(", "1", "if", "msg", ".", "pitch", "<", "0", "else", "-", "1", ")", "else", ":", "print", "(", "'Unhandled:'", ",", "msg", ")" ]
Callback function to handle incoming MIDI messages.
[ "Callback", "function", "to", "handle", "incoming", "MIDI", "messages", "." ]
53152797f3dedd0fa56d66068313f5484e469a68
https://github.com/jayferg/faderport/blob/53152797f3dedd0fa56d66068313f5484e469a68/faderport.py#L177-L193
244,443
jayferg/faderport
faderport.py
FaderPort.fader
def fader(self, value: int): """Move the fader to a new position in the range 0 to 1023.""" self._fader = int(value) if 0 < value < 1024 else 0 self.outport.send(mido.Message('control_change', control=0, value=self._fader >> 7)) self.outport.send(mido.Message('control_change', control=32, value=self._fader & 0x7F))
python
def fader(self, value: int): """Move the fader to a new position in the range 0 to 1023.""" self._fader = int(value) if 0 < value < 1024 else 0 self.outport.send(mido.Message('control_change', control=0, value=self._fader >> 7)) self.outport.send(mido.Message('control_change', control=32, value=self._fader & 0x7F))
[ "def", "fader", "(", "self", ",", "value", ":", "int", ")", ":", "self", ".", "_fader", "=", "int", "(", "value", ")", "if", "0", "<", "value", "<", "1024", "else", "0", "self", ".", "outport", ".", "send", "(", "mido", ".", "Message", "(", "'control_change'", ",", "control", "=", "0", ",", "value", "=", "self", ".", "_fader", ">>", "7", ")", ")", "self", ".", "outport", ".", "send", "(", "mido", ".", "Message", "(", "'control_change'", ",", "control", "=", "32", ",", "value", "=", "self", ".", "_fader", "&", "0x7F", ")", ")" ]
Move the fader to a new position in the range 0 to 1023.
[ "Move", "the", "fader", "to", "a", "new", "position", "in", "the", "range", "0", "to", "1023", "." ]
53152797f3dedd0fa56d66068313f5484e469a68
https://github.com/jayferg/faderport/blob/53152797f3dedd0fa56d66068313f5484e469a68/faderport.py#L234-L240
244,444
jayferg/faderport
faderport.py
FaderPort.light_on
def light_on(self, button: Button): """Turn the light on for the given Button. NOTE! If yuo turn the "Off" button light on, the fader won't report value updates when it's moved.""" self.outport.send(mido.Message('polytouch', note=button.light, value=1))
python
def light_on(self, button: Button): """Turn the light on for the given Button. NOTE! If yuo turn the "Off" button light on, the fader won't report value updates when it's moved.""" self.outport.send(mido.Message('polytouch', note=button.light, value=1))
[ "def", "light_on", "(", "self", ",", "button", ":", "Button", ")", ":", "self", ".", "outport", ".", "send", "(", "mido", ".", "Message", "(", "'polytouch'", ",", "note", "=", "button", ".", "light", ",", "value", "=", "1", ")", ")" ]
Turn the light on for the given Button. NOTE! If yuo turn the "Off" button light on, the fader won't report value updates when it's moved.
[ "Turn", "the", "light", "on", "for", "the", "given", "Button", "." ]
53152797f3dedd0fa56d66068313f5484e469a68
https://github.com/jayferg/faderport/blob/53152797f3dedd0fa56d66068313f5484e469a68/faderport.py#L242-L247
244,445
kallimachos/chios
chios/remotecode/__init__.py
RemoteCodeBlock.run
def run(self): """Fetch remote code.""" link = self.content[0] try: r = requests.get(link) r.raise_for_status() self.content = [r.text] return super(RemoteCodeBlock, self).run() except Exception: document = self.state.document err = 'Unable to resolve ' + link return [document.reporter.warning(str(err), line=self.lineno)]
python
def run(self): """Fetch remote code.""" link = self.content[0] try: r = requests.get(link) r.raise_for_status() self.content = [r.text] return super(RemoteCodeBlock, self).run() except Exception: document = self.state.document err = 'Unable to resolve ' + link return [document.reporter.warning(str(err), line=self.lineno)]
[ "def", "run", "(", "self", ")", ":", "link", "=", "self", ".", "content", "[", "0", "]", "try", ":", "r", "=", "requests", ".", "get", "(", "link", ")", "r", ".", "raise_for_status", "(", ")", "self", ".", "content", "=", "[", "r", ".", "text", "]", "return", "super", "(", "RemoteCodeBlock", ",", "self", ")", ".", "run", "(", ")", "except", "Exception", ":", "document", "=", "self", ".", "state", ".", "document", "err", "=", "'Unable to resolve '", "+", "link", "return", "[", "document", ".", "reporter", ".", "warning", "(", "str", "(", "err", ")", ",", "line", "=", "self", ".", "lineno", ")", "]" ]
Fetch remote code.
[ "Fetch", "remote", "code", "." ]
e14044e4019d57089c625d4ad2f73ccb66b8b7b8
https://github.com/kallimachos/chios/blob/e14044e4019d57089c625d4ad2f73ccb66b8b7b8/chios/remotecode/__init__.py#L33-L44
244,446
rameshg87/pyremotevbox
pyremotevbox/ZSI/address.py
Address.setUp
def setUp(self): '''Look for WS-Address ''' toplist = filter(lambda wsa: wsa.ADDRESS==self.wsAddressURI, WSA_LIST) epr = 'EndpointReferenceType' for WSA in toplist+WSA_LIST: if (self.wsAddressURI is not None and self.wsAddressURI != WSA.ADDRESS) or \ _has_type_definition(WSA.ADDRESS, epr) is True: break else: raise EvaluateException,\ 'enabling wsAddressing requires the inclusion of that namespace' self.wsAddressURI = WSA.ADDRESS self.anonymousURI = WSA.ANONYMOUS self._replyTo = WSA.ANONYMOUS
python
def setUp(self): '''Look for WS-Address ''' toplist = filter(lambda wsa: wsa.ADDRESS==self.wsAddressURI, WSA_LIST) epr = 'EndpointReferenceType' for WSA in toplist+WSA_LIST: if (self.wsAddressURI is not None and self.wsAddressURI != WSA.ADDRESS) or \ _has_type_definition(WSA.ADDRESS, epr) is True: break else: raise EvaluateException,\ 'enabling wsAddressing requires the inclusion of that namespace' self.wsAddressURI = WSA.ADDRESS self.anonymousURI = WSA.ANONYMOUS self._replyTo = WSA.ANONYMOUS
[ "def", "setUp", "(", "self", ")", ":", "toplist", "=", "filter", "(", "lambda", "wsa", ":", "wsa", ".", "ADDRESS", "==", "self", ".", "wsAddressURI", ",", "WSA_LIST", ")", "epr", "=", "'EndpointReferenceType'", "for", "WSA", "in", "toplist", "+", "WSA_LIST", ":", "if", "(", "self", ".", "wsAddressURI", "is", "not", "None", "and", "self", ".", "wsAddressURI", "!=", "WSA", ".", "ADDRESS", ")", "or", "_has_type_definition", "(", "WSA", ".", "ADDRESS", ",", "epr", ")", "is", "True", ":", "break", "else", ":", "raise", "EvaluateException", ",", "'enabling wsAddressing requires the inclusion of that namespace'", "self", ".", "wsAddressURI", "=", "WSA", ".", "ADDRESS", "self", ".", "anonymousURI", "=", "WSA", ".", "ANONYMOUS", "self", ".", "_replyTo", "=", "WSA", ".", "ANONYMOUS" ]
Look for WS-Address
[ "Look", "for", "WS", "-", "Address" ]
123dffff27da57c8faa3ac1dd4c68b1cf4558b1a
https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/address.py#L32-L47
244,447
rameshg87/pyremotevbox
pyremotevbox/ZSI/address.py
Address.setRequest
def setRequest(self, endPointReference, action): '''Call For Request ''' self._action = action self.header_pyobjs = None pyobjs = [] namespaceURI = self.wsAddressURI addressTo = self._addressTo messageID = self._messageID = "uuid:%s" %time.time() # Set Message Information Headers # MessageID typecode = GED(namespaceURI, "MessageID") pyobjs.append(typecode.pyclass(messageID)) # Action typecode = GED(namespaceURI, "Action") pyobjs.append(typecode.pyclass(action)) # To typecode = GED(namespaceURI, "To") pyobjs.append(typecode.pyclass(addressTo)) # From typecode = GED(namespaceURI, "From") mihFrom = typecode.pyclass() mihFrom._Address = self.anonymousURI pyobjs.append(mihFrom) if endPointReference: if hasattr(endPointReference, 'typecode') is False: raise EvaluateException, 'endPointReference must have a typecode attribute' if isinstance(endPointReference.typecode, \ GTD(namespaceURI ,'EndpointReferenceType')) is False: raise EvaluateException, 'endPointReference must be of type %s' \ %GTD(namespaceURI ,'EndpointReferenceType') ReferenceProperties = getattr(endPointReference, '_ReferenceProperties', None) if ReferenceProperties is not None: for v in getattr(ReferenceProperties, '_any', ()): if not hasattr(v,'typecode'): raise EvaluateException, '<any> element, instance missing typecode attribute' pyobjs.append(v) self.header_pyobjs = tuple(pyobjs)
python
def setRequest(self, endPointReference, action): '''Call For Request ''' self._action = action self.header_pyobjs = None pyobjs = [] namespaceURI = self.wsAddressURI addressTo = self._addressTo messageID = self._messageID = "uuid:%s" %time.time() # Set Message Information Headers # MessageID typecode = GED(namespaceURI, "MessageID") pyobjs.append(typecode.pyclass(messageID)) # Action typecode = GED(namespaceURI, "Action") pyobjs.append(typecode.pyclass(action)) # To typecode = GED(namespaceURI, "To") pyobjs.append(typecode.pyclass(addressTo)) # From typecode = GED(namespaceURI, "From") mihFrom = typecode.pyclass() mihFrom._Address = self.anonymousURI pyobjs.append(mihFrom) if endPointReference: if hasattr(endPointReference, 'typecode') is False: raise EvaluateException, 'endPointReference must have a typecode attribute' if isinstance(endPointReference.typecode, \ GTD(namespaceURI ,'EndpointReferenceType')) is False: raise EvaluateException, 'endPointReference must be of type %s' \ %GTD(namespaceURI ,'EndpointReferenceType') ReferenceProperties = getattr(endPointReference, '_ReferenceProperties', None) if ReferenceProperties is not None: for v in getattr(ReferenceProperties, '_any', ()): if not hasattr(v,'typecode'): raise EvaluateException, '<any> element, instance missing typecode attribute' pyobjs.append(v) self.header_pyobjs = tuple(pyobjs)
[ "def", "setRequest", "(", "self", ",", "endPointReference", ",", "action", ")", ":", "self", ".", "_action", "=", "action", "self", ".", "header_pyobjs", "=", "None", "pyobjs", "=", "[", "]", "namespaceURI", "=", "self", ".", "wsAddressURI", "addressTo", "=", "self", ".", "_addressTo", "messageID", "=", "self", ".", "_messageID", "=", "\"uuid:%s\"", "%", "time", ".", "time", "(", ")", "# Set Message Information Headers", "# MessageID", "typecode", "=", "GED", "(", "namespaceURI", ",", "\"MessageID\"", ")", "pyobjs", ".", "append", "(", "typecode", ".", "pyclass", "(", "messageID", ")", ")", "# Action", "typecode", "=", "GED", "(", "namespaceURI", ",", "\"Action\"", ")", "pyobjs", ".", "append", "(", "typecode", ".", "pyclass", "(", "action", ")", ")", "# To", "typecode", "=", "GED", "(", "namespaceURI", ",", "\"To\"", ")", "pyobjs", ".", "append", "(", "typecode", ".", "pyclass", "(", "addressTo", ")", ")", "# From", "typecode", "=", "GED", "(", "namespaceURI", ",", "\"From\"", ")", "mihFrom", "=", "typecode", ".", "pyclass", "(", ")", "mihFrom", ".", "_Address", "=", "self", ".", "anonymousURI", "pyobjs", ".", "append", "(", "mihFrom", ")", "if", "endPointReference", ":", "if", "hasattr", "(", "endPointReference", ",", "'typecode'", ")", "is", "False", ":", "raise", "EvaluateException", ",", "'endPointReference must have a typecode attribute'", "if", "isinstance", "(", "endPointReference", ".", "typecode", ",", "GTD", "(", "namespaceURI", ",", "'EndpointReferenceType'", ")", ")", "is", "False", ":", "raise", "EvaluateException", ",", "'endPointReference must be of type %s'", "%", "GTD", "(", "namespaceURI", ",", "'EndpointReferenceType'", ")", "ReferenceProperties", "=", "getattr", "(", "endPointReference", ",", "'_ReferenceProperties'", ",", "None", ")", "if", "ReferenceProperties", "is", "not", "None", ":", "for", "v", "in", "getattr", "(", "ReferenceProperties", ",", "'_any'", ",", "(", ")", ")", ":", "if", "not", "hasattr", "(", "v", ",", "'typecode'", ")", ":", "raise", "EvaluateException", ",", "'<any> element, instance missing typecode attribute'", "pyobjs", ".", "append", "(", "v", ")", "self", ".", "header_pyobjs", "=", "tuple", "(", "pyobjs", ")" ]
Call For Request
[ "Call", "For", "Request" ]
123dffff27da57c8faa3ac1dd4c68b1cf4558b1a
https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/address.py#L148-L194
244,448
MakerReduxCorp/PLOD
PLOD/__init__.py
PLOD.upsert
def upsert(self, key, value, entry): '''Update or Insert an entry into the list of dictionaries. If a dictionary in the list is found where key matches the value, then the FIRST matching list entry is replaced with entry else the entry is appended to the end of the list. The new entry is not examined in any way. It is, in fact, possible to upsert an entry that does not match the supplied key/value. Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "wigs": 68 }, ... {"name": "Larry", "age": 18, "wigs": [3, 2, 9]}, ... {"name": "Joe", "age": 20, "income": 15000, "wigs": [1, 2, 3]}, ... {"name": "Bill", "age": 19, "income": 29000 }, ... ] >>> entryA = {"name": "Willie", "age": 77} >>> myPLOD = PLOD(test) >>> print myPLOD.upsert("name", "Willie", entryA).returnString() [ {age: 18, income: 93000, name: 'Jim' , wigs: 68}, {age: 18, income: None , name: 'Larry' , wigs: [3, 2, 9]}, {age: 20, income: 15000, name: 'Joe' , wigs: [1, 2, 3]}, {age: 19, income: 29000, name: 'Bill' , wigs: None }, {age: 77, income: None , name: 'Willie', wigs: None } ] >>> entryB = {"name": "Joe", "age": 20, "income": 30, "wigs": [3, 2, 9]} >>> print myPLOD.upsert("name", "Joe", entryB).returnString() [ {age: 18, income: 93000, name: 'Jim' , wigs: 68}, {age: 18, income: None , name: 'Larry' , wigs: [3, 2, 9]}, {age: 20, income: 30, name: 'Joe' , wigs: [3, 2, 9]}, {age: 19, income: 29000, name: 'Bill' , wigs: None }, {age: 77, income: None , name: 'Willie', wigs: None } ] :param key: The dictionary key to examine. :param value: The value to search for as referenced by the key. :param entry: The replacement (or new) entry for the list. :returns: class ''' index=internal.get_index(self.table, key, self.EQUAL, value) if index is None: self.index_track.append(len(self.table)) self.table.append(entry) else: self.table[index]=entry return self
python
def upsert(self, key, value, entry): '''Update or Insert an entry into the list of dictionaries. If a dictionary in the list is found where key matches the value, then the FIRST matching list entry is replaced with entry else the entry is appended to the end of the list. The new entry is not examined in any way. It is, in fact, possible to upsert an entry that does not match the supplied key/value. Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "wigs": 68 }, ... {"name": "Larry", "age": 18, "wigs": [3, 2, 9]}, ... {"name": "Joe", "age": 20, "income": 15000, "wigs": [1, 2, 3]}, ... {"name": "Bill", "age": 19, "income": 29000 }, ... ] >>> entryA = {"name": "Willie", "age": 77} >>> myPLOD = PLOD(test) >>> print myPLOD.upsert("name", "Willie", entryA).returnString() [ {age: 18, income: 93000, name: 'Jim' , wigs: 68}, {age: 18, income: None , name: 'Larry' , wigs: [3, 2, 9]}, {age: 20, income: 15000, name: 'Joe' , wigs: [1, 2, 3]}, {age: 19, income: 29000, name: 'Bill' , wigs: None }, {age: 77, income: None , name: 'Willie', wigs: None } ] >>> entryB = {"name": "Joe", "age": 20, "income": 30, "wigs": [3, 2, 9]} >>> print myPLOD.upsert("name", "Joe", entryB).returnString() [ {age: 18, income: 93000, name: 'Jim' , wigs: 68}, {age: 18, income: None , name: 'Larry' , wigs: [3, 2, 9]}, {age: 20, income: 30, name: 'Joe' , wigs: [3, 2, 9]}, {age: 19, income: 29000, name: 'Bill' , wigs: None }, {age: 77, income: None , name: 'Willie', wigs: None } ] :param key: The dictionary key to examine. :param value: The value to search for as referenced by the key. :param entry: The replacement (or new) entry for the list. :returns: class ''' index=internal.get_index(self.table, key, self.EQUAL, value) if index is None: self.index_track.append(len(self.table)) self.table.append(entry) else: self.table[index]=entry return self
[ "def", "upsert", "(", "self", ",", "key", ",", "value", ",", "entry", ")", ":", "index", "=", "internal", ".", "get_index", "(", "self", ".", "table", ",", "key", ",", "self", ".", "EQUAL", ",", "value", ")", "if", "index", "is", "None", ":", "self", ".", "index_track", ".", "append", "(", "len", "(", "self", ".", "table", ")", ")", "self", ".", "table", ".", "append", "(", "entry", ")", "else", ":", "self", ".", "table", "[", "index", "]", "=", "entry", "return", "self" ]
Update or Insert an entry into the list of dictionaries. If a dictionary in the list is found where key matches the value, then the FIRST matching list entry is replaced with entry else the entry is appended to the end of the list. The new entry is not examined in any way. It is, in fact, possible to upsert an entry that does not match the supplied key/value. Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "wigs": 68 }, ... {"name": "Larry", "age": 18, "wigs": [3, 2, 9]}, ... {"name": "Joe", "age": 20, "income": 15000, "wigs": [1, 2, 3]}, ... {"name": "Bill", "age": 19, "income": 29000 }, ... ] >>> entryA = {"name": "Willie", "age": 77} >>> myPLOD = PLOD(test) >>> print myPLOD.upsert("name", "Willie", entryA).returnString() [ {age: 18, income: 93000, name: 'Jim' , wigs: 68}, {age: 18, income: None , name: 'Larry' , wigs: [3, 2, 9]}, {age: 20, income: 15000, name: 'Joe' , wigs: [1, 2, 3]}, {age: 19, income: 29000, name: 'Bill' , wigs: None }, {age: 77, income: None , name: 'Willie', wigs: None } ] >>> entryB = {"name": "Joe", "age": 20, "income": 30, "wigs": [3, 2, 9]} >>> print myPLOD.upsert("name", "Joe", entryB).returnString() [ {age: 18, income: 93000, name: 'Jim' , wigs: 68}, {age: 18, income: None , name: 'Larry' , wigs: [3, 2, 9]}, {age: 20, income: 30, name: 'Joe' , wigs: [3, 2, 9]}, {age: 19, income: 29000, name: 'Bill' , wigs: None }, {age: 77, income: None , name: 'Willie', wigs: None } ] :param key: The dictionary key to examine. :param value: The value to search for as referenced by the key. :param entry: The replacement (or new) entry for the list. :returns: class
[ "Update", "or", "Insert", "an", "entry", "into", "the", "list", "of", "dictionaries", "." ]
707502cd928e5be6bd5e46d7f6de7da0e188cf1e
https://github.com/MakerReduxCorp/PLOD/blob/707502cd928e5be6bd5e46d7f6de7da0e188cf1e/PLOD/__init__.py#L195-L249
244,449
MakerReduxCorp/PLOD
PLOD/__init__.py
PLOD.insert
def insert(self, new_entry): '''Insert a new entry to the end of the list of dictionaries. This entry retains the original index tracking but adds this entry incrementally at the end. >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "wigs": 68 }, ... {"name": "Larry", "age": 18, "wigs": [3, 2, 9]}, ... {"name": "Joe", "age": 20, "income": 15000, "wigs": [1, 2, 3]}, ... {"name": "Bill", "age": 19, "income": 29000 }, ... ] >>> entryA = {"name": "Willie", "age": 77} >>> print PLOD(test).insert(entryA).returnString() [ {age: 18, income: 93000, name: 'Jim' , wigs: 68}, {age: 18, income: None , name: 'Larry' , wigs: [3, 2, 9]}, {age: 20, income: 15000, name: 'Joe' , wigs: [1, 2, 3]}, {age: 19, income: 29000, name: 'Bill' , wigs: None }, {age: 77, income: None , name: 'Willie', wigs: None } ] :param new_entry: The new list entry to insert. ''' self.index_track.append(len(self.table)) self.table.append(new_entry) return self
python
def insert(self, new_entry): '''Insert a new entry to the end of the list of dictionaries. This entry retains the original index tracking but adds this entry incrementally at the end. >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "wigs": 68 }, ... {"name": "Larry", "age": 18, "wigs": [3, 2, 9]}, ... {"name": "Joe", "age": 20, "income": 15000, "wigs": [1, 2, 3]}, ... {"name": "Bill", "age": 19, "income": 29000 }, ... ] >>> entryA = {"name": "Willie", "age": 77} >>> print PLOD(test).insert(entryA).returnString() [ {age: 18, income: 93000, name: 'Jim' , wigs: 68}, {age: 18, income: None , name: 'Larry' , wigs: [3, 2, 9]}, {age: 20, income: 15000, name: 'Joe' , wigs: [1, 2, 3]}, {age: 19, income: 29000, name: 'Bill' , wigs: None }, {age: 77, income: None , name: 'Willie', wigs: None } ] :param new_entry: The new list entry to insert. ''' self.index_track.append(len(self.table)) self.table.append(new_entry) return self
[ "def", "insert", "(", "self", ",", "new_entry", ")", ":", "self", ".", "index_track", ".", "append", "(", "len", "(", "self", ".", "table", ")", ")", "self", ".", "table", ".", "append", "(", "new_entry", ")", "return", "self" ]
Insert a new entry to the end of the list of dictionaries. This entry retains the original index tracking but adds this entry incrementally at the end. >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "wigs": 68 }, ... {"name": "Larry", "age": 18, "wigs": [3, 2, 9]}, ... {"name": "Joe", "age": 20, "income": 15000, "wigs": [1, 2, 3]}, ... {"name": "Bill", "age": 19, "income": 29000 }, ... ] >>> entryA = {"name": "Willie", "age": 77} >>> print PLOD(test).insert(entryA).returnString() [ {age: 18, income: 93000, name: 'Jim' , wigs: 68}, {age: 18, income: None , name: 'Larry' , wigs: [3, 2, 9]}, {age: 20, income: 15000, name: 'Joe' , wigs: [1, 2, 3]}, {age: 19, income: 29000, name: 'Bill' , wigs: None }, {age: 77, income: None , name: 'Willie', wigs: None } ] :param new_entry: The new list entry to insert.
[ "Insert", "a", "new", "entry", "to", "the", "end", "of", "the", "list", "of", "dictionaries", "." ]
707502cd928e5be6bd5e46d7f6de7da0e188cf1e
https://github.com/MakerReduxCorp/PLOD/blob/707502cd928e5be6bd5e46d7f6de7da0e188cf1e/PLOD/__init__.py#L251-L278
244,450
MakerReduxCorp/PLOD
PLOD/__init__.py
PLOD.deleteByOrigIndex
def deleteByOrigIndex(self, index): """Removes a single entry from the list given the index reference. The index, in this instance, is a reference to the *original* list indexing as seen when the list was first inserted into PLOD. An example: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "wigs": 68 }, ... {"name": "Larry", "age": 18, "wigs": [3, 2, 9]}, ... {"name": "Joe", "age": 20, "income": 15000, "wigs": [1, 2, 3]}, ... {"name": "Bill", "age": 19, "income": 29000 }, ... ] >>> myPLOD = PLOD(test) >>> print myPLOD.sort("name").returnString() [ {age: 19, income: 29000, name: 'Bill' , wigs: None }, {age: 18, income: 93000, name: 'Jim' , wigs: 68}, {age: 20, income: 15000, name: 'Joe' , wigs: [1, 2, 3]}, {age: 18, income: None , name: 'Larry', wigs: [3, 2, 9]} ] >>> print myPLOD.deleteByOrigIndex(0).returnString() [ {age: 19, income: 29000, name: 'Bill' , wigs: None }, {age: 20, income: 15000, name: 'Joe' , wigs: [1, 2, 3]}, {age: 18, income: None , name: 'Larry', wigs: [3, 2, 9]} ] As you can see in the example, the list was sorted by 'name', which placed 'Bill' as the first entry. Yet, when the deleteByOrigIndex was passed a zero (for the first entry), it removed 'Jim' instead since it was the original first entry. :param index: An integer representing the place of entry in the original list of dictionaries. :return: self """ result = [] result_tracker = [] for counter, row in enumerate(self.table): if self.index_track[counter] != index: result.append(row) result_tracker.append(self.index_track[counter]) self.table = result self.index_track = result_tracker return self
python
def deleteByOrigIndex(self, index): """Removes a single entry from the list given the index reference. The index, in this instance, is a reference to the *original* list indexing as seen when the list was first inserted into PLOD. An example: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "wigs": 68 }, ... {"name": "Larry", "age": 18, "wigs": [3, 2, 9]}, ... {"name": "Joe", "age": 20, "income": 15000, "wigs": [1, 2, 3]}, ... {"name": "Bill", "age": 19, "income": 29000 }, ... ] >>> myPLOD = PLOD(test) >>> print myPLOD.sort("name").returnString() [ {age: 19, income: 29000, name: 'Bill' , wigs: None }, {age: 18, income: 93000, name: 'Jim' , wigs: 68}, {age: 20, income: 15000, name: 'Joe' , wigs: [1, 2, 3]}, {age: 18, income: None , name: 'Larry', wigs: [3, 2, 9]} ] >>> print myPLOD.deleteByOrigIndex(0).returnString() [ {age: 19, income: 29000, name: 'Bill' , wigs: None }, {age: 20, income: 15000, name: 'Joe' , wigs: [1, 2, 3]}, {age: 18, income: None , name: 'Larry', wigs: [3, 2, 9]} ] As you can see in the example, the list was sorted by 'name', which placed 'Bill' as the first entry. Yet, when the deleteByOrigIndex was passed a zero (for the first entry), it removed 'Jim' instead since it was the original first entry. :param index: An integer representing the place of entry in the original list of dictionaries. :return: self """ result = [] result_tracker = [] for counter, row in enumerate(self.table): if self.index_track[counter] != index: result.append(row) result_tracker.append(self.index_track[counter]) self.table = result self.index_track = result_tracker return self
[ "def", "deleteByOrigIndex", "(", "self", ",", "index", ")", ":", "result", "=", "[", "]", "result_tracker", "=", "[", "]", "for", "counter", ",", "row", "in", "enumerate", "(", "self", ".", "table", ")", ":", "if", "self", ".", "index_track", "[", "counter", "]", "!=", "index", ":", "result", ".", "append", "(", "row", ")", "result_tracker", ".", "append", "(", "self", ".", "index_track", "[", "counter", "]", ")", "self", ".", "table", "=", "result", "self", ".", "index_track", "=", "result_tracker", "return", "self" ]
Removes a single entry from the list given the index reference. The index, in this instance, is a reference to the *original* list indexing as seen when the list was first inserted into PLOD. An example: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "wigs": 68 }, ... {"name": "Larry", "age": 18, "wigs": [3, 2, 9]}, ... {"name": "Joe", "age": 20, "income": 15000, "wigs": [1, 2, 3]}, ... {"name": "Bill", "age": 19, "income": 29000 }, ... ] >>> myPLOD = PLOD(test) >>> print myPLOD.sort("name").returnString() [ {age: 19, income: 29000, name: 'Bill' , wigs: None }, {age: 18, income: 93000, name: 'Jim' , wigs: 68}, {age: 20, income: 15000, name: 'Joe' , wigs: [1, 2, 3]}, {age: 18, income: None , name: 'Larry', wigs: [3, 2, 9]} ] >>> print myPLOD.deleteByOrigIndex(0).returnString() [ {age: 19, income: 29000, name: 'Bill' , wigs: None }, {age: 20, income: 15000, name: 'Joe' , wigs: [1, 2, 3]}, {age: 18, income: None , name: 'Larry', wigs: [3, 2, 9]} ] As you can see in the example, the list was sorted by 'name', which placed 'Bill' as the first entry. Yet, when the deleteByOrigIndex was passed a zero (for the first entry), it removed 'Jim' instead since it was the original first entry. :param index: An integer representing the place of entry in the original list of dictionaries. :return: self
[ "Removes", "a", "single", "entry", "from", "the", "list", "given", "the", "index", "reference", "." ]
707502cd928e5be6bd5e46d7f6de7da0e188cf1e
https://github.com/MakerReduxCorp/PLOD/blob/707502cd928e5be6bd5e46d7f6de7da0e188cf1e/PLOD/__init__.py#L280-L328
244,451
MakerReduxCorp/PLOD
PLOD/__init__.py
PLOD.deleteByOrigIndexList
def deleteByOrigIndexList(self, indexList): """Remove entries from the list given the index references. The index, in this instance, is a reference to the *original* list indexing as seen when the list was first inserted into PLOD. An example: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "wigs": 68 }, ... {"name": "Larry", "age": 18, "wigs": [3, 2, 9]}, ... {"name": "Joe", "age": 20, "income": 15000, "wigs": [1, 2, 3]}, ... {"name": "Bill", "age": 19, "income": 29000 }, ... ] >>> myPLOD = PLOD(test) >>> print myPLOD.sort("name").returnString() [ {age: 19, income: 29000, name: 'Bill' , wigs: None }, {age: 18, income: 93000, name: 'Jim' , wigs: 68}, {age: 20, income: 15000, name: 'Joe' , wigs: [1, 2, 3]}, {age: 18, income: None , name: 'Larry', wigs: [3, 2, 9]} ] >>> listA = [0, 1] >>> print myPLOD.deleteByOrigIndexList(listA).returnString() [ {age: 20, income: 15000, name: 'Joe' , wigs: [1, 2, 3]}, {age: 18, income: None , name: 'Larry', wigs: [3, 2, 9]} ] As you can see in the example, the list was sorted by 'name', which rearranged the entries. Yet, when the deleteByOrigIndexList was passed a [0, 1] (for the first and second entries), it removed 'Jim' and "Larry" since those were the original first and second entries. :param indexList: A list of integer representing the places of entry in the original list of dictionaries. :return: self """ result = [] result_tracker = [] counter = 0 for row in self.table: if not counter in indexList: result.append(row) result_tracker.append(self.index_track[counter]) counter += 1 self.table = result self.index_track = result_tracker return self
python
def deleteByOrigIndexList(self, indexList): """Remove entries from the list given the index references. The index, in this instance, is a reference to the *original* list indexing as seen when the list was first inserted into PLOD. An example: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "wigs": 68 }, ... {"name": "Larry", "age": 18, "wigs": [3, 2, 9]}, ... {"name": "Joe", "age": 20, "income": 15000, "wigs": [1, 2, 3]}, ... {"name": "Bill", "age": 19, "income": 29000 }, ... ] >>> myPLOD = PLOD(test) >>> print myPLOD.sort("name").returnString() [ {age: 19, income: 29000, name: 'Bill' , wigs: None }, {age: 18, income: 93000, name: 'Jim' , wigs: 68}, {age: 20, income: 15000, name: 'Joe' , wigs: [1, 2, 3]}, {age: 18, income: None , name: 'Larry', wigs: [3, 2, 9]} ] >>> listA = [0, 1] >>> print myPLOD.deleteByOrigIndexList(listA).returnString() [ {age: 20, income: 15000, name: 'Joe' , wigs: [1, 2, 3]}, {age: 18, income: None , name: 'Larry', wigs: [3, 2, 9]} ] As you can see in the example, the list was sorted by 'name', which rearranged the entries. Yet, when the deleteByOrigIndexList was passed a [0, 1] (for the first and second entries), it removed 'Jim' and "Larry" since those were the original first and second entries. :param indexList: A list of integer representing the places of entry in the original list of dictionaries. :return: self """ result = [] result_tracker = [] counter = 0 for row in self.table: if not counter in indexList: result.append(row) result_tracker.append(self.index_track[counter]) counter += 1 self.table = result self.index_track = result_tracker return self
[ "def", "deleteByOrigIndexList", "(", "self", ",", "indexList", ")", ":", "result", "=", "[", "]", "result_tracker", "=", "[", "]", "counter", "=", "0", "for", "row", "in", "self", ".", "table", ":", "if", "not", "counter", "in", "indexList", ":", "result", ".", "append", "(", "row", ")", "result_tracker", ".", "append", "(", "self", ".", "index_track", "[", "counter", "]", ")", "counter", "+=", "1", "self", ".", "table", "=", "result", "self", ".", "index_track", "=", "result_tracker", "return", "self" ]
Remove entries from the list given the index references. The index, in this instance, is a reference to the *original* list indexing as seen when the list was first inserted into PLOD. An example: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "wigs": 68 }, ... {"name": "Larry", "age": 18, "wigs": [3, 2, 9]}, ... {"name": "Joe", "age": 20, "income": 15000, "wigs": [1, 2, 3]}, ... {"name": "Bill", "age": 19, "income": 29000 }, ... ] >>> myPLOD = PLOD(test) >>> print myPLOD.sort("name").returnString() [ {age: 19, income: 29000, name: 'Bill' , wigs: None }, {age: 18, income: 93000, name: 'Jim' , wigs: 68}, {age: 20, income: 15000, name: 'Joe' , wigs: [1, 2, 3]}, {age: 18, income: None , name: 'Larry', wigs: [3, 2, 9]} ] >>> listA = [0, 1] >>> print myPLOD.deleteByOrigIndexList(listA).returnString() [ {age: 20, income: 15000, name: 'Joe' , wigs: [1, 2, 3]}, {age: 18, income: None , name: 'Larry', wigs: [3, 2, 9]} ] As you can see in the example, the list was sorted by 'name', which rearranged the entries. Yet, when the deleteByOrigIndexList was passed a [0, 1] (for the first and second entries), it removed 'Jim' and "Larry" since those were the original first and second entries. :param indexList: A list of integer representing the places of entry in the original list of dictionaries. :return: self
[ "Remove", "entries", "from", "the", "list", "given", "the", "index", "references", "." ]
707502cd928e5be6bd5e46d7f6de7da0e188cf1e
https://github.com/MakerReduxCorp/PLOD/blob/707502cd928e5be6bd5e46d7f6de7da0e188cf1e/PLOD/__init__.py#L330-L380
244,452
MakerReduxCorp/PLOD
PLOD/__init__.py
PLOD.renumber
def renumber(self, key, start=1, increment=1, insert=False): '''Incrementally number a key based on the current order of the list. Please note that if an entry in the list does not have the specified key, it is NOT created (unless insert=True is passed). The entry is, however, still counted. Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "order": 2}, ... {"name": "Larry", "age": 18, "order": 3}, ... {"name": "Joe", "age": 20, "income": 15000, "order": 1}, ... {"name": "Bill", "age": 19, "income": 29000}, ... ] >>> print PLOD(test).renumber("order", start=10).returnString(honorMissing=True) [ {age: 18, income: 93000, name: 'Jim' , order: 10}, {age: 18, name: 'Larry', order: 11}, {age: 20, income: 15000, name: 'Joe' , order: 12}, {age: 19, income: 29000, name: 'Bill' } ] >>> print PLOD(test).renumber("order", increment=2, insert=True).returnString(honorMissing=True) [ {age: 18, income: 93000, name: 'Jim' , order: 1}, {age: 18, name: 'Larry', order: 3}, {age: 20, income: 15000, name: 'Joe' , order: 5}, {age: 19, income: 29000, name: 'Bill' , order: 7} ] .. versionadded:: 0.1.2 :param key: The dictionary key (or cascading list of keys) that should receive the numbering. The previous value is replaced, regardles of type or content. Every entry is still counted; even if the key is missing. :param start: Defaults to 1. The starting number to begin counting with. :param increment: Defaults to 1. The amount to increment by for each entry in the list. :param insert: If True, then the key is inserted if missing. Else, the key is not inserted. Defaults to False. :returns: self ''' result = [] counter = start if insert: self.addKey(key, 0) for row in self.table: if internal.detect_member(row, key): row = internal.modify_member(row, key, counter) result.append(row) counter += increment self.table = result return self
python
def renumber(self, key, start=1, increment=1, insert=False): '''Incrementally number a key based on the current order of the list. Please note that if an entry in the list does not have the specified key, it is NOT created (unless insert=True is passed). The entry is, however, still counted. Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "order": 2}, ... {"name": "Larry", "age": 18, "order": 3}, ... {"name": "Joe", "age": 20, "income": 15000, "order": 1}, ... {"name": "Bill", "age": 19, "income": 29000}, ... ] >>> print PLOD(test).renumber("order", start=10).returnString(honorMissing=True) [ {age: 18, income: 93000, name: 'Jim' , order: 10}, {age: 18, name: 'Larry', order: 11}, {age: 20, income: 15000, name: 'Joe' , order: 12}, {age: 19, income: 29000, name: 'Bill' } ] >>> print PLOD(test).renumber("order", increment=2, insert=True).returnString(honorMissing=True) [ {age: 18, income: 93000, name: 'Jim' , order: 1}, {age: 18, name: 'Larry', order: 3}, {age: 20, income: 15000, name: 'Joe' , order: 5}, {age: 19, income: 29000, name: 'Bill' , order: 7} ] .. versionadded:: 0.1.2 :param key: The dictionary key (or cascading list of keys) that should receive the numbering. The previous value is replaced, regardles of type or content. Every entry is still counted; even if the key is missing. :param start: Defaults to 1. The starting number to begin counting with. :param increment: Defaults to 1. The amount to increment by for each entry in the list. :param insert: If True, then the key is inserted if missing. Else, the key is not inserted. Defaults to False. :returns: self ''' result = [] counter = start if insert: self.addKey(key, 0) for row in self.table: if internal.detect_member(row, key): row = internal.modify_member(row, key, counter) result.append(row) counter += increment self.table = result return self
[ "def", "renumber", "(", "self", ",", "key", ",", "start", "=", "1", ",", "increment", "=", "1", ",", "insert", "=", "False", ")", ":", "result", "=", "[", "]", "counter", "=", "start", "if", "insert", ":", "self", ".", "addKey", "(", "key", ",", "0", ")", "for", "row", "in", "self", ".", "table", ":", "if", "internal", ".", "detect_member", "(", "row", ",", "key", ")", ":", "row", "=", "internal", ".", "modify_member", "(", "row", ",", "key", ",", "counter", ")", "result", ".", "append", "(", "row", ")", "counter", "+=", "increment", "self", ".", "table", "=", "result", "return", "self" ]
Incrementally number a key based on the current order of the list. Please note that if an entry in the list does not have the specified key, it is NOT created (unless insert=True is passed). The entry is, however, still counted. Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "order": 2}, ... {"name": "Larry", "age": 18, "order": 3}, ... {"name": "Joe", "age": 20, "income": 15000, "order": 1}, ... {"name": "Bill", "age": 19, "income": 29000}, ... ] >>> print PLOD(test).renumber("order", start=10).returnString(honorMissing=True) [ {age: 18, income: 93000, name: 'Jim' , order: 10}, {age: 18, name: 'Larry', order: 11}, {age: 20, income: 15000, name: 'Joe' , order: 12}, {age: 19, income: 29000, name: 'Bill' } ] >>> print PLOD(test).renumber("order", increment=2, insert=True).returnString(honorMissing=True) [ {age: 18, income: 93000, name: 'Jim' , order: 1}, {age: 18, name: 'Larry', order: 3}, {age: 20, income: 15000, name: 'Joe' , order: 5}, {age: 19, income: 29000, name: 'Bill' , order: 7} ] .. versionadded:: 0.1.2 :param key: The dictionary key (or cascading list of keys) that should receive the numbering. The previous value is replaced, regardles of type or content. Every entry is still counted; even if the key is missing. :param start: Defaults to 1. The starting number to begin counting with. :param increment: Defaults to 1. The amount to increment by for each entry in the list. :param insert: If True, then the key is inserted if missing. Else, the key is not inserted. Defaults to False. :returns: self
[ "Incrementally", "number", "a", "key", "based", "on", "the", "current", "order", "of", "the", "list", "." ]
707502cd928e5be6bd5e46d7f6de7da0e188cf1e
https://github.com/MakerReduxCorp/PLOD/blob/707502cd928e5be6bd5e46d7f6de7da0e188cf1e/PLOD/__init__.py#L388-L443
244,453
MakerReduxCorp/PLOD
PLOD/__init__.py
PLOD.sort
def sort(self, key, reverse=False, none_greater=False): '''Sort the list in the order of the dictionary key. Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "wigs": 68 }, ... {"name": "Larry", "age": 18, "wigs": [3, 2, 9]}, ... {"name": "Joe", "age": 20, "income": 15000, "wigs": [1, 2, 3]}, ... {"name": "Bill", "age": 19, "income": 29000 }, ... ] >>> print PLOD(test).sort("name").returnString() [ {age: 19, income: 29000, name: 'Bill' , wigs: None }, {age: 18, income: 93000, name: 'Jim' , wigs: 68}, {age: 20, income: 15000, name: 'Joe' , wigs: [1, 2, 3]}, {age: 18, income: None , name: 'Larry', wigs: [3, 2, 9]} ] >>> print PLOD(test).sort("income").returnString() [ {age: 18, income: None , name: 'Larry', wigs: [3, 2, 9]}, {age: 20, income: 15000, name: 'Joe' , wigs: [1, 2, 3]}, {age: 19, income: 29000, name: 'Bill' , wigs: None }, {age: 18, income: 93000, name: 'Jim' , wigs: 68} ] >>> print PLOD(test).sort(["age", "income"]).returnString() [ {age: 18, income: None , name: 'Larry', wigs: [3, 2, 9]}, {age: 18, income: 93000, name: 'Jim' , wigs: 68}, {age: 19, income: 29000, name: 'Bill' , wigs: None }, {age: 20, income: 15000, name: 'Joe' , wigs: [1, 2, 3]} ] .. versionadded:: 0.0.2 :param key: A dictionary key (or a list of keys) that should be the basis of the sorting. :param reverse: Defaults to False. If True, then list is sorted decrementally. :param none_greater: Defaults to False. If True, then entries missing the key/value pair are considered be of greater value than the non-missing values. :returns: self ''' for i in range(0, len(self.table)): min = i for j in range(i + 1, len(self.table)): if internal.is_first_lessor(self.table[j], self.table[min], key, none_greater=none_greater, reverse=reverse): min = j if i!=min: self.table[i], self.table[min] = self.table[min], self.table[i] # swap self.index_track[i], self.index_track[min] = self.index_track[min], self.index_track[i] # swap return self
python
def sort(self, key, reverse=False, none_greater=False): '''Sort the list in the order of the dictionary key. Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "wigs": 68 }, ... {"name": "Larry", "age": 18, "wigs": [3, 2, 9]}, ... {"name": "Joe", "age": 20, "income": 15000, "wigs": [1, 2, 3]}, ... {"name": "Bill", "age": 19, "income": 29000 }, ... ] >>> print PLOD(test).sort("name").returnString() [ {age: 19, income: 29000, name: 'Bill' , wigs: None }, {age: 18, income: 93000, name: 'Jim' , wigs: 68}, {age: 20, income: 15000, name: 'Joe' , wigs: [1, 2, 3]}, {age: 18, income: None , name: 'Larry', wigs: [3, 2, 9]} ] >>> print PLOD(test).sort("income").returnString() [ {age: 18, income: None , name: 'Larry', wigs: [3, 2, 9]}, {age: 20, income: 15000, name: 'Joe' , wigs: [1, 2, 3]}, {age: 19, income: 29000, name: 'Bill' , wigs: None }, {age: 18, income: 93000, name: 'Jim' , wigs: 68} ] >>> print PLOD(test).sort(["age", "income"]).returnString() [ {age: 18, income: None , name: 'Larry', wigs: [3, 2, 9]}, {age: 18, income: 93000, name: 'Jim' , wigs: 68}, {age: 19, income: 29000, name: 'Bill' , wigs: None }, {age: 20, income: 15000, name: 'Joe' , wigs: [1, 2, 3]} ] .. versionadded:: 0.0.2 :param key: A dictionary key (or a list of keys) that should be the basis of the sorting. :param reverse: Defaults to False. If True, then list is sorted decrementally. :param none_greater: Defaults to False. If True, then entries missing the key/value pair are considered be of greater value than the non-missing values. :returns: self ''' for i in range(0, len(self.table)): min = i for j in range(i + 1, len(self.table)): if internal.is_first_lessor(self.table[j], self.table[min], key, none_greater=none_greater, reverse=reverse): min = j if i!=min: self.table[i], self.table[min] = self.table[min], self.table[i] # swap self.index_track[i], self.index_track[min] = self.index_track[min], self.index_track[i] # swap return self
[ "def", "sort", "(", "self", ",", "key", ",", "reverse", "=", "False", ",", "none_greater", "=", "False", ")", ":", "for", "i", "in", "range", "(", "0", ",", "len", "(", "self", ".", "table", ")", ")", ":", "min", "=", "i", "for", "j", "in", "range", "(", "i", "+", "1", ",", "len", "(", "self", ".", "table", ")", ")", ":", "if", "internal", ".", "is_first_lessor", "(", "self", ".", "table", "[", "j", "]", ",", "self", ".", "table", "[", "min", "]", ",", "key", ",", "none_greater", "=", "none_greater", ",", "reverse", "=", "reverse", ")", ":", "min", "=", "j", "if", "i", "!=", "min", ":", "self", ".", "table", "[", "i", "]", ",", "self", ".", "table", "[", "min", "]", "=", "self", ".", "table", "[", "min", "]", ",", "self", ".", "table", "[", "i", "]", "# swap", "self", ".", "index_track", "[", "i", "]", ",", "self", ".", "index_track", "[", "min", "]", "=", "self", ".", "index_track", "[", "min", "]", ",", "self", ".", "index_track", "[", "i", "]", "# swap", "return", "self" ]
Sort the list in the order of the dictionary key. Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "wigs": 68 }, ... {"name": "Larry", "age": 18, "wigs": [3, 2, 9]}, ... {"name": "Joe", "age": 20, "income": 15000, "wigs": [1, 2, 3]}, ... {"name": "Bill", "age": 19, "income": 29000 }, ... ] >>> print PLOD(test).sort("name").returnString() [ {age: 19, income: 29000, name: 'Bill' , wigs: None }, {age: 18, income: 93000, name: 'Jim' , wigs: 68}, {age: 20, income: 15000, name: 'Joe' , wigs: [1, 2, 3]}, {age: 18, income: None , name: 'Larry', wigs: [3, 2, 9]} ] >>> print PLOD(test).sort("income").returnString() [ {age: 18, income: None , name: 'Larry', wigs: [3, 2, 9]}, {age: 20, income: 15000, name: 'Joe' , wigs: [1, 2, 3]}, {age: 19, income: 29000, name: 'Bill' , wigs: None }, {age: 18, income: 93000, name: 'Jim' , wigs: 68} ] >>> print PLOD(test).sort(["age", "income"]).returnString() [ {age: 18, income: None , name: 'Larry', wigs: [3, 2, 9]}, {age: 18, income: 93000, name: 'Jim' , wigs: 68}, {age: 19, income: 29000, name: 'Bill' , wigs: None }, {age: 20, income: 15000, name: 'Joe' , wigs: [1, 2, 3]} ] .. versionadded:: 0.0.2 :param key: A dictionary key (or a list of keys) that should be the basis of the sorting. :param reverse: Defaults to False. If True, then list is sorted decrementally. :param none_greater: Defaults to False. If True, then entries missing the key/value pair are considered be of greater value than the non-missing values. :returns: self
[ "Sort", "the", "list", "in", "the", "order", "of", "the", "dictionary", "key", "." ]
707502cd928e5be6bd5e46d7f6de7da0e188cf1e
https://github.com/MakerReduxCorp/PLOD/blob/707502cd928e5be6bd5e46d7f6de7da0e188cf1e/PLOD/__init__.py#L445-L498
244,454
MakerReduxCorp/PLOD
PLOD/__init__.py
PLOD.hasKey
def hasKey(self, key, notNone=False): '''Return entries where the key is present. Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "wigs": 68 }, ... {"name": "Larry", "age": 18, "wigs": [3, 2, 9]}, ... {"name": "Joe", "age": 20, "income": None , "wigs": [1, 2, 3]}, ... {"name": "Bill", "age": 19, "income": 29000 }, ... ] >>> print PLOD(test).hasKey("income").returnString() [ {age: 18, income: 93000, name: 'Jim' , wigs: 68}, {age: 20, income: None , name: 'Joe' , wigs: [1, 2, 3]}, {age: 19, income: 29000, name: 'Bill', wigs: None } ] >>> print PLOD(test).hasKey("income", notNone=True).returnString() [ {age: 18, income: 93000, name: 'Jim' , wigs: 68}, {age: 19, income: 29000, name: 'Bill', wigs: None} ] .. versionadded:: 0.1.2 :param key: The dictionary key (or cascading list of keys) to locate. :param notNone: If True, then None is the equivalent of a missing key. Otherwise, a key with a value of None is NOT considered missing. :returns: self ''' result = [] result_tracker = [] for counter, row in enumerate(self.table): (target, _, value) = internal.dict_crawl(row, key) if target: if notNone==False or not value is None: result.append(row) result_tracker.append(self.index_track[counter]) self.table = result self.index_track = result_tracker return self
python
def hasKey(self, key, notNone=False): '''Return entries where the key is present. Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "wigs": 68 }, ... {"name": "Larry", "age": 18, "wigs": [3, 2, 9]}, ... {"name": "Joe", "age": 20, "income": None , "wigs": [1, 2, 3]}, ... {"name": "Bill", "age": 19, "income": 29000 }, ... ] >>> print PLOD(test).hasKey("income").returnString() [ {age: 18, income: 93000, name: 'Jim' , wigs: 68}, {age: 20, income: None , name: 'Joe' , wigs: [1, 2, 3]}, {age: 19, income: 29000, name: 'Bill', wigs: None } ] >>> print PLOD(test).hasKey("income", notNone=True).returnString() [ {age: 18, income: 93000, name: 'Jim' , wigs: 68}, {age: 19, income: 29000, name: 'Bill', wigs: None} ] .. versionadded:: 0.1.2 :param key: The dictionary key (or cascading list of keys) to locate. :param notNone: If True, then None is the equivalent of a missing key. Otherwise, a key with a value of None is NOT considered missing. :returns: self ''' result = [] result_tracker = [] for counter, row in enumerate(self.table): (target, _, value) = internal.dict_crawl(row, key) if target: if notNone==False or not value is None: result.append(row) result_tracker.append(self.index_track[counter]) self.table = result self.index_track = result_tracker return self
[ "def", "hasKey", "(", "self", ",", "key", ",", "notNone", "=", "False", ")", ":", "result", "=", "[", "]", "result_tracker", "=", "[", "]", "for", "counter", ",", "row", "in", "enumerate", "(", "self", ".", "table", ")", ":", "(", "target", ",", "_", ",", "value", ")", "=", "internal", ".", "dict_crawl", "(", "row", ",", "key", ")", "if", "target", ":", "if", "notNone", "==", "False", "or", "not", "value", "is", "None", ":", "result", ".", "append", "(", "row", ")", "result_tracker", ".", "append", "(", "self", ".", "index_track", "[", "counter", "]", ")", "self", ".", "table", "=", "result", "self", ".", "index_track", "=", "result_tracker", "return", "self" ]
Return entries where the key is present. Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "wigs": 68 }, ... {"name": "Larry", "age": 18, "wigs": [3, 2, 9]}, ... {"name": "Joe", "age": 20, "income": None , "wigs": [1, 2, 3]}, ... {"name": "Bill", "age": 19, "income": 29000 }, ... ] >>> print PLOD(test).hasKey("income").returnString() [ {age: 18, income: 93000, name: 'Jim' , wigs: 68}, {age: 20, income: None , name: 'Joe' , wigs: [1, 2, 3]}, {age: 19, income: 29000, name: 'Bill', wigs: None } ] >>> print PLOD(test).hasKey("income", notNone=True).returnString() [ {age: 18, income: 93000, name: 'Jim' , wigs: 68}, {age: 19, income: 29000, name: 'Bill', wigs: None} ] .. versionadded:: 0.1.2 :param key: The dictionary key (or cascading list of keys) to locate. :param notNone: If True, then None is the equivalent of a missing key. Otherwise, a key with a value of None is NOT considered missing. :returns: self
[ "Return", "entries", "where", "the", "key", "is", "present", "." ]
707502cd928e5be6bd5e46d7f6de7da0e188cf1e
https://github.com/MakerReduxCorp/PLOD/blob/707502cd928e5be6bd5e46d7f6de7da0e188cf1e/PLOD/__init__.py#L707-L750
244,455
MakerReduxCorp/PLOD
PLOD/__init__.py
PLOD.returnString
def returnString(self, limit=False, omitBrackets=False, executable=False, honorMissing=False): '''Return a string containing the list of dictionaries in easy human-readable read format. Each entry is on one line. Key/value pairs are 'spaced' in such a way as to have them all line up vertically if using a monospace font. The fields are normalized to alphabetical order. Missing keys in a dictionary are inserted with a value of 'None' unless *honorMissing* is set to True. Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "order": 2}, ... {"name": "Larry", "age": 18, "order": 3}, ... {"name": "Joe", "age": 20, "income": 15000, "order": 1}, ... {"name": "Bill", "age": 19, "income": 29000, "order": 4}, ... ] >>> print PLOD(test).returnString() [ {age: 18, income: 93000, name: 'Jim' , order: 2}, {age: 18, income: None , name: 'Larry', order: 3}, {age: 20, income: 15000, name: 'Joe' , order: 1}, {age: 19, income: 29000, name: 'Bill' , order: 4} ] >>> print PLOD(test).returnString(limit=3, omitBrackets=True, executable=True) {'age': 18, 'income': 93000, 'name': 'Jim' , 'order': 2}, {'age': 18, 'income': None , 'name': 'Larry', 'order': 3}, {'age': 20, 'income': 15000, 'name': 'Joe' , 'order': 1} >>> print PLOD(test).returnString(honorMissing=True) [ {age: 18, income: 93000, name: 'Jim' , order: 2}, {age: 18, name: 'Larry', order: 3}, {age: 20, income: 15000, name: 'Joe' , order: 1}, {age: 19, income: 29000, name: 'Bill' , order: 4} ] :param limit: A number limiting the quantity of entries to return. Defaults to False, which means that the full list is returned. :param omitBrackets: If set to True, the outer square brackets representing the entire list are omitted. Defaults to False. :param executable: If set to True, the string is formatted in such a way that it conforms to Python syntax. Defaults to False. :param honorMissing: If set to True, keys that are missing in a dictionary are simply skipped with spaces. If False, then the key is display and given a value of None. Defaults to False. :return: A string containing a formatted textual representation of the list of dictionaries. ''' result = "" # we limit the table if needed if not limit: limit = len(self.table) used_table = [] for i in range(limit): if len(self.table)>i: used_table.append(internal.convert_to_dict(self.table[i])) # we locate all of the attributes and their lengths attr_width = {} # first pass to get the keys themselves for row in used_table: for key in row: if not key in attr_width: attr_width[key] = 0 # get a sorted list of keys attr_order = attr_width.keys() attr_order.sort() # not get minimum widths # (this is done as a seperate step to account for 'None' and other conditions. for row in used_table: for key in attr_width: if not key in row: if not honorMissing: if attr_width[key] < len("None"): attr_width[key] = len("None") else: if len(repr(row[key])) > attr_width[key]: attr_width[key] = len(repr(row[key])) # now we do the pretty print if not omitBrackets: result += "[\n" body = [] for row in used_table: row_string = "" if not omitBrackets: row_string += " " row_string += "{" middle = [] for key in attr_order: if key in row: # build the key if executable: item = "'"+str(key) + "': " else: item = str(key) + ": " # build the value s = repr(row[key]) if type(row[key]) is typemod.IntType: s = s.rjust(attr_width[key]) else: if honorMissing: # build the key item = " "*len(str(key)) if executable: item += " " item += " " # build the value s="" else: # build the key if executable: item = "'"+str(key) + "': " else: item = str(key) + ": " # build the value s = "None" item += s.ljust(attr_width[key]) middle.append(item) # row_string += ", ".join(middle) row_string += internal.special_join(middle) row_string += "}" body.append(row_string) result += ",\n".join(body) if len(body) and not omitBrackets: result += "\n" if not omitBrackets: result += "]" return result
python
def returnString(self, limit=False, omitBrackets=False, executable=False, honorMissing=False): '''Return a string containing the list of dictionaries in easy human-readable read format. Each entry is on one line. Key/value pairs are 'spaced' in such a way as to have them all line up vertically if using a monospace font. The fields are normalized to alphabetical order. Missing keys in a dictionary are inserted with a value of 'None' unless *honorMissing* is set to True. Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "order": 2}, ... {"name": "Larry", "age": 18, "order": 3}, ... {"name": "Joe", "age": 20, "income": 15000, "order": 1}, ... {"name": "Bill", "age": 19, "income": 29000, "order": 4}, ... ] >>> print PLOD(test).returnString() [ {age: 18, income: 93000, name: 'Jim' , order: 2}, {age: 18, income: None , name: 'Larry', order: 3}, {age: 20, income: 15000, name: 'Joe' , order: 1}, {age: 19, income: 29000, name: 'Bill' , order: 4} ] >>> print PLOD(test).returnString(limit=3, omitBrackets=True, executable=True) {'age': 18, 'income': 93000, 'name': 'Jim' , 'order': 2}, {'age': 18, 'income': None , 'name': 'Larry', 'order': 3}, {'age': 20, 'income': 15000, 'name': 'Joe' , 'order': 1} >>> print PLOD(test).returnString(honorMissing=True) [ {age: 18, income: 93000, name: 'Jim' , order: 2}, {age: 18, name: 'Larry', order: 3}, {age: 20, income: 15000, name: 'Joe' , order: 1}, {age: 19, income: 29000, name: 'Bill' , order: 4} ] :param limit: A number limiting the quantity of entries to return. Defaults to False, which means that the full list is returned. :param omitBrackets: If set to True, the outer square brackets representing the entire list are omitted. Defaults to False. :param executable: If set to True, the string is formatted in such a way that it conforms to Python syntax. Defaults to False. :param honorMissing: If set to True, keys that are missing in a dictionary are simply skipped with spaces. If False, then the key is display and given a value of None. Defaults to False. :return: A string containing a formatted textual representation of the list of dictionaries. ''' result = "" # we limit the table if needed if not limit: limit = len(self.table) used_table = [] for i in range(limit): if len(self.table)>i: used_table.append(internal.convert_to_dict(self.table[i])) # we locate all of the attributes and their lengths attr_width = {} # first pass to get the keys themselves for row in used_table: for key in row: if not key in attr_width: attr_width[key] = 0 # get a sorted list of keys attr_order = attr_width.keys() attr_order.sort() # not get minimum widths # (this is done as a seperate step to account for 'None' and other conditions. for row in used_table: for key in attr_width: if not key in row: if not honorMissing: if attr_width[key] < len("None"): attr_width[key] = len("None") else: if len(repr(row[key])) > attr_width[key]: attr_width[key] = len(repr(row[key])) # now we do the pretty print if not omitBrackets: result += "[\n" body = [] for row in used_table: row_string = "" if not omitBrackets: row_string += " " row_string += "{" middle = [] for key in attr_order: if key in row: # build the key if executable: item = "'"+str(key) + "': " else: item = str(key) + ": " # build the value s = repr(row[key]) if type(row[key]) is typemod.IntType: s = s.rjust(attr_width[key]) else: if honorMissing: # build the key item = " "*len(str(key)) if executable: item += " " item += " " # build the value s="" else: # build the key if executable: item = "'"+str(key) + "': " else: item = str(key) + ": " # build the value s = "None" item += s.ljust(attr_width[key]) middle.append(item) # row_string += ", ".join(middle) row_string += internal.special_join(middle) row_string += "}" body.append(row_string) result += ",\n".join(body) if len(body) and not omitBrackets: result += "\n" if not omitBrackets: result += "]" return result
[ "def", "returnString", "(", "self", ",", "limit", "=", "False", ",", "omitBrackets", "=", "False", ",", "executable", "=", "False", ",", "honorMissing", "=", "False", ")", ":", "result", "=", "\"\"", "# we limit the table if needed", "if", "not", "limit", ":", "limit", "=", "len", "(", "self", ".", "table", ")", "used_table", "=", "[", "]", "for", "i", "in", "range", "(", "limit", ")", ":", "if", "len", "(", "self", ".", "table", ")", ">", "i", ":", "used_table", ".", "append", "(", "internal", ".", "convert_to_dict", "(", "self", ".", "table", "[", "i", "]", ")", ")", "# we locate all of the attributes and their lengths", "attr_width", "=", "{", "}", "# first pass to get the keys themselves", "for", "row", "in", "used_table", ":", "for", "key", "in", "row", ":", "if", "not", "key", "in", "attr_width", ":", "attr_width", "[", "key", "]", "=", "0", "# get a sorted list of keys", "attr_order", "=", "attr_width", ".", "keys", "(", ")", "attr_order", ".", "sort", "(", ")", "# not get minimum widths", "# (this is done as a seperate step to account for 'None' and other conditions.", "for", "row", "in", "used_table", ":", "for", "key", "in", "attr_width", ":", "if", "not", "key", "in", "row", ":", "if", "not", "honorMissing", ":", "if", "attr_width", "[", "key", "]", "<", "len", "(", "\"None\"", ")", ":", "attr_width", "[", "key", "]", "=", "len", "(", "\"None\"", ")", "else", ":", "if", "len", "(", "repr", "(", "row", "[", "key", "]", ")", ")", ">", "attr_width", "[", "key", "]", ":", "attr_width", "[", "key", "]", "=", "len", "(", "repr", "(", "row", "[", "key", "]", ")", ")", "# now we do the pretty print", "if", "not", "omitBrackets", ":", "result", "+=", "\"[\\n\"", "body", "=", "[", "]", "for", "row", "in", "used_table", ":", "row_string", "=", "\"\"", "if", "not", "omitBrackets", ":", "row_string", "+=", "\" \"", "row_string", "+=", "\"{\"", "middle", "=", "[", "]", "for", "key", "in", "attr_order", ":", "if", "key", "in", "row", ":", "# build the key", "if", "executable", ":", "item", "=", "\"'\"", "+", "str", "(", "key", ")", "+", "\"': \"", "else", ":", "item", "=", "str", "(", "key", ")", "+", "\": \"", "# build the value", "s", "=", "repr", "(", "row", "[", "key", "]", ")", "if", "type", "(", "row", "[", "key", "]", ")", "is", "typemod", ".", "IntType", ":", "s", "=", "s", ".", "rjust", "(", "attr_width", "[", "key", "]", ")", "else", ":", "if", "honorMissing", ":", "# build the key", "item", "=", "\" \"", "*", "len", "(", "str", "(", "key", ")", ")", "if", "executable", ":", "item", "+=", "\" \"", "item", "+=", "\" \"", "# build the value", "s", "=", "\"\"", "else", ":", "# build the key", "if", "executable", ":", "item", "=", "\"'\"", "+", "str", "(", "key", ")", "+", "\"': \"", "else", ":", "item", "=", "str", "(", "key", ")", "+", "\": \"", "# build the value", "s", "=", "\"None\"", "item", "+=", "s", ".", "ljust", "(", "attr_width", "[", "key", "]", ")", "middle", ".", "append", "(", "item", ")", "# row_string += \", \".join(middle)", "row_string", "+=", "internal", ".", "special_join", "(", "middle", ")", "row_string", "+=", "\"}\"", "body", ".", "append", "(", "row_string", ")", "result", "+=", "\",\\n\"", ".", "join", "(", "body", ")", "if", "len", "(", "body", ")", "and", "not", "omitBrackets", ":", "result", "+=", "\"\\n\"", "if", "not", "omitBrackets", ":", "result", "+=", "\"]\"", "return", "result" ]
Return a string containing the list of dictionaries in easy human-readable read format. Each entry is on one line. Key/value pairs are 'spaced' in such a way as to have them all line up vertically if using a monospace font. The fields are normalized to alphabetical order. Missing keys in a dictionary are inserted with a value of 'None' unless *honorMissing* is set to True. Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "order": 2}, ... {"name": "Larry", "age": 18, "order": 3}, ... {"name": "Joe", "age": 20, "income": 15000, "order": 1}, ... {"name": "Bill", "age": 19, "income": 29000, "order": 4}, ... ] >>> print PLOD(test).returnString() [ {age: 18, income: 93000, name: 'Jim' , order: 2}, {age: 18, income: None , name: 'Larry', order: 3}, {age: 20, income: 15000, name: 'Joe' , order: 1}, {age: 19, income: 29000, name: 'Bill' , order: 4} ] >>> print PLOD(test).returnString(limit=3, omitBrackets=True, executable=True) {'age': 18, 'income': 93000, 'name': 'Jim' , 'order': 2}, {'age': 18, 'income': None , 'name': 'Larry', 'order': 3}, {'age': 20, 'income': 15000, 'name': 'Joe' , 'order': 1} >>> print PLOD(test).returnString(honorMissing=True) [ {age: 18, income: 93000, name: 'Jim' , order: 2}, {age: 18, name: 'Larry', order: 3}, {age: 20, income: 15000, name: 'Joe' , order: 1}, {age: 19, income: 29000, name: 'Bill' , order: 4} ] :param limit: A number limiting the quantity of entries to return. Defaults to False, which means that the full list is returned. :param omitBrackets: If set to True, the outer square brackets representing the entire list are omitted. Defaults to False. :param executable: If set to True, the string is formatted in such a way that it conforms to Python syntax. Defaults to False. :param honorMissing: If set to True, keys that are missing in a dictionary are simply skipped with spaces. If False, then the key is display and given a value of None. Defaults to False. :return: A string containing a formatted textual representation of the list of dictionaries.
[ "Return", "a", "string", "containing", "the", "list", "of", "dictionaries", "in", "easy", "human", "-", "readable", "read", "format", "." ]
707502cd928e5be6bd5e46d7f6de7da0e188cf1e
https://github.com/MakerReduxCorp/PLOD/blob/707502cd928e5be6bd5e46d7f6de7da0e188cf1e/PLOD/__init__.py#L932-L1064
244,456
MakerReduxCorp/PLOD
PLOD/__init__.py
PLOD.returnIndexList
def returnIndexList(self, limit=False): '''Return a list of integers that are list-index references to the original list of dictionaries." Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "order": 2}, ... {"name": "Larry", "age": 18, "order": 3}, ... {"name": "Joe", "age": 20, "income": 15000, "order": 1}, ... {"name": "Bill", "age": 19, "income": 29000, "order": 4}, ... ] >>> print PLOD(test).returnIndexList() [0, 1, 2, 3] >>> print PLOD(test).sort("name").returnIndexList() [3, 0, 2, 1] :param limit: A number limiting the quantity of entries to return. Defaults to False, which means that the full list is returned. :return: A list of integers representing the original indices. ''' if limit==False: return self.index_track result = [] for i in range(limit): if len(self.table)>i: result.append(self.index_track[i]) return result
python
def returnIndexList(self, limit=False): '''Return a list of integers that are list-index references to the original list of dictionaries." Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "order": 2}, ... {"name": "Larry", "age": 18, "order": 3}, ... {"name": "Joe", "age": 20, "income": 15000, "order": 1}, ... {"name": "Bill", "age": 19, "income": 29000, "order": 4}, ... ] >>> print PLOD(test).returnIndexList() [0, 1, 2, 3] >>> print PLOD(test).sort("name").returnIndexList() [3, 0, 2, 1] :param limit: A number limiting the quantity of entries to return. Defaults to False, which means that the full list is returned. :return: A list of integers representing the original indices. ''' if limit==False: return self.index_track result = [] for i in range(limit): if len(self.table)>i: result.append(self.index_track[i]) return result
[ "def", "returnIndexList", "(", "self", ",", "limit", "=", "False", ")", ":", "if", "limit", "==", "False", ":", "return", "self", ".", "index_track", "result", "=", "[", "]", "for", "i", "in", "range", "(", "limit", ")", ":", "if", "len", "(", "self", ".", "table", ")", ">", "i", ":", "result", ".", "append", "(", "self", ".", "index_track", "[", "i", "]", ")", "return", "result" ]
Return a list of integers that are list-index references to the original list of dictionaries." Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "order": 2}, ... {"name": "Larry", "age": 18, "order": 3}, ... {"name": "Joe", "age": 20, "income": 15000, "order": 1}, ... {"name": "Bill", "age": 19, "income": 29000, "order": 4}, ... ] >>> print PLOD(test).returnIndexList() [0, 1, 2, 3] >>> print PLOD(test).sort("name").returnIndexList() [3, 0, 2, 1] :param limit: A number limiting the quantity of entries to return. Defaults to False, which means that the full list is returned. :return: A list of integers representing the original indices.
[ "Return", "a", "list", "of", "integers", "that", "are", "list", "-", "index", "references", "to", "the", "original", "list", "of", "dictionaries", "." ]
707502cd928e5be6bd5e46d7f6de7da0e188cf1e
https://github.com/MakerReduxCorp/PLOD/blob/707502cd928e5be6bd5e46d7f6de7da0e188cf1e/PLOD/__init__.py#L1202-L1231
244,457
MakerReduxCorp/PLOD
PLOD/__init__.py
PLOD.returnOneEntry
def returnOneEntry(self, last=False): '''Return the first entry in the current list. If 'last=True', then the last entry is returned." Returns None is the list is empty. Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "order": 2}, ... {"name": "Larry", "age": 18, "order": 3}, ... {"name": "Joe", "age": 20, "income": 15000, "order": 1}, ... {"name": "Bill", "age": 19, "income": 29000, "order": 4}, ... ] >>> print PLOD(test).returnOneEntry() {'age': 18, 'order': 2, 'name': 'Jim', 'income': 93000} >>> print PLOD(test).returnOneEntry(last=True) {'age': 19, 'order': 4, 'name': 'Bill', 'income': 29000} :param last: If True, the last entry is returned rather than the first. :return: A list entry, or None if the list is empty. ''' if len(self.table)==0: return None else: if last: return self.table[len(self.table)-1] else: return self.table[0]
python
def returnOneEntry(self, last=False): '''Return the first entry in the current list. If 'last=True', then the last entry is returned." Returns None is the list is empty. Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "order": 2}, ... {"name": "Larry", "age": 18, "order": 3}, ... {"name": "Joe", "age": 20, "income": 15000, "order": 1}, ... {"name": "Bill", "age": 19, "income": 29000, "order": 4}, ... ] >>> print PLOD(test).returnOneEntry() {'age': 18, 'order': 2, 'name': 'Jim', 'income': 93000} >>> print PLOD(test).returnOneEntry(last=True) {'age': 19, 'order': 4, 'name': 'Bill', 'income': 29000} :param last: If True, the last entry is returned rather than the first. :return: A list entry, or None if the list is empty. ''' if len(self.table)==0: return None else: if last: return self.table[len(self.table)-1] else: return self.table[0]
[ "def", "returnOneEntry", "(", "self", ",", "last", "=", "False", ")", ":", "if", "len", "(", "self", ".", "table", ")", "==", "0", ":", "return", "None", "else", ":", "if", "last", ":", "return", "self", ".", "table", "[", "len", "(", "self", ".", "table", ")", "-", "1", "]", "else", ":", "return", "self", ".", "table", "[", "0", "]" ]
Return the first entry in the current list. If 'last=True', then the last entry is returned." Returns None is the list is empty. Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "order": 2}, ... {"name": "Larry", "age": 18, "order": 3}, ... {"name": "Joe", "age": 20, "income": 15000, "order": 1}, ... {"name": "Bill", "age": 19, "income": 29000, "order": 4}, ... ] >>> print PLOD(test).returnOneEntry() {'age': 18, 'order': 2, 'name': 'Jim', 'income': 93000} >>> print PLOD(test).returnOneEntry(last=True) {'age': 19, 'order': 4, 'name': 'Bill', 'income': 29000} :param last: If True, the last entry is returned rather than the first. :return: A list entry, or None if the list is empty.
[ "Return", "the", "first", "entry", "in", "the", "current", "list", ".", "If", "last", "=", "True", "then", "the", "last", "entry", "is", "returned", "." ]
707502cd928e5be6bd5e46d7f6de7da0e188cf1e
https://github.com/MakerReduxCorp/PLOD/blob/707502cd928e5be6bd5e46d7f6de7da0e188cf1e/PLOD/__init__.py#L1269-L1299
244,458
MakerReduxCorp/PLOD
PLOD/__init__.py
PLOD.returnValue
def returnValue(self, key, last=False): '''Return the key's value for the first entry in the current list. If 'last=True', then the last entry is referenced." Returns None is the list is empty or the key is missing. Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "order": 2}, ... {"name": "Larry", "age": 18, "order": 3}, ... {"name": "Joe", "age": 20, "income": 15000, "order": 1}, ... {"name": "Bill", "age": 19, "income": 29000, "order": 4}, ... ] >>> print PLOD(test).returnValue("name") Jim >>> print PLOD(test).sort("name").returnValue("name", last=True) Larry >>> print PLOD(test).sort("name").returnValue("income", last=True) None :param last: If True, the last entry is used rather than the first. :return: A value, or None if the list is empty or the key is missing. ''' row = self.returnOneEntry(last=last) if not row: return None dict_row = internal.convert_to_dict(row) return dict_row.get(key, None)
python
def returnValue(self, key, last=False): '''Return the key's value for the first entry in the current list. If 'last=True', then the last entry is referenced." Returns None is the list is empty or the key is missing. Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "order": 2}, ... {"name": "Larry", "age": 18, "order": 3}, ... {"name": "Joe", "age": 20, "income": 15000, "order": 1}, ... {"name": "Bill", "age": 19, "income": 29000, "order": 4}, ... ] >>> print PLOD(test).returnValue("name") Jim >>> print PLOD(test).sort("name").returnValue("name", last=True) Larry >>> print PLOD(test).sort("name").returnValue("income", last=True) None :param last: If True, the last entry is used rather than the first. :return: A value, or None if the list is empty or the key is missing. ''' row = self.returnOneEntry(last=last) if not row: return None dict_row = internal.convert_to_dict(row) return dict_row.get(key, None)
[ "def", "returnValue", "(", "self", ",", "key", ",", "last", "=", "False", ")", ":", "row", "=", "self", ".", "returnOneEntry", "(", "last", "=", "last", ")", "if", "not", "row", ":", "return", "None", "dict_row", "=", "internal", ".", "convert_to_dict", "(", "row", ")", "return", "dict_row", ".", "get", "(", "key", ",", "None", ")" ]
Return the key's value for the first entry in the current list. If 'last=True', then the last entry is referenced." Returns None is the list is empty or the key is missing. Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "order": 2}, ... {"name": "Larry", "age": 18, "order": 3}, ... {"name": "Joe", "age": 20, "income": 15000, "order": 1}, ... {"name": "Bill", "age": 19, "income": 29000, "order": 4}, ... ] >>> print PLOD(test).returnValue("name") Jim >>> print PLOD(test).sort("name").returnValue("name", last=True) Larry >>> print PLOD(test).sort("name").returnValue("income", last=True) None :param last: If True, the last entry is used rather than the first. :return: A value, or None if the list is empty or the key is missing.
[ "Return", "the", "key", "s", "value", "for", "the", "first", "entry", "in", "the", "current", "list", ".", "If", "last", "=", "True", "then", "the", "last", "entry", "is", "referenced", "." ]
707502cd928e5be6bd5e46d7f6de7da0e188cf1e
https://github.com/MakerReduxCorp/PLOD/blob/707502cd928e5be6bd5e46d7f6de7da0e188cf1e/PLOD/__init__.py#L1301-L1331
244,459
MakerReduxCorp/PLOD
PLOD/__init__.py
PLOD.returnValueList
def returnValueList(self, key_list, last=False): '''Return a list of key values for the first entry in the current list. If 'last=True', then the last entry is referenced." Returns None is the list is empty. If a key is missing, then that entry in the list is None. Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "order": 2}, ... {"name": "Larry", "age": 18, "order": 3}, ... {"name": "Joe", "age": 20, "income": 15000, "order": 1}, ... {"name": "Bill", "age": 19, "income": 29000, "order": 4}, ... ] >>> print PLOD(test).returnValueList(["name", "income"]) ['Jim', 93000] >>> print PLOD(test).sort("name").returnValueList(["name", "income"], last=True) ['Larry', None] :param last: If True, the last entry is used rather than the first. :return: A value, or None if the list is empty. ''' result = [] row = self.returnOneEntry(last=last) if not row: return None dict_row = internal.convert_to_dict(row) for field in key_list: result.append(dict_row.get(field, None)) return result
python
def returnValueList(self, key_list, last=False): '''Return a list of key values for the first entry in the current list. If 'last=True', then the last entry is referenced." Returns None is the list is empty. If a key is missing, then that entry in the list is None. Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "order": 2}, ... {"name": "Larry", "age": 18, "order": 3}, ... {"name": "Joe", "age": 20, "income": 15000, "order": 1}, ... {"name": "Bill", "age": 19, "income": 29000, "order": 4}, ... ] >>> print PLOD(test).returnValueList(["name", "income"]) ['Jim', 93000] >>> print PLOD(test).sort("name").returnValueList(["name", "income"], last=True) ['Larry', None] :param last: If True, the last entry is used rather than the first. :return: A value, or None if the list is empty. ''' result = [] row = self.returnOneEntry(last=last) if not row: return None dict_row = internal.convert_to_dict(row) for field in key_list: result.append(dict_row.get(field, None)) return result
[ "def", "returnValueList", "(", "self", ",", "key_list", ",", "last", "=", "False", ")", ":", "result", "=", "[", "]", "row", "=", "self", ".", "returnOneEntry", "(", "last", "=", "last", ")", "if", "not", "row", ":", "return", "None", "dict_row", "=", "internal", ".", "convert_to_dict", "(", "row", ")", "for", "field", "in", "key_list", ":", "result", ".", "append", "(", "dict_row", ".", "get", "(", "field", ",", "None", ")", ")", "return", "result" ]
Return a list of key values for the first entry in the current list. If 'last=True', then the last entry is referenced." Returns None is the list is empty. If a key is missing, then that entry in the list is None. Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "order": 2}, ... {"name": "Larry", "age": 18, "order": 3}, ... {"name": "Joe", "age": 20, "income": 15000, "order": 1}, ... {"name": "Bill", "age": 19, "income": 29000, "order": 4}, ... ] >>> print PLOD(test).returnValueList(["name", "income"]) ['Jim', 93000] >>> print PLOD(test).sort("name").returnValueList(["name", "income"], last=True) ['Larry', None] :param last: If True, the last entry is used rather than the first. :return: A value, or None if the list is empty.
[ "Return", "a", "list", "of", "key", "values", "for", "the", "first", "entry", "in", "the", "current", "list", ".", "If", "last", "=", "True", "then", "the", "last", "entry", "is", "referenced", "." ]
707502cd928e5be6bd5e46d7f6de7da0e188cf1e
https://github.com/MakerReduxCorp/PLOD/blob/707502cd928e5be6bd5e46d7f6de7da0e188cf1e/PLOD/__init__.py#L1333-L1365
244,460
theirc/rapidsms-multitenancy
multitenancy/admin.py
TenantGroupAdmin.get_queryset
def get_queryset(self, request): """Limit to TenantGroups that this user can access.""" qs = super(TenantGroupAdmin, self).get_queryset(request) if not request.user.is_superuser: qs = qs.filter(tenantrole__user=request.user, tenantrole__role=TenantRole.ROLE_GROUP_MANAGER) return qs
python
def get_queryset(self, request): """Limit to TenantGroups that this user can access.""" qs = super(TenantGroupAdmin, self).get_queryset(request) if not request.user.is_superuser: qs = qs.filter(tenantrole__user=request.user, tenantrole__role=TenantRole.ROLE_GROUP_MANAGER) return qs
[ "def", "get_queryset", "(", "self", ",", "request", ")", ":", "qs", "=", "super", "(", "TenantGroupAdmin", ",", "self", ")", ".", "get_queryset", "(", "request", ")", "if", "not", "request", ".", "user", ".", "is_superuser", ":", "qs", "=", "qs", ".", "filter", "(", "tenantrole__user", "=", "request", ".", "user", ",", "tenantrole__role", "=", "TenantRole", ".", "ROLE_GROUP_MANAGER", ")", "return", "qs" ]
Limit to TenantGroups that this user can access.
[ "Limit", "to", "TenantGroups", "that", "this", "user", "can", "access", "." ]
121bd0a628e691a88aade2e10045cba43af2dfcb
https://github.com/theirc/rapidsms-multitenancy/blob/121bd0a628e691a88aade2e10045cba43af2dfcb/multitenancy/admin.py#L67-L73
244,461
theirc/rapidsms-multitenancy
multitenancy/admin.py
TenantAdmin.get_queryset
def get_queryset(self, request): """Limit to Tenants that this user can access.""" qs = super(TenantAdmin, self).get_queryset(request) if not request.user.is_superuser: tenants_by_group_manager_role = qs.filter( group__tenantrole__user=request.user, group__tenantrole__role=TenantRole.ROLE_GROUP_MANAGER ) tenants_by_tenant_manager_role = qs.filter( tenantrole__user=request.user, tenantrole__role=TenantRole.ROLE_TENANT_MANAGER ) return tenants_by_group_manager_role | tenants_by_tenant_manager_role return qs
python
def get_queryset(self, request): """Limit to Tenants that this user can access.""" qs = super(TenantAdmin, self).get_queryset(request) if not request.user.is_superuser: tenants_by_group_manager_role = qs.filter( group__tenantrole__user=request.user, group__tenantrole__role=TenantRole.ROLE_GROUP_MANAGER ) tenants_by_tenant_manager_role = qs.filter( tenantrole__user=request.user, tenantrole__role=TenantRole.ROLE_TENANT_MANAGER ) return tenants_by_group_manager_role | tenants_by_tenant_manager_role return qs
[ "def", "get_queryset", "(", "self", ",", "request", ")", ":", "qs", "=", "super", "(", "TenantAdmin", ",", "self", ")", ".", "get_queryset", "(", "request", ")", "if", "not", "request", ".", "user", ".", "is_superuser", ":", "tenants_by_group_manager_role", "=", "qs", ".", "filter", "(", "group__tenantrole__user", "=", "request", ".", "user", ",", "group__tenantrole__role", "=", "TenantRole", ".", "ROLE_GROUP_MANAGER", ")", "tenants_by_tenant_manager_role", "=", "qs", ".", "filter", "(", "tenantrole__user", "=", "request", ".", "user", ",", "tenantrole__role", "=", "TenantRole", ".", "ROLE_TENANT_MANAGER", ")", "return", "tenants_by_group_manager_role", "|", "tenants_by_tenant_manager_role", "return", "qs" ]
Limit to Tenants that this user can access.
[ "Limit", "to", "Tenants", "that", "this", "user", "can", "access", "." ]
121bd0a628e691a88aade2e10045cba43af2dfcb
https://github.com/theirc/rapidsms-multitenancy/blob/121bd0a628e691a88aade2e10045cba43af2dfcb/multitenancy/admin.py#L129-L142
244,462
ronaldguillen/wave
wave/parsers.py
FormParser.parse
def parse(self, stream, media_type=None, parser_context=None): """ Parses the incoming bytestream as a URL encoded form, and returns the resulting QueryDict. """ parser_context = parser_context or {} encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET) data = QueryDict(stream.read(), encoding=encoding) return data
python
def parse(self, stream, media_type=None, parser_context=None): """ Parses the incoming bytestream as a URL encoded form, and returns the resulting QueryDict. """ parser_context = parser_context or {} encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET) data = QueryDict(stream.read(), encoding=encoding) return data
[ "def", "parse", "(", "self", ",", "stream", ",", "media_type", "=", "None", ",", "parser_context", "=", "None", ")", ":", "parser_context", "=", "parser_context", "or", "{", "}", "encoding", "=", "parser_context", ".", "get", "(", "'encoding'", ",", "settings", ".", "DEFAULT_CHARSET", ")", "data", "=", "QueryDict", "(", "stream", ".", "read", "(", ")", ",", "encoding", "=", "encoding", ")", "return", "data" ]
Parses the incoming bytestream as a URL encoded form, and returns the resulting QueryDict.
[ "Parses", "the", "incoming", "bytestream", "as", "a", "URL", "encoded", "form", "and", "returns", "the", "resulting", "QueryDict", "." ]
20bb979c917f7634d8257992e6d449dc751256a9
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/parsers.py#L79-L87
244,463
ronaldguillen/wave
wave/parsers.py
MultiPartParser.parse
def parse(self, stream, media_type=None, parser_context=None): """ Parses the incoming bytestream as a multipart encoded form, and returns a DataAndFiles object. `.data` will be a `QueryDict` containing all the form parameters. `.files` will be a `QueryDict` containing all the form files. """ parser_context = parser_context or {} request = parser_context['request'] encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET) meta = request.META.copy() meta['CONTENT_TYPE'] = media_type upload_handlers = request.upload_handlers try: parser = DjangoMultiPartParser(meta, stream, upload_handlers, encoding) data, files = parser.parse() return DataAndFiles(data, files) except MultiPartParserError as exc: raise ParseError('Multipart form parse error - %s' % six.text_type(exc))
python
def parse(self, stream, media_type=None, parser_context=None): """ Parses the incoming bytestream as a multipart encoded form, and returns a DataAndFiles object. `.data` will be a `QueryDict` containing all the form parameters. `.files` will be a `QueryDict` containing all the form files. """ parser_context = parser_context or {} request = parser_context['request'] encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET) meta = request.META.copy() meta['CONTENT_TYPE'] = media_type upload_handlers = request.upload_handlers try: parser = DjangoMultiPartParser(meta, stream, upload_handlers, encoding) data, files = parser.parse() return DataAndFiles(data, files) except MultiPartParserError as exc: raise ParseError('Multipart form parse error - %s' % six.text_type(exc))
[ "def", "parse", "(", "self", ",", "stream", ",", "media_type", "=", "None", ",", "parser_context", "=", "None", ")", ":", "parser_context", "=", "parser_context", "or", "{", "}", "request", "=", "parser_context", "[", "'request'", "]", "encoding", "=", "parser_context", ".", "get", "(", "'encoding'", ",", "settings", ".", "DEFAULT_CHARSET", ")", "meta", "=", "request", ".", "META", ".", "copy", "(", ")", "meta", "[", "'CONTENT_TYPE'", "]", "=", "media_type", "upload_handlers", "=", "request", ".", "upload_handlers", "try", ":", "parser", "=", "DjangoMultiPartParser", "(", "meta", ",", "stream", ",", "upload_handlers", ",", "encoding", ")", "data", ",", "files", "=", "parser", ".", "parse", "(", ")", "return", "DataAndFiles", "(", "data", ",", "files", ")", "except", "MultiPartParserError", "as", "exc", ":", "raise", "ParseError", "(", "'Multipart form parse error - %s'", "%", "six", ".", "text_type", "(", "exc", ")", ")" ]
Parses the incoming bytestream as a multipart encoded form, and returns a DataAndFiles object. `.data` will be a `QueryDict` containing all the form parameters. `.files` will be a `QueryDict` containing all the form files.
[ "Parses", "the", "incoming", "bytestream", "as", "a", "multipart", "encoded", "form", "and", "returns", "a", "DataAndFiles", "object", "." ]
20bb979c917f7634d8257992e6d449dc751256a9
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/parsers.py#L97-L117
244,464
ronaldguillen/wave
wave/parsers.py
FileUploadParser.parse
def parse(self, stream, media_type=None, parser_context=None): """ Treats the incoming bytestream as a raw file upload and returns a `DataAndFiles` object. `.data` will be None (we expect request body to be a file content). `.files` will be a `QueryDict` containing one 'file' element. """ parser_context = parser_context or {} request = parser_context['request'] encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET) meta = request.META upload_handlers = request.upload_handlers filename = self.get_filename(stream, media_type, parser_context) # Note that this code is extracted from Django's handling of # file uploads in MultiPartParser. content_type = meta.get('HTTP_CONTENT_TYPE', meta.get('CONTENT_TYPE', '')) try: content_length = int(meta.get('HTTP_CONTENT_LENGTH', meta.get('CONTENT_LENGTH', 0))) except (ValueError, TypeError): content_length = None # See if the handler will want to take care of the parsing. for handler in upload_handlers: result = handler.handle_raw_input(None, meta, content_length, None, encoding) if result is not None: return DataAndFiles({}, {'file': result[1]}) # This is the standard case. possible_sizes = [x.chunk_size for x in upload_handlers if x.chunk_size] chunk_size = min([2 ** 31 - 4] + possible_sizes) chunks = ChunkIter(stream, chunk_size) counters = [0] * len(upload_handlers) for index, handler in enumerate(upload_handlers): try: handler.new_file(None, filename, content_type, content_length, encoding) except StopFutureHandlers: upload_handlers = upload_handlers[:index + 1] break for chunk in chunks: for index, handler in enumerate(upload_handlers): chunk_length = len(chunk) chunk = handler.receive_data_chunk(chunk, counters[index]) counters[index] += chunk_length if chunk is None: break for index, handler in enumerate(upload_handlers): file_obj = handler.file_complete(counters[index]) if file_obj: return DataAndFiles({}, {'file': file_obj}) raise ParseError("FileUpload parse error - " "none of upload handlers can handle the stream")
python
def parse(self, stream, media_type=None, parser_context=None): """ Treats the incoming bytestream as a raw file upload and returns a `DataAndFiles` object. `.data` will be None (we expect request body to be a file content). `.files` will be a `QueryDict` containing one 'file' element. """ parser_context = parser_context or {} request = parser_context['request'] encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET) meta = request.META upload_handlers = request.upload_handlers filename = self.get_filename(stream, media_type, parser_context) # Note that this code is extracted from Django's handling of # file uploads in MultiPartParser. content_type = meta.get('HTTP_CONTENT_TYPE', meta.get('CONTENT_TYPE', '')) try: content_length = int(meta.get('HTTP_CONTENT_LENGTH', meta.get('CONTENT_LENGTH', 0))) except (ValueError, TypeError): content_length = None # See if the handler will want to take care of the parsing. for handler in upload_handlers: result = handler.handle_raw_input(None, meta, content_length, None, encoding) if result is not None: return DataAndFiles({}, {'file': result[1]}) # This is the standard case. possible_sizes = [x.chunk_size for x in upload_handlers if x.chunk_size] chunk_size = min([2 ** 31 - 4] + possible_sizes) chunks = ChunkIter(stream, chunk_size) counters = [0] * len(upload_handlers) for index, handler in enumerate(upload_handlers): try: handler.new_file(None, filename, content_type, content_length, encoding) except StopFutureHandlers: upload_handlers = upload_handlers[:index + 1] break for chunk in chunks: for index, handler in enumerate(upload_handlers): chunk_length = len(chunk) chunk = handler.receive_data_chunk(chunk, counters[index]) counters[index] += chunk_length if chunk is None: break for index, handler in enumerate(upload_handlers): file_obj = handler.file_complete(counters[index]) if file_obj: return DataAndFiles({}, {'file': file_obj}) raise ParseError("FileUpload parse error - " "none of upload handlers can handle the stream")
[ "def", "parse", "(", "self", ",", "stream", ",", "media_type", "=", "None", ",", "parser_context", "=", "None", ")", ":", "parser_context", "=", "parser_context", "or", "{", "}", "request", "=", "parser_context", "[", "'request'", "]", "encoding", "=", "parser_context", ".", "get", "(", "'encoding'", ",", "settings", ".", "DEFAULT_CHARSET", ")", "meta", "=", "request", ".", "META", "upload_handlers", "=", "request", ".", "upload_handlers", "filename", "=", "self", ".", "get_filename", "(", "stream", ",", "media_type", ",", "parser_context", ")", "# Note that this code is extracted from Django's handling of", "# file uploads in MultiPartParser.", "content_type", "=", "meta", ".", "get", "(", "'HTTP_CONTENT_TYPE'", ",", "meta", ".", "get", "(", "'CONTENT_TYPE'", ",", "''", ")", ")", "try", ":", "content_length", "=", "int", "(", "meta", ".", "get", "(", "'HTTP_CONTENT_LENGTH'", ",", "meta", ".", "get", "(", "'CONTENT_LENGTH'", ",", "0", ")", ")", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "content_length", "=", "None", "# See if the handler will want to take care of the parsing.", "for", "handler", "in", "upload_handlers", ":", "result", "=", "handler", ".", "handle_raw_input", "(", "None", ",", "meta", ",", "content_length", ",", "None", ",", "encoding", ")", "if", "result", "is", "not", "None", ":", "return", "DataAndFiles", "(", "{", "}", ",", "{", "'file'", ":", "result", "[", "1", "]", "}", ")", "# This is the standard case.", "possible_sizes", "=", "[", "x", ".", "chunk_size", "for", "x", "in", "upload_handlers", "if", "x", ".", "chunk_size", "]", "chunk_size", "=", "min", "(", "[", "2", "**", "31", "-", "4", "]", "+", "possible_sizes", ")", "chunks", "=", "ChunkIter", "(", "stream", ",", "chunk_size", ")", "counters", "=", "[", "0", "]", "*", "len", "(", "upload_handlers", ")", "for", "index", ",", "handler", "in", "enumerate", "(", "upload_handlers", ")", ":", "try", ":", "handler", ".", "new_file", "(", "None", ",", "filename", ",", "content_type", ",", "content_length", ",", "encoding", ")", "except", "StopFutureHandlers", ":", "upload_handlers", "=", "upload_handlers", "[", ":", "index", "+", "1", "]", "break", "for", "chunk", "in", "chunks", ":", "for", "index", ",", "handler", "in", "enumerate", "(", "upload_handlers", ")", ":", "chunk_length", "=", "len", "(", "chunk", ")", "chunk", "=", "handler", ".", "receive_data_chunk", "(", "chunk", ",", "counters", "[", "index", "]", ")", "counters", "[", "index", "]", "+=", "chunk_length", "if", "chunk", "is", "None", ":", "break", "for", "index", ",", "handler", "in", "enumerate", "(", "upload_handlers", ")", ":", "file_obj", "=", "handler", ".", "file_complete", "(", "counters", "[", "index", "]", ")", "if", "file_obj", ":", "return", "DataAndFiles", "(", "{", "}", ",", "{", "'file'", ":", "file_obj", "}", ")", "raise", "ParseError", "(", "\"FileUpload parse error - \"", "\"none of upload handlers can handle the stream\"", ")" ]
Treats the incoming bytestream as a raw file upload and returns a `DataAndFiles` object. `.data` will be None (we expect request body to be a file content). `.files` will be a `QueryDict` containing one 'file' element.
[ "Treats", "the", "incoming", "bytestream", "as", "a", "raw", "file", "upload", "and", "returns", "a", "DataAndFiles", "object", "." ]
20bb979c917f7634d8257992e6d449dc751256a9
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/parsers.py#L126-L189
244,465
ronaldguillen/wave
wave/parsers.py
FileUploadParser.get_filename
def get_filename(self, stream, media_type, parser_context): """ Detects the uploaded file name. First searches a 'filename' url kwarg. Then tries to parse Content-Disposition header. """ try: return parser_context['kwargs']['filename'] except KeyError: pass try: meta = parser_context['request'].META disposition = parse_header(meta['HTTP_CONTENT_DISPOSITION'].encode('utf-8')) filename_parm = disposition[1] if 'filename*' in filename_parm: return self.get_encoded_filename(filename_parm) return force_text(filename_parm['filename']) except (AttributeError, KeyError, ValueError): pass
python
def get_filename(self, stream, media_type, parser_context): """ Detects the uploaded file name. First searches a 'filename' url kwarg. Then tries to parse Content-Disposition header. """ try: return parser_context['kwargs']['filename'] except KeyError: pass try: meta = parser_context['request'].META disposition = parse_header(meta['HTTP_CONTENT_DISPOSITION'].encode('utf-8')) filename_parm = disposition[1] if 'filename*' in filename_parm: return self.get_encoded_filename(filename_parm) return force_text(filename_parm['filename']) except (AttributeError, KeyError, ValueError): pass
[ "def", "get_filename", "(", "self", ",", "stream", ",", "media_type", ",", "parser_context", ")", ":", "try", ":", "return", "parser_context", "[", "'kwargs'", "]", "[", "'filename'", "]", "except", "KeyError", ":", "pass", "try", ":", "meta", "=", "parser_context", "[", "'request'", "]", ".", "META", "disposition", "=", "parse_header", "(", "meta", "[", "'HTTP_CONTENT_DISPOSITION'", "]", ".", "encode", "(", "'utf-8'", ")", ")", "filename_parm", "=", "disposition", "[", "1", "]", "if", "'filename*'", "in", "filename_parm", ":", "return", "self", ".", "get_encoded_filename", "(", "filename_parm", ")", "return", "force_text", "(", "filename_parm", "[", "'filename'", "]", ")", "except", "(", "AttributeError", ",", "KeyError", ",", "ValueError", ")", ":", "pass" ]
Detects the uploaded file name. First searches a 'filename' url kwarg. Then tries to parse Content-Disposition header.
[ "Detects", "the", "uploaded", "file", "name", ".", "First", "searches", "a", "filename", "url", "kwarg", ".", "Then", "tries", "to", "parse", "Content", "-", "Disposition", "header", "." ]
20bb979c917f7634d8257992e6d449dc751256a9
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/parsers.py#L191-L209
244,466
edwards-lab/MVtest
meanvar/mvstandardizer.py
Standardizer.destandardize
def destandardize(self, estimates, se, **kwargs): """Revert the betas and variance components back to the original scale. """ pvalues = kwargs["pvalues"] v = kwargs["v"] nonmissing=kwargs["nonmissing"] pheno = self.datasource.phenotype_data[self.idx][self.datasource.phenotype_data[self.idx] != PhenoCovar.missing_encoding] covariates = [] mmx = [] ssx = [] a = [1,0] for c in self.datasource.covariate_data: covariates.append(c[c!=PhenoCovar.missing_encoding]) mmx.append(numpy.mean(covariates[-1])) ssx.append(numpy.std(covariates[-1])) a.append(-mmx[-1]/ssx[-1]) if len(mmx) < 1: mmx = 1 ssx = 1 else: mmx = numpy.array(mmx) ssx = numpy.array(ssx) covariates = numpy.array(covariates) ssy = numpy.std(pheno) mmy = numpy.mean(pheno) # Quick scratch pad for Chun's new destandardization ccount = len(covariates) + 2 a=numpy.array(a) meanpar = list([mmy + ssy * (estimates[0] - numpy.sum(estimates[2:ccount]*mmx/ssx)), estimates[1] * ssy]) meanse = [ssy*numpy.sqrt(a.dot(v[0:ccount, 0:ccount]).dot(a.transpose())), ssy * se[1]] varpar = [2*numpy.log(ssy) + estimates[ccount] - numpy.sum(estimates[ccount+2:]*mmx/ssx), estimates[ccount+1]] varse = [numpy.sqrt(a.dot(v[ccount:, ccount:]).dot(a.transpose())), se[ccount+1]] if ccount > 2: meanpar += list(estimates[2:ccount] * ssy / ssx) meanse += list(ssy * se[2:ccount]/ssx) varpar += list(estimates[ccount+2:]/ssx) varse += list(se[ccount+2:]/ssx) pvals = 2*scipy.stats.norm.cdf(-numpy.absolute(numpy.array(meanpar+varpar)/numpy.array(meanse+varse))) return meanpar+varpar, meanse + varse, pvals
python
def destandardize(self, estimates, se, **kwargs): """Revert the betas and variance components back to the original scale. """ pvalues = kwargs["pvalues"] v = kwargs["v"] nonmissing=kwargs["nonmissing"] pheno = self.datasource.phenotype_data[self.idx][self.datasource.phenotype_data[self.idx] != PhenoCovar.missing_encoding] covariates = [] mmx = [] ssx = [] a = [1,0] for c in self.datasource.covariate_data: covariates.append(c[c!=PhenoCovar.missing_encoding]) mmx.append(numpy.mean(covariates[-1])) ssx.append(numpy.std(covariates[-1])) a.append(-mmx[-1]/ssx[-1]) if len(mmx) < 1: mmx = 1 ssx = 1 else: mmx = numpy.array(mmx) ssx = numpy.array(ssx) covariates = numpy.array(covariates) ssy = numpy.std(pheno) mmy = numpy.mean(pheno) # Quick scratch pad for Chun's new destandardization ccount = len(covariates) + 2 a=numpy.array(a) meanpar = list([mmy + ssy * (estimates[0] - numpy.sum(estimates[2:ccount]*mmx/ssx)), estimates[1] * ssy]) meanse = [ssy*numpy.sqrt(a.dot(v[0:ccount, 0:ccount]).dot(a.transpose())), ssy * se[1]] varpar = [2*numpy.log(ssy) + estimates[ccount] - numpy.sum(estimates[ccount+2:]*mmx/ssx), estimates[ccount+1]] varse = [numpy.sqrt(a.dot(v[ccount:, ccount:]).dot(a.transpose())), se[ccount+1]] if ccount > 2: meanpar += list(estimates[2:ccount] * ssy / ssx) meanse += list(ssy * se[2:ccount]/ssx) varpar += list(estimates[ccount+2:]/ssx) varse += list(se[ccount+2:]/ssx) pvals = 2*scipy.stats.norm.cdf(-numpy.absolute(numpy.array(meanpar+varpar)/numpy.array(meanse+varse))) return meanpar+varpar, meanse + varse, pvals
[ "def", "destandardize", "(", "self", ",", "estimates", ",", "se", ",", "*", "*", "kwargs", ")", ":", "pvalues", "=", "kwargs", "[", "\"pvalues\"", "]", "v", "=", "kwargs", "[", "\"v\"", "]", "nonmissing", "=", "kwargs", "[", "\"nonmissing\"", "]", "pheno", "=", "self", ".", "datasource", ".", "phenotype_data", "[", "self", ".", "idx", "]", "[", "self", ".", "datasource", ".", "phenotype_data", "[", "self", ".", "idx", "]", "!=", "PhenoCovar", ".", "missing_encoding", "]", "covariates", "=", "[", "]", "mmx", "=", "[", "]", "ssx", "=", "[", "]", "a", "=", "[", "1", ",", "0", "]", "for", "c", "in", "self", ".", "datasource", ".", "covariate_data", ":", "covariates", ".", "append", "(", "c", "[", "c", "!=", "PhenoCovar", ".", "missing_encoding", "]", ")", "mmx", ".", "append", "(", "numpy", ".", "mean", "(", "covariates", "[", "-", "1", "]", ")", ")", "ssx", ".", "append", "(", "numpy", ".", "std", "(", "covariates", "[", "-", "1", "]", ")", ")", "a", ".", "append", "(", "-", "mmx", "[", "-", "1", "]", "/", "ssx", "[", "-", "1", "]", ")", "if", "len", "(", "mmx", ")", "<", "1", ":", "mmx", "=", "1", "ssx", "=", "1", "else", ":", "mmx", "=", "numpy", ".", "array", "(", "mmx", ")", "ssx", "=", "numpy", ".", "array", "(", "ssx", ")", "covariates", "=", "numpy", ".", "array", "(", "covariates", ")", "ssy", "=", "numpy", ".", "std", "(", "pheno", ")", "mmy", "=", "numpy", ".", "mean", "(", "pheno", ")", "# Quick scratch pad for Chun's new destandardization", "ccount", "=", "len", "(", "covariates", ")", "+", "2", "a", "=", "numpy", ".", "array", "(", "a", ")", "meanpar", "=", "list", "(", "[", "mmy", "+", "ssy", "*", "(", "estimates", "[", "0", "]", "-", "numpy", ".", "sum", "(", "estimates", "[", "2", ":", "ccount", "]", "*", "mmx", "/", "ssx", ")", ")", ",", "estimates", "[", "1", "]", "*", "ssy", "]", ")", "meanse", "=", "[", "ssy", "*", "numpy", ".", "sqrt", "(", "a", ".", "dot", "(", "v", "[", "0", ":", "ccount", ",", "0", ":", "ccount", "]", ")", ".", "dot", "(", "a", ".", "transpose", "(", ")", ")", ")", ",", "ssy", "*", "se", "[", "1", "]", "]", "varpar", "=", "[", "2", "*", "numpy", ".", "log", "(", "ssy", ")", "+", "estimates", "[", "ccount", "]", "-", "numpy", ".", "sum", "(", "estimates", "[", "ccount", "+", "2", ":", "]", "*", "mmx", "/", "ssx", ")", ",", "estimates", "[", "ccount", "+", "1", "]", "]", "varse", "=", "[", "numpy", ".", "sqrt", "(", "a", ".", "dot", "(", "v", "[", "ccount", ":", ",", "ccount", ":", "]", ")", ".", "dot", "(", "a", ".", "transpose", "(", ")", ")", ")", ",", "se", "[", "ccount", "+", "1", "]", "]", "if", "ccount", ">", "2", ":", "meanpar", "+=", "list", "(", "estimates", "[", "2", ":", "ccount", "]", "*", "ssy", "/", "ssx", ")", "meanse", "+=", "list", "(", "ssy", "*", "se", "[", "2", ":", "ccount", "]", "/", "ssx", ")", "varpar", "+=", "list", "(", "estimates", "[", "ccount", "+", "2", ":", "]", "/", "ssx", ")", "varse", "+=", "list", "(", "se", "[", "ccount", "+", "2", ":", "]", "/", "ssx", ")", "pvals", "=", "2", "*", "scipy", ".", "stats", ".", "norm", ".", "cdf", "(", "-", "numpy", ".", "absolute", "(", "numpy", ".", "array", "(", "meanpar", "+", "varpar", ")", "/", "numpy", ".", "array", "(", "meanse", "+", "varse", ")", ")", ")", "return", "meanpar", "+", "varpar", ",", "meanse", "+", "varse", ",", "pvals" ]
Revert the betas and variance components back to the original scale.
[ "Revert", "the", "betas", "and", "variance", "components", "back", "to", "the", "original", "scale", "." ]
fe8cf627464ef59d68b7eda628a19840d033882f
https://github.com/edwards-lab/MVtest/blob/fe8cf627464ef59d68b7eda628a19840d033882f/meanvar/mvstandardizer.py#L71-L121
244,467
yougov/vr.builder
vr/builder/models.py
App.tar
def tar(self, appname, appversion): """ Given an app name and version to be used in the tarball name, create a tar.bz2 file with all of this folder's contents inside. Return a Build object with attributes for appname, appversion, time, and path. """ name_tmpl = '%(app)s-%(version)s-%(time)s.tar.bz2' time = utc.now() name = name_tmpl % {'app': appname, 'version': appversion, 'time': time.strftime('%Y-%m-%dT%H-%M')} if not os.path.exists(TARBALL_HOME): os.mkdir(TARBALL_HOME) tarball = os.path.join(TARBALL_HOME, name) tar_params = {'filename': tarball, 'folder': self.folder} tar_result = run('tar -C %(folder)s -cjf %(filename)s .' % tar_params) tar_result.raise_for_status() return Build(appname, appversion, time, tarball)
python
def tar(self, appname, appversion): """ Given an app name and version to be used in the tarball name, create a tar.bz2 file with all of this folder's contents inside. Return a Build object with attributes for appname, appversion, time, and path. """ name_tmpl = '%(app)s-%(version)s-%(time)s.tar.bz2' time = utc.now() name = name_tmpl % {'app': appname, 'version': appversion, 'time': time.strftime('%Y-%m-%dT%H-%M')} if not os.path.exists(TARBALL_HOME): os.mkdir(TARBALL_HOME) tarball = os.path.join(TARBALL_HOME, name) tar_params = {'filename': tarball, 'folder': self.folder} tar_result = run('tar -C %(folder)s -cjf %(filename)s .' % tar_params) tar_result.raise_for_status() return Build(appname, appversion, time, tarball)
[ "def", "tar", "(", "self", ",", "appname", ",", "appversion", ")", ":", "name_tmpl", "=", "'%(app)s-%(version)s-%(time)s.tar.bz2'", "time", "=", "utc", ".", "now", "(", ")", "name", "=", "name_tmpl", "%", "{", "'app'", ":", "appname", ",", "'version'", ":", "appversion", ",", "'time'", ":", "time", ".", "strftime", "(", "'%Y-%m-%dT%H-%M'", ")", "}", "if", "not", "os", ".", "path", ".", "exists", "(", "TARBALL_HOME", ")", ":", "os", ".", "mkdir", "(", "TARBALL_HOME", ")", "tarball", "=", "os", ".", "path", ".", "join", "(", "TARBALL_HOME", ",", "name", ")", "tar_params", "=", "{", "'filename'", ":", "tarball", ",", "'folder'", ":", "self", ".", "folder", "}", "tar_result", "=", "run", "(", "'tar -C %(folder)s -cjf %(filename)s .'", "%", "tar_params", ")", "tar_result", ".", "raise_for_status", "(", ")", "return", "Build", "(", "appname", ",", "appversion", ",", "time", ",", "tarball", ")" ]
Given an app name and version to be used in the tarball name, create a tar.bz2 file with all of this folder's contents inside. Return a Build object with attributes for appname, appversion, time, and path.
[ "Given", "an", "app", "name", "and", "version", "to", "be", "used", "in", "the", "tarball", "name", "create", "a", "tar", ".", "bz2", "file", "with", "all", "of", "this", "folder", "s", "contents", "inside", "." ]
666b28f997d0cff52e82eed4ace1c73fee4b2136
https://github.com/yougov/vr.builder/blob/666b28f997d0cff52e82eed4ace1c73fee4b2136/vr/builder/models.py#L94-L114
244,468
rosenbrockc/acorn
acorn/config.py
config_dir
def config_dir(mkcustom=False): """Returns the configuration directory for custom package settings. """ from acorn.utility import reporoot from acorn.base import testmode from os import path alternate = path.join(path.abspath(path.expanduser("~")), ".acorn") if testmode or (not path.isdir(alternate) and not mkcustom): return path.join(reporoot, "acorn", "config") else: if mkcustom:# pragma: no cover #This never gets reached when we are in testmode because we don't #want to clobber the user's local config cache. from os import mkdir mkdir(alternate) return alternate
python
def config_dir(mkcustom=False): """Returns the configuration directory for custom package settings. """ from acorn.utility import reporoot from acorn.base import testmode from os import path alternate = path.join(path.abspath(path.expanduser("~")), ".acorn") if testmode or (not path.isdir(alternate) and not mkcustom): return path.join(reporoot, "acorn", "config") else: if mkcustom:# pragma: no cover #This never gets reached when we are in testmode because we don't #want to clobber the user's local config cache. from os import mkdir mkdir(alternate) return alternate
[ "def", "config_dir", "(", "mkcustom", "=", "False", ")", ":", "from", "acorn", ".", "utility", "import", "reporoot", "from", "acorn", ".", "base", "import", "testmode", "from", "os", "import", "path", "alternate", "=", "path", ".", "join", "(", "path", ".", "abspath", "(", "path", ".", "expanduser", "(", "\"~\"", ")", ")", ",", "\".acorn\"", ")", "if", "testmode", "or", "(", "not", "path", ".", "isdir", "(", "alternate", ")", "and", "not", "mkcustom", ")", ":", "return", "path", ".", "join", "(", "reporoot", ",", "\"acorn\"", ",", "\"config\"", ")", "else", ":", "if", "mkcustom", ":", "# pragma: no cover", "#This never gets reached when we are in testmode because we don't", "#want to clobber the user's local config cache.", "from", "os", "import", "mkdir", "mkdir", "(", "alternate", ")", "return", "alternate" ]
Returns the configuration directory for custom package settings.
[ "Returns", "the", "configuration", "directory", "for", "custom", "package", "settings", "." ]
9a44d1a1ad8bfc2c54a6b56d9efe54433a797820
https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/config.py#L16-L31
244,469
rosenbrockc/acorn
acorn/config.py
_package_path
def _package_path(package): """Returns the full path to the default package configuration file. Args: package (str): name of the python package to return a path for. """ from os import path confdir = config_dir() return path.join(confdir, "{}.cfg".format(package))
python
def _package_path(package): """Returns the full path to the default package configuration file. Args: package (str): name of the python package to return a path for. """ from os import path confdir = config_dir() return path.join(confdir, "{}.cfg".format(package))
[ "def", "_package_path", "(", "package", ")", ":", "from", "os", "import", "path", "confdir", "=", "config_dir", "(", ")", "return", "path", ".", "join", "(", "confdir", ",", "\"{}.cfg\"", ".", "format", "(", "package", ")", ")" ]
Returns the full path to the default package configuration file. Args: package (str): name of the python package to return a path for.
[ "Returns", "the", "full", "path", "to", "the", "default", "package", "configuration", "file", "." ]
9a44d1a1ad8bfc2c54a6b56d9efe54433a797820
https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/config.py#L33-L41
244,470
rosenbrockc/acorn
acorn/config.py
_read_single
def _read_single(parser, filepath): """Reads a single config file into the parser, silently failing if the file does not exist. Args: parser (ConfigParser): parser to read the file into. filepath (str): full path to the config file. """ from os import path global packages if path.isfile(filepath): parser.readfp(open(filepath))
python
def _read_single(parser, filepath): """Reads a single config file into the parser, silently failing if the file does not exist. Args: parser (ConfigParser): parser to read the file into. filepath (str): full path to the config file. """ from os import path global packages if path.isfile(filepath): parser.readfp(open(filepath))
[ "def", "_read_single", "(", "parser", ",", "filepath", ")", ":", "from", "os", "import", "path", "global", "packages", "if", "path", ".", "isfile", "(", "filepath", ")", ":", "parser", ".", "readfp", "(", "open", "(", "filepath", ")", ")" ]
Reads a single config file into the parser, silently failing if the file does not exist. Args: parser (ConfigParser): parser to read the file into. filepath (str): full path to the config file.
[ "Reads", "a", "single", "config", "file", "into", "the", "parser", "silently", "failing", "if", "the", "file", "does", "not", "exist", "." ]
9a44d1a1ad8bfc2c54a6b56d9efe54433a797820
https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/config.py#L43-L54
244,471
rosenbrockc/acorn
acorn/config.py
settings
def settings(package, reload_=False): """Returns the config settings for the specified package. Args: package (str): name of the python package to get settings for. """ global packages if package not in packages or reload_: from os import path result = CaseConfigParser() if package != "acorn": confpath = _package_path(package) _read_single(result, confpath) _read_single(result, _package_path("acorn")) packages[package] = result return packages[package]
python
def settings(package, reload_=False): """Returns the config settings for the specified package. Args: package (str): name of the python package to get settings for. """ global packages if package not in packages or reload_: from os import path result = CaseConfigParser() if package != "acorn": confpath = _package_path(package) _read_single(result, confpath) _read_single(result, _package_path("acorn")) packages[package] = result return packages[package]
[ "def", "settings", "(", "package", ",", "reload_", "=", "False", ")", ":", "global", "packages", "if", "package", "not", "in", "packages", "or", "reload_", ":", "from", "os", "import", "path", "result", "=", "CaseConfigParser", "(", ")", "if", "package", "!=", "\"acorn\"", ":", "confpath", "=", "_package_path", "(", "package", ")", "_read_single", "(", "result", ",", "confpath", ")", "_read_single", "(", "result", ",", "_package_path", "(", "\"acorn\"", ")", ")", "packages", "[", "package", "]", "=", "result", "return", "packages", "[", "package", "]" ]
Returns the config settings for the specified package. Args: package (str): name of the python package to get settings for.
[ "Returns", "the", "config", "settings", "for", "the", "specified", "package", "." ]
9a44d1a1ad8bfc2c54a6b56d9efe54433a797820
https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/config.py#L56-L72
244,472
rosenbrockc/acorn
acorn/config.py
descriptors
def descriptors(package): """Returns a dictionary of descriptors deserialized from JSON for the specified package. Args: package (str): name of the python package to get settings for. """ from os import path dpath = _descriptor_path(package) if path.isfile(dpath): import json with open(dpath) as f: jdb = json.load(f) return jdb else: return None
python
def descriptors(package): """Returns a dictionary of descriptors deserialized from JSON for the specified package. Args: package (str): name of the python package to get settings for. """ from os import path dpath = _descriptor_path(package) if path.isfile(dpath): import json with open(dpath) as f: jdb = json.load(f) return jdb else: return None
[ "def", "descriptors", "(", "package", ")", ":", "from", "os", "import", "path", "dpath", "=", "_descriptor_path", "(", "package", ")", "if", "path", ".", "isfile", "(", "dpath", ")", ":", "import", "json", "with", "open", "(", "dpath", ")", "as", "f", ":", "jdb", "=", "json", ".", "load", "(", "f", ")", "return", "jdb", "else", ":", "return", "None" ]
Returns a dictionary of descriptors deserialized from JSON for the specified package. Args: package (str): name of the python package to get settings for.
[ "Returns", "a", "dictionary", "of", "descriptors", "deserialized", "from", "JSON", "for", "the", "specified", "package", "." ]
9a44d1a1ad8bfc2c54a6b56d9efe54433a797820
https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/config.py#L83-L98
244,473
walidsa3d/torrentutils
torrentutils/core.py
parse_magnet
def parse_magnet(magnet_uri): """returns a dictionary of parameters contained in a magnet uri""" data = defaultdict(list) if not magnet_uri.startswith('magnet:'): return data else: magnet_uri = magnet_uri.strip('magnet:?') for segment in magnet_uri.split('&'): key, value = segment.split('=') if key == 'dn': data['name'] = requests.utils.unquote(value).replace('+', '.') elif key == 'xt': data['infoHash'] = value.strip('urn:btih:') elif key == 'tr': data['trackers'].append(requests.utils.unquote(value)) else: data[key] = value return data
python
def parse_magnet(magnet_uri): """returns a dictionary of parameters contained in a magnet uri""" data = defaultdict(list) if not magnet_uri.startswith('magnet:'): return data else: magnet_uri = magnet_uri.strip('magnet:?') for segment in magnet_uri.split('&'): key, value = segment.split('=') if key == 'dn': data['name'] = requests.utils.unquote(value).replace('+', '.') elif key == 'xt': data['infoHash'] = value.strip('urn:btih:') elif key == 'tr': data['trackers'].append(requests.utils.unquote(value)) else: data[key] = value return data
[ "def", "parse_magnet", "(", "magnet_uri", ")", ":", "data", "=", "defaultdict", "(", "list", ")", "if", "not", "magnet_uri", ".", "startswith", "(", "'magnet:'", ")", ":", "return", "data", "else", ":", "magnet_uri", "=", "magnet_uri", ".", "strip", "(", "'magnet:?'", ")", "for", "segment", "in", "magnet_uri", ".", "split", "(", "'&'", ")", ":", "key", ",", "value", "=", "segment", ".", "split", "(", "'='", ")", "if", "key", "==", "'dn'", ":", "data", "[", "'name'", "]", "=", "requests", ".", "utils", ".", "unquote", "(", "value", ")", ".", "replace", "(", "'+'", ",", "'.'", ")", "elif", "key", "==", "'xt'", ":", "data", "[", "'infoHash'", "]", "=", "value", ".", "strip", "(", "'urn:btih:'", ")", "elif", "key", "==", "'tr'", ":", "data", "[", "'trackers'", "]", ".", "append", "(", "requests", ".", "utils", ".", "unquote", "(", "value", ")", ")", "else", ":", "data", "[", "key", "]", "=", "value", "return", "data" ]
returns a dictionary of parameters contained in a magnet uri
[ "returns", "a", "dictionary", "of", "parameters", "contained", "in", "a", "magnet", "uri" ]
a13d637c4222934e84922ebc63d59efb29fe9e39
https://github.com/walidsa3d/torrentutils/blob/a13d637c4222934e84922ebc63d59efb29fe9e39/torrentutils/core.py#L19-L36
244,474
walidsa3d/torrentutils
torrentutils/core.py
parse_torrent_file
def parse_torrent_file(torrent): """parse local or remote torrent file""" link_re = re.compile(r'^(http?s|ftp)') if link_re.match(torrent): response = requests.get(torrent, headers=HEADERS, timeout=20) data = parse_torrent_buffer(response.content) elif os.path.isfile(torrent): with open(torrent, 'rb') as f: data = parse_torrent_buffer(f.read()) else: data = None return data
python
def parse_torrent_file(torrent): """parse local or remote torrent file""" link_re = re.compile(r'^(http?s|ftp)') if link_re.match(torrent): response = requests.get(torrent, headers=HEADERS, timeout=20) data = parse_torrent_buffer(response.content) elif os.path.isfile(torrent): with open(torrent, 'rb') as f: data = parse_torrent_buffer(f.read()) else: data = None return data
[ "def", "parse_torrent_file", "(", "torrent", ")", ":", "link_re", "=", "re", ".", "compile", "(", "r'^(http?s|ftp)'", ")", "if", "link_re", ".", "match", "(", "torrent", ")", ":", "response", "=", "requests", ".", "get", "(", "torrent", ",", "headers", "=", "HEADERS", ",", "timeout", "=", "20", ")", "data", "=", "parse_torrent_buffer", "(", "response", ".", "content", ")", "elif", "os", ".", "path", ".", "isfile", "(", "torrent", ")", ":", "with", "open", "(", "torrent", ",", "'rb'", ")", "as", "f", ":", "data", "=", "parse_torrent_buffer", "(", "f", ".", "read", "(", ")", ")", "else", ":", "data", "=", "None", "return", "data" ]
parse local or remote torrent file
[ "parse", "local", "or", "remote", "torrent", "file" ]
a13d637c4222934e84922ebc63d59efb29fe9e39
https://github.com/walidsa3d/torrentutils/blob/a13d637c4222934e84922ebc63d59efb29fe9e39/torrentutils/core.py#L48-L59
244,475
walidsa3d/torrentutils
torrentutils/core.py
parse_torrent_buffer
def parse_torrent_buffer(torrent): """parse a torrent buffer""" md = {} try: metadata = bencode.bdecode(torrent) except bencode.BTL.BTFailure: print 'Not a valid encoded torrent' return None if 'announce-list' in metadata: md['trackers'] = [] for tracker in metadata['announce-list']: md['trackers'].append(tracker[0]) if 'announce' in metadata: md['trackers'].append(metadata['announce']) md['trackers'] = list(set(md['trackers'])) if 'name' in metadata['info']: md['name'] = metadata['info']['name'] webseeds = [] if 'httpseeds' in metadata: webseeds = metadata['httpseeds'] if 'url-list' in metadata: webseeds += md['url-list'] if webseeds: md['webseeds'] = webseeds if 'created by' in metadata: md['creator'] = metadata['created by'] if 'creation date' in metadata: utc_dt = datetime.utcfromtimestamp(metadata['creation date']) md['created'] = utc_dt.strftime('%Y-%m-%d %H:%M:%S') if 'comment' in metadata: md['comment'] = metadata['comment'] md['piece_size'] = metadata['info']['piece length'] if 'length' in metadata['info']: md['file'] = {'path': metadata['info']['name'], 'length': metadata['info']['length']} if 'files' in metadata['info']: md['files'] = [] for item in metadata['info']['files']: md['files'].append( {'path': item['path'][0], 'length': item['length']}) # TODO check if torrent is private and encoding hashcontents = bencode.bencode(metadata['info']) digest = hashlib.sha1(hashcontents).digest() md['infoHash'] = hashlib.sha1(hashcontents).hexdigest() b32hash = base64.b32encode(digest) md['infoHash_b32'] = b32hash md['pieces'] = _split_pieces(metadata['info']['pieces']) md['total_size'] = hsize(sum([x['length'] for x in md['files']])) return md
python
def parse_torrent_buffer(torrent): """parse a torrent buffer""" md = {} try: metadata = bencode.bdecode(torrent) except bencode.BTL.BTFailure: print 'Not a valid encoded torrent' return None if 'announce-list' in metadata: md['trackers'] = [] for tracker in metadata['announce-list']: md['trackers'].append(tracker[0]) if 'announce' in metadata: md['trackers'].append(metadata['announce']) md['trackers'] = list(set(md['trackers'])) if 'name' in metadata['info']: md['name'] = metadata['info']['name'] webseeds = [] if 'httpseeds' in metadata: webseeds = metadata['httpseeds'] if 'url-list' in metadata: webseeds += md['url-list'] if webseeds: md['webseeds'] = webseeds if 'created by' in metadata: md['creator'] = metadata['created by'] if 'creation date' in metadata: utc_dt = datetime.utcfromtimestamp(metadata['creation date']) md['created'] = utc_dt.strftime('%Y-%m-%d %H:%M:%S') if 'comment' in metadata: md['comment'] = metadata['comment'] md['piece_size'] = metadata['info']['piece length'] if 'length' in metadata['info']: md['file'] = {'path': metadata['info']['name'], 'length': metadata['info']['length']} if 'files' in metadata['info']: md['files'] = [] for item in metadata['info']['files']: md['files'].append( {'path': item['path'][0], 'length': item['length']}) # TODO check if torrent is private and encoding hashcontents = bencode.bencode(metadata['info']) digest = hashlib.sha1(hashcontents).digest() md['infoHash'] = hashlib.sha1(hashcontents).hexdigest() b32hash = base64.b32encode(digest) md['infoHash_b32'] = b32hash md['pieces'] = _split_pieces(metadata['info']['pieces']) md['total_size'] = hsize(sum([x['length'] for x in md['files']])) return md
[ "def", "parse_torrent_buffer", "(", "torrent", ")", ":", "md", "=", "{", "}", "try", ":", "metadata", "=", "bencode", ".", "bdecode", "(", "torrent", ")", "except", "bencode", ".", "BTL", ".", "BTFailure", ":", "print", "'Not a valid encoded torrent'", "return", "None", "if", "'announce-list'", "in", "metadata", ":", "md", "[", "'trackers'", "]", "=", "[", "]", "for", "tracker", "in", "metadata", "[", "'announce-list'", "]", ":", "md", "[", "'trackers'", "]", ".", "append", "(", "tracker", "[", "0", "]", ")", "if", "'announce'", "in", "metadata", ":", "md", "[", "'trackers'", "]", ".", "append", "(", "metadata", "[", "'announce'", "]", ")", "md", "[", "'trackers'", "]", "=", "list", "(", "set", "(", "md", "[", "'trackers'", "]", ")", ")", "if", "'name'", "in", "metadata", "[", "'info'", "]", ":", "md", "[", "'name'", "]", "=", "metadata", "[", "'info'", "]", "[", "'name'", "]", "webseeds", "=", "[", "]", "if", "'httpseeds'", "in", "metadata", ":", "webseeds", "=", "metadata", "[", "'httpseeds'", "]", "if", "'url-list'", "in", "metadata", ":", "webseeds", "+=", "md", "[", "'url-list'", "]", "if", "webseeds", ":", "md", "[", "'webseeds'", "]", "=", "webseeds", "if", "'created by'", "in", "metadata", ":", "md", "[", "'creator'", "]", "=", "metadata", "[", "'created by'", "]", "if", "'creation date'", "in", "metadata", ":", "utc_dt", "=", "datetime", ".", "utcfromtimestamp", "(", "metadata", "[", "'creation date'", "]", ")", "md", "[", "'created'", "]", "=", "utc_dt", ".", "strftime", "(", "'%Y-%m-%d %H:%M:%S'", ")", "if", "'comment'", "in", "metadata", ":", "md", "[", "'comment'", "]", "=", "metadata", "[", "'comment'", "]", "md", "[", "'piece_size'", "]", "=", "metadata", "[", "'info'", "]", "[", "'piece length'", "]", "if", "'length'", "in", "metadata", "[", "'info'", "]", ":", "md", "[", "'file'", "]", "=", "{", "'path'", ":", "metadata", "[", "'info'", "]", "[", "'name'", "]", ",", "'length'", ":", "metadata", "[", "'info'", "]", "[", "'length'", "]", "}", "if", "'files'", "in", "metadata", "[", "'info'", "]", ":", "md", "[", "'files'", "]", "=", "[", "]", "for", "item", "in", "metadata", "[", "'info'", "]", "[", "'files'", "]", ":", "md", "[", "'files'", "]", ".", "append", "(", "{", "'path'", ":", "item", "[", "'path'", "]", "[", "0", "]", ",", "'length'", ":", "item", "[", "'length'", "]", "}", ")", "# TODO check if torrent is private and encoding", "hashcontents", "=", "bencode", ".", "bencode", "(", "metadata", "[", "'info'", "]", ")", "digest", "=", "hashlib", ".", "sha1", "(", "hashcontents", ")", ".", "digest", "(", ")", "md", "[", "'infoHash'", "]", "=", "hashlib", ".", "sha1", "(", "hashcontents", ")", ".", "hexdigest", "(", ")", "b32hash", "=", "base64", ".", "b32encode", "(", "digest", ")", "md", "[", "'infoHash_b32'", "]", "=", "b32hash", "md", "[", "'pieces'", "]", "=", "_split_pieces", "(", "metadata", "[", "'info'", "]", "[", "'pieces'", "]", ")", "md", "[", "'total_size'", "]", "=", "hsize", "(", "sum", "(", "[", "x", "[", "'length'", "]", "for", "x", "in", "md", "[", "'files'", "]", "]", ")", ")", "return", "md" ]
parse a torrent buffer
[ "parse", "a", "torrent", "buffer" ]
a13d637c4222934e84922ebc63d59efb29fe9e39
https://github.com/walidsa3d/torrentutils/blob/a13d637c4222934e84922ebc63d59efb29fe9e39/torrentutils/core.py#L62-L110
244,476
walidsa3d/torrentutils
torrentutils/core.py
hsize
def hsize(bytes): """converts a bytes to human-readable format""" sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'] if bytes == 0: return '0 Byte' i = int(math.floor(math.log(bytes) / math.log(1024))) r = round(bytes / math.pow(1024, i), 2) return str(r) + '' + sizes[i]
python
def hsize(bytes): """converts a bytes to human-readable format""" sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'] if bytes == 0: return '0 Byte' i = int(math.floor(math.log(bytes) / math.log(1024))) r = round(bytes / math.pow(1024, i), 2) return str(r) + '' + sizes[i]
[ "def", "hsize", "(", "bytes", ")", ":", "sizes", "=", "[", "'Bytes'", ",", "'KB'", ",", "'MB'", ",", "'GB'", ",", "'TB'", "]", "if", "bytes", "==", "0", ":", "return", "'0 Byte'", "i", "=", "int", "(", "math", ".", "floor", "(", "math", ".", "log", "(", "bytes", ")", "/", "math", ".", "log", "(", "1024", ")", ")", ")", "r", "=", "round", "(", "bytes", "/", "math", ".", "pow", "(", "1024", ",", "i", ")", ",", "2", ")", "return", "str", "(", "r", ")", "+", "''", "+", "sizes", "[", "i", "]" ]
converts a bytes to human-readable format
[ "converts", "a", "bytes", "to", "human", "-", "readable", "format" ]
a13d637c4222934e84922ebc63d59efb29fe9e39
https://github.com/walidsa3d/torrentutils/blob/a13d637c4222934e84922ebc63d59efb29fe9e39/torrentutils/core.py#L120-L127
244,477
walidsa3d/torrentutils
torrentutils/core.py
ratio
def ratio(leechs, seeds): """ computes the torrent ratio""" try: ratio = float(seeds) / float(leechs) except ZeroDivisionError: ratio = int(seeds) return ratio
python
def ratio(leechs, seeds): """ computes the torrent ratio""" try: ratio = float(seeds) / float(leechs) except ZeroDivisionError: ratio = int(seeds) return ratio
[ "def", "ratio", "(", "leechs", ",", "seeds", ")", ":", "try", ":", "ratio", "=", "float", "(", "seeds", ")", "/", "float", "(", "leechs", ")", "except", "ZeroDivisionError", ":", "ratio", "=", "int", "(", "seeds", ")", "return", "ratio" ]
computes the torrent ratio
[ "computes", "the", "torrent", "ratio" ]
a13d637c4222934e84922ebc63d59efb29fe9e39
https://github.com/walidsa3d/torrentutils/blob/a13d637c4222934e84922ebc63d59efb29fe9e39/torrentutils/core.py#L130-L136
244,478
walidsa3d/torrentutils
torrentutils/core.py
to_torrent
def to_torrent(magnet_link): """turn a magnet link to a link to a torrent file""" infoHash = parse_magnet(magnet_link)['infoHash'] torcache = 'http://torcache.net/torrent/' + infoHash + '.torrent' torrage = 'https://torrage.com/torrent/' + infoHash + '.torrent' reflektor = 'http://reflektor.karmorra.info/torrent/' + \ infoHash + '.torrent' thetorrent = 'http://TheTorrent.org/'+infoHash btcache = 'http://www.btcache.me/torrent/'+infoHash for link in [torcache, torrage, reflektor, btcache, thetorrent]: try: print "Checking "+link response = requests.head(link, headers=HEADERS) if response.headers['content-type'] in ['application/x-bittorrent', 'application/octet-stream']: return link except requests.exceptions.ConnectionError: pass return
python
def to_torrent(magnet_link): """turn a magnet link to a link to a torrent file""" infoHash = parse_magnet(magnet_link)['infoHash'] torcache = 'http://torcache.net/torrent/' + infoHash + '.torrent' torrage = 'https://torrage.com/torrent/' + infoHash + '.torrent' reflektor = 'http://reflektor.karmorra.info/torrent/' + \ infoHash + '.torrent' thetorrent = 'http://TheTorrent.org/'+infoHash btcache = 'http://www.btcache.me/torrent/'+infoHash for link in [torcache, torrage, reflektor, btcache, thetorrent]: try: print "Checking "+link response = requests.head(link, headers=HEADERS) if response.headers['content-type'] in ['application/x-bittorrent', 'application/octet-stream']: return link except requests.exceptions.ConnectionError: pass return
[ "def", "to_torrent", "(", "magnet_link", ")", ":", "infoHash", "=", "parse_magnet", "(", "magnet_link", ")", "[", "'infoHash'", "]", "torcache", "=", "'http://torcache.net/torrent/'", "+", "infoHash", "+", "'.torrent'", "torrage", "=", "'https://torrage.com/torrent/'", "+", "infoHash", "+", "'.torrent'", "reflektor", "=", "'http://reflektor.karmorra.info/torrent/'", "+", "infoHash", "+", "'.torrent'", "thetorrent", "=", "'http://TheTorrent.org/'", "+", "infoHash", "btcache", "=", "'http://www.btcache.me/torrent/'", "+", "infoHash", "for", "link", "in", "[", "torcache", ",", "torrage", ",", "reflektor", ",", "btcache", ",", "thetorrent", "]", ":", "try", ":", "print", "\"Checking \"", "+", "link", "response", "=", "requests", ".", "head", "(", "link", ",", "headers", "=", "HEADERS", ")", "if", "response", ".", "headers", "[", "'content-type'", "]", "in", "[", "'application/x-bittorrent'", ",", "'application/octet-stream'", "]", ":", "return", "link", "except", "requests", ".", "exceptions", ".", "ConnectionError", ":", "pass", "return" ]
turn a magnet link to a link to a torrent file
[ "turn", "a", "magnet", "link", "to", "a", "link", "to", "a", "torrent", "file" ]
a13d637c4222934e84922ebc63d59efb29fe9e39
https://github.com/walidsa3d/torrentutils/blob/a13d637c4222934e84922ebc63d59efb29fe9e39/torrentutils/core.py#L139-L157
244,479
datadesk/django-greeking
greeking/latimes_ipsum.py
get_story
def get_story(): """ Returns a boiler plate story as an object. """ return Story( slug="la-data-latimes-ipsum", headline="This is not a headline", byline="This is not a byline", pub_date=datetime.now(), canonical_url="http://www.example.com/", kicker="This is not a kicker", description=lorem_ipsum.COMMON_P.split(".")[0], sources="This is not a source", credits="This is not a credit", content=six.text_type('\n\n'.join(lorem_ipsum.paragraphs(6))), image=get_image(900) )
python
def get_story(): """ Returns a boiler plate story as an object. """ return Story( slug="la-data-latimes-ipsum", headline="This is not a headline", byline="This is not a byline", pub_date=datetime.now(), canonical_url="http://www.example.com/", kicker="This is not a kicker", description=lorem_ipsum.COMMON_P.split(".")[0], sources="This is not a source", credits="This is not a credit", content=six.text_type('\n\n'.join(lorem_ipsum.paragraphs(6))), image=get_image(900) )
[ "def", "get_story", "(", ")", ":", "return", "Story", "(", "slug", "=", "\"la-data-latimes-ipsum\"", ",", "headline", "=", "\"This is not a headline\"", ",", "byline", "=", "\"This is not a byline\"", ",", "pub_date", "=", "datetime", ".", "now", "(", ")", ",", "canonical_url", "=", "\"http://www.example.com/\"", ",", "kicker", "=", "\"This is not a kicker\"", ",", "description", "=", "lorem_ipsum", ".", "COMMON_P", ".", "split", "(", "\".\"", ")", "[", "0", "]", ",", "sources", "=", "\"This is not a source\"", ",", "credits", "=", "\"This is not a credit\"", ",", "content", "=", "six", ".", "text_type", "(", "'\\n\\n'", ".", "join", "(", "lorem_ipsum", ".", "paragraphs", "(", "6", ")", ")", ")", ",", "image", "=", "get_image", "(", "900", ")", ")" ]
Returns a boiler plate story as an object.
[ "Returns", "a", "boiler", "plate", "story", "as", "an", "object", "." ]
72509c94952279503bbe8d5a710c1fd344da0670
https://github.com/datadesk/django-greeking/blob/72509c94952279503bbe8d5a710c1fd344da0670/greeking/latimes_ipsum.py#L80-L96
244,480
datadesk/django-greeking
greeking/latimes_ipsum.py
get_related_items
def get_related_items(count=4): """ Returns the requested number of boiler plate related items as a list. """ defaults = dict( headline="This is not a headline", url="http://www.example.com/", image=get_image(400, 400) ) return [RelatedItem(**defaults) for x in range(0, count)]
python
def get_related_items(count=4): """ Returns the requested number of boiler plate related items as a list. """ defaults = dict( headline="This is not a headline", url="http://www.example.com/", image=get_image(400, 400) ) return [RelatedItem(**defaults) for x in range(0, count)]
[ "def", "get_related_items", "(", "count", "=", "4", ")", ":", "defaults", "=", "dict", "(", "headline", "=", "\"This is not a headline\"", ",", "url", "=", "\"http://www.example.com/\"", ",", "image", "=", "get_image", "(", "400", ",", "400", ")", ")", "return", "[", "RelatedItem", "(", "*", "*", "defaults", ")", "for", "x", "in", "range", "(", "0", ",", "count", ")", "]" ]
Returns the requested number of boiler plate related items as a list.
[ "Returns", "the", "requested", "number", "of", "boiler", "plate", "related", "items", "as", "a", "list", "." ]
72509c94952279503bbe8d5a710c1fd344da0670
https://github.com/datadesk/django-greeking/blob/72509c94952279503bbe8d5a710c1fd344da0670/greeking/latimes_ipsum.py#L99-L108
244,481
datadesk/django-greeking
greeking/latimes_ipsum.py
get_image
def get_image(width, height=None, background_color="cccccc", random_background_color=False): """ Returns image with caption, credit, and random background color as requested. """ return Image( url=placeholdit.get_url( width, height=height, background_color=background_color, random_background_color=random_background_color ), credit="This is not an image credit", caption="This is not a caption" )
python
def get_image(width, height=None, background_color="cccccc", random_background_color=False): """ Returns image with caption, credit, and random background color as requested. """ return Image( url=placeholdit.get_url( width, height=height, background_color=background_color, random_background_color=random_background_color ), credit="This is not an image credit", caption="This is not a caption" )
[ "def", "get_image", "(", "width", ",", "height", "=", "None", ",", "background_color", "=", "\"cccccc\"", ",", "random_background_color", "=", "False", ")", ":", "return", "Image", "(", "url", "=", "placeholdit", ".", "get_url", "(", "width", ",", "height", "=", "height", ",", "background_color", "=", "background_color", ",", "random_background_color", "=", "random_background_color", ")", ",", "credit", "=", "\"This is not an image credit\"", ",", "caption", "=", "\"This is not a caption\"", ")" ]
Returns image with caption, credit, and random background color as requested.
[ "Returns", "image", "with", "caption", "credit", "and", "random", "background", "color", "as", "requested", "." ]
72509c94952279503bbe8d5a710c1fd344da0670
https://github.com/datadesk/django-greeking/blob/72509c94952279503bbe8d5a710c1fd344da0670/greeking/latimes_ipsum.py#L111-L124
244,482
ronaldguillen/wave
wave/validators.py
UniqueValidator.filter_queryset
def filter_queryset(self, value, queryset): """ Filter the queryset to all instances matching the given attribute. """ filter_kwargs = {self.field_name: value} return queryset.filter(**filter_kwargs)
python
def filter_queryset(self, value, queryset): """ Filter the queryset to all instances matching the given attribute. """ filter_kwargs = {self.field_name: value} return queryset.filter(**filter_kwargs)
[ "def", "filter_queryset", "(", "self", ",", "value", ",", "queryset", ")", ":", "filter_kwargs", "=", "{", "self", ".", "field_name", ":", "value", "}", "return", "queryset", ".", "filter", "(", "*", "*", "filter_kwargs", ")" ]
Filter the queryset to all instances matching the given attribute.
[ "Filter", "the", "queryset", "to", "all", "instances", "matching", "the", "given", "attribute", "." ]
20bb979c917f7634d8257992e6d449dc751256a9
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/validators.py#L42-L47
244,483
ronaldguillen/wave
wave/validators.py
UniqueValidator.exclude_current_instance
def exclude_current_instance(self, queryset): """ If an instance is being updated, then do not include that instance itself as a uniqueness conflict. """ if self.instance is not None: return queryset.exclude(pk=self.instance.pk) return queryset
python
def exclude_current_instance(self, queryset): """ If an instance is being updated, then do not include that instance itself as a uniqueness conflict. """ if self.instance is not None: return queryset.exclude(pk=self.instance.pk) return queryset
[ "def", "exclude_current_instance", "(", "self", ",", "queryset", ")", ":", "if", "self", ".", "instance", "is", "not", "None", ":", "return", "queryset", ".", "exclude", "(", "pk", "=", "self", ".", "instance", ".", "pk", ")", "return", "queryset" ]
If an instance is being updated, then do not include that instance itself as a uniqueness conflict.
[ "If", "an", "instance", "is", "being", "updated", "then", "do", "not", "include", "that", "instance", "itself", "as", "a", "uniqueness", "conflict", "." ]
20bb979c917f7634d8257992e6d449dc751256a9
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/validators.py#L49-L56
244,484
ronaldguillen/wave
wave/validators.py
UniqueTogetherValidator.enforce_required_fields
def enforce_required_fields(self, attrs): """ The `UniqueTogetherValidator` always forces an implied 'required' state on the fields it applies to. """ if self.instance is not None: return missing = { field_name: self.missing_message for field_name in self.fields if field_name not in attrs } if missing: raise ValidationError(missing)
python
def enforce_required_fields(self, attrs): """ The `UniqueTogetherValidator` always forces an implied 'required' state on the fields it applies to. """ if self.instance is not None: return missing = { field_name: self.missing_message for field_name in self.fields if field_name not in attrs } if missing: raise ValidationError(missing)
[ "def", "enforce_required_fields", "(", "self", ",", "attrs", ")", ":", "if", "self", ".", "instance", "is", "not", "None", ":", "return", "missing", "=", "{", "field_name", ":", "self", ".", "missing_message", "for", "field_name", "in", "self", ".", "fields", "if", "field_name", "not", "in", "attrs", "}", "if", "missing", ":", "raise", "ValidationError", "(", "missing", ")" ]
The `UniqueTogetherValidator` always forces an implied 'required' state on the fields it applies to.
[ "The", "UniqueTogetherValidator", "always", "forces", "an", "implied", "required", "state", "on", "the", "fields", "it", "applies", "to", "." ]
20bb979c917f7634d8257992e6d449dc751256a9
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/validators.py#L95-L109
244,485
ronaldguillen/wave
wave/validators.py
UniqueTogetherValidator.filter_queryset
def filter_queryset(self, attrs, queryset): """ Filter the queryset to all instances matching the given attributes. """ # If this is an update, then any unprovided field should # have it's value set based on the existing instance attribute. if self.instance is not None: for field_name in self.fields: if field_name not in attrs: attrs[field_name] = getattr(self.instance, field_name) # Determine the filter keyword arguments and filter the queryset. filter_kwargs = { field_name: attrs[field_name] for field_name in self.fields } return queryset.filter(**filter_kwargs)
python
def filter_queryset(self, attrs, queryset): """ Filter the queryset to all instances matching the given attributes. """ # If this is an update, then any unprovided field should # have it's value set based on the existing instance attribute. if self.instance is not None: for field_name in self.fields: if field_name not in attrs: attrs[field_name] = getattr(self.instance, field_name) # Determine the filter keyword arguments and filter the queryset. filter_kwargs = { field_name: attrs[field_name] for field_name in self.fields } return queryset.filter(**filter_kwargs)
[ "def", "filter_queryset", "(", "self", ",", "attrs", ",", "queryset", ")", ":", "# If this is an update, then any unprovided field should", "# have it's value set based on the existing instance attribute.", "if", "self", ".", "instance", "is", "not", "None", ":", "for", "field_name", "in", "self", ".", "fields", ":", "if", "field_name", "not", "in", "attrs", ":", "attrs", "[", "field_name", "]", "=", "getattr", "(", "self", ".", "instance", ",", "field_name", ")", "# Determine the filter keyword arguments and filter the queryset.", "filter_kwargs", "=", "{", "field_name", ":", "attrs", "[", "field_name", "]", "for", "field_name", "in", "self", ".", "fields", "}", "return", "queryset", ".", "filter", "(", "*", "*", "filter_kwargs", ")" ]
Filter the queryset to all instances matching the given attributes.
[ "Filter", "the", "queryset", "to", "all", "instances", "matching", "the", "given", "attributes", "." ]
20bb979c917f7634d8257992e6d449dc751256a9
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/validators.py#L111-L127
244,486
praekelt/panya
panya/view_modifiers/items.py
GetItem.modify
def modify(self, view): """ adds the get item as extra context """ view.params['extra_context'][self.get['name']] = self.get['value'] return view
python
def modify(self, view): """ adds the get item as extra context """ view.params['extra_context'][self.get['name']] = self.get['value'] return view
[ "def", "modify", "(", "self", ",", "view", ")", ":", "view", ".", "params", "[", "'extra_context'", "]", "[", "self", ".", "get", "[", "'name'", "]", "]", "=", "self", ".", "get", "[", "'value'", "]", "return", "view" ]
adds the get item as extra context
[ "adds", "the", "get", "item", "as", "extra", "context" ]
0fd621e15a7c11a2716a9554a2f820d6259818e5
https://github.com/praekelt/panya/blob/0fd621e15a7c11a2716a9554a2f820d6259818e5/panya/view_modifiers/items.py#L33-L38
244,487
fogcitymarathoner/s3_mysql_backup
s3_mysql_backup/scripts/get_bucket_list.py
get_bucket_list
def get_bucket_list(): """ Get list of S3 Buckets """ args = parser.parse_args() for b in s3_conn(args.aws_access_key_id, args.aws_secret_access_key).get_all_buckets(): print(''.join([i if ord(i) < 128 else ' ' for i in b.name]))
python
def get_bucket_list(): """ Get list of S3 Buckets """ args = parser.parse_args() for b in s3_conn(args.aws_access_key_id, args.aws_secret_access_key).get_all_buckets(): print(''.join([i if ord(i) < 128 else ' ' for i in b.name]))
[ "def", "get_bucket_list", "(", ")", ":", "args", "=", "parser", ".", "parse_args", "(", ")", "for", "b", "in", "s3_conn", "(", "args", ".", "aws_access_key_id", ",", "args", ".", "aws_secret_access_key", ")", ".", "get_all_buckets", "(", ")", ":", "print", "(", "''", ".", "join", "(", "[", "i", "if", "ord", "(", "i", ")", "<", "128", "else", "' '", "for", "i", "in", "b", ".", "name", "]", ")", ")" ]
Get list of S3 Buckets
[ "Get", "list", "of", "S3", "Buckets" ]
8a0fb3e51a7b873eb4287d4954548a0dbab0e734
https://github.com/fogcitymarathoner/s3_mysql_backup/blob/8a0fb3e51a7b873eb4287d4954548a0dbab0e734/s3_mysql_backup/scripts/get_bucket_list.py#L11-L17
244,488
slarse/clanimtk
clanimtk/core.py
_get_back_up_generator
def _get_back_up_generator(frame_function, *args, **kwargs): """Create a generator for the provided animation function that backs up the cursor after a frame. Assumes that the animation function provides a generator that yields strings of constant width and height. Args: frame_function: A function that returns a FrameGenerator. args: Arguments for frame_function. kwargs: Keyword arguments for frame_function. Returns: a generator that generates backspace/backline characters for the animation func generator. """ lines = next(frame_function(*args, **kwargs)).split('\n') width = len(lines[0]) height = len(lines) if height == 1: return util.BACKSPACE_GEN(width) return util.BACKLINE_GEN(height)
python
def _get_back_up_generator(frame_function, *args, **kwargs): """Create a generator for the provided animation function that backs up the cursor after a frame. Assumes that the animation function provides a generator that yields strings of constant width and height. Args: frame_function: A function that returns a FrameGenerator. args: Arguments for frame_function. kwargs: Keyword arguments for frame_function. Returns: a generator that generates backspace/backline characters for the animation func generator. """ lines = next(frame_function(*args, **kwargs)).split('\n') width = len(lines[0]) height = len(lines) if height == 1: return util.BACKSPACE_GEN(width) return util.BACKLINE_GEN(height)
[ "def", "_get_back_up_generator", "(", "frame_function", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "lines", "=", "next", "(", "frame_function", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")", ".", "split", "(", "'\\n'", ")", "width", "=", "len", "(", "lines", "[", "0", "]", ")", "height", "=", "len", "(", "lines", ")", "if", "height", "==", "1", ":", "return", "util", ".", "BACKSPACE_GEN", "(", "width", ")", "return", "util", ".", "BACKLINE_GEN", "(", "height", ")" ]
Create a generator for the provided animation function that backs up the cursor after a frame. Assumes that the animation function provides a generator that yields strings of constant width and height. Args: frame_function: A function that returns a FrameGenerator. args: Arguments for frame_function. kwargs: Keyword arguments for frame_function. Returns: a generator that generates backspace/backline characters for the animation func generator.
[ "Create", "a", "generator", "for", "the", "provided", "animation", "function", "that", "backs", "up", "the", "cursor", "after", "a", "frame", ".", "Assumes", "that", "the", "animation", "function", "provides", "a", "generator", "that", "yields", "strings", "of", "constant", "width", "and", "height", "." ]
cb93d2e914c3ecc4e0007745ff4d546318cf3902
https://github.com/slarse/clanimtk/blob/cb93d2e914c3ecc4e0007745ff4d546318cf3902/clanimtk/core.py#L252-L270
244,489
slarse/clanimtk
clanimtk/core.py
_backspaced_single_line_animation
def _backspaced_single_line_animation(animation_, *args, **kwargs): """Turn an animation into an automatically backspaced animation. Args: animation: A function that returns a generator that yields strings for animation frames. args: Arguments for the animation function. kwargs: Keyword arguments for the animation function. Returns: the animation generator, with backspaces applied to each but the first frame. """ animation_gen = animation_(*args, **kwargs) yield next(animation_gen) # no backing up on the first frame yield from util.concatechain( util.BACKSPACE_GEN(kwargs['width']), animation_gen)
python
def _backspaced_single_line_animation(animation_, *args, **kwargs): """Turn an animation into an automatically backspaced animation. Args: animation: A function that returns a generator that yields strings for animation frames. args: Arguments for the animation function. kwargs: Keyword arguments for the animation function. Returns: the animation generator, with backspaces applied to each but the first frame. """ animation_gen = animation_(*args, **kwargs) yield next(animation_gen) # no backing up on the first frame yield from util.concatechain( util.BACKSPACE_GEN(kwargs['width']), animation_gen)
[ "def", "_backspaced_single_line_animation", "(", "animation_", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "animation_gen", "=", "animation_", "(", "*", "args", ",", "*", "*", "kwargs", ")", "yield", "next", "(", "animation_gen", ")", "# no backing up on the first frame", "yield", "from", "util", ".", "concatechain", "(", "util", ".", "BACKSPACE_GEN", "(", "kwargs", "[", "'width'", "]", ")", ",", "animation_gen", ")" ]
Turn an animation into an automatically backspaced animation. Args: animation: A function that returns a generator that yields strings for animation frames. args: Arguments for the animation function. kwargs: Keyword arguments for the animation function. Returns: the animation generator, with backspaces applied to each but the first frame.
[ "Turn", "an", "animation", "into", "an", "automatically", "backspaced", "animation", "." ]
cb93d2e914c3ecc4e0007745ff4d546318cf3902
https://github.com/slarse/clanimtk/blob/cb93d2e914c3ecc4e0007745ff4d546318cf3902/clanimtk/core.py#L273-L288
244,490
slarse/clanimtk
clanimtk/core.py
Animate._raise_if_annotated
def _raise_if_annotated(self, func): """Raise TypeError if a function is decorated with Annotate, as such functions cause visual bugs when decorated with Animate. Animate should be wrapped by Annotate instead. Args: func (function): Any callable. Raises: TypeError """ if hasattr(func, ANNOTATED) and getattr(func, ANNOTATED): msg = ('Functions decorated with {!r} ' 'should not be decorated with {!r}.\n' 'Please reverse the order of the decorators!'.format( self.__class__.__name__, Annotate.__name__)) raise TypeError(msg)
python
def _raise_if_annotated(self, func): """Raise TypeError if a function is decorated with Annotate, as such functions cause visual bugs when decorated with Animate. Animate should be wrapped by Annotate instead. Args: func (function): Any callable. Raises: TypeError """ if hasattr(func, ANNOTATED) and getattr(func, ANNOTATED): msg = ('Functions decorated with {!r} ' 'should not be decorated with {!r}.\n' 'Please reverse the order of the decorators!'.format( self.__class__.__name__, Annotate.__name__)) raise TypeError(msg)
[ "def", "_raise_if_annotated", "(", "self", ",", "func", ")", ":", "if", "hasattr", "(", "func", ",", "ANNOTATED", ")", "and", "getattr", "(", "func", ",", "ANNOTATED", ")", ":", "msg", "=", "(", "'Functions decorated with {!r} '", "'should not be decorated with {!r}.\\n'", "'Please reverse the order of the decorators!'", ".", "format", "(", "self", ".", "__class__", ".", "__name__", ",", "Annotate", ".", "__name__", ")", ")", "raise", "TypeError", "(", "msg", ")" ]
Raise TypeError if a function is decorated with Annotate, as such functions cause visual bugs when decorated with Animate. Animate should be wrapped by Annotate instead. Args: func (function): Any callable. Raises: TypeError
[ "Raise", "TypeError", "if", "a", "function", "is", "decorated", "with", "Annotate", "as", "such", "functions", "cause", "visual", "bugs", "when", "decorated", "with", "Animate", "." ]
cb93d2e914c3ecc4e0007745ff4d546318cf3902
https://github.com/slarse/clanimtk/blob/cb93d2e914c3ecc4e0007745ff4d546318cf3902/clanimtk/core.py#L61-L77
244,491
slarse/clanimtk
clanimtk/core.py
Annotate._start_print
def _start_print(self): """Print the start message with or without newline depending on the self._start_no_nl variable. """ if self._start_no_nl: sys.stdout.write(self._start_msg) sys.stdout.flush() else: print(self._start_msg)
python
def _start_print(self): """Print the start message with or without newline depending on the self._start_no_nl variable. """ if self._start_no_nl: sys.stdout.write(self._start_msg) sys.stdout.flush() else: print(self._start_msg)
[ "def", "_start_print", "(", "self", ")", ":", "if", "self", ".", "_start_no_nl", ":", "sys", ".", "stdout", ".", "write", "(", "self", ".", "_start_msg", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "else", ":", "print", "(", "self", ".", "_start_msg", ")" ]
Print the start message with or without newline depending on the self._start_no_nl variable.
[ "Print", "the", "start", "message", "with", "or", "without", "newline", "depending", "on", "the", "self", ".", "_start_no_nl", "variable", "." ]
cb93d2e914c3ecc4e0007745ff4d546318cf3902
https://github.com/slarse/clanimtk/blob/cb93d2e914c3ecc4e0007745ff4d546318cf3902/clanimtk/core.py#L125-L133
244,492
slarse/clanimtk
clanimtk/core.py
Animation.reset
def reset(self): """Reset the current animation generator.""" animation_gen = self._frame_function(*self._animation_args, **self._animation_kwargs) self._current_generator = itertools.cycle( util.concatechain(animation_gen, self._back_up_generator))
python
def reset(self): """Reset the current animation generator.""" animation_gen = self._frame_function(*self._animation_args, **self._animation_kwargs) self._current_generator = itertools.cycle( util.concatechain(animation_gen, self._back_up_generator))
[ "def", "reset", "(", "self", ")", ":", "animation_gen", "=", "self", ".", "_frame_function", "(", "*", "self", ".", "_animation_args", ",", "*", "*", "self", ".", "_animation_kwargs", ")", "self", ".", "_current_generator", "=", "itertools", ".", "cycle", "(", "util", ".", "concatechain", "(", "animation_gen", ",", "self", ".", "_back_up_generator", ")", ")" ]
Reset the current animation generator.
[ "Reset", "the", "current", "animation", "generator", "." ]
cb93d2e914c3ecc4e0007745ff4d546318cf3902
https://github.com/slarse/clanimtk/blob/cb93d2e914c3ecc4e0007745ff4d546318cf3902/clanimtk/core.py#L212-L217
244,493
slarse/clanimtk
clanimtk/core.py
Animation.get_erase_frame
def get_erase_frame(self): """Return a frame that completely erases the current frame, and then backs up. Assumes that the current frame is of constant width.""" lines = self._current_frame.split('\n') width = len(lines[0]) height = len(lines) line = ' ' * width if height == 1: frame = line + BACKSPACE * width else: frame = '\n'.join([line] * height) + BACKLINE * (height - 1) return frame
python
def get_erase_frame(self): """Return a frame that completely erases the current frame, and then backs up. Assumes that the current frame is of constant width.""" lines = self._current_frame.split('\n') width = len(lines[0]) height = len(lines) line = ' ' * width if height == 1: frame = line + BACKSPACE * width else: frame = '\n'.join([line] * height) + BACKLINE * (height - 1) return frame
[ "def", "get_erase_frame", "(", "self", ")", ":", "lines", "=", "self", ".", "_current_frame", ".", "split", "(", "'\\n'", ")", "width", "=", "len", "(", "lines", "[", "0", "]", ")", "height", "=", "len", "(", "lines", ")", "line", "=", "' '", "*", "width", "if", "height", "==", "1", ":", "frame", "=", "line", "+", "BACKSPACE", "*", "width", "else", ":", "frame", "=", "'\\n'", ".", "join", "(", "[", "line", "]", "*", "height", ")", "+", "BACKLINE", "*", "(", "height", "-", "1", ")", "return", "frame" ]
Return a frame that completely erases the current frame, and then backs up. Assumes that the current frame is of constant width.
[ "Return", "a", "frame", "that", "completely", "erases", "the", "current", "frame", "and", "then", "backs", "up", "." ]
cb93d2e914c3ecc4e0007745ff4d546318cf3902
https://github.com/slarse/clanimtk/blob/cb93d2e914c3ecc4e0007745ff4d546318cf3902/clanimtk/core.py#L219-L232
244,494
etcher-be/emiz
emiz/weather/custom_metar/custom_metar.py
CustomMetar.string
def string(self): # noqa: C901 """ Return a human-readable version of the decoded report. """ lines = ["station: %s" % self.station_id] if self.type: lines.append("type: %s" % self.report_type()) if self.time: lines.append("time: %s" % self.time.ctime()) if self.temp: lines.append("temperature: %s" % self.temp.string("C")) if self.dewpt: lines.append("dew point: %s" % self.dewpt.string("C")) if self.wind_speed: lines.append("wind: %s" % self.wind()) if self.wind_speed_peak: lines.append("peak wind: %s" % self.peak_wind()) if self.wind_shift_time: lines.append("wind shift: %s" % self.wind_shift()) if self.vis: lines.append("visibility: %s" % self.visibility()) if self.runway: lines.append("visual range: %s" % self.runway_visual_range()) if self.press: lines.append(f"pressure: {self.press.string('MB')} {self.press.string('IN')} {self.press.string('MM')}") if self.weather: lines.append("weather: %s" % self.present_weather()) if self.sky: lines.append("sky: %s" % self.sky_conditions("\n ")) if self.press_sea_level: lines.append("sea-level pressure: %s" % self.press_sea_level.string("mb")) if self.max_temp_6hr: lines.append("6-hour max temp: %s" % str(self.max_temp_6hr)) if self.max_temp_6hr: lines.append("6-hour min temp: %s" % str(self.min_temp_6hr)) if self.max_temp_24hr: lines.append("24-hour max temp: %s" % str(self.max_temp_24hr)) if self.max_temp_24hr: lines.append("24-hour min temp: %s" % str(self.min_temp_24hr)) if self.precip_1hr: lines.append("1-hour precipitation: %s" % str(self.precip_1hr)) if self.precip_3hr: lines.append("3-hour precipitation: %s" % str(self.precip_3hr)) if self.precip_6hr: lines.append("6-hour precipitation: %s" % str(self.precip_6hr)) if self.precip_24hr: lines.append("24-hour precipitation: %s" % str(self.precip_24hr)) if self._remarks: lines.append("remarks:") lines.append("- " + self.remarks("\n- ")) if self._unparsed_remarks: lines.append("- " + ' '.join(self._unparsed_remarks)) lines.append("METAR: " + self.code) return "\n".join(lines)
python
def string(self): # noqa: C901 """ Return a human-readable version of the decoded report. """ lines = ["station: %s" % self.station_id] if self.type: lines.append("type: %s" % self.report_type()) if self.time: lines.append("time: %s" % self.time.ctime()) if self.temp: lines.append("temperature: %s" % self.temp.string("C")) if self.dewpt: lines.append("dew point: %s" % self.dewpt.string("C")) if self.wind_speed: lines.append("wind: %s" % self.wind()) if self.wind_speed_peak: lines.append("peak wind: %s" % self.peak_wind()) if self.wind_shift_time: lines.append("wind shift: %s" % self.wind_shift()) if self.vis: lines.append("visibility: %s" % self.visibility()) if self.runway: lines.append("visual range: %s" % self.runway_visual_range()) if self.press: lines.append(f"pressure: {self.press.string('MB')} {self.press.string('IN')} {self.press.string('MM')}") if self.weather: lines.append("weather: %s" % self.present_weather()) if self.sky: lines.append("sky: %s" % self.sky_conditions("\n ")) if self.press_sea_level: lines.append("sea-level pressure: %s" % self.press_sea_level.string("mb")) if self.max_temp_6hr: lines.append("6-hour max temp: %s" % str(self.max_temp_6hr)) if self.max_temp_6hr: lines.append("6-hour min temp: %s" % str(self.min_temp_6hr)) if self.max_temp_24hr: lines.append("24-hour max temp: %s" % str(self.max_temp_24hr)) if self.max_temp_24hr: lines.append("24-hour min temp: %s" % str(self.min_temp_24hr)) if self.precip_1hr: lines.append("1-hour precipitation: %s" % str(self.precip_1hr)) if self.precip_3hr: lines.append("3-hour precipitation: %s" % str(self.precip_3hr)) if self.precip_6hr: lines.append("6-hour precipitation: %s" % str(self.precip_6hr)) if self.precip_24hr: lines.append("24-hour precipitation: %s" % str(self.precip_24hr)) if self._remarks: lines.append("remarks:") lines.append("- " + self.remarks("\n- ")) if self._unparsed_remarks: lines.append("- " + ' '.join(self._unparsed_remarks)) lines.append("METAR: " + self.code) return "\n".join(lines)
[ "def", "string", "(", "self", ")", ":", "# noqa: C901", "lines", "=", "[", "\"station: %s\"", "%", "self", ".", "station_id", "]", "if", "self", ".", "type", ":", "lines", ".", "append", "(", "\"type: %s\"", "%", "self", ".", "report_type", "(", ")", ")", "if", "self", ".", "time", ":", "lines", ".", "append", "(", "\"time: %s\"", "%", "self", ".", "time", ".", "ctime", "(", ")", ")", "if", "self", ".", "temp", ":", "lines", ".", "append", "(", "\"temperature: %s\"", "%", "self", ".", "temp", ".", "string", "(", "\"C\"", ")", ")", "if", "self", ".", "dewpt", ":", "lines", ".", "append", "(", "\"dew point: %s\"", "%", "self", ".", "dewpt", ".", "string", "(", "\"C\"", ")", ")", "if", "self", ".", "wind_speed", ":", "lines", ".", "append", "(", "\"wind: %s\"", "%", "self", ".", "wind", "(", ")", ")", "if", "self", ".", "wind_speed_peak", ":", "lines", ".", "append", "(", "\"peak wind: %s\"", "%", "self", ".", "peak_wind", "(", ")", ")", "if", "self", ".", "wind_shift_time", ":", "lines", ".", "append", "(", "\"wind shift: %s\"", "%", "self", ".", "wind_shift", "(", ")", ")", "if", "self", ".", "vis", ":", "lines", ".", "append", "(", "\"visibility: %s\"", "%", "self", ".", "visibility", "(", ")", ")", "if", "self", ".", "runway", ":", "lines", ".", "append", "(", "\"visual range: %s\"", "%", "self", ".", "runway_visual_range", "(", ")", ")", "if", "self", ".", "press", ":", "lines", ".", "append", "(", "f\"pressure: {self.press.string('MB')} {self.press.string('IN')} {self.press.string('MM')}\"", ")", "if", "self", ".", "weather", ":", "lines", ".", "append", "(", "\"weather: %s\"", "%", "self", ".", "present_weather", "(", ")", ")", "if", "self", ".", "sky", ":", "lines", ".", "append", "(", "\"sky: %s\"", "%", "self", ".", "sky_conditions", "(", "\"\\n \"", ")", ")", "if", "self", ".", "press_sea_level", ":", "lines", ".", "append", "(", "\"sea-level pressure: %s\"", "%", "self", ".", "press_sea_level", ".", "string", "(", "\"mb\"", ")", ")", "if", "self", ".", "max_temp_6hr", ":", "lines", ".", "append", "(", "\"6-hour max temp: %s\"", "%", "str", "(", "self", ".", "max_temp_6hr", ")", ")", "if", "self", ".", "max_temp_6hr", ":", "lines", ".", "append", "(", "\"6-hour min temp: %s\"", "%", "str", "(", "self", ".", "min_temp_6hr", ")", ")", "if", "self", ".", "max_temp_24hr", ":", "lines", ".", "append", "(", "\"24-hour max temp: %s\"", "%", "str", "(", "self", ".", "max_temp_24hr", ")", ")", "if", "self", ".", "max_temp_24hr", ":", "lines", ".", "append", "(", "\"24-hour min temp: %s\"", "%", "str", "(", "self", ".", "min_temp_24hr", ")", ")", "if", "self", ".", "precip_1hr", ":", "lines", ".", "append", "(", "\"1-hour precipitation: %s\"", "%", "str", "(", "self", ".", "precip_1hr", ")", ")", "if", "self", ".", "precip_3hr", ":", "lines", ".", "append", "(", "\"3-hour precipitation: %s\"", "%", "str", "(", "self", ".", "precip_3hr", ")", ")", "if", "self", ".", "precip_6hr", ":", "lines", ".", "append", "(", "\"6-hour precipitation: %s\"", "%", "str", "(", "self", ".", "precip_6hr", ")", ")", "if", "self", ".", "precip_24hr", ":", "lines", ".", "append", "(", "\"24-hour precipitation: %s\"", "%", "str", "(", "self", ".", "precip_24hr", ")", ")", "if", "self", ".", "_remarks", ":", "lines", ".", "append", "(", "\"remarks:\"", ")", "lines", ".", "append", "(", "\"- \"", "+", "self", ".", "remarks", "(", "\"\\n- \"", ")", ")", "if", "self", ".", "_unparsed_remarks", ":", "lines", ".", "append", "(", "\"- \"", "+", "' '", ".", "join", "(", "self", ".", "_unparsed_remarks", ")", ")", "lines", ".", "append", "(", "\"METAR: \"", "+", "self", ".", "code", ")", "return", "\"\\n\"", ".", "join", "(", "lines", ")" ]
Return a human-readable version of the decoded report.
[ "Return", "a", "human", "-", "readable", "version", "of", "the", "decoded", "report", "." ]
1c3e32711921d7e600e85558ffe5d337956372de
https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/weather/custom_metar/custom_metar.py#L63-L116
244,495
etcher-be/emiz
emiz/weather/custom_metar/custom_metar.py
CustomMetar._handlePressure
def _handlePressure(self, d): """ Parse an altimeter-pressure group. The following attributes are set: press [int] """ press = d['press'] if press != '////': press = float(press.replace('O', '0')) if d['unit']: if d['unit'] == 'A' or (d['unit2'] and d['unit2'] == 'INS'): self.press = CustomPressure(press / 100, 'IN') elif d['unit'] == 'SLP': if press < 500: press = press / 10 + 1000 else: press = press / 10 + 900 self.press = CustomPressure(press) self._remarks.append("sea-level pressure %.1fhPa" % press) else: self.press = CustomPressure(press) elif press > 2500: self.press = CustomPressure(press / 100, 'IN') else: self.press = CustomPressure(press)
python
def _handlePressure(self, d): """ Parse an altimeter-pressure group. The following attributes are set: press [int] """ press = d['press'] if press != '////': press = float(press.replace('O', '0')) if d['unit']: if d['unit'] == 'A' or (d['unit2'] and d['unit2'] == 'INS'): self.press = CustomPressure(press / 100, 'IN') elif d['unit'] == 'SLP': if press < 500: press = press / 10 + 1000 else: press = press / 10 + 900 self.press = CustomPressure(press) self._remarks.append("sea-level pressure %.1fhPa" % press) else: self.press = CustomPressure(press) elif press > 2500: self.press = CustomPressure(press / 100, 'IN') else: self.press = CustomPressure(press)
[ "def", "_handlePressure", "(", "self", ",", "d", ")", ":", "press", "=", "d", "[", "'press'", "]", "if", "press", "!=", "'////'", ":", "press", "=", "float", "(", "press", ".", "replace", "(", "'O'", ",", "'0'", ")", ")", "if", "d", "[", "'unit'", "]", ":", "if", "d", "[", "'unit'", "]", "==", "'A'", "or", "(", "d", "[", "'unit2'", "]", "and", "d", "[", "'unit2'", "]", "==", "'INS'", ")", ":", "self", ".", "press", "=", "CustomPressure", "(", "press", "/", "100", ",", "'IN'", ")", "elif", "d", "[", "'unit'", "]", "==", "'SLP'", ":", "if", "press", "<", "500", ":", "press", "=", "press", "/", "10", "+", "1000", "else", ":", "press", "=", "press", "/", "10", "+", "900", "self", ".", "press", "=", "CustomPressure", "(", "press", ")", "self", ".", "_remarks", ".", "append", "(", "\"sea-level pressure %.1fhPa\"", "%", "press", ")", "else", ":", "self", ".", "press", "=", "CustomPressure", "(", "press", ")", "elif", "press", ">", "2500", ":", "self", ".", "press", "=", "CustomPressure", "(", "press", "/", "100", ",", "'IN'", ")", "else", ":", "self", ".", "press", "=", "CustomPressure", "(", "press", ")" ]
Parse an altimeter-pressure group. The following attributes are set: press [int]
[ "Parse", "an", "altimeter", "-", "pressure", "group", "." ]
1c3e32711921d7e600e85558ffe5d337956372de
https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/weather/custom_metar/custom_metar.py#L118-L143
244,496
etcher-be/emiz
emiz/weather/custom_metar/custom_metar.py
CustomMetar._handleSealvlPressRemark
def _handleSealvlPressRemark(self, d): """ Parse the sea-level pressure remark group. """ value = float(d['press']) / 10.0 if value < 50: value += 1000 else: value += 900 if not self.press: self.press = CustomPressure(value) self.press_sea_level = CustomPressure(value)
python
def _handleSealvlPressRemark(self, d): """ Parse the sea-level pressure remark group. """ value = float(d['press']) / 10.0 if value < 50: value += 1000 else: value += 900 if not self.press: self.press = CustomPressure(value) self.press_sea_level = CustomPressure(value)
[ "def", "_handleSealvlPressRemark", "(", "self", ",", "d", ")", ":", "value", "=", "float", "(", "d", "[", "'press'", "]", ")", "/", "10.0", "if", "value", "<", "50", ":", "value", "+=", "1000", "else", ":", "value", "+=", "900", "if", "not", "self", ".", "press", ":", "self", ".", "press", "=", "CustomPressure", "(", "value", ")", "self", ".", "press_sea_level", "=", "CustomPressure", "(", "value", ")" ]
Parse the sea-level pressure remark group.
[ "Parse", "the", "sea", "-", "level", "pressure", "remark", "group", "." ]
1c3e32711921d7e600e85558ffe5d337956372de
https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/weather/custom_metar/custom_metar.py#L146-L157
244,497
scottgigante/tasklogger
tasklogger/api.py
get_tasklogger
def get_tasklogger(name="TaskLogger"): """Get a TaskLogger object Parameters ---------- logger : str, optional (default: "TaskLogger") Unique name of the logger to retrieve Returns ------- logger : TaskLogger """ try: return logging.getLogger(name).tasklogger except AttributeError: return logger.TaskLogger(name)
python
def get_tasklogger(name="TaskLogger"): """Get a TaskLogger object Parameters ---------- logger : str, optional (default: "TaskLogger") Unique name of the logger to retrieve Returns ------- logger : TaskLogger """ try: return logging.getLogger(name).tasklogger except AttributeError: return logger.TaskLogger(name)
[ "def", "get_tasklogger", "(", "name", "=", "\"TaskLogger\"", ")", ":", "try", ":", "return", "logging", ".", "getLogger", "(", "name", ")", ".", "tasklogger", "except", "AttributeError", ":", "return", "logger", ".", "TaskLogger", "(", "name", ")" ]
Get a TaskLogger object Parameters ---------- logger : str, optional (default: "TaskLogger") Unique name of the logger to retrieve Returns ------- logger : TaskLogger
[ "Get", "a", "TaskLogger", "object" ]
06a263715d2db0653615c17b2df14b8272967b8d
https://github.com/scottgigante/tasklogger/blob/06a263715d2db0653615c17b2df14b8272967b8d/tasklogger/api.py#L6-L21
244,498
scottgigante/tasklogger
tasklogger/api.py
log_debug
def log_debug(msg, logger="TaskLogger"): """Log a DEBUG message Convenience function to log a message to the default Logger Parameters ---------- msg : str Message to be logged logger : str, optional (default: "TaskLogger") Unique name of the logger to retrieve Returns ------- logger : TaskLogger """ tasklogger = get_tasklogger(logger) tasklogger.debug(msg) return tasklogger
python
def log_debug(msg, logger="TaskLogger"): """Log a DEBUG message Convenience function to log a message to the default Logger Parameters ---------- msg : str Message to be logged logger : str, optional (default: "TaskLogger") Unique name of the logger to retrieve Returns ------- logger : TaskLogger """ tasklogger = get_tasklogger(logger) tasklogger.debug(msg) return tasklogger
[ "def", "log_debug", "(", "msg", ",", "logger", "=", "\"TaskLogger\"", ")", ":", "tasklogger", "=", "get_tasklogger", "(", "logger", ")", "tasklogger", ".", "debug", "(", "msg", ")", "return", "tasklogger" ]
Log a DEBUG message Convenience function to log a message to the default Logger Parameters ---------- msg : str Message to be logged logger : str, optional (default: "TaskLogger") Unique name of the logger to retrieve Returns ------- logger : TaskLogger
[ "Log", "a", "DEBUG", "message" ]
06a263715d2db0653615c17b2df14b8272967b8d
https://github.com/scottgigante/tasklogger/blob/06a263715d2db0653615c17b2df14b8272967b8d/tasklogger/api.py#L68-L86
244,499
scottgigante/tasklogger
tasklogger/api.py
log_info
def log_info(msg, logger="TaskLogger"): """Log an INFO message Convenience function to log a message to the default Logger Parameters ---------- msg : str Message to be logged logger : str, optional (default: "TaskLogger") Unique name of the logger to retrieve Returns ------- logger : TaskLogger """ tasklogger = get_tasklogger(logger) tasklogger.info(msg) return tasklogger
python
def log_info(msg, logger="TaskLogger"): """Log an INFO message Convenience function to log a message to the default Logger Parameters ---------- msg : str Message to be logged logger : str, optional (default: "TaskLogger") Unique name of the logger to retrieve Returns ------- logger : TaskLogger """ tasklogger = get_tasklogger(logger) tasklogger.info(msg) return tasklogger
[ "def", "log_info", "(", "msg", ",", "logger", "=", "\"TaskLogger\"", ")", ":", "tasklogger", "=", "get_tasklogger", "(", "logger", ")", "tasklogger", ".", "info", "(", "msg", ")", "return", "tasklogger" ]
Log an INFO message Convenience function to log a message to the default Logger Parameters ---------- msg : str Message to be logged logger : str, optional (default: "TaskLogger") Unique name of the logger to retrieve Returns ------- logger : TaskLogger
[ "Log", "an", "INFO", "message" ]
06a263715d2db0653615c17b2df14b8272967b8d
https://github.com/scottgigante/tasklogger/blob/06a263715d2db0653615c17b2df14b8272967b8d/tasklogger/api.py#L89-L107