repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
unbservices/clams | clams/__init__.py | _parse_doc | def _parse_doc(doc=''):
"""Parse a docstring into title and description.
Args
----
doc : str
A docstring, optionally with a title line, separated from a description
line by at least one blank line.
Returns
-------
title : str
The first line of the docstring.
des... | python | def _parse_doc(doc=''):
"""Parse a docstring into title and description.
Args
----
doc : str
A docstring, optionally with a title line, separated from a description
line by at least one blank line.
Returns
-------
title : str
The first line of the docstring.
des... | [
"def",
"_parse_doc",
"(",
"doc",
"=",
"''",
")",
":",
"title",
",",
"description",
"=",
"''",
",",
"''",
"if",
"doc",
":",
"sp",
"=",
"doc",
".",
"split",
"(",
"'\\n'",
",",
"1",
")",
"title",
"=",
"sp",
"[",
"0",
"]",
".",
"strip",
"(",
")",... | Parse a docstring into title and description.
Args
----
doc : str
A docstring, optionally with a title line, separated from a description
line by at least one blank line.
Returns
-------
title : str
The first line of the docstring.
description : str
The rest... | [
"Parse",
"a",
"docstring",
"into",
"title",
"and",
"description",
"."
] | train | https://github.com/unbservices/clams/blob/2ae0a36eb8f82a153d27f74ef37688f976952789/clams/__init__.py#L154-L177 |
unbservices/clams | clams/__init__.py | command | def command(name):
"""Create a command, using the wrapped function as the handler.
Args
----
name : str
Name given to the created Command instance.
Returns
-------
Command
A new instance of Command, with handler set to the wrapped function.
"""
# TODO(nick): It wou... | python | def command(name):
"""Create a command, using the wrapped function as the handler.
Args
----
name : str
Name given to the created Command instance.
Returns
-------
Command
A new instance of Command, with handler set to the wrapped function.
"""
# TODO(nick): It wou... | [
"def",
"command",
"(",
"name",
")",
":",
"# TODO(nick): It would be nice if this didn't transform the handler. That",
"# way, handlers could be used and tested independently of this system.",
"# Unfortunately that's one of the better properties of the previous",
"# system that wasn't preser... | Create a command, using the wrapped function as the handler.
Args
----
name : str
Name given to the created Command instance.
Returns
-------
Command
A new instance of Command, with handler set to the wrapped function. | [
"Create",
"a",
"command",
"using",
"the",
"wrapped",
"function",
"as",
"the",
"handler",
"."
] | train | https://github.com/unbservices/clams/blob/2ae0a36eb8f82a153d27f74ef37688f976952789/clams/__init__.py#L180-L206 |
unbservices/clams | clams/__init__.py | register_command | def register_command(parent_command, name):
"""Create and register a command with a parent command.
Args
----
parent_comand : Command
The parent command.
name : str
Name given to the created Command instance.
Example
-------
.. testcode::
mygit = Command(name='s... | python | def register_command(parent_command, name):
"""Create and register a command with a parent command.
Args
----
parent_comand : Command
The parent command.
name : str
Name given to the created Command instance.
Example
-------
.. testcode::
mygit = Command(name='s... | [
"def",
"register_command",
"(",
"parent_command",
",",
"name",
")",
":",
"def",
"wrapper",
"(",
"func",
")",
":",
"c",
"=",
"command",
"(",
"name",
")",
"(",
"func",
")",
"parent_command",
".",
"add_subcommand",
"(",
"c",
")",
"return",
"wrapper"
] | Create and register a command with a parent command.
Args
----
parent_comand : Command
The parent command.
name : str
Name given to the created Command instance.
Example
-------
.. testcode::
mygit = Command(name='status')
@register_command(mygit, 'status')
... | [
"Create",
"and",
"register",
"a",
"command",
"with",
"a",
"parent",
"command",
"."
] | train | https://github.com/unbservices/clams/blob/2ae0a36eb8f82a153d27f74ef37688f976952789/clams/__init__.py#L246-L277 |
unbservices/clams | clams/__init__.py | Command._get_handler | def _get_handler(self, namespace, remove_handler=False):
"""Get a handler (if present) from a namespace.
Returns
-------
function or None
The handler defined in the namespace.
"""
if hasattr(namespace, '_func'):
_func = namespace._func
... | python | def _get_handler(self, namespace, remove_handler=False):
"""Get a handler (if present) from a namespace.
Returns
-------
function or None
The handler defined in the namespace.
"""
if hasattr(namespace, '_func'):
_func = namespace._func
... | [
"def",
"_get_handler",
"(",
"self",
",",
"namespace",
",",
"remove_handler",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"namespace",
",",
"'_func'",
")",
":",
"_func",
"=",
"namespace",
".",
"_func",
"if",
"remove_handler",
":",
"del",
"namespace",
".",... | Get a handler (if present) from a namespace.
Returns
-------
function or None
The handler defined in the namespace. | [
"Get",
"a",
"handler",
"(",
"if",
"present",
")",
"from",
"a",
"namespace",
"."
] | train | https://github.com/unbservices/clams/blob/2ae0a36eb8f82a153d27f74ef37688f976952789/clams/__init__.py#L345-L358 |
unbservices/clams | clams/__init__.py | Command._attach_arguments | def _attach_arguments(self):
"""Add the registered arguments to the parser."""
for arg in self.arguments:
self.parser.add_argument(*arg[0], **arg[1]) | python | def _attach_arguments(self):
"""Add the registered arguments to the parser."""
for arg in self.arguments:
self.parser.add_argument(*arg[0], **arg[1]) | [
"def",
"_attach_arguments",
"(",
"self",
")",
":",
"for",
"arg",
"in",
"self",
".",
"arguments",
":",
"self",
".",
"parser",
".",
"add_argument",
"(",
"*",
"arg",
"[",
"0",
"]",
",",
"*",
"*",
"arg",
"[",
"1",
"]",
")"
] | Add the registered arguments to the parser. | [
"Add",
"the",
"registered",
"arguments",
"to",
"the",
"parser",
"."
] | train | https://github.com/unbservices/clams/blob/2ae0a36eb8f82a153d27f74ef37688f976952789/clams/__init__.py#L360-L363 |
unbservices/clams | clams/__init__.py | Command._attach_subcommands | def _attach_subcommands(self):
"""Create a subparser and add the registered commands to it.
This will also call ``_init`` on each subcommand (in turn invoking its
``_attach_subcommands`` method).
"""
if self.subcommands:
self.subparsers = self.parser.add_subparsers()... | python | def _attach_subcommands(self):
"""Create a subparser and add the registered commands to it.
This will also call ``_init`` on each subcommand (in turn invoking its
``_attach_subcommands`` method).
"""
if self.subcommands:
self.subparsers = self.parser.add_subparsers()... | [
"def",
"_attach_subcommands",
"(",
"self",
")",
":",
"if",
"self",
".",
"subcommands",
":",
"self",
".",
"subparsers",
"=",
"self",
".",
"parser",
".",
"add_subparsers",
"(",
")",
"for",
"subcommand",
"in",
"self",
".",
"subcommands",
":",
"subparser",
"="... | Create a subparser and add the registered commands to it.
This will also call ``_init`` on each subcommand (in turn invoking its
``_attach_subcommands`` method). | [
"Create",
"a",
"subparser",
"and",
"add",
"the",
"registered",
"commands",
"to",
"it",
"."
] | train | https://github.com/unbservices/clams/blob/2ae0a36eb8f82a153d27f74ef37688f976952789/clams/__init__.py#L365-L379 |
unbservices/clams | clams/__init__.py | Command._init | def _init(self, parser):
"""Initialize/Build the ``argparse.ArgumentParser`` and subparsers.
This internal version of ``init`` is used to ensure that all
subcommands have a properly initialized parser.
Args
----
parser : argparse.ArgumentParser
The parser fo... | python | def _init(self, parser):
"""Initialize/Build the ``argparse.ArgumentParser`` and subparsers.
This internal version of ``init`` is used to ensure that all
subcommands have a properly initialized parser.
Args
----
parser : argparse.ArgumentParser
The parser fo... | [
"def",
"_init",
"(",
"self",
",",
"parser",
")",
":",
"assert",
"isinstance",
"(",
"parser",
",",
"argparse",
".",
"ArgumentParser",
")",
"self",
".",
"_init_parser",
"(",
"parser",
")",
"self",
".",
"_attach_arguments",
"(",
")",
"self",
".",
"_attach_sub... | Initialize/Build the ``argparse.ArgumentParser`` and subparsers.
This internal version of ``init`` is used to ensure that all
subcommands have a properly initialized parser.
Args
----
parser : argparse.ArgumentParser
The parser for this command. | [
"Initialize",
"/",
"Build",
"the",
"argparse",
".",
"ArgumentParser",
"and",
"subparsers",
"."
] | train | https://github.com/unbservices/clams/blob/2ae0a36eb8f82a153d27f74ef37688f976952789/clams/__init__.py#L381-L398 |
unbservices/clams | clams/__init__.py | Command.parse_args | def parse_args(self, args=None, namespace=None):
"""Parse the command-line arguments and call the associated handler.
The signature is the same as `argparse.ArgumentParser.parse_args
<https://docs.python.org/2/library/argparse.html#argparse.ArgumentParser.parse_args>`_.
Args
--... | python | def parse_args(self, args=None, namespace=None):
"""Parse the command-line arguments and call the associated handler.
The signature is the same as `argparse.ArgumentParser.parse_args
<https://docs.python.org/2/library/argparse.html#argparse.ArgumentParser.parse_args>`_.
Args
--... | [
"def",
"parse_args",
"(",
"self",
",",
"args",
"=",
"None",
",",
"namespace",
"=",
"None",
")",
":",
"assert",
"self",
".",
"initialized",
",",
"'`init` must be called before `parse_args`.'",
"namespace",
"=",
"self",
".",
"parser",
".",
"parse_args",
"(",
"ar... | Parse the command-line arguments and call the associated handler.
The signature is the same as `argparse.ArgumentParser.parse_args
<https://docs.python.org/2/library/argparse.html#argparse.ArgumentParser.parse_args>`_.
Args
----
args : list
A list of argument string... | [
"Parse",
"the",
"command",
"-",
"line",
"arguments",
"and",
"call",
"the",
"associated",
"handler",
"."
] | train | https://github.com/unbservices/clams/blob/2ae0a36eb8f82a153d27f74ef37688f976952789/clams/__init__.py#L414-L438 |
jut-io/jut-python-tools | jut/commands/jobs.py | _print_jobs | def _print_jobs(jobs, token_manager, app_url, options):
"""
internal method to print the provided jobs array in a nice tabular
format
"""
accountids = set()
for job in jobs:
if job['user'] != 'jut.internal.user':
accountids.add(job['user'])
account_lookup = {
'j... | python | def _print_jobs(jobs, token_manager, app_url, options):
"""
internal method to print the provided jobs array in a nice tabular
format
"""
accountids = set()
for job in jobs:
if job['user'] != 'jut.internal.user':
accountids.add(job['user'])
account_lookup = {
'j... | [
"def",
"_print_jobs",
"(",
"jobs",
",",
"token_manager",
",",
"app_url",
",",
"options",
")",
":",
"accountids",
"=",
"set",
"(",
")",
"for",
"job",
"in",
"jobs",
":",
"if",
"job",
"[",
"'user'",
"]",
"!=",
"'jut.internal.user'",
":",
"accountids",
".",
... | internal method to print the provided jobs array in a nice tabular
format | [
"internal",
"method",
"to",
"print",
"the",
"provided",
"jobs",
"array",
"in",
"a",
"nice",
"tabular",
"format"
] | train | https://github.com/jut-io/jut-python-tools/blob/65574d23f51a7bbced9bb25010d02da5ca5d906f/jut/commands/jobs.py#L22-L114 |
jut-io/jut-python-tools | jut/commands/jobs.py | list | def list(options):
"""
show all currently running jobs
"""
configuration = config.get_default()
app_url = configuration['app_url']
if options.deployment != None:
deployment_name = options.deployment
else:
deployment_name = configuration['deployment_name']
client_id = c... | python | def list(options):
"""
show all currently running jobs
"""
configuration = config.get_default()
app_url = configuration['app_url']
if options.deployment != None:
deployment_name = options.deployment
else:
deployment_name = configuration['deployment_name']
client_id = c... | [
"def",
"list",
"(",
"options",
")",
":",
"configuration",
"=",
"config",
".",
"get_default",
"(",
")",
"app_url",
"=",
"configuration",
"[",
"'app_url'",
"]",
"if",
"options",
".",
"deployment",
"!=",
"None",
":",
"deployment_name",
"=",
"options",
".",
"d... | show all currently running jobs | [
"show",
"all",
"currently",
"running",
"jobs"
] | train | https://github.com/jut-io/jut-python-tools/blob/65574d23f51a7bbced9bb25010d02da5ca5d906f/jut/commands/jobs.py#L116-L145 |
jut-io/jut-python-tools | jut/commands/jobs.py | kill | def kill(options):
"""
kill a specific job by id
"""
configuration = config.get_default()
app_url = configuration['app_url']
if options.deployment != None:
deployment_name = options.deployment
else:
deployment_name = configuration['deployment_name']
client_id = configu... | python | def kill(options):
"""
kill a specific job by id
"""
configuration = config.get_default()
app_url = configuration['app_url']
if options.deployment != None:
deployment_name = options.deployment
else:
deployment_name = configuration['deployment_name']
client_id = configu... | [
"def",
"kill",
"(",
"options",
")",
":",
"configuration",
"=",
"config",
".",
"get_default",
"(",
")",
"app_url",
"=",
"configuration",
"[",
"'app_url'",
"]",
"if",
"options",
".",
"deployment",
"!=",
"None",
":",
"deployment_name",
"=",
"options",
".",
"d... | kill a specific job by id | [
"kill",
"a",
"specific",
"job",
"by",
"id"
] | train | https://github.com/jut-io/jut-python-tools/blob/65574d23f51a7bbced9bb25010d02da5ca5d906f/jut/commands/jobs.py#L148-L188 |
xtrementl/focus | focus/registry.py | Registry.get | def get(self, key):
""" Executes the callable registered at the specified key and returns
its value. Subsequent queries are cached internally.
`key`
String key for a previously stored callable.
"""
if not key in self._actions:
return None... | python | def get(self, key):
""" Executes the callable registered at the specified key and returns
its value. Subsequent queries are cached internally.
`key`
String key for a previously stored callable.
"""
if not key in self._actions:
return None... | [
"def",
"get",
"(",
"self",
",",
"key",
")",
":",
"if",
"not",
"key",
"in",
"self",
".",
"_actions",
":",
"return",
"None",
"if",
"not",
"key",
"in",
"self",
".",
"_cache",
":",
"self",
".",
"_cache",
"[",
"key",
"]",
"=",
"self",
".",
"_actions",... | Executes the callable registered at the specified key and returns
its value. Subsequent queries are cached internally.
`key`
String key for a previously stored callable. | [
"Executes",
"the",
"callable",
"registered",
"at",
"the",
"specified",
"key",
"and",
"returns",
"its",
"value",
".",
"Subsequent",
"queries",
"are",
"cached",
"internally",
"."
] | train | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/registry.py#L30-L43 |
xtrementl/focus | focus/registry.py | Registry.register | def register(self, key, value):
""" Registers a callable with the specified key.
`key`
String key to identify a callable.
`value`
Callable object.
"""
self._actions[key] = value
# invalidate cache of results for existing key
... | python | def register(self, key, value):
""" Registers a callable with the specified key.
`key`
String key to identify a callable.
`value`
Callable object.
"""
self._actions[key] = value
# invalidate cache of results for existing key
... | [
"def",
"register",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"self",
".",
"_actions",
"[",
"key",
"]",
"=",
"value",
"# invalidate cache of results for existing key",
"if",
"key",
"in",
"self",
".",
"_cache",
":",
"del",
"self",
".",
"_cache",
"[",
... | Registers a callable with the specified key.
`key`
String key to identify a callable.
`value`
Callable object. | [
"Registers",
"a",
"callable",
"with",
"the",
"specified",
"key",
"."
] | train | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/registry.py#L45-L58 |
xtrementl/focus | focus/registry.py | Registry.deregister | def deregister(self, key):
""" Deregisters an existing key.
`key`
String key to deregister.
Returns boolean.
"""
if not key in self._actions:
return False
del self._actions[key]
if key in self._cache:
del se... | python | def deregister(self, key):
""" Deregisters an existing key.
`key`
String key to deregister.
Returns boolean.
"""
if not key in self._actions:
return False
del self._actions[key]
if key in self._cache:
del se... | [
"def",
"deregister",
"(",
"self",
",",
"key",
")",
":",
"if",
"not",
"key",
"in",
"self",
".",
"_actions",
":",
"return",
"False",
"del",
"self",
".",
"_actions",
"[",
"key",
"]",
"if",
"key",
"in",
"self",
".",
"_cache",
":",
"del",
"self",
".",
... | Deregisters an existing key.
`key`
String key to deregister.
Returns boolean. | [
"Deregisters",
"an",
"existing",
"key",
"."
] | train | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/registry.py#L60-L77 |
xtrementl/focus | focus/registry.py | ExtRegistry.get | def get(self, key):
""" Executes the callable registered at the specified key and returns
its value along with type info. Subsequent queries are cached
internally.
`key`
String key for a previously stored callable.
"""
obj = super(ExtRegi... | python | def get(self, key):
""" Executes the callable registered at the specified key and returns
its value along with type info. Subsequent queries are cached
internally.
`key`
String key for a previously stored callable.
"""
obj = super(ExtRegi... | [
"def",
"get",
"(",
"self",
",",
"key",
")",
":",
"obj",
"=",
"super",
"(",
"ExtRegistry",
",",
"self",
")",
".",
"get",
"(",
"key",
")",
"if",
"obj",
"is",
"None",
":",
"return",
"obj",
"return",
"(",
"obj",
",",
"self",
".",
"_type_info",
".",
... | Executes the callable registered at the specified key and returns
its value along with type info. Subsequent queries are cached
internally.
`key`
String key for a previously stored callable. | [
"Executes",
"the",
"callable",
"registered",
"at",
"the",
"specified",
"key",
"and",
"returns",
"its",
"value",
"along",
"with",
"type",
"info",
".",
"Subsequent",
"queries",
"are",
"cached",
"internally",
"."
] | train | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/registry.py#L95-L108 |
xtrementl/focus | focus/registry.py | ExtRegistry.register | def register(self, key, value, type_info):
""" Registers a callable with the specified key and type info.
`key`
String key to identify a callable.
`value`
Callable object.
`type_info`
Dictionary with type information about the ... | python | def register(self, key, value, type_info):
""" Registers a callable with the specified key and type info.
`key`
String key to identify a callable.
`value`
Callable object.
`type_info`
Dictionary with type information about the ... | [
"def",
"register",
"(",
"self",
",",
"key",
",",
"value",
",",
"type_info",
")",
":",
"# check for existing action",
"old_action",
"=",
"self",
".",
"_actions",
".",
"get",
"(",
"key",
")",
"# update existing type info if value hasn't changed",
"if",
"old_action",
... | Registers a callable with the specified key and type info.
`key`
String key to identify a callable.
`value`
Callable object.
`type_info`
Dictionary with type information about the value provided. | [
"Registers",
"a",
"callable",
"with",
"the",
"specified",
"key",
"and",
"type",
"info",
"."
] | train | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/registry.py#L110-L130 |
xtrementl/focus | focus/registry.py | ExtRegistry.deregister | def deregister(self, key):
""" Deregisters an existing key.
`key`
String key to deregister.
Returns boolean.
"""
res = super(ExtRegistry, self).deregister(key)
if key in self._type_info:
del self._type_info[key]
return re... | python | def deregister(self, key):
""" Deregisters an existing key.
`key`
String key to deregister.
Returns boolean.
"""
res = super(ExtRegistry, self).deregister(key)
if key in self._type_info:
del self._type_info[key]
return re... | [
"def",
"deregister",
"(",
"self",
",",
"key",
")",
":",
"res",
"=",
"super",
"(",
"ExtRegistry",
",",
"self",
")",
".",
"deregister",
"(",
"key",
")",
"if",
"key",
"in",
"self",
".",
"_type_info",
":",
"del",
"self",
".",
"_type_info",
"[",
"key",
... | Deregisters an existing key.
`key`
String key to deregister.
Returns boolean. | [
"Deregisters",
"an",
"existing",
"key",
"."
] | train | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/registry.py#L132-L144 |
svasilev94/GraphLibrary | graphlibrary/dijkstra.py | dijkstra | def dijkstra(G, start, weight='weight'):
"""
Compute shortest path length between satrt
and all other reachable nodes for a weight graph.
return -> ({vertex: weight form start, }, {vertex: predeseccor, })
"""
if start not in G.vertices:
raise GraphInsertError("Vertex %s doesn't ex... | python | def dijkstra(G, start, weight='weight'):
"""
Compute shortest path length between satrt
and all other reachable nodes for a weight graph.
return -> ({vertex: weight form start, }, {vertex: predeseccor, })
"""
if start not in G.vertices:
raise GraphInsertError("Vertex %s doesn't ex... | [
"def",
"dijkstra",
"(",
"G",
",",
"start",
",",
"weight",
"=",
"'weight'",
")",
":",
"if",
"start",
"not",
"in",
"G",
".",
"vertices",
":",
"raise",
"GraphInsertError",
"(",
"\"Vertex %s doesn't exist.\"",
"%",
"(",
"start",
",",
")",
")",
"visited",
"="... | Compute shortest path length between satrt
and all other reachable nodes for a weight graph.
return -> ({vertex: weight form start, }, {vertex: predeseccor, }) | [
"Compute",
"shortest",
"path",
"length",
"between",
"satrt",
"and",
"all",
"other",
"reachable",
"nodes",
"for",
"a",
"weight",
"graph",
".",
"return",
"-",
">",
"(",
"{",
"vertex",
":",
"weight",
"form",
"start",
"}",
"{",
"vertex",
":",
"predeseccor",
... | train | https://github.com/svasilev94/GraphLibrary/blob/bf979a80bdea17eeb25955f0c119ca8f711ef62b/graphlibrary/dijkstra.py#L6-L32 |
svasilev94/GraphLibrary | graphlibrary/dijkstra.py | dijkstra_single_path_length | def dijkstra_single_path_length(G, start, end):
"""
Compute shortest path length between satrt
and end for a weight graph. return -> (length, [path])
"""
if start not in G.vertices:
raise GraphInsertError("Vertex %s doesn't exist." % (start,))
if end not in G.vertices:
ra... | python | def dijkstra_single_path_length(G, start, end):
"""
Compute shortest path length between satrt
and end for a weight graph. return -> (length, [path])
"""
if start not in G.vertices:
raise GraphInsertError("Vertex %s doesn't exist." % (start,))
if end not in G.vertices:
ra... | [
"def",
"dijkstra_single_path_length",
"(",
"G",
",",
"start",
",",
"end",
")",
":",
"if",
"start",
"not",
"in",
"G",
".",
"vertices",
":",
"raise",
"GraphInsertError",
"(",
"\"Vertex %s doesn't exist.\"",
"%",
"(",
"start",
",",
")",
")",
"if",
"end",
"not... | Compute shortest path length between satrt
and end for a weight graph. return -> (length, [path]) | [
"Compute",
"shortest",
"path",
"length",
"between",
"satrt",
"and",
"end",
"for",
"a",
"weight",
"graph",
".",
"return",
"-",
">",
"(",
"length",
"[",
"path",
"]",
")"
] | train | https://github.com/svasilev94/GraphLibrary/blob/bf979a80bdea17eeb25955f0c119ca8f711ef62b/graphlibrary/dijkstra.py#L35-L54 |
KnowledgeLinks/rdfframework | rdfframework/ingesters/xmlingester.py | run_extractor | def run_extractor(*args, **kwargs):
"""
Initializes and runs an extractor
"""
# pdb.set_trace()
extractor = Extractor(*args, **kwargs)
result = extractor.run(**kwargs) | python | def run_extractor(*args, **kwargs):
"""
Initializes and runs an extractor
"""
# pdb.set_trace()
extractor = Extractor(*args, **kwargs)
result = extractor.run(**kwargs) | [
"def",
"run_extractor",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# pdb.set_trace()",
"extractor",
"=",
"Extractor",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"result",
"=",
"extractor",
".",
"run",
"(",
"*",
"*",
"kwargs",
")"
] | Initializes and runs an extractor | [
"Initializes",
"and",
"runs",
"an",
"extractor"
] | train | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/ingesters/xmlingester.py#L96-L102 |
KnowledgeLinks/rdfframework | rdfframework/ingesters/xmlingester.py | Extractor.run | def run(self, tag=None, output=None, **kwargs):
"""
runs the extractor
Args:
-----
output: ['filepath', None]
"""
start = datetime.datetime.now()
count = 0
if tag:
tag = Uri(tag)
xml_generator = etree.iterparse(self.so... | python | def run(self, tag=None, output=None, **kwargs):
"""
runs the extractor
Args:
-----
output: ['filepath', None]
"""
start = datetime.datetime.now()
count = 0
if tag:
tag = Uri(tag)
xml_generator = etree.iterparse(self.so... | [
"def",
"run",
"(",
"self",
",",
"tag",
"=",
"None",
",",
"output",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"start",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"count",
"=",
"0",
"if",
"tag",
":",
"tag",
"=",
"Uri",
"(",
"... | runs the extractor
Args:
-----
output: ['filepath', None] | [
"runs",
"the",
"extractor"
] | train | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/ingesters/xmlingester.py#L39-L77 |
KnowledgeLinks/rdfframework | rdfframework/datasets/RemoteException.py | exc_info | def exc_info(hide_calls = 0):
'''as sys.exc_info() but returns a remote exception object'''
ErrorType, thrownError, traceback = sys.exc_info()
for i in range(hide_calls):
if traceback.tb_next:
traceback = traceback.tb_next
err = withTracebackPrint(ErrorType, thrownError, traceback)
... | python | def exc_info(hide_calls = 0):
'''as sys.exc_info() but returns a remote exception object'''
ErrorType, thrownError, traceback = sys.exc_info()
for i in range(hide_calls):
if traceback.tb_next:
traceback = traceback.tb_next
err = withTracebackPrint(ErrorType, thrownError, traceback)
... | [
"def",
"exc_info",
"(",
"hide_calls",
"=",
"0",
")",
":",
"ErrorType",
",",
"thrownError",
",",
"traceback",
"=",
"sys",
".",
"exc_info",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"hide_calls",
")",
":",
"if",
"traceback",
".",
"tb_next",
":",
"traceba... | as sys.exc_info() but returns a remote exception object | [
"as",
"sys",
".",
"exc_info",
"()",
"but",
"returns",
"a",
"remote",
"exception",
"object"
] | train | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/datasets/RemoteException.py#L7-L14 |
KnowledgeLinks/rdfframework | rdfframework/datasets/RemoteException.py | withTracebackPrint | def withTracebackPrint(ErrorType, thrownError, _traceback):
'''returns an Exception object for the given ErrorType of the thrownError
and the _traceback
can be used like withTracebackPrint(*sys.exc_info())'''
file = StringIO.StringIO()
traceback.print_exception(ErrorType, thrownError, _traceback, file = fi... | python | def withTracebackPrint(ErrorType, thrownError, _traceback):
'''returns an Exception object for the given ErrorType of the thrownError
and the _traceback
can be used like withTracebackPrint(*sys.exc_info())'''
file = StringIO.StringIO()
traceback.print_exception(ErrorType, thrownError, _traceback, file = fi... | [
"def",
"withTracebackPrint",
"(",
"ErrorType",
",",
"thrownError",
",",
"_traceback",
")",
":",
"file",
"=",
"StringIO",
".",
"StringIO",
"(",
")",
"traceback",
".",
"print_exception",
"(",
"ErrorType",
",",
"thrownError",
",",
"_traceback",
",",
"file",
"=",
... | returns an Exception object for the given ErrorType of the thrownError
and the _traceback
can be used like withTracebackPrint(*sys.exc_info()) | [
"returns",
"an",
"Exception",
"object",
"for",
"the",
"given",
"ErrorType",
"of",
"the",
"thrownError",
"and",
"the",
"_traceback"
] | train | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/datasets/RemoteException.py#L16-L23 |
KnowledgeLinks/rdfframework | rdfframework/datasets/RemoteException.py | _newRemoteException | def _newRemoteException(ErrorType):
'''create a new RemoteExceptionType from a given errortype'''
RemoteErrorBaseType = _RemoteExceptionMeta('', (ErrorType,), {})
class RemoteException(RemoteErrorBaseType):
BaseExceptionType = ErrorType
def __init__(self, thrownError, tracebackString):
... | python | def _newRemoteException(ErrorType):
'''create a new RemoteExceptionType from a given errortype'''
RemoteErrorBaseType = _RemoteExceptionMeta('', (ErrorType,), {})
class RemoteException(RemoteErrorBaseType):
BaseExceptionType = ErrorType
def __init__(self, thrownError, tracebackString):
... | [
"def",
"_newRemoteException",
"(",
"ErrorType",
")",
":",
"RemoteErrorBaseType",
"=",
"_RemoteExceptionMeta",
"(",
"''",
",",
"(",
"ErrorType",
",",
")",
",",
"{",
"}",
")",
"class",
"RemoteException",
"(",
"RemoteErrorBaseType",
")",
":",
"BaseExceptionType",
"... | create a new RemoteExceptionType from a given errortype | [
"create",
"a",
"new",
"RemoteExceptionType",
"from",
"a",
"given",
"errortype"
] | train | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/datasets/RemoteException.py#L41-L61 |
KnowledgeLinks/rdfframework | rdfframework/datasets/RemoteException.py | asRemoteException | def asRemoteException(ErrorType):
'''return the remote exception version of the error above
you can catch errors as usally:
>>> try:
raise asRemoteException(ValueError)
except ValueError:
pass
or you can catch the remote Exception
>>> try:
raise asRemoteException(ReferenceError)(ReferenceError(),'')
except asRemote... | python | def asRemoteException(ErrorType):
'''return the remote exception version of the error above
you can catch errors as usally:
>>> try:
raise asRemoteException(ValueError)
except ValueError:
pass
or you can catch the remote Exception
>>> try:
raise asRemoteException(ReferenceError)(ReferenceError(),'')
except asRemote... | [
"def",
"asRemoteException",
"(",
"ErrorType",
")",
":",
"RemoteException",
"=",
"_remoteExceptionCache",
".",
"get",
"(",
"ErrorType",
")",
"if",
"RemoteException",
"is",
"None",
":",
"RemoteException",
"=",
"_newRemoteException",
"(",
"ErrorType",
")",
"_remoteExce... | return the remote exception version of the error above
you can catch errors as usally:
>>> try:
raise asRemoteException(ValueError)
except ValueError:
pass
or you can catch the remote Exception
>>> try:
raise asRemoteException(ReferenceError)(ReferenceError(),'')
except asRemoteException(ReferenceError):
pass | [
"return",
"the",
"remote",
"exception",
"version",
"of",
"the",
"error",
"above",
"you",
"can",
"catch",
"errors",
"as",
"usally",
":",
">>>",
"try",
":",
"raise",
"asRemoteException",
"(",
"ValueError",
")",
"except",
"ValueError",
":",
"pass",
"or",
"you",... | train | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/datasets/RemoteException.py#L64-L83 |
KnowledgeLinks/rdfframework | rdfframework/datasets/RemoteException.py | _loadError | def _loadError(ErrorType, thrownError, tracebackString):
'''constructor of RemoteExceptions'''
RemoteException = asRemoteException(ErrorType)
return RemoteException(thrownError, tracebackString) | python | def _loadError(ErrorType, thrownError, tracebackString):
'''constructor of RemoteExceptions'''
RemoteException = asRemoteException(ErrorType)
return RemoteException(thrownError, tracebackString) | [
"def",
"_loadError",
"(",
"ErrorType",
",",
"thrownError",
",",
"tracebackString",
")",
":",
"RemoteException",
"=",
"asRemoteException",
"(",
"ErrorType",
")",
"return",
"RemoteException",
"(",
"thrownError",
",",
"tracebackString",
")"
] | constructor of RemoteExceptions | [
"constructor",
"of",
"RemoteExceptions"
] | train | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/datasets/RemoteException.py#L85-L88 |
c0ntrol-x/p4rr0t007 | p4rr0t007/web.py | Application.json_response | def json_response(self, data, code=200, indent=2, headers={}):
"""Useful for restful APIs
:param data: a native python object, must be json serialiable, otherwise will be handled by :py:meth:`Application.json_handle_weird`
:param code: the http status code
:param indent: how many charact... | python | def json_response(self, data, code=200, indent=2, headers={}):
"""Useful for restful APIs
:param data: a native python object, must be json serialiable, otherwise will be handled by :py:meth:`Application.json_handle_weird`
:param code: the http status code
:param indent: how many charact... | [
"def",
"json_response",
"(",
"self",
",",
"data",
",",
"code",
"=",
"200",
",",
"indent",
"=",
"2",
",",
"headers",
"=",
"{",
"}",
")",
":",
"headers",
"=",
"headers",
".",
"copy",
"(",
")",
"headers",
"[",
"'Content-Type'",
"]",
"=",
"'application/j... | Useful for restful APIs
:param data: a native python object, must be json serialiable, otherwise will be handled by :py:meth:`Application.json_handle_weird`
:param code: the http status code
:param indent: how many characters to indent when generating the json
:param headers: a dict with... | [
"Useful",
"for",
"restful",
"APIs",
":",
"param",
"data",
":",
"a",
"native",
"python",
"object",
"must",
"be",
"json",
"serialiable",
"otherwise",
"will",
"be",
"handled",
"by",
":",
"py",
":",
"meth",
":",
"Application",
".",
"json_handle_weird",
":",
"p... | train | https://github.com/c0ntrol-x/p4rr0t007/blob/6fe88ec1231a778b9f1d13bc61332581715d646e/p4rr0t007/web.py#L70-L82 |
c0ntrol-x/p4rr0t007 | p4rr0t007/web.py | Application.template_response | def template_response(self, name, context=None, content_type='text/html', code=200, minify=True):
"""
:param name: the name of the template file, must exist inside of the configured ``template_folder`` parameter of the class constructor.
:param context: a dictionary whose keys will be available ... | python | def template_response(self, name, context=None, content_type='text/html', code=200, minify=True):
"""
:param name: the name of the template file, must exist inside of the configured ``template_folder`` parameter of the class constructor.
:param context: a dictionary whose keys will be available ... | [
"def",
"template_response",
"(",
"self",
",",
"name",
",",
"context",
"=",
"None",
",",
"content_type",
"=",
"'text/html'",
",",
"code",
"=",
"200",
",",
"minify",
"=",
"True",
")",
":",
"context",
"=",
"OrderedDict",
"(",
"context",
"or",
"{",
"}",
")... | :param name: the name of the template file, must exist inside of the configured ``template_folder`` parameter of the class constructor.
:param context: a dictionary whose keys will be available within the target template file.
:param content_type: a string with the content-type. Defaults to ``text/html`... | [
":",
"param",
"name",
":",
"the",
"name",
"of",
"the",
"template",
"file",
"must",
"exist",
"inside",
"of",
"the",
"configured",
"template_folder",
"parameter",
"of",
"the",
"class",
"constructor",
".",
":",
"param",
"context",
":",
"a",
"dictionary",
"whose... | train | https://github.com/c0ntrol-x/p4rr0t007/blob/6fe88ec1231a778b9f1d13bc61332581715d646e/p4rr0t007/web.py#L84-L105 |
c0ntrol-x/p4rr0t007 | p4rr0t007/web.py | Application.text_response | def text_response(self, contents, code=200, headers={}):
"""shortcut to return simple plain/text messages in the response.
:param contents: a string with the response contents
:param code: the http status code
:param headers: a dict with optional headers
:returns: a :py:class:`f... | python | def text_response(self, contents, code=200, headers={}):
"""shortcut to return simple plain/text messages in the response.
:param contents: a string with the response contents
:param code: the http status code
:param headers: a dict with optional headers
:returns: a :py:class:`f... | [
"def",
"text_response",
"(",
"self",
",",
"contents",
",",
"code",
"=",
"200",
",",
"headers",
"=",
"{",
"}",
")",
":",
"return",
"Response",
"(",
"contents",
",",
"status",
"=",
"code",
",",
"headers",
"=",
"{",
"'Content-Type'",
":",
"'text/plain'",
... | shortcut to return simple plain/text messages in the response.
:param contents: a string with the response contents
:param code: the http status code
:param headers: a dict with optional headers
:returns: a :py:class:`flask.Response` with the ``text/plain`` **Content-Type** header. | [
"shortcut",
"to",
"return",
"simple",
"plain",
"/",
"text",
"messages",
"in",
"the",
"response",
"."
] | train | https://github.com/c0ntrol-x/p4rr0t007/blob/6fe88ec1231a778b9f1d13bc61332581715d646e/p4rr0t007/web.py#L107-L117 |
c0ntrol-x/p4rr0t007 | p4rr0t007/web.py | Application.get_json_request | def get_json_request(self):
"""
friendly method to parse a proper json request (i.e.: **application/json** or **text/json**)
:returns: a dict with the parsed data, unless the request data does not contain a valid json string or the content-type do not portray a json request.
"""
... | python | def get_json_request(self):
"""
friendly method to parse a proper json request (i.e.: **application/json** or **text/json**)
:returns: a dict with the parsed data, unless the request data does not contain a valid json string or the content-type do not portray a json request.
"""
... | [
"def",
"get_json_request",
"(",
"self",
")",
":",
"content_type",
"=",
"request",
".",
"headers",
".",
"get",
"(",
"'Content-Type'",
",",
"'text/plain'",
")",
"if",
"content_type",
"not",
"in",
"(",
"'application/json'",
",",
"'text/json'",
")",
":",
"self",
... | friendly method to parse a proper json request (i.e.: **application/json** or **text/json**)
:returns: a dict with the parsed data, unless the request data does not contain a valid json string or the content-type do not portray a json request. | [
"friendly",
"method",
"to",
"parse",
"a",
"proper",
"json",
"request",
"(",
"i",
".",
"e",
".",
":",
"**",
"application",
"/",
"json",
"**",
"or",
"**",
"text",
"/",
"json",
"**",
")",
":",
"returns",
":",
"a",
"dict",
"with",
"the",
"parsed",
"dat... | train | https://github.com/c0ntrol-x/p4rr0t007/blob/6fe88ec1231a778b9f1d13bc61332581715d646e/p4rr0t007/web.py#L119-L138 |
c0ntrol-x/p4rr0t007 | p4rr0t007/web.py | Application.handle_exception | def handle_exception(self, e):
"""called by flask when an exception happens. p4rr0t007 always returns
a 500.html response that must exist under the given
``template_folder`` constructor param.
"""
sys.stderr.write("p4rr0t007 handled an error:")
sys.stderr.write(traceback.... | python | def handle_exception(self, e):
"""called by flask when an exception happens. p4rr0t007 always returns
a 500.html response that must exist under the given
``template_folder`` constructor param.
"""
sys.stderr.write("p4rr0t007 handled an error:")
sys.stderr.write(traceback.... | [
"def",
"handle_exception",
"(",
"self",
",",
"e",
")",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"p4rr0t007 handled an error:\"",
")",
"sys",
".",
"stderr",
".",
"write",
"(",
"traceback",
".",
"format_exc",
"(",
"e",
")",
")",
"sys",
".",
"stderr"... | called by flask when an exception happens. p4rr0t007 always returns
a 500.html response that must exist under the given
``template_folder`` constructor param. | [
"called",
"by",
"flask",
"when",
"an",
"exception",
"happens",
".",
"p4rr0t007",
"always",
"returns",
"a",
"500",
".",
"html",
"response",
"that",
"must",
"exist",
"under",
"the",
"given",
"template_folder",
"constructor",
"param",
"."
] | train | https://github.com/c0ntrol-x/p4rr0t007/blob/6fe88ec1231a778b9f1d13bc61332581715d646e/p4rr0t007/web.py#L140-L157 |
rohithpr/py-timed-dialog | ptd/dialog.py | TimedDialog.button_input | def button_input(self, title, message, buttons, default, timeout=None, dimensions=None):
'''
Function to accept input in the form of a button click.
'''
# Create the dialog box
self.response = default
self.top = tkinter.Tk()
self.top.title(title)
# Use d... | python | def button_input(self, title, message, buttons, default, timeout=None, dimensions=None):
'''
Function to accept input in the form of a button click.
'''
# Create the dialog box
self.response = default
self.top = tkinter.Tk()
self.top.title(title)
# Use d... | [
"def",
"button_input",
"(",
"self",
",",
"title",
",",
"message",
",",
"buttons",
",",
"default",
",",
"timeout",
"=",
"None",
",",
"dimensions",
"=",
"None",
")",
":",
"# Create the dialog box",
"self",
".",
"response",
"=",
"default",
"self",
".",
"top",... | Function to accept input in the form of a button click. | [
"Function",
"to",
"accept",
"input",
"in",
"the",
"form",
"of",
"a",
"button",
"click",
"."
] | train | https://github.com/rohithpr/py-timed-dialog/blob/6ca2d8d3ea4da5bac016d4b2f56c3c3a822ecf56/ptd/dialog.py#L25-L59 |
mgagne/wafflehaus.iweb | wafflehaus/iweb/keystone/user_filter/blacklist.py | filter_factory | def filter_factory(global_conf, **local_conf):
"""Returns a WSGI filter app for use with paste.deploy."""
conf = global_conf.copy()
conf.update(local_conf)
def blacklist(app):
return BlacklistFilter(app, conf)
return blacklist | python | def filter_factory(global_conf, **local_conf):
"""Returns a WSGI filter app for use with paste.deploy."""
conf = global_conf.copy()
conf.update(local_conf)
def blacklist(app):
return BlacklistFilter(app, conf)
return blacklist | [
"def",
"filter_factory",
"(",
"global_conf",
",",
"*",
"*",
"local_conf",
")",
":",
"conf",
"=",
"global_conf",
".",
"copy",
"(",
")",
"conf",
".",
"update",
"(",
"local_conf",
")",
"def",
"blacklist",
"(",
"app",
")",
":",
"return",
"BlacklistFilter",
"... | Returns a WSGI filter app for use with paste.deploy. | [
"Returns",
"a",
"WSGI",
"filter",
"app",
"for",
"use",
"with",
"paste",
".",
"deploy",
"."
] | train | https://github.com/mgagne/wafflehaus.iweb/blob/8ac625582c1180391fe022d1db19f70a2dfb376a/wafflehaus/iweb/keystone/user_filter/blacklist.py#L89-L96 |
sysr-q/chrw | chrw/v1.py | rate_limited | def rate_limited(max_per_second):
""" Sort of based off of an answer about
rate limiting on Stack Overflow.
Definitely **not** thread safe, so
don't even think about it, buddy.
"""
import datetime
min_request_time = datetime.timedelta(seconds=max_per_second)
last_time_called... | python | def rate_limited(max_per_second):
""" Sort of based off of an answer about
rate limiting on Stack Overflow.
Definitely **not** thread safe, so
don't even think about it, buddy.
"""
import datetime
min_request_time = datetime.timedelta(seconds=max_per_second)
last_time_called... | [
"def",
"rate_limited",
"(",
"max_per_second",
")",
":",
"import",
"datetime",
"min_request_time",
"=",
"datetime",
".",
"timedelta",
"(",
"seconds",
"=",
"max_per_second",
")",
"last_time_called",
"=",
"[",
"None",
"]",
"def",
"decorate",
"(",
"func",
")",
":"... | Sort of based off of an answer about
rate limiting on Stack Overflow.
Definitely **not** thread safe, so
don't even think about it, buddy. | [
"Sort",
"of",
"based",
"off",
"of",
"an",
"answer",
"about",
"rate",
"limiting",
"on",
"Stack",
"Overflow",
"."
] | train | https://github.com/sysr-q/chrw/blob/071b53f5bd4fdea06599e6b95997db53ed930f7b/chrw/v1.py#L14-L39 |
sysr-q/chrw | chrw/v1.py | wrapper.shorten | def shorten(self, url, custom=None, give_delete=True):
"""
Sends a URL shorten request to the API.
:param url: the URL to shrink
:type url: str
:param custom: a custom URL to request
:type custom: str
:param give_delete: would we like a de... | python | def shorten(self, url, custom=None, give_delete=True):
"""
Sends a URL shorten request to the API.
:param url: the URL to shrink
:type url: str
:param custom: a custom URL to request
:type custom: str
:param give_delete: would we like a de... | [
"def",
"shorten",
"(",
"self",
",",
"url",
",",
"custom",
"=",
"None",
",",
"give_delete",
"=",
"True",
")",
":",
"data",
"=",
"self",
".",
"fetch",
"(",
"\"/submit\"",
",",
"{",
"\"long\"",
":",
"url",
",",
"\"short\"",
":",
"custom",
"if",
"custom"... | Sends a URL shorten request to the API.
:param url: the URL to shrink
:type url: str
:param custom: a custom URL to request
:type custom: str
:param give_delete: would we like a deletion key to be returned?
:type give_delete: bool
:ret... | [
"Sends",
"a",
"URL",
"shorten",
"request",
"to",
"the",
"API",
"."
] | train | https://github.com/sysr-q/chrw/blob/071b53f5bd4fdea06599e6b95997db53ed930f7b/chrw/v1.py#L78-L97 |
sysr-q/chrw | chrw/v1.py | wrapper.delete | def delete(self, url, code):
"""
Request a URL be deleted.
This will only work if you supply the valid deletion code.
:param url: the shortened url to delete
:type url: str
:param code: the deletion code given to you on URL shorten
:type ... | python | def delete(self, url, code):
"""
Request a URL be deleted.
This will only work if you supply the valid deletion code.
:param url: the shortened url to delete
:type url: str
:param code: the deletion code given to you on URL shorten
:type ... | [
"def",
"delete",
"(",
"self",
",",
"url",
",",
"code",
")",
":",
"data",
"=",
"self",
".",
"fetch",
"(",
"\"/delete\"",
",",
"{",
"\"short\"",
":",
"url",
",",
"\"delete\"",
":",
"code",
"}",
")",
"return",
"data"
] | Request a URL be deleted.
This will only work if you supply the valid deletion code.
:param url: the shortened url to delete
:type url: str
:param code: the deletion code given to you on URL shorten
:type code: str
:return: the deletion request's... | [
"Request",
"a",
"URL",
"be",
"deleted",
"."
] | train | https://github.com/sysr-q/chrw/blob/071b53f5bd4fdea06599e6b95997db53ed930f7b/chrw/v1.py#L114-L132 |
sysr-q/chrw | chrw/v1.py | wrapper.fetch | def fetch(self, url, pdata, store_to_self=True):
"""
This does the bulk of the work for the wrapper.
It will send a POST request, to the API URL, with
all required data, as well as the api_key given,
and will handle various replies, raising exceptions
... | python | def fetch(self, url, pdata, store_to_self=True):
"""
This does the bulk of the work for the wrapper.
It will send a POST request, to the API URL, with
all required data, as well as the api_key given,
and will handle various replies, raising exceptions
... | [
"def",
"fetch",
"(",
"self",
",",
"url",
",",
"pdata",
",",
"store_to_self",
"=",
"True",
")",
":",
"url",
"=",
"self",
".",
"schema",
"+",
"'://'",
"+",
"self",
".",
"base",
"+",
"url",
"post",
"=",
"dict",
"(",
"pdata",
".",
"items",
"(",
")",
... | This does the bulk of the work for the wrapper.
It will send a POST request, to the API URL, with
all required data, as well as the api_key given,
and will handle various replies, raising exceptions
as required.
:param url: the url segment to POST to (unbuil... | [
"This",
"does",
"the",
"bulk",
"of",
"the",
"work",
"for",
"the",
"wrapper",
"."
] | train | https://github.com/sysr-q/chrw/blob/071b53f5bd4fdea06599e6b95997db53ed930f7b/chrw/v1.py#L151-L198 |
Ceasar/easywatch | easywatch/easywatch.py | watch | def watch(path, handler):
"""Watch a directory for events.
- path should be the directory to watch
- handler should a function which takes an event_type and src_path
and does something interesting. event_type will be one of 'created',
'deleted', 'modified', or 'moved'. src_path will be t... | python | def watch(path, handler):
"""Watch a directory for events.
- path should be the directory to watch
- handler should a function which takes an event_type and src_path
and does something interesting. event_type will be one of 'created',
'deleted', 'modified', or 'moved'. src_path will be t... | [
"def",
"watch",
"(",
"path",
",",
"handler",
")",
":",
"# let the user just deal with events",
"@",
"functools",
".",
"wraps",
"(",
"handler",
")",
"def",
"wrapper",
"(",
"self",
",",
"event",
")",
":",
"if",
"not",
"event",
".",
"is_directory",
":",
"retu... | Watch a directory for events.
- path should be the directory to watch
- handler should a function which takes an event_type and src_path
and does something interesting. event_type will be one of 'created',
'deleted', 'modified', or 'moved'. src_path will be the absolute
path to the f... | [
"Watch",
"a",
"directory",
"for",
"events",
".",
"-",
"path",
"should",
"be",
"the",
"directory",
"to",
"watch",
"-",
"handler",
"should",
"a",
"function",
"which",
"takes",
"an",
"event_type",
"and",
"src_path",
"and",
"does",
"something",
"interesting",
".... | train | https://github.com/Ceasar/easywatch/blob/1dd464d2acca5932473759b187dec4eb63dab2d9/easywatch/easywatch.py#L13-L36 |
cfobel/clutter-webcam-viewer | clutter_webcam_viewer/warp.py | WarpActor.rotate | def rotate(self, shift):
'''
Rotate 90 degrees clockwise `shift` times. If `shift` is negative,
rotate counter-clockwise.
'''
self.child_corners.values[:] = np.roll(self.child_corners
.values, shift, axis=0)
self.update_tr... | python | def rotate(self, shift):
'''
Rotate 90 degrees clockwise `shift` times. If `shift` is negative,
rotate counter-clockwise.
'''
self.child_corners.values[:] = np.roll(self.child_corners
.values, shift, axis=0)
self.update_tr... | [
"def",
"rotate",
"(",
"self",
",",
"shift",
")",
":",
"self",
".",
"child_corners",
".",
"values",
"[",
":",
"]",
"=",
"np",
".",
"roll",
"(",
"self",
".",
"child_corners",
".",
"values",
",",
"shift",
",",
"axis",
"=",
"0",
")",
"self",
".",
"up... | Rotate 90 degrees clockwise `shift` times. If `shift` is negative,
rotate counter-clockwise. | [
"Rotate",
"90",
"degrees",
"clockwise",
"shift",
"times",
".",
"If",
"shift",
"is",
"negative",
"rotate",
"counter",
"-",
"clockwise",
"."
] | train | https://github.com/cfobel/clutter-webcam-viewer/blob/b227d2ae02d750194e65c13bcf178550755c3afc/clutter_webcam_viewer/warp.py#L109-L116 |
ymotongpoo/pysuddendeath | suddendeath/__init__.py | message_length | def message_length(message):
'''
message_length returns visual length of message.
Ascii chars are counted as 1, non-asciis are 2.
:param str message: random unicode mixed text
:rtype: int
'''
length = 0
for char in map(east_asian_width, message):
if char == 'W':
leng... | python | def message_length(message):
'''
message_length returns visual length of message.
Ascii chars are counted as 1, non-asciis are 2.
:param str message: random unicode mixed text
:rtype: int
'''
length = 0
for char in map(east_asian_width, message):
if char == 'W':
leng... | [
"def",
"message_length",
"(",
"message",
")",
":",
"length",
"=",
"0",
"for",
"char",
"in",
"map",
"(",
"east_asian_width",
",",
"message",
")",
":",
"if",
"char",
"==",
"'W'",
":",
"length",
"+=",
"2",
"elif",
"char",
"==",
"'Na'",
":",
"length",
"+... | message_length returns visual length of message.
Ascii chars are counted as 1, non-asciis are 2.
:param str message: random unicode mixed text
:rtype: int | [
"message_length",
"returns",
"visual",
"length",
"of",
"message",
".",
"Ascii",
"chars",
"are",
"counted",
"as",
"1",
"non",
"-",
"asciis",
"are",
"2",
"."
] | train | https://github.com/ymotongpoo/pysuddendeath/blob/2ce26d3229e60ce1f1fd5f032a7b0512dec25c5a/suddendeath/__init__.py#L32-L47 |
ymotongpoo/pysuddendeath | suddendeath/__init__.py | suddendeathmessage | def suddendeathmessage(message):
'''
suddendeathmessage returns "突然の死" like ascii art decorated message string.
:param str message: random unicode mixed text
:rtype: str
'''
msg_len = message_length(message)
header_len = msg_len // 2 + 2
footer_len = (msg_len // 2) * 2 + 1
footer_pa... | python | def suddendeathmessage(message):
'''
suddendeathmessage returns "突然の死" like ascii art decorated message string.
:param str message: random unicode mixed text
:rtype: str
'''
msg_len = message_length(message)
header_len = msg_len // 2 + 2
footer_len = (msg_len // 2) * 2 + 1
footer_pa... | [
"def",
"suddendeathmessage",
"(",
"message",
")",
":",
"msg_len",
"=",
"message_length",
"(",
"message",
")",
"header_len",
"=",
"msg_len",
"//",
"2",
"+",
"2",
"footer_len",
"=",
"(",
"msg_len",
"//",
"2",
")",
"*",
"2",
"+",
"1",
"footer_pattern",
"=",... | suddendeathmessage returns "突然の死" like ascii art decorated message string.
:param str message: random unicode mixed text
:rtype: str | [
"suddendeathmessage",
"returns",
"突然の死",
"like",
"ascii",
"art",
"decorated",
"message",
"string",
"."
] | train | https://github.com/ymotongpoo/pysuddendeath/blob/2ce26d3229e60ce1f1fd5f032a7b0512dec25c5a/suddendeath/__init__.py#L50-L69 |
openpermissions/perch | perch/migrate.py | migration | def migration(resource, version, previous_version=''):
"""Register a migration function"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
migrated = func(*args, **kwargs)
return migrated
m = Migration(wrapper, resource, version, previous_version... | python | def migration(resource, version, previous_version=''):
"""Register a migration function"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
migrated = func(*args, **kwargs)
return migrated
m = Migration(wrapper, resource, version, previous_version... | [
"def",
"migration",
"(",
"resource",
",",
"version",
",",
"previous_version",
"=",
"''",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"mi... | Register a migration function | [
"Register",
"a",
"migration",
"function"
] | train | https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/migrate.py#L101-L115 |
openpermissions/perch | perch/migrate.py | create | def create(resource_path, previous_version=None, package='perch.migrations'):
"""Create a new migration"""
pkg, obj = resource_path.rsplit('.', 1)
module = importlib.import_module(pkg)
resource = getattr(module, obj)
version = uuid4().hex
target_module = importlib.import_module(package)
targ... | python | def create(resource_path, previous_version=None, package='perch.migrations'):
"""Create a new migration"""
pkg, obj = resource_path.rsplit('.', 1)
module = importlib.import_module(pkg)
resource = getattr(module, obj)
version = uuid4().hex
target_module = importlib.import_module(package)
targ... | [
"def",
"create",
"(",
"resource_path",
",",
"previous_version",
"=",
"None",
",",
"package",
"=",
"'perch.migrations'",
")",
":",
"pkg",
",",
"obj",
"=",
"resource_path",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"module",
"=",
"importlib",
".",
"import_mo... | Create a new migration | [
"Create",
"a",
"new",
"migration"
] | train | https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/migrate.py#L118-L136 |
openpermissions/perch | perch/migrate.py | collect | def collect(package='perch.migrations'):
"""
Import all modules inside the perch.migrations package and return the
registered migrations
"""
package = importlib.import_module(package)
for loader, name, is_pkg in pkgutil.walk_packages(package.__path__):
importlib.import_module(package.__... | python | def collect(package='perch.migrations'):
"""
Import all modules inside the perch.migrations package and return the
registered migrations
"""
package = importlib.import_module(package)
for loader, name, is_pkg in pkgutil.walk_packages(package.__path__):
importlib.import_module(package.__... | [
"def",
"collect",
"(",
"package",
"=",
"'perch.migrations'",
")",
":",
"package",
"=",
"importlib",
".",
"import_module",
"(",
"package",
")",
"for",
"loader",
",",
"name",
",",
"is_pkg",
"in",
"pkgutil",
".",
"walk_packages",
"(",
"package",
".",
"__path__"... | Import all modules inside the perch.migrations package and return the
registered migrations | [
"Import",
"all",
"modules",
"inside",
"the",
"perch",
".",
"migrations",
"package",
"and",
"return",
"the",
"registered",
"migrations"
] | train | https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/migrate.py#L139-L149 |
openpermissions/perch | perch/migrate.py | run_migrations | def run_migrations(migrations):
"""
Run migrations for a resource type
:param: a dicitionary of migrations
"""
for resource, resource_migrations in migrations.items():
for version in resource_migrations:
to_migrate = yield resource_version.get(
key=[resource.reso... | python | def run_migrations(migrations):
"""
Run migrations for a resource type
:param: a dicitionary of migrations
"""
for resource, resource_migrations in migrations.items():
for version in resource_migrations:
to_migrate = yield resource_version.get(
key=[resource.reso... | [
"def",
"run_migrations",
"(",
"migrations",
")",
":",
"for",
"resource",
",",
"resource_migrations",
"in",
"migrations",
".",
"items",
"(",
")",
":",
"for",
"version",
"in",
"resource_migrations",
":",
"to_migrate",
"=",
"yield",
"resource_version",
".",
"get",
... | Run migrations for a resource type
:param: a dicitionary of migrations | [
"Run",
"migrations",
"for",
"a",
"resource",
"type"
] | train | https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/migrate.py#L153-L173 |
openpermissions/perch | perch/migrate.py | _migrate_resource | def _migrate_resource(instance, migrations, version=''):
"""
Migrate a resource instance
Subresources are migrated first, then the resource is recursively migrated
:param instance: a perch.Document instance
:param migrations: the migrations for a resource
:param version: the current resource v... | python | def _migrate_resource(instance, migrations, version=''):
"""
Migrate a resource instance
Subresources are migrated first, then the resource is recursively migrated
:param instance: a perch.Document instance
:param migrations: the migrations for a resource
:param version: the current resource v... | [
"def",
"_migrate_resource",
"(",
"instance",
",",
"migrations",
",",
"version",
"=",
"''",
")",
":",
"if",
"version",
"not",
"in",
"migrations",
":",
"return",
"instance",
"instance",
"=",
"_migrate_subresources",
"(",
"instance",
",",
"migrations",
"[",
"vers... | Migrate a resource instance
Subresources are migrated first, then the resource is recursively migrated
:param instance: a perch.Document instance
:param migrations: the migrations for a resource
:param version: the current resource version to migrate | [
"Migrate",
"a",
"resource",
"instance"
] | train | https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/migrate.py#L176-L204 |
openpermissions/perch | perch/migrate.py | _migrate_subresources | def _migrate_subresources(parent, migrations):
"""
Migrate a resource's subresources
:param parent: the parent perch.Document instance
:param migrations: the migrations for a resource
"""
for subresource, resource_migrations in migrations.items():
parent = _migrate_subresource(
... | python | def _migrate_subresources(parent, migrations):
"""
Migrate a resource's subresources
:param parent: the parent perch.Document instance
:param migrations: the migrations for a resource
"""
for subresource, resource_migrations in migrations.items():
parent = _migrate_subresource(
... | [
"def",
"_migrate_subresources",
"(",
"parent",
",",
"migrations",
")",
":",
"for",
"subresource",
",",
"resource_migrations",
"in",
"migrations",
".",
"items",
"(",
")",
":",
"parent",
"=",
"_migrate_subresource",
"(",
"subresource",
",",
"parent",
",",
"resourc... | Migrate a resource's subresources
:param parent: the parent perch.Document instance
:param migrations: the migrations for a resource | [
"Migrate",
"a",
"resource",
"s",
"subresources"
] | train | https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/migrate.py#L207-L221 |
openpermissions/perch | perch/migrate.py | _migrate_subresource | def _migrate_subresource(subresource, parent, migrations):
"""
Migrate a resource's subresource
:param subresource: the perch.SubResource instance
:param parent: the parent perch.Document instance
:param migrations: the migrations for a resource
"""
for key, doc in getattr(parent, subresour... | python | def _migrate_subresource(subresource, parent, migrations):
"""
Migrate a resource's subresource
:param subresource: the perch.SubResource instance
:param parent: the parent perch.Document instance
:param migrations: the migrations for a resource
"""
for key, doc in getattr(parent, subresour... | [
"def",
"_migrate_subresource",
"(",
"subresource",
",",
"parent",
",",
"migrations",
")",
":",
"for",
"key",
",",
"doc",
"in",
"getattr",
"(",
"parent",
",",
"subresource",
".",
"parent_key",
",",
"{",
"}",
")",
".",
"items",
"(",
")",
":",
"for",
"mig... | Migrate a resource's subresource
:param subresource: the perch.SubResource instance
:param parent: the parent perch.Document instance
:param migrations: the migrations for a resource | [
"Migrate",
"a",
"resource",
"s",
"subresource"
] | train | https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/migrate.py#L224-L248 |
msfrank/cifparser | cifparser/parser.py | print_ast | def print_ast(f):
"""
:param f:
:type f: file
:return:
"""
for linenum,indent,value in iter_lines(f):
print("{0}{1}|{2}".format(str(linenum).rjust(3), ' ' * indent, value)) | python | def print_ast(f):
"""
:param f:
:type f: file
:return:
"""
for linenum,indent,value in iter_lines(f):
print("{0}{1}|{2}".format(str(linenum).rjust(3), ' ' * indent, value)) | [
"def",
"print_ast",
"(",
"f",
")",
":",
"for",
"linenum",
",",
"indent",
",",
"value",
"in",
"iter_lines",
"(",
"f",
")",
":",
"print",
"(",
"\"{0}{1}|{2}\"",
".",
"format",
"(",
"str",
"(",
"linenum",
")",
".",
"rjust",
"(",
"3",
")",
",",
"' '",
... | :param f:
:type f: file
:return: | [
":",
"param",
"f",
":",
":",
"type",
"f",
":",
"file",
":",
"return",
":"
] | train | https://github.com/msfrank/cifparser/blob/ecd899ba2e7b990e2cec62b115742d830e7e4384/cifparser/parser.py#L414-L421 |
msfrank/cifparser | cifparser/parser.py | ParserContext.pop_frame | def pop_frame(self):
"""
Remove and return the frame at the top of the stack.
:returns: The top frame
:rtype: Frame
:raises Exception: If there are no frames on the stack
"""
self.frames.pop(0)
if len(self.frames) == 0:
raise Exception("stack ... | python | def pop_frame(self):
"""
Remove and return the frame at the top of the stack.
:returns: The top frame
:rtype: Frame
:raises Exception: If there are no frames on the stack
"""
self.frames.pop(0)
if len(self.frames) == 0:
raise Exception("stack ... | [
"def",
"pop_frame",
"(",
"self",
")",
":",
"self",
".",
"frames",
".",
"pop",
"(",
"0",
")",
"if",
"len",
"(",
"self",
".",
"frames",
")",
"==",
"0",
":",
"raise",
"Exception",
"(",
"\"stack is exhausted\"",
")",
"return",
"self",
".",
"frames",
"[",... | Remove and return the frame at the top of the stack.
:returns: The top frame
:rtype: Frame
:raises Exception: If there are no frames on the stack | [
"Remove",
"and",
"return",
"the",
"frame",
"at",
"the",
"top",
"of",
"the",
"stack",
"."
] | train | https://github.com/msfrank/cifparser/blob/ecd899ba2e7b990e2cec62b115742d830e7e4384/cifparser/parser.py#L191-L202 |
msfrank/cifparser | cifparser/parser.py | ParserContext.append_child_object | def append_child_object(self, linenum, indent, path):
"""
:param linenum: The line number of the frame.
:type linenum: int
:param indent: The indentation level of the frame.
:type indent: int
:param path:
:type path: Path
"""
frame = self.current_f... | python | def append_child_object(self, linenum, indent, path):
"""
:param linenum: The line number of the frame.
:type linenum: int
:param indent: The indentation level of the frame.
:type indent: int
:param path:
:type path: Path
"""
frame = self.current_f... | [
"def",
"append_child_object",
"(",
"self",
",",
"linenum",
",",
"indent",
",",
"path",
")",
":",
"frame",
"=",
"self",
".",
"current_frame",
"(",
")",
"assert",
"isinstance",
"(",
"frame",
",",
"RootFrame",
")",
"or",
"isinstance",
"(",
"frame",
",",
"Co... | :param linenum: The line number of the frame.
:type linenum: int
:param indent: The indentation level of the frame.
:type indent: int
:param path:
:type path: Path | [
":",
"param",
"linenum",
":",
"The",
"line",
"number",
"of",
"the",
"frame",
".",
":",
"type",
"linenum",
":",
"int",
":",
"param",
"indent",
":",
"The",
"indentation",
"level",
"of",
"the",
"frame",
".",
":",
"type",
"indent",
":",
"int",
":",
"para... | train | https://github.com/msfrank/cifparser/blob/ecd899ba2e7b990e2cec62b115742d830e7e4384/cifparser/parser.py#L204-L223 |
msfrank/cifparser | cifparser/parser.py | ParserContext.append_sibling_object | def append_sibling_object(self, linenum, indent, path):
"""
:param linenum: The line number of the frame.
:type linenum: int
:param indent: The indentation level of the frame.
:type indent: int
:param path:
:type path: Path
"""
frame = self.current... | python | def append_sibling_object(self, linenum, indent, path):
"""
:param linenum: The line number of the frame.
:type linenum: int
:param indent: The indentation level of the frame.
:type indent: int
:param path:
:type path: Path
"""
frame = self.current... | [
"def",
"append_sibling_object",
"(",
"self",
",",
"linenum",
",",
"indent",
",",
"path",
")",
":",
"frame",
"=",
"self",
".",
"current_frame",
"(",
")",
"assert",
"frame",
".",
"indent",
"is",
"not",
"None",
"and",
"frame",
".",
"indent",
"==",
"indent",... | :param linenum: The line number of the frame.
:type linenum: int
:param indent: The indentation level of the frame.
:type indent: int
:param path:
:type path: Path | [
":",
"param",
"linenum",
":",
"The",
"line",
"number",
"of",
"the",
"frame",
".",
":",
"type",
"linenum",
":",
"int",
":",
"param",
"indent",
":",
"The",
"indentation",
"level",
"of",
"the",
"frame",
".",
":",
"type",
"indent",
":",
"int",
":",
"para... | train | https://github.com/msfrank/cifparser/blob/ecd899ba2e7b990e2cec62b115742d830e7e4384/cifparser/parser.py#L225-L237 |
msfrank/cifparser | cifparser/parser.py | ParserContext.append_child_field | def append_child_field(self, linenum, indent, field_name, field_value):
"""
:param linenum: The line number of the frame.
:type linenum: int
:param indent: The indentation level of the frame.
:type indent: int
:param path:
:type path: Path
:param field_nam... | python | def append_child_field(self, linenum, indent, field_name, field_value):
"""
:param linenum: The line number of the frame.
:type linenum: int
:param indent: The indentation level of the frame.
:type indent: int
:param path:
:type path: Path
:param field_nam... | [
"def",
"append_child_field",
"(",
"self",
",",
"linenum",
",",
"indent",
",",
"field_name",
",",
"field_value",
")",
":",
"frame",
"=",
"self",
".",
"current_frame",
"(",
")",
"assert",
"isinstance",
"(",
"frame",
",",
"RootFrame",
")",
"or",
"isinstance",
... | :param linenum: The line number of the frame.
:type linenum: int
:param indent: The indentation level of the frame.
:type indent: int
:param path:
:type path: Path
:param field_name:
:type field_name: str
:param field_value:
:type field_value: str | [
":",
"param",
"linenum",
":",
"The",
"line",
"number",
"of",
"the",
"frame",
".",
":",
"type",
"linenum",
":",
"int",
":",
"param",
"indent",
":",
"The",
"indentation",
"level",
"of",
"the",
"frame",
".",
":",
"type",
"indent",
":",
"int",
":",
"para... | train | https://github.com/msfrank/cifparser/blob/ecd899ba2e7b990e2cec62b115742d830e7e4384/cifparser/parser.py#L254-L273 |
msfrank/cifparser | cifparser/parser.py | ParserContext.append_sibling_field | def append_sibling_field(self, linenum, indent, field_name, field_value):
"""
:param linenum: The line number of the frame.
:type linenum: int
:param indent: The indentation level of the frame.
:type indent: int
:param path:
:type path: Path
:param field_n... | python | def append_sibling_field(self, linenum, indent, field_name, field_value):
"""
:param linenum: The line number of the frame.
:type linenum: int
:param indent: The indentation level of the frame.
:type indent: int
:param path:
:type path: Path
:param field_n... | [
"def",
"append_sibling_field",
"(",
"self",
",",
"linenum",
",",
"indent",
",",
"field_name",
",",
"field_value",
")",
":",
"frame",
"=",
"self",
".",
"current_frame",
"(",
")",
"assert",
"frame",
".",
"indent",
"is",
"not",
"None",
"and",
"frame",
".",
... | :param linenum: The line number of the frame.
:type linenum: int
:param indent: The indentation level of the frame.
:type indent: int
:param path:
:type path: Path
:param field_name:
:type field_name: str
:param field_value:
:type field_value: str | [
":",
"param",
"linenum",
":",
"The",
"line",
"number",
"of",
"the",
"frame",
".",
":",
"type",
"linenum",
":",
"int",
":",
"param",
"indent",
":",
"The",
"indentation",
"level",
"of",
"the",
"frame",
".",
":",
"type",
"indent",
":",
"int",
":",
"para... | train | https://github.com/msfrank/cifparser/blob/ecd899ba2e7b990e2cec62b115742d830e7e4384/cifparser/parser.py#L275-L291 |
msfrank/cifparser | cifparser/parser.py | ParserContext.append_value_continuation | def append_value_continuation(self, linenum, indent, continuation):
"""
:param linenum: The line number of the frame.
:type linenum: int
:param indent: The indentation level of the frame.
:type indent: int
:param continuation:
:type continuation: str
"""
... | python | def append_value_continuation(self, linenum, indent, continuation):
"""
:param linenum: The line number of the frame.
:type linenum: int
:param indent: The indentation level of the frame.
:type indent: int
:param continuation:
:type continuation: str
"""
... | [
"def",
"append_value_continuation",
"(",
"self",
",",
"linenum",
",",
"indent",
",",
"continuation",
")",
":",
"frame",
"=",
"self",
".",
"current_frame",
"(",
")",
"assert",
"isinstance",
"(",
"frame",
",",
"FieldFrame",
")",
"or",
"isinstance",
"(",
"frame... | :param linenum: The line number of the frame.
:type linenum: int
:param indent: The indentation level of the frame.
:type indent: int
:param continuation:
:type continuation: str | [
":",
"param",
"linenum",
":",
"The",
"line",
"number",
"of",
"the",
"frame",
".",
":",
"type",
"linenum",
":",
"int",
":",
"param",
"indent",
":",
"The",
"indentation",
"level",
"of",
"the",
"frame",
".",
":",
"type",
"indent",
":",
"int",
":",
"para... | train | https://github.com/msfrank/cifparser/blob/ecd899ba2e7b990e2cec62b115742d830e7e4384/cifparser/parser.py#L312-L331 |
msfrank/cifparser | cifparser/parser.py | ParserContext.append_list_continuation | def append_list_continuation(self, linenum, indent, continuation):
"""
:param linenum: The line number of the frame.
:type linenum: int
:param indent: The indentation level of the frame.
:type indent: int
:param continuation:
:type continuation: str
"""
... | python | def append_list_continuation(self, linenum, indent, continuation):
"""
:param linenum: The line number of the frame.
:type linenum: int
:param indent: The indentation level of the frame.
:type indent: int
:param continuation:
:type continuation: str
"""
... | [
"def",
"append_list_continuation",
"(",
"self",
",",
"linenum",
",",
"indent",
",",
"continuation",
")",
":",
"frame",
"=",
"self",
".",
"current_frame",
"(",
")",
"assert",
"isinstance",
"(",
"frame",
",",
"FieldFrame",
")",
"or",
"isinstance",
"(",
"frame"... | :param linenum: The line number of the frame.
:type linenum: int
:param indent: The indentation level of the frame.
:type indent: int
:param continuation:
:type continuation: str | [
":",
"param",
"linenum",
":",
"The",
"line",
"number",
"of",
"the",
"frame",
".",
":",
"type",
"linenum",
":",
"int",
":",
"param",
"indent",
":",
"The",
"indentation",
"level",
"of",
"the",
"frame",
".",
":",
"type",
"indent",
":",
"int",
":",
"para... | train | https://github.com/msfrank/cifparser/blob/ecd899ba2e7b990e2cec62b115742d830e7e4384/cifparser/parser.py#L333-L351 |
tylerbutler/propane | propane/importing.py | dict_to_querystring | def dict_to_querystring(dictionary):
"""Converts a dict to a querystring suitable to be appended to a URL."""
s = u""
for d in dictionary.keys():
s = unicode.format(u"{0}{1}={2}&", s, d, dictionary[d])
return s[:-1] | python | def dict_to_querystring(dictionary):
"""Converts a dict to a querystring suitable to be appended to a URL."""
s = u""
for d in dictionary.keys():
s = unicode.format(u"{0}{1}={2}&", s, d, dictionary[d])
return s[:-1] | [
"def",
"dict_to_querystring",
"(",
"dictionary",
")",
":",
"s",
"=",
"u\"\"",
"for",
"d",
"in",
"dictionary",
".",
"keys",
"(",
")",
":",
"s",
"=",
"unicode",
".",
"format",
"(",
"u\"{0}{1}={2}&\"",
",",
"s",
",",
"d",
",",
"dictionary",
"[",
"d",
"]... | Converts a dict to a querystring suitable to be appended to a URL. | [
"Converts",
"a",
"dict",
"to",
"a",
"querystring",
"suitable",
"to",
"be",
"appended",
"to",
"a",
"URL",
"."
] | train | https://github.com/tylerbutler/propane/blob/6c404285ab8d78865b7175a5c8adf8fae12d6be5/propane/importing.py#L22-L27 |
nickmilon/Hellas | Hellas/Delphi.py | logging_format | def logging_format(verbose=2, style='txt'):
"""returns a format
:parameter:
- str style: defines style of output format (defaults to txt)
- txt plain text
- dict like text which can be casted to dict
"""
frmt = "'dt':'%(asctime)s', 'lv':'%(levelname)-7s', 'ln':'%(name)s'"... | python | def logging_format(verbose=2, style='txt'):
"""returns a format
:parameter:
- str style: defines style of output format (defaults to txt)
- txt plain text
- dict like text which can be casted to dict
"""
frmt = "'dt':'%(asctime)s', 'lv':'%(levelname)-7s', 'ln':'%(name)s'"... | [
"def",
"logging_format",
"(",
"verbose",
"=",
"2",
",",
"style",
"=",
"'txt'",
")",
":",
"frmt",
"=",
"\"'dt':'%(asctime)s', 'lv':'%(levelname)-7s', 'ln':'%(name)s'\"",
"if",
"verbose",
">",
"1",
":",
"frmt",
"+=",
"\",\\t'Func': '%(funcName)-12s','line':%(lineno)5d, 'mod... | returns a format
:parameter:
- str style: defines style of output format (defaults to txt)
- txt plain text
- dict like text which can be casted to dict | [
"returns",
"a",
"format",
":",
"parameter",
":",
"-",
"str",
"style",
":",
"defines",
"style",
"of",
"output",
"format",
"(",
"defaults",
"to",
"txt",
")",
"-",
"txt",
"plain",
"text",
"-",
"dict",
"like",
"text",
"which",
"can",
"be",
"casted",
"to",
... | train | https://github.com/nickmilon/Hellas/blob/542e4778692fbec90753942946f20100412ec9ee/Hellas/Delphi.py#L110-L130 |
nickmilon/Hellas | Hellas/Delphi.py | logger_multi | def logger_multi(
loggerName="", # top
level_consol=logging.DEBUG,
level_file=logging.DEBUG,
filename=None,
verbose=1,
when='midnight',
interval=1,
backupCount=7):
"""a logger that logs to file as well as as screen
see http://pythonhosted.org//log... | python | def logger_multi(
loggerName="", # top
level_consol=logging.DEBUG,
level_file=logging.DEBUG,
filename=None,
verbose=1,
when='midnight',
interval=1,
backupCount=7):
"""a logger that logs to file as well as as screen
see http://pythonhosted.org//log... | [
"def",
"logger_multi",
"(",
"loggerName",
"=",
"\"\"",
",",
"# top",
"level_consol",
"=",
"logging",
".",
"DEBUG",
",",
"level_file",
"=",
"logging",
".",
"DEBUG",
",",
"filename",
"=",
"None",
",",
"verbose",
"=",
"1",
",",
"when",
"=",
"'midnight'",
",... | a logger that logs to file as well as as screen
see http://pythonhosted.org//logutils/ http://plumberjack.blogspot.gr/2010/10/supporting-alternative-formatting.html
:Todo:
- use new style formating for python > v3 i.e formatter = logging.Formatter(frmt.replace(" ", ""), style='{')
#frmtC = frmt.t... | [
"a",
"logger",
"that",
"logs",
"to",
"file",
"as",
"well",
"as",
"as",
"screen",
"see",
"http",
":",
"//",
"pythonhosted",
".",
"org",
"//",
"logutils",
"/",
"http",
":",
"//",
"plumberjack",
".",
"blogspot",
".",
"gr",
"/",
"2010",
"/",
"10",
"/",
... | train | https://github.com/nickmilon/Hellas/blob/542e4778692fbec90753942946f20100412ec9ee/Hellas/Delphi.py#L142-L178 |
nickmilon/Hellas | Hellas/Delphi.py | auto_retry | def auto_retry(exception_t, retries=3, sleepSeconds=1, back_of_factor=1, msg='', auto_log=1, raise_on_failure=True):
"""a generic auto-retry function @wrapper - decorator
:param Exception exception_t: exception (or tuple of exceptions) to auto retry
:param int retries: max retries before it raises the Exc... | python | def auto_retry(exception_t, retries=3, sleepSeconds=1, back_of_factor=1, msg='', auto_log=1, raise_on_failure=True):
"""a generic auto-retry function @wrapper - decorator
:param Exception exception_t: exception (or tuple of exceptions) to auto retry
:param int retries: max retries before it raises the Exc... | [
"def",
"auto_retry",
"(",
"exception_t",
",",
"retries",
"=",
"3",
",",
"sleepSeconds",
"=",
"1",
",",
"back_of_factor",
"=",
"1",
",",
"msg",
"=",
"''",
",",
"auto_log",
"=",
"1",
",",
"raise_on_failure",
"=",
"True",
")",
":",
"def",
"wrapper",
"(",
... | a generic auto-retry function @wrapper - decorator
:param Exception exception_t: exception (or tuple of exceptions) to auto retry
:param int retries: max retries before it raises the Exception (defaults to 3)
:param int_or_float sleepSeconds: base sleep seconds between retries (defaults to 1)
:param i... | [
"a",
"generic",
"auto",
"-",
"retry",
"function",
"@wrapper",
"-",
"decorator"
] | train | https://github.com/nickmilon/Hellas/blob/542e4778692fbec90753942946f20100412ec9ee/Hellas/Delphi.py#L181-L217 |
nickmilon/Hellas | Hellas/Delphi.py | pp_obj | def pp_obj(obj, out_path=None, indent=4, sort_keys=False, ensure_ascii=False, default=None):
"""
pretty prints a (list tuple, dict etc) object
:useful:
- when we want to avoid importing pprint if we have already imported json
- when we want to pprint to file without breaking json compatibi... | python | def pp_obj(obj, out_path=None, indent=4, sort_keys=False, ensure_ascii=False, default=None):
"""
pretty prints a (list tuple, dict etc) object
:useful:
- when we want to avoid importing pprint if we have already imported json
- when we want to pprint to file without breaking json compatibi... | [
"def",
"pp_obj",
"(",
"obj",
",",
"out_path",
"=",
"None",
",",
"indent",
"=",
"4",
",",
"sort_keys",
"=",
"False",
",",
"ensure_ascii",
"=",
"False",
",",
"default",
"=",
"None",
")",
":",
"rt",
"=",
"anyjson",
".",
"dumps",
"(",
"obj",
",",
"sort... | pretty prints a (list tuple, dict etc) object
:useful:
- when we want to avoid importing pprint if we have already imported json
- when we want to pprint to file without breaking json compatibility | [
"pretty",
"prints",
"a",
"(",
"list",
"tuple",
"dict",
"etc",
")",
"object"
] | train | https://github.com/nickmilon/Hellas/blob/542e4778692fbec90753942946f20100412ec9ee/Hellas/Delphi.py#L225-L240 |
nickmilon/Hellas | Hellas/Delphi.py | time_func | def time_func(func):
"""
time a function decorator
:param args: any args to pass to the function
:paran kwargs: any key arguments to pass to the function
(if 'operations' is in kwargs keys it is used to calculate operations per second)
"""
def timed(*args, **kwargs):
ts = time.t... | python | def time_func(func):
"""
time a function decorator
:param args: any args to pass to the function
:paran kwargs: any key arguments to pass to the function
(if 'operations' is in kwargs keys it is used to calculate operations per second)
"""
def timed(*args, **kwargs):
ts = time.t... | [
"def",
"time_func",
"(",
"func",
")",
":",
"def",
"timed",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"ts",
"=",
"time",
".",
"time",
"(",
")",
"result",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"secs",
"=",
"tim... | time a function decorator
:param args: any args to pass to the function
:paran kwargs: any key arguments to pass to the function
(if 'operations' is in kwargs keys it is used to calculate operations per second) | [
"time",
"a",
"function",
"decorator",
":",
"param",
"args",
":",
"any",
"args",
"to",
"pass",
"to",
"the",
"function",
":",
"paran",
"kwargs",
":",
"any",
"key",
"arguments",
"to",
"pass",
"to",
"the",
"function",
"(",
"if",
"operations",
"is",
"in",
"... | train | https://github.com/nickmilon/Hellas/blob/542e4778692fbec90753942946f20100412ec9ee/Hellas/Delphi.py#L243-L258 |
nickmilon/Hellas | Hellas/Delphi.py | visualise | def visualise(seq, sort=lambda x: x[0]):
"""visualises as seq or dictionary"""
frmt = "{:6} {:8,d} {}"
if isinstance(seq, dict):
seq = seq.items()
if sort:
seq = sorted(seq, key=sort)
mx, mn = max([i[1] for i in seq]), min([i[1] for i in seq])
range = mx - mn
for i in seq:
... | python | def visualise(seq, sort=lambda x: x[0]):
"""visualises as seq or dictionary"""
frmt = "{:6} {:8,d} {}"
if isinstance(seq, dict):
seq = seq.items()
if sort:
seq = sorted(seq, key=sort)
mx, mn = max([i[1] for i in seq]), min([i[1] for i in seq])
range = mx - mn
for i in seq:
... | [
"def",
"visualise",
"(",
"seq",
",",
"sort",
"=",
"lambda",
"x",
":",
"x",
"[",
"0",
"]",
")",
":",
"frmt",
"=",
"\"{:6} {:8,d} {}\"",
"if",
"isinstance",
"(",
"seq",
",",
"dict",
")",
":",
"seq",
"=",
"seq",
".",
"items",
"(",
")",
"if",
"sort",... | visualises as seq or dictionary | [
"visualises",
"as",
"seq",
"or",
"dictionary"
] | train | https://github.com/nickmilon/Hellas/blob/542e4778692fbec90753942946f20100412ec9ee/Hellas/Delphi.py#L269-L280 |
nickmilon/Hellas | Hellas/Delphi.py | Color.help | def help(cls):
"""prints named colors"""
print("for named colors use :")
for c in sorted(list(cls.colors.items())):
print("{:10} {}".format(*c)) | python | def help(cls):
"""prints named colors"""
print("for named colors use :")
for c in sorted(list(cls.colors.items())):
print("{:10} {}".format(*c)) | [
"def",
"help",
"(",
"cls",
")",
":",
"print",
"(",
"\"for named colors use :\"",
")",
"for",
"c",
"in",
"sorted",
"(",
"list",
"(",
"cls",
".",
"colors",
".",
"items",
"(",
")",
")",
")",
":",
"print",
"(",
"\"{:10} {}\"",
".",
"format",
"(",
"*",
... | prints named colors | [
"prints",
"named",
"colors"
] | train | https://github.com/nickmilon/Hellas/blob/542e4778692fbec90753942946f20100412ec9ee/Hellas/Delphi.py#L47-L51 |
nickmilon/Hellas | Hellas/Delphi.py | Color.color_code | def color_code(cls, color):
""" returns code for color
:param tuple_or_code color: either a tuple as in colors.values or a string key to colors dictionary
"""
if not isinstance(color, tuple):
color = cls.colors[color]
return "{:d};{}".format(color[0], str(color[1]) i... | python | def color_code(cls, color):
""" returns code for color
:param tuple_or_code color: either a tuple as in colors.values or a string key to colors dictionary
"""
if not isinstance(color, tuple):
color = cls.colors[color]
return "{:d};{}".format(color[0], str(color[1]) i... | [
"def",
"color_code",
"(",
"cls",
",",
"color",
")",
":",
"if",
"not",
"isinstance",
"(",
"color",
",",
"tuple",
")",
":",
"color",
"=",
"cls",
".",
"colors",
"[",
"color",
"]",
"return",
"\"{:d};{}\"",
".",
"format",
"(",
"color",
"[",
"0",
"]",
",... | returns code for color
:param tuple_or_code color: either a tuple as in colors.values or a string key to colors dictionary | [
"returns",
"code",
"for",
"color",
":",
"param",
"tuple_or_code",
"color",
":",
"either",
"a",
"tuple",
"as",
"in",
"colors",
".",
"values",
"or",
"a",
"string",
"key",
"to",
"colors",
"dictionary"
] | train | https://github.com/nickmilon/Hellas/blob/542e4778692fbec90753942946f20100412ec9ee/Hellas/Delphi.py#L54-L60 |
nickmilon/Hellas | Hellas/Delphi.py | Color.printc | def printc(cls, txt, color=colors.red):
"""Print in color."""
print(cls.color_txt(txt, color)) | python | def printc(cls, txt, color=colors.red):
"""Print in color."""
print(cls.color_txt(txt, color)) | [
"def",
"printc",
"(",
"cls",
",",
"txt",
",",
"color",
"=",
"colors",
".",
"red",
")",
":",
"print",
"(",
"cls",
".",
"color_txt",
"(",
"txt",
",",
"color",
")",
")"
] | Print in color. | [
"Print",
"in",
"color",
"."
] | train | https://github.com/nickmilon/Hellas/blob/542e4778692fbec90753942946f20100412ec9ee/Hellas/Delphi.py#L73-L75 |
delfick/gitmit | gitmit/cache.py | get_all_cached_commit_times | def get_all_cached_commit_times(root_folder):
"""
Find the gitmit cached commit_times and return them if they are the right shape.
This means the file is a list of dictionaries.
If they aren't, issue a warning and return an empty list, it is just a cache
after all!
"""
result = []
loca... | python | def get_all_cached_commit_times(root_folder):
"""
Find the gitmit cached commit_times and return them if they are the right shape.
This means the file is a list of dictionaries.
If they aren't, issue a warning and return an empty list, it is just a cache
after all!
"""
result = []
loca... | [
"def",
"get_all_cached_commit_times",
"(",
"root_folder",
")",
":",
"result",
"=",
"[",
"]",
"location",
"=",
"cache_location",
"(",
"root_folder",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"location",
")",
":",
"try",
":",
"result",
"=",
"json",
... | Find the gitmit cached commit_times and return them if they are the right shape.
This means the file is a list of dictionaries.
If they aren't, issue a warning and return an empty list, it is just a cache
after all! | [
"Find",
"the",
"gitmit",
"cached",
"commit_times",
"and",
"return",
"them",
"if",
"they",
"are",
"the",
"right",
"shape",
"."
] | train | https://github.com/delfick/gitmit/blob/ae0aef14a06b25ad2811f8f47cc97e68a0910eae/gitmit/cache.py#L20-L42 |
delfick/gitmit | gitmit/cache.py | get_cached_commit_times | def get_cached_commit_times(root_folder, parent_dir, sorted_relpaths):
"""
Get the cached commit times for the combination of this parent_dir and relpaths
Return the commit assigned to this combination and the actual times!
"""
result = get_all_cached_commit_times(root_folder)
for item in resu... | python | def get_cached_commit_times(root_folder, parent_dir, sorted_relpaths):
"""
Get the cached commit times for the combination of this parent_dir and relpaths
Return the commit assigned to this combination and the actual times!
"""
result = get_all_cached_commit_times(root_folder)
for item in resu... | [
"def",
"get_cached_commit_times",
"(",
"root_folder",
",",
"parent_dir",
",",
"sorted_relpaths",
")",
":",
"result",
"=",
"get_all_cached_commit_times",
"(",
"root_folder",
")",
"for",
"item",
"in",
"result",
":",
"if",
"sorted",
"(",
"item",
".",
"get",
"(",
... | Get the cached commit times for the combination of this parent_dir and relpaths
Return the commit assigned to this combination and the actual times! | [
"Get",
"the",
"cached",
"commit",
"times",
"for",
"the",
"combination",
"of",
"this",
"parent_dir",
"and",
"relpaths"
] | train | https://github.com/delfick/gitmit/blob/ae0aef14a06b25ad2811f8f47cc97e68a0910eae/gitmit/cache.py#L44-L56 |
delfick/gitmit | gitmit/cache.py | set_cached_commit_times | def set_cached_commit_times(root_folder, parent_dir, first_commit, commit_times, sorted_relpaths):
"""
Set the cached commit times in a json file at cache_location(root_folder)
We first get what is currently in the cache and either modify the existing
entry for this combo of parent_dir and sorted_relpa... | python | def set_cached_commit_times(root_folder, parent_dir, first_commit, commit_times, sorted_relpaths):
"""
Set the cached commit times in a json file at cache_location(root_folder)
We first get what is currently in the cache and either modify the existing
entry for this combo of parent_dir and sorted_relpa... | [
"def",
"set_cached_commit_times",
"(",
"root_folder",
",",
"parent_dir",
",",
"first_commit",
",",
"commit_times",
",",
"sorted_relpaths",
")",
":",
"current",
"=",
"get_all_cached_commit_times",
"(",
"root_folder",
")",
"location",
"=",
"cache_location",
"(",
"root_f... | Set the cached commit times in a json file at cache_location(root_folder)
We first get what is currently in the cache and either modify the existing
entry for this combo of parent_dir and sorted_relpaths.
Or add to the entries.
We then ensure there's less than 5 entries to keep the cache from growing... | [
"Set",
"the",
"cached",
"commit",
"times",
"in",
"a",
"json",
"file",
"at",
"cache_location",
"(",
"root_folder",
")"
] | train | https://github.com/delfick/gitmit/blob/ae0aef14a06b25ad2811f8f47cc97e68a0910eae/gitmit/cache.py#L58-L96 |
slarse/pdfebc-core | pdfebc_core/email_utils.py | send_with_attachments | async def send_with_attachments(subject, message, filepaths, config):
"""Send an email from the user (a gmail) to the receiver.
Args:
subject (str): Subject of the email.
message (str): A message.
filepaths (list(str)): Filepaths to files to be attached.
config (defaultdict): A ... | python | async def send_with_attachments(subject, message, filepaths, config):
"""Send an email from the user (a gmail) to the receiver.
Args:
subject (str): Subject of the email.
message (str): A message.
filepaths (list(str)): Filepaths to files to be attached.
config (defaultdict): A ... | [
"async",
"def",
"send_with_attachments",
"(",
"subject",
",",
"message",
",",
"filepaths",
",",
"config",
")",
":",
"email_",
"=",
"MIMEMultipart",
"(",
")",
"email_",
".",
"attach",
"(",
"MIMEText",
"(",
"message",
")",
")",
"email_",
"[",
"\"Subject\"",
... | Send an email from the user (a gmail) to the receiver.
Args:
subject (str): Subject of the email.
message (str): A message.
filepaths (list(str)): Filepaths to files to be attached.
config (defaultdict): A defaultdict. | [
"Send",
"an",
"email",
"from",
"the",
"user",
"(",
"a",
"gmail",
")",
"to",
"the",
"receiver",
"."
] | train | https://github.com/slarse/pdfebc-core/blob/fc40857bc42365b7434714333e37d7a3487603a0/pdfebc_core/email_utils.py#L36-L51 |
slarse/pdfebc-core | pdfebc_core/email_utils.py | _attach_files | def _attach_files(filepaths, email_):
"""Take a list of filepaths and attach the files to a MIMEMultipart.
Args:
filepaths (list(str)): A list of filepaths.
email_ (email.MIMEMultipart): A MIMEMultipart email_.
"""
for filepath in filepaths:
base = os.path.basename(filepath)
... | python | def _attach_files(filepaths, email_):
"""Take a list of filepaths and attach the files to a MIMEMultipart.
Args:
filepaths (list(str)): A list of filepaths.
email_ (email.MIMEMultipart): A MIMEMultipart email_.
"""
for filepath in filepaths:
base = os.path.basename(filepath)
... | [
"def",
"_attach_files",
"(",
"filepaths",
",",
"email_",
")",
":",
"for",
"filepath",
"in",
"filepaths",
":",
"base",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"filepath",
")",
"with",
"open",
"(",
"filepath",
",",
"\"rb\"",
")",
"as",
"file",
":",... | Take a list of filepaths and attach the files to a MIMEMultipart.
Args:
filepaths (list(str)): A list of filepaths.
email_ (email.MIMEMultipart): A MIMEMultipart email_. | [
"Take",
"a",
"list",
"of",
"filepaths",
"and",
"attach",
"the",
"files",
"to",
"a",
"MIMEMultipart",
"."
] | train | https://github.com/slarse/pdfebc-core/blob/fc40857bc42365b7434714333e37d7a3487603a0/pdfebc_core/email_utils.py#L53-L65 |
slarse/pdfebc-core | pdfebc_core/email_utils.py | _send_email | async def _send_email(email_, config, loop=asyncio.get_event_loop()):
"""Send an email.
Args:
email_ (email.MIMEMultipart): The email to send.
config (defaultdict): A defaultdict.
"""
smtp_server = get_attribute_from_config(config, EMAIL_SECTION_KEY, SMTP_SERVER_KEY)
smtp_port = int... | python | async def _send_email(email_, config, loop=asyncio.get_event_loop()):
"""Send an email.
Args:
email_ (email.MIMEMultipart): The email to send.
config (defaultdict): A defaultdict.
"""
smtp_server = get_attribute_from_config(config, EMAIL_SECTION_KEY, SMTP_SERVER_KEY)
smtp_port = int... | [
"async",
"def",
"_send_email",
"(",
"email_",
",",
"config",
",",
"loop",
"=",
"asyncio",
".",
"get_event_loop",
"(",
")",
")",
":",
"smtp_server",
"=",
"get_attribute_from_config",
"(",
"config",
",",
"EMAIL_SECTION_KEY",
",",
"SMTP_SERVER_KEY",
")",
"smtp_port... | Send an email.
Args:
email_ (email.MIMEMultipart): The email to send.
config (defaultdict): A defaultdict. | [
"Send",
"an",
"email",
"."
] | train | https://github.com/slarse/pdfebc-core/blob/fc40857bc42365b7434714333e37d7a3487603a0/pdfebc_core/email_utils.py#L67-L83 |
slarse/pdfebc-core | pdfebc_core/email_utils.py | send_files_preconf | async def send_files_preconf(filepaths, config_path=CONFIG_PATH):
"""Send files using the config.ini settings.
Args:
filepaths (list(str)): A list of filepaths.
"""
config = read_config(config_path)
subject = "PDF files from pdfebc"
message = ""
await send_with_attachments(subject, ... | python | async def send_files_preconf(filepaths, config_path=CONFIG_PATH):
"""Send files using the config.ini settings.
Args:
filepaths (list(str)): A list of filepaths.
"""
config = read_config(config_path)
subject = "PDF files from pdfebc"
message = ""
await send_with_attachments(subject, ... | [
"async",
"def",
"send_files_preconf",
"(",
"filepaths",
",",
"config_path",
"=",
"CONFIG_PATH",
")",
":",
"config",
"=",
"read_config",
"(",
"config_path",
")",
"subject",
"=",
"\"PDF files from pdfebc\"",
"message",
"=",
"\"\"",
"await",
"send_with_attachments",
"(... | Send files using the config.ini settings.
Args:
filepaths (list(str)): A list of filepaths. | [
"Send",
"files",
"using",
"the",
"config",
".",
"ini",
"settings",
"."
] | train | https://github.com/slarse/pdfebc-core/blob/fc40857bc42365b7434714333e37d7a3487603a0/pdfebc_core/email_utils.py#L85-L94 |
tdgunes/pyplyn | pyplyn/pyp.py | Pipe.make_assertions | def make_assertions(input_pipe, other_pipes, output_pipe):
"""
To assure that the pipe is correctly settled
:param input_pipe:
:param other_pipes: can be []
:param output_pipe:
:return:
"""
assert isinstance(input_pipe, elements.InPypElement), 'Wrong input... | python | def make_assertions(input_pipe, other_pipes, output_pipe):
"""
To assure that the pipe is correctly settled
:param input_pipe:
:param other_pipes: can be []
:param output_pipe:
:return:
"""
assert isinstance(input_pipe, elements.InPypElement), 'Wrong input... | [
"def",
"make_assertions",
"(",
"input_pipe",
",",
"other_pipes",
",",
"output_pipe",
")",
":",
"assert",
"isinstance",
"(",
"input_pipe",
",",
"elements",
".",
"InPypElement",
")",
",",
"'Wrong input element type, want a InPypElement!'",
"assert",
"isinstance",
"(",
"... | To assure that the pipe is correctly settled
:param input_pipe:
:param other_pipes: can be []
:param output_pipe:
:return: | [
"To",
"assure",
"that",
"the",
"pipe",
"is",
"correctly",
"settled",
":",
"param",
"input_pipe",
":",
":",
"param",
"other_pipes",
":",
"can",
"be",
"[]",
":",
"param",
"output_pipe",
":",
":",
"return",
":"
] | train | https://github.com/tdgunes/pyplyn/blob/4b390e9b6137432d5e3db17436fc32d2238d1eff/pyplyn/pyp.py#L32-L43 |
tdgunes/pyplyn | pyplyn/pyp.py | Pipe.run | def run(self):
"""
Let the pipe flow
:return:
"""
assert len(self.elements) >= 2, "In order flow, pipe needs 2 or more elements"
in_pipe = self.elements[0]
other_pipes = self.elements[1:-1]
out_pipe = self.elements[-1]
self.make_assertions(in_pipe... | python | def run(self):
"""
Let the pipe flow
:return:
"""
assert len(self.elements) >= 2, "In order flow, pipe needs 2 or more elements"
in_pipe = self.elements[0]
other_pipes = self.elements[1:-1]
out_pipe = self.elements[-1]
self.make_assertions(in_pipe... | [
"def",
"run",
"(",
"self",
")",
":",
"assert",
"len",
"(",
"self",
".",
"elements",
")",
">=",
"2",
",",
"\"In order flow, pipe needs 2 or more elements\"",
"in_pipe",
"=",
"self",
".",
"elements",
"[",
"0",
"]",
"other_pipes",
"=",
"self",
".",
"elements",
... | Let the pipe flow
:return: | [
"Let",
"the",
"pipe",
"flow",
":",
"return",
":"
] | train | https://github.com/tdgunes/pyplyn/blob/4b390e9b6137432d5e3db17436fc32d2238d1eff/pyplyn/pyp.py#L46-L69 |
pbrisk/unicum | unicum/linkedobject.py | LinkedObject.register_link | def register_link(self, obj, attr=None):
"""
creates link from obj.attr to self
:param obj: object to register link to
:param attr: attribute name to register link to
"""
name = repr(self)
if not name:
return self
l = self.__class__._get_links(... | python | def register_link(self, obj, attr=None):
"""
creates link from obj.attr to self
:param obj: object to register link to
:param attr: attribute name to register link to
"""
name = repr(self)
if not name:
return self
l = self.__class__._get_links(... | [
"def",
"register_link",
"(",
"self",
",",
"obj",
",",
"attr",
"=",
"None",
")",
":",
"name",
"=",
"repr",
"(",
"self",
")",
"if",
"not",
"name",
":",
"return",
"self",
"l",
"=",
"self",
".",
"__class__",
".",
"_get_links",
"(",
")",
"if",
"name",
... | creates link from obj.attr to self
:param obj: object to register link to
:param attr: attribute name to register link to | [
"creates",
"link",
"from",
"obj",
".",
"attr",
"to",
"self",
":",
"param",
"obj",
":",
"object",
"to",
"register",
"link",
"to",
":",
"param",
"attr",
":",
"attribute",
"name",
"to",
"register",
"link",
"to"
] | train | https://github.com/pbrisk/unicum/blob/24bfa7355f36847a06646c58e9fd75bd3b689bfe/unicum/linkedobject.py#L80-L95 |
pbrisk/unicum | unicum/linkedobject.py | LinkedObject.remove_link | def remove_link(self, obj, attr=None):
"""
removes link from obj.attr
"""
name = repr(self)
if not name:
return self
l = self.__class__._get_links()
v = WeakAttrLink(None, obj) if attr is None else WeakAttrLink(obj, attr)
if name in l:
... | python | def remove_link(self, obj, attr=None):
"""
removes link from obj.attr
"""
name = repr(self)
if not name:
return self
l = self.__class__._get_links()
v = WeakAttrLink(None, obj) if attr is None else WeakAttrLink(obj, attr)
if name in l:
... | [
"def",
"remove_link",
"(",
"self",
",",
"obj",
",",
"attr",
"=",
"None",
")",
":",
"name",
"=",
"repr",
"(",
"self",
")",
"if",
"not",
"name",
":",
"return",
"self",
"l",
"=",
"self",
".",
"__class__",
".",
"_get_links",
"(",
")",
"v",
"=",
"Weak... | removes link from obj.attr | [
"removes",
"link",
"from",
"obj",
".",
"attr"
] | train | https://github.com/pbrisk/unicum/blob/24bfa7355f36847a06646c58e9fd75bd3b689bfe/unicum/linkedobject.py#L97-L111 |
pbrisk/unicum | unicum/linkedobject.py | LinkedObject.update_link | def update_link(self):
"""
redirects all links to self (the new linked object)
"""
name = repr(self)
if not name:
return self
l = self.__class__._get_links()
to_be_changed = list()
if name in l:
for wal in l[name]:
... | python | def update_link(self):
"""
redirects all links to self (the new linked object)
"""
name = repr(self)
if not name:
return self
l = self.__class__._get_links()
to_be_changed = list()
if name in l:
for wal in l[name]:
... | [
"def",
"update_link",
"(",
"self",
")",
":",
"name",
"=",
"repr",
"(",
"self",
")",
"if",
"not",
"name",
":",
"return",
"self",
"l",
"=",
"self",
".",
"__class__",
".",
"_get_links",
"(",
")",
"to_be_changed",
"=",
"list",
"(",
")",
"if",
"name",
"... | redirects all links to self (the new linked object) | [
"redirects",
"all",
"links",
"to",
"self",
"(",
"the",
"new",
"linked",
"object",
")"
] | train | https://github.com/pbrisk/unicum/blob/24bfa7355f36847a06646c58e9fd75bd3b689bfe/unicum/linkedobject.py#L113-L132 |
minhhoit/yacms | yacms/blog/management/commands/import_blogger.py | Command.handle_import | def handle_import(self, options):
"""
Gets posts from Blogger.
"""
blog_id = options.get("blog_id")
if blog_id is None:
raise CommandError("Usage is import_blogger %s" % self.args)
try:
from gdata import service
except ImportError:
... | python | def handle_import(self, options):
"""
Gets posts from Blogger.
"""
blog_id = options.get("blog_id")
if blog_id is None:
raise CommandError("Usage is import_blogger %s" % self.args)
try:
from gdata import service
except ImportError:
... | [
"def",
"handle_import",
"(",
"self",
",",
"options",
")",
":",
"blog_id",
"=",
"options",
".",
"get",
"(",
"\"blog_id\"",
")",
"if",
"blog_id",
"is",
"None",
":",
"raise",
"CommandError",
"(",
"\"Usage is import_blogger %s\"",
"%",
"self",
".",
"args",
")",
... | Gets posts from Blogger. | [
"Gets",
"posts",
"from",
"Blogger",
"."
] | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/blog/management/commands/import_blogger.py#L25-L113 |
fedora-infra/fmn.lib | fmn/lib/__init__.py | recipients | def recipients(preferences, message, valid_paths, config):
""" The main API function.
Accepts a fedmsg message as an argument.
Returns a dict mapping context names to lists of recipients.
"""
rule_cache = dict()
results = defaultdict(list)
notified = set()
for preference in preferenc... | python | def recipients(preferences, message, valid_paths, config):
""" The main API function.
Accepts a fedmsg message as an argument.
Returns a dict mapping context names to lists of recipients.
"""
rule_cache = dict()
results = defaultdict(list)
notified = set()
for preference in preferenc... | [
"def",
"recipients",
"(",
"preferences",
",",
"message",
",",
"valid_paths",
",",
"config",
")",
":",
"rule_cache",
"=",
"dict",
"(",
")",
"results",
"=",
"defaultdict",
"(",
"list",
")",
"notified",
"=",
"set",
"(",
")",
"for",
"preference",
"in",
"pref... | The main API function.
Accepts a fedmsg message as an argument.
Returns a dict mapping context names to lists of recipients. | [
"The",
"main",
"API",
"function",
"."
] | train | https://github.com/fedora-infra/fmn.lib/blob/3120725556153d07c1809530f0fadcf250439110/fmn/lib/__init__.py#L29-L64 |
fedora-infra/fmn.lib | fmn/lib/__init__.py | matches | def matches(filter, message, valid_paths, rule_cache, config):
""" Returns True if the given filter matches the given message. """
if not filter['rules']:
return False
for rule in filter['rules']:
fn = rule['fn']
negated = rule['negated']
arguments = rule['arguments']
... | python | def matches(filter, message, valid_paths, rule_cache, config):
""" Returns True if the given filter matches the given message. """
if not filter['rules']:
return False
for rule in filter['rules']:
fn = rule['fn']
negated = rule['negated']
arguments = rule['arguments']
... | [
"def",
"matches",
"(",
"filter",
",",
"message",
",",
"valid_paths",
",",
"rule_cache",
",",
"config",
")",
":",
"if",
"not",
"filter",
"[",
"'rules'",
"]",
":",
"return",
"False",
"for",
"rule",
"in",
"filter",
"[",
"'rules'",
"]",
":",
"fn",
"=",
"... | Returns True if the given filter matches the given message. | [
"Returns",
"True",
"if",
"the",
"given",
"filter",
"matches",
"the",
"given",
"message",
"."
] | train | https://github.com/fedora-infra/fmn.lib/blob/3120725556153d07c1809530f0fadcf250439110/fmn/lib/__init__.py#L67-L94 |
fedora-infra/fmn.lib | fmn/lib/__init__.py | load_preferences | def load_preferences(session, config, valid_paths,
cull_disabled=False, openid=None,
cull_backends=None):
""" Every rule for every filter for every context for every user.
Any preferences in the DB that are for contexts that are disabled in the
config are omitted h... | python | def load_preferences(session, config, valid_paths,
cull_disabled=False, openid=None,
cull_backends=None):
""" Every rule for every filter for every context for every user.
Any preferences in the DB that are for contexts that are disabled in the
config are omitted h... | [
"def",
"load_preferences",
"(",
"session",
",",
"config",
",",
"valid_paths",
",",
"cull_disabled",
"=",
"False",
",",
"openid",
"=",
"None",
",",
"cull_backends",
"=",
"None",
")",
":",
"cull_backends",
"=",
"cull_backends",
"or",
"[",
"]",
"query",
"=",
... | Every rule for every filter for every context for every user.
Any preferences in the DB that are for contexts that are disabled in the
config are omitted here.
If the `openid` argument is None, then this is an expensive query that
loads, practically, the whole database. However, if an openid string i... | [
"Every",
"rule",
"for",
"every",
"filter",
"for",
"every",
"context",
"for",
"every",
"user",
"."
] | train | https://github.com/fedora-infra/fmn.lib/blob/3120725556153d07c1809530f0fadcf250439110/fmn/lib/__init__.py#L97-L127 |
fedora-infra/fmn.lib | fmn/lib/__init__.py | load_rules | def load_rules(root='fmn.rules'):
""" Load the big list of allowed callable rules. """
module = __import__(root, fromlist=[root.split('.')[0]])
hinting_helpers = fmn.lib.hinting.__dict__.values()
rules = {}
for name in dir(module):
obj = getattr(module, name)
# Ignore non-callabl... | python | def load_rules(root='fmn.rules'):
""" Load the big list of allowed callable rules. """
module = __import__(root, fromlist=[root.split('.')[0]])
hinting_helpers = fmn.lib.hinting.__dict__.values()
rules = {}
for name in dir(module):
obj = getattr(module, name)
# Ignore non-callabl... | [
"def",
"load_rules",
"(",
"root",
"=",
"'fmn.rules'",
")",
":",
"module",
"=",
"__import__",
"(",
"root",
",",
"fromlist",
"=",
"[",
"root",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
"]",
")",
"hinting_helpers",
"=",
"fmn",
".",
"lib",
".",
"hi... | Load the big list of allowed callable rules. | [
"Load",
"the",
"big",
"list",
"of",
"allowed",
"callable",
"rules",
"."
] | train | https://github.com/fedora-infra/fmn.lib/blob/3120725556153d07c1809530f0fadcf250439110/fmn/lib/__init__.py#L130-L187 |
TaurusOlson/fntools | fntools/fntools.py | use_with | def use_with(data, fn, *attrs):
"""Apply a function on the attributes of the data
:param data: an object
:param fn: a function
:param attrs: some attributes of the object
:returns: an object
Let's create some data first::
>>> from collections import namedtuple
>>> Person = nam... | python | def use_with(data, fn, *attrs):
"""Apply a function on the attributes of the data
:param data: an object
:param fn: a function
:param attrs: some attributes of the object
:returns: an object
Let's create some data first::
>>> from collections import namedtuple
>>> Person = nam... | [
"def",
"use_with",
"(",
"data",
",",
"fn",
",",
"*",
"attrs",
")",
":",
"args",
"=",
"[",
"getattr",
"(",
"data",
",",
"x",
")",
"for",
"x",
"in",
"attrs",
"]",
"return",
"fn",
"(",
"*",
"args",
")"
] | Apply a function on the attributes of the data
:param data: an object
:param fn: a function
:param attrs: some attributes of the object
:returns: an object
Let's create some data first::
>>> from collections import namedtuple
>>> Person = namedtuple('Person', ('name', 'age', 'gend... | [
"Apply",
"a",
"function",
"on",
"the",
"attributes",
"of",
"the",
"data"
] | train | https://github.com/TaurusOlson/fntools/blob/316080c7b5bfdd88c9f3fac4a67deb5be3c319e5/fntools/fntools.py#L26-L48 |
TaurusOlson/fntools | fntools/fntools.py | rmap | def rmap(fn, coll, is_iterable=None):
"""A recursive map
:param fn: a function
:param coll: a list
:param isiterable: a predicate function determining whether a value is iterable.
:returns: a list
>>> rmap(lambda x: 2*x, [1, 2, [3, 4]])
[2, 4, [6, 8]]
"""
result = []
for x in ... | python | def rmap(fn, coll, is_iterable=None):
"""A recursive map
:param fn: a function
:param coll: a list
:param isiterable: a predicate function determining whether a value is iterable.
:returns: a list
>>> rmap(lambda x: 2*x, [1, 2, [3, 4]])
[2, 4, [6, 8]]
"""
result = []
for x in ... | [
"def",
"rmap",
"(",
"fn",
",",
"coll",
",",
"is_iterable",
"=",
"None",
")",
":",
"result",
"=",
"[",
"]",
"for",
"x",
"in",
"coll",
":",
"if",
"is_iterable",
"is",
"None",
":",
"is_iterable",
"=",
"isiterable",
"if",
"is_iterable",
"(",
"x",
")",
... | A recursive map
:param fn: a function
:param coll: a list
:param isiterable: a predicate function determining whether a value is iterable.
:returns: a list
>>> rmap(lambda x: 2*x, [1, 2, [3, 4]])
[2, 4, [6, 8]] | [
"A",
"recursive",
"map"
] | train | https://github.com/TaurusOlson/fntools/blob/316080c7b5bfdd88c9f3fac4a67deb5be3c319e5/fntools/fntools.py#L129-L151 |
TaurusOlson/fntools | fntools/fntools.py | replace | def replace(x, old, new, fn=operator.eq):
"""
Replace x with new if fn(x, old) is True.
:param x: Any value
:param old: The old value we want to replace
:param new: The value replacing old
:param fn:
The predicate function determining the relation between x and
old. By default ... | python | def replace(x, old, new, fn=operator.eq):
"""
Replace x with new if fn(x, old) is True.
:param x: Any value
:param old: The old value we want to replace
:param new: The value replacing old
:param fn:
The predicate function determining the relation between x and
old. By default ... | [
"def",
"replace",
"(",
"x",
",",
"old",
",",
"new",
",",
"fn",
"=",
"operator",
".",
"eq",
")",
":",
"return",
"new",
"if",
"fn",
"(",
"x",
",",
"old",
")",
"else",
"x"
] | Replace x with new if fn(x, old) is True.
:param x: Any value
:param old: The old value we want to replace
:param new: The value replacing old
:param fn:
The predicate function determining the relation between x and
old. By default fn is the equality function.
:returns: x or new
... | [
"Replace",
"x",
"with",
"new",
"if",
"fn",
"(",
"x",
"old",
")",
"is",
"True",
"."
] | train | https://github.com/TaurusOlson/fntools/blob/316080c7b5bfdd88c9f3fac4a67deb5be3c319e5/fntools/fntools.py#L155-L171 |
TaurusOlson/fntools | fntools/fntools.py | compose | def compose(*fns):
"""Return the function composed with the given functions
:param fns: functions
:returns: a function
>>> add2 = lambda x: x+2
>>> mult3 = lambda x: x*3
>>> new_fn = compose(add2, mult3)
>>> new_fn(2)
8
.. note:: compose(fn1, fn2, fn3) is the same as fn1(fn2(fn3))... | python | def compose(*fns):
"""Return the function composed with the given functions
:param fns: functions
:returns: a function
>>> add2 = lambda x: x+2
>>> mult3 = lambda x: x*3
>>> new_fn = compose(add2, mult3)
>>> new_fn(2)
8
.. note:: compose(fn1, fn2, fn3) is the same as fn1(fn2(fn3))... | [
"def",
"compose",
"(",
"*",
"fns",
")",
":",
"def",
"compose2",
"(",
"f",
",",
"g",
")",
":",
"return",
"lambda",
"x",
":",
"f",
"(",
"g",
"(",
"x",
")",
")",
"return",
"reduce",
"(",
"compose2",
",",
"fns",
")"
] | Return the function composed with the given functions
:param fns: functions
:returns: a function
>>> add2 = lambda x: x+2
>>> mult3 = lambda x: x*3
>>> new_fn = compose(add2, mult3)
>>> new_fn(2)
8
.. note:: compose(fn1, fn2, fn3) is the same as fn1(fn2(fn3))
which means that t... | [
"Return",
"the",
"function",
"composed",
"with",
"the",
"given",
"functions"
] | train | https://github.com/TaurusOlson/fntools/blob/316080c7b5bfdd88c9f3fac4a67deb5be3c319e5/fntools/fntools.py#L174-L192 |
TaurusOlson/fntools | fntools/fntools.py | groupby | def groupby(fn, coll):
"""Group elements in sub-collections by fn
:param fn: a function
:param coll: a collection
:returns: a dictionary
>>> groupby(len, ['John', 'Terry', 'Eric', 'Graham', 'Mickael'])
{4: ['John', 'Eric'], 5: ['Terry'], 6: ['Graham'], 7: ['Mickael']}
"""
d = collecti... | python | def groupby(fn, coll):
"""Group elements in sub-collections by fn
:param fn: a function
:param coll: a collection
:returns: a dictionary
>>> groupby(len, ['John', 'Terry', 'Eric', 'Graham', 'Mickael'])
{4: ['John', 'Eric'], 5: ['Terry'], 6: ['Graham'], 7: ['Mickael']}
"""
d = collecti... | [
"def",
"groupby",
"(",
"fn",
",",
"coll",
")",
":",
"d",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"for",
"item",
"in",
"coll",
":",
"key",
"=",
"fn",
"(",
"item",
")",
"d",
"[",
"key",
"]",
".",
"append",
"(",
"item",
")",
"ret... | Group elements in sub-collections by fn
:param fn: a function
:param coll: a collection
:returns: a dictionary
>>> groupby(len, ['John', 'Terry', 'Eric', 'Graham', 'Mickael'])
{4: ['John', 'Eric'], 5: ['Terry'], 6: ['Graham'], 7: ['Mickael']} | [
"Group",
"elements",
"in",
"sub",
"-",
"collections",
"by",
"fn"
] | train | https://github.com/TaurusOlson/fntools/blob/316080c7b5bfdd88c9f3fac4a67deb5be3c319e5/fntools/fntools.py#L195-L210 |
TaurusOlson/fntools | fntools/fntools.py | reductions | def reductions(fn, seq, acc=None):
"""Return the intermediate values of a reduction
:param fn: a function
:param seq: a sequence
:param acc: the accumulator
:returns: a list
>>> reductions(lambda x, y: x + y, [1, 2, 3])
[1, 3, 6]
>>> reductions(lambda x, y: x + y, [1, 2, 3], 10)
[... | python | def reductions(fn, seq, acc=None):
"""Return the intermediate values of a reduction
:param fn: a function
:param seq: a sequence
:param acc: the accumulator
:returns: a list
>>> reductions(lambda x, y: x + y, [1, 2, 3])
[1, 3, 6]
>>> reductions(lambda x, y: x + y, [1, 2, 3], 10)
[... | [
"def",
"reductions",
"(",
"fn",
",",
"seq",
",",
"acc",
"=",
"None",
")",
":",
"indexes",
"=",
"xrange",
"(",
"len",
"(",
"seq",
")",
")",
"if",
"acc",
":",
"return",
"map",
"(",
"lambda",
"i",
":",
"reduce",
"(",
"lambda",
"x",
",",
"y",
":",
... | Return the intermediate values of a reduction
:param fn: a function
:param seq: a sequence
:param acc: the accumulator
:returns: a list
>>> reductions(lambda x, y: x + y, [1, 2, 3])
[1, 3, 6]
>>> reductions(lambda x, y: x + y, [1, 2, 3], 10)
[11, 13, 16] | [
"Return",
"the",
"intermediate",
"values",
"of",
"a",
"reduction"
] | train | https://github.com/TaurusOlson/fntools/blob/316080c7b5bfdd88c9f3fac4a67deb5be3c319e5/fntools/fntools.py#L213-L232 |
TaurusOlson/fntools | fntools/fntools.py | split | def split(coll, factor):
"""Split a collection by using a factor
:param coll: a collection
:param factor: a collection of factors
:returns: a dictionary
>>> bands = ('Led Zeppelin', 'Debussy', 'Metallica', 'Iron Maiden', 'Bach')
>>> styles = ('rock', 'classic', 'rock', 'rock', 'classic')
>... | python | def split(coll, factor):
"""Split a collection by using a factor
:param coll: a collection
:param factor: a collection of factors
:returns: a dictionary
>>> bands = ('Led Zeppelin', 'Debussy', 'Metallica', 'Iron Maiden', 'Bach')
>>> styles = ('rock', 'classic', 'rock', 'rock', 'classic')
>... | [
"def",
"split",
"(",
"coll",
",",
"factor",
")",
":",
"groups",
"=",
"groupby",
"(",
"lambda",
"x",
":",
"x",
"[",
"0",
"]",
",",
"itertools",
".",
"izip",
"(",
"factor",
",",
"coll",
")",
")",
"return",
"dmap",
"(",
"lambda",
"x",
":",
"[",
"y... | Split a collection by using a factor
:param coll: a collection
:param factor: a collection of factors
:returns: a dictionary
>>> bands = ('Led Zeppelin', 'Debussy', 'Metallica', 'Iron Maiden', 'Bach')
>>> styles = ('rock', 'classic', 'rock', 'rock', 'classic')
>>> split(bands, styles)
{'cl... | [
"Split",
"a",
"collection",
"by",
"using",
"a",
"factor"
] | train | https://github.com/TaurusOlson/fntools/blob/316080c7b5bfdd88c9f3fac4a67deb5be3c319e5/fntools/fntools.py#L235-L249 |
TaurusOlson/fntools | fntools/fntools.py | assoc | def assoc(_d, key, value):
"""Associate a key with a value in a dictionary
:param _d: a dictionary
:param key: a key in the dictionary
:param value: a value for the key
:returns: a new dictionary
>>> data = {}
>>> new_data = assoc(data, 'name', 'Holy Grail')
>>> new_data
{'name': '... | python | def assoc(_d, key, value):
"""Associate a key with a value in a dictionary
:param _d: a dictionary
:param key: a key in the dictionary
:param value: a value for the key
:returns: a new dictionary
>>> data = {}
>>> new_data = assoc(data, 'name', 'Holy Grail')
>>> new_data
{'name': '... | [
"def",
"assoc",
"(",
"_d",
",",
"key",
",",
"value",
")",
":",
"d",
"=",
"deepcopy",
"(",
"_d",
")",
"d",
"[",
"key",
"]",
"=",
"value",
"return",
"d"
] | Associate a key with a value in a dictionary
:param _d: a dictionary
:param key: a key in the dictionary
:param value: a value for the key
:returns: a new dictionary
>>> data = {}
>>> new_data = assoc(data, 'name', 'Holy Grail')
>>> new_data
{'name': 'Holy Grail'}
>>> data
{}
... | [
"Associate",
"a",
"key",
"with",
"a",
"value",
"in",
"a",
"dictionary"
] | train | https://github.com/TaurusOlson/fntools/blob/316080c7b5bfdd88c9f3fac4a67deb5be3c319e5/fntools/fntools.py#L252-L272 |
TaurusOlson/fntools | fntools/fntools.py | pipe | def pipe(data, *fns):
"""Apply functions recursively on your data
:param data: the data
:param fns: functions
:returns: an object
>>> inc = lambda x: x + 1
>>> pipe(42, inc, str)
'43'
"""
return reduce(lambda acc, f: f(acc), fns, data) | python | def pipe(data, *fns):
"""Apply functions recursively on your data
:param data: the data
:param fns: functions
:returns: an object
>>> inc = lambda x: x + 1
>>> pipe(42, inc, str)
'43'
"""
return reduce(lambda acc, f: f(acc), fns, data) | [
"def",
"pipe",
"(",
"data",
",",
"*",
"fns",
")",
":",
"return",
"reduce",
"(",
"lambda",
"acc",
",",
"f",
":",
"f",
"(",
"acc",
")",
",",
"fns",
",",
"data",
")"
] | Apply functions recursively on your data
:param data: the data
:param fns: functions
:returns: an object
>>> inc = lambda x: x + 1
>>> pipe(42, inc, str)
'43' | [
"Apply",
"functions",
"recursively",
"on",
"your",
"data"
] | train | https://github.com/TaurusOlson/fntools/blob/316080c7b5bfdd88c9f3fac4a67deb5be3c319e5/fntools/fntools.py#L332-L344 |
TaurusOlson/fntools | fntools/fntools.py | shift | def shift(func, *args, **kwargs):
"""This function is basically a beefed up lambda x: func(x, *args, **kwargs)
:func:`shift` comes in handy when it is used in a pipeline with a function that
needs the passed value as its first argument.
:param func: a function
:param args: objects
:param kwarg... | python | def shift(func, *args, **kwargs):
"""This function is basically a beefed up lambda x: func(x, *args, **kwargs)
:func:`shift` comes in handy when it is used in a pipeline with a function that
needs the passed value as its first argument.
:param func: a function
:param args: objects
:param kwarg... | [
"def",
"shift",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapped",
"(",
"x",
")",
":",
"return",
"func",
"(",
"x",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"wra... | This function is basically a beefed up lambda x: func(x, *args, **kwargs)
:func:`shift` comes in handy when it is used in a pipeline with a function that
needs the passed value as its first argument.
:param func: a function
:param args: objects
:param kwargs: keywords
>>> def div(x, y): retur... | [
"This",
"function",
"is",
"basically",
"a",
"beefed",
"up",
"lambda",
"x",
":",
"func",
"(",
"x",
"*",
"args",
"**",
"kwargs",
")"
] | train | https://github.com/TaurusOlson/fntools/blob/316080c7b5bfdd88c9f3fac4a67deb5be3c319e5/fntools/fntools.py#L362-L389 |
TaurusOlson/fntools | fntools/fntools.py | update | def update(records, column, values):
"""Update the column of records
:param records: a list of dictionaries
:param column: a string
:param values: an iterable or a function
:returns: new records with the columns updated
>>> movies = [
... {'title': 'The Holy Grail', 'year': 1975, 'budget':... | python | def update(records, column, values):
"""Update the column of records
:param records: a list of dictionaries
:param column: a string
:param values: an iterable or a function
:returns: new records with the columns updated
>>> movies = [
... {'title': 'The Holy Grail', 'year': 1975, 'budget':... | [
"def",
"update",
"(",
"records",
",",
"column",
",",
"values",
")",
":",
"new_records",
"=",
"deepcopy",
"(",
"records",
")",
"if",
"values",
".",
"__class__",
".",
"__name__",
"==",
"'function'",
":",
"for",
"row",
"in",
"new_records",
":",
"row",
"[",
... | Update the column of records
:param records: a list of dictionaries
:param column: a string
:param values: an iterable or a function
:returns: new records with the columns updated
>>> movies = [
... {'title': 'The Holy Grail', 'year': 1975, 'budget': 4E5, 'total_gross': 5E6},
... {'title':... | [
"Update",
"the",
"column",
"of",
"records"
] | train | https://github.com/TaurusOlson/fntools/blob/316080c7b5bfdd88c9f3fac4a67deb5be3c319e5/fntools/fntools.py#L408-L441 |
TaurusOlson/fntools | fntools/fntools.py | duplicates | def duplicates(coll):
"""Return the duplicated items in the given collection
:param coll: a collection
:returns: a list of the duplicated items in the collection
>>> duplicates([1, 1, 2, 3, 3, 4, 1, 1])
[1, 3]
"""
return list(set(x for x in coll if coll.count(x) > 1)) | python | def duplicates(coll):
"""Return the duplicated items in the given collection
:param coll: a collection
:returns: a list of the duplicated items in the collection
>>> duplicates([1, 1, 2, 3, 3, 4, 1, 1])
[1, 3]
"""
return list(set(x for x in coll if coll.count(x) > 1)) | [
"def",
"duplicates",
"(",
"coll",
")",
":",
"return",
"list",
"(",
"set",
"(",
"x",
"for",
"x",
"in",
"coll",
"if",
"coll",
".",
"count",
"(",
"x",
")",
">",
"1",
")",
")"
] | Return the duplicated items in the given collection
:param coll: a collection
:returns: a list of the duplicated items in the collection
>>> duplicates([1, 1, 2, 3, 3, 4, 1, 1])
[1, 3] | [
"Return",
"the",
"duplicated",
"items",
"in",
"the",
"given",
"collection"
] | train | https://github.com/TaurusOlson/fntools/blob/316080c7b5bfdd88c9f3fac4a67deb5be3c319e5/fntools/fntools.py#L446-L456 |
TaurusOlson/fntools | fntools/fntools.py | pluck | def pluck(record, *keys, **kwargs):
"""Return the record with the selected keys
:param record: a list of dictionaries
:param keys: some keys from the record
:param kwargs: keywords determining how to deal with the keys
>>> d = {'name': 'Lancelot', 'actor': 'John Cleese', 'color': 'blue'}
>>> p... | python | def pluck(record, *keys, **kwargs):
"""Return the record with the selected keys
:param record: a list of dictionaries
:param keys: some keys from the record
:param kwargs: keywords determining how to deal with the keys
>>> d = {'name': 'Lancelot', 'actor': 'John Cleese', 'color': 'blue'}
>>> p... | [
"def",
"pluck",
"(",
"record",
",",
"*",
"keys",
",",
"*",
"*",
"kwargs",
")",
":",
"default",
"=",
"kwargs",
".",
"get",
"(",
"'default'",
",",
"None",
")",
"return",
"reduce",
"(",
"lambda",
"a",
",",
"x",
":",
"assoc",
"(",
"a",
",",
"x",
",... | Return the record with the selected keys
:param record: a list of dictionaries
:param keys: some keys from the record
:param kwargs: keywords determining how to deal with the keys
>>> d = {'name': 'Lancelot', 'actor': 'John Cleese', 'color': 'blue'}
>>> pluck(d, 'name', 'color')
{'color': 'blu... | [
"Return",
"the",
"record",
"with",
"the",
"selected",
"keys"
] | train | https://github.com/TaurusOlson/fntools/blob/316080c7b5bfdd88c9f3fac4a67deb5be3c319e5/fntools/fntools.py#L460-L479 |
TaurusOlson/fntools | fntools/fntools.py | pluck_each | def pluck_each(records, columns):
"""Return the records with the selected columns
:param records: a list of dictionaries
:param columns: a list or a tuple
:returns: a list of dictionaries with the selected columns
>>> movies = [
... {'title': 'The Holy Grail', 'year': 1975, 'budget': 4E5, 'tot... | python | def pluck_each(records, columns):
"""Return the records with the selected columns
:param records: a list of dictionaries
:param columns: a list or a tuple
:returns: a list of dictionaries with the selected columns
>>> movies = [
... {'title': 'The Holy Grail', 'year': 1975, 'budget': 4E5, 'tot... | [
"def",
"pluck_each",
"(",
"records",
",",
"columns",
")",
":",
"return",
"[",
"pluck",
"(",
"records",
"[",
"i",
"]",
",",
"*",
"columns",
")",
"for",
"i",
",",
"_",
"in",
"enumerate",
"(",
"records",
")",
"]"
] | Return the records with the selected columns
:param records: a list of dictionaries
:param columns: a list or a tuple
:returns: a list of dictionaries with the selected columns
>>> movies = [
... {'title': 'The Holy Grail', 'year': 1975, 'budget': 4E5, 'total_gross': 5E6},
... {'title': 'Life ... | [
"Return",
"the",
"records",
"with",
"the",
"selected",
"columns"
] | train | https://github.com/TaurusOlson/fntools/blob/316080c7b5bfdd88c9f3fac4a67deb5be3c319e5/fntools/fntools.py#L482-L498 |
TaurusOlson/fntools | fntools/fntools.py | use | def use(data, attrs):
"""Return the values of the attributes for the given data
:param data: the data
:param attrs: strings
:returns: a list
With a dict::
>>> band = {'name': 'Metallica', 'singer': 'James Hetfield', 'guitarist': 'Kirk Hammet'}
>>> use(band, ('name', 'date', 'singe... | python | def use(data, attrs):
"""Return the values of the attributes for the given data
:param data: the data
:param attrs: strings
:returns: a list
With a dict::
>>> band = {'name': 'Metallica', 'singer': 'James Hetfield', 'guitarist': 'Kirk Hammet'}
>>> use(band, ('name', 'date', 'singe... | [
"def",
"use",
"(",
"data",
",",
"attrs",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"if",
"not",
"isiterable",
"(",
"attrs",
")",
":",
"attrs",
"=",
"[",
"attrs",
"]",
"coll",
"=",
"map",
"(",
"data",
".",
"get",
",",
"at... | Return the values of the attributes for the given data
:param data: the data
:param attrs: strings
:returns: a list
With a dict::
>>> band = {'name': 'Metallica', 'singer': 'James Hetfield', 'guitarist': 'Kirk Hammet'}
>>> use(band, ('name', 'date', 'singer'))
['Metallica', No... | [
"Return",
"the",
"values",
"of",
"the",
"attributes",
"for",
"the",
"given",
"data"
] | train | https://github.com/TaurusOlson/fntools/blob/316080c7b5bfdd88c9f3fac4a67deb5be3c319e5/fntools/fntools.py#L501-L529 |
TaurusOlson/fntools | fntools/fntools.py | get_in | def get_in(record, *keys, **kwargs):
"""Return the value corresponding to the keys in a nested record
:param record: a dictionary
:param keys: strings
:param kwargs: keywords
:returns: the value for the keys
>>> d = {'id': {'name': 'Lancelot', 'actor': 'John Cleese', 'color': 'blue'}}
>>> ... | python | def get_in(record, *keys, **kwargs):
"""Return the value corresponding to the keys in a nested record
:param record: a dictionary
:param keys: strings
:param kwargs: keywords
:returns: the value for the keys
>>> d = {'id': {'name': 'Lancelot', 'actor': 'John Cleese', 'color': 'blue'}}
>>> ... | [
"def",
"get_in",
"(",
"record",
",",
"*",
"keys",
",",
"*",
"*",
"kwargs",
")",
":",
"default",
"=",
"kwargs",
".",
"get",
"(",
"'default'",
",",
"None",
")",
"return",
"reduce",
"(",
"lambda",
"a",
",",
"x",
":",
"a",
".",
"get",
"(",
"x",
","... | Return the value corresponding to the keys in a nested record
:param record: a dictionary
:param keys: strings
:param kwargs: keywords
:returns: the value for the keys
>>> d = {'id': {'name': 'Lancelot', 'actor': 'John Cleese', 'color': 'blue'}}
>>> get_in(d, 'id', 'name')
'Lancelot'
... | [
"Return",
"the",
"value",
"corresponding",
"to",
"the",
"keys",
"in",
"a",
"nested",
"record"
] | train | https://github.com/TaurusOlson/fntools/blob/316080c7b5bfdd88c9f3fac4a67deb5be3c319e5/fntools/fntools.py#L532-L549 |
TaurusOlson/fntools | fntools/fntools.py | valueof | def valueof(records, key):
"""Extract the value corresponding to the given key in all the dictionaries
>>> bands = [{'name': 'Led Zeppelin', 'singer': 'Robert Plant', 'guitarist': 'Jimmy Page'},
... {'name': 'Metallica', 'singer': 'James Hetfield', 'guitarist': 'Kirk Hammet'}]
>>> valueof(bands, 'singe... | python | def valueof(records, key):
"""Extract the value corresponding to the given key in all the dictionaries
>>> bands = [{'name': 'Led Zeppelin', 'singer': 'Robert Plant', 'guitarist': 'Jimmy Page'},
... {'name': 'Metallica', 'singer': 'James Hetfield', 'guitarist': 'Kirk Hammet'}]
>>> valueof(bands, 'singe... | [
"def",
"valueof",
"(",
"records",
",",
"key",
")",
":",
"if",
"isinstance",
"(",
"records",
",",
"dict",
")",
":",
"records",
"=",
"[",
"records",
"]",
"return",
"map",
"(",
"operator",
".",
"itemgetter",
"(",
"key",
")",
",",
"records",
")"
] | Extract the value corresponding to the given key in all the dictionaries
>>> bands = [{'name': 'Led Zeppelin', 'singer': 'Robert Plant', 'guitarist': 'Jimmy Page'},
... {'name': 'Metallica', 'singer': 'James Hetfield', 'guitarist': 'Kirk Hammet'}]
>>> valueof(bands, 'singer')
['Robert Plant', 'James He... | [
"Extract",
"the",
"value",
"corresponding",
"to",
"the",
"given",
"key",
"in",
"all",
"the",
"dictionaries"
] | train | https://github.com/TaurusOlson/fntools/blob/316080c7b5bfdd88c9f3fac4a67deb5be3c319e5/fntools/fntools.py#L553-L564 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.