repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_documentation_string stringlengths 1 47.2k | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|
riga/law | law/util.py | human_time_diff | def human_time_diff(*args, **kwargs):
"""
Returns a human readable time difference. The largest unit is days. All *args* and *kwargs* are
passed to ``datetime.timedelta``. Example:
.. code-block:: python
human_time_diff(seconds=1233)
# -> "20 minutes, 33 seconds"
human_time_di... | python | def human_time_diff(*args, **kwargs):
"""
Returns a human readable time difference. The largest unit is days. All *args* and *kwargs* are
passed to ``datetime.timedelta``. Example:
.. code-block:: python
human_time_diff(seconds=1233)
# -> "20 minutes, 33 seconds"
human_time_di... | Returns a human readable time difference. The largest unit is days. All *args* and *kwargs* are
passed to ``datetime.timedelta``. Example:
.. code-block:: python
human_time_diff(seconds=1233)
# -> "20 minutes, 33 seconds"
human_time_diff(seconds=90001)
# -> "1 day, 1 hour, 1 s... | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/util.py#L701-L724 |
riga/law | law/util.py | is_file_exists_error | def is_file_exists_error(e):
"""
Returns whether the exception *e* was raised due to an already existing file or directory.
"""
if six.PY3:
return isinstance(e, FileExistsError) # noqa: F821
else:
return isinstance(e, OSError) and e.errno == 17 | python | def is_file_exists_error(e):
"""
Returns whether the exception *e* was raised due to an already existing file or directory.
"""
if six.PY3:
return isinstance(e, FileExistsError) # noqa: F821
else:
return isinstance(e, OSError) and e.errno == 17 | Returns whether the exception *e* was raised due to an already existing file or directory. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/util.py#L727-L734 |
riga/law | law/util.py | send_mail | def send_mail(recipient, sender, subject="", content="", smtp_host="127.0.0.1", smtp_port=25):
"""
Lightweight mail functionality. Sends an mail from *sender* to *recipient* with *subject* and
*content*. *smtp_host* and *smtp_port* are forwarded to the ``smtplib.SMTP`` constructor. *True*
is returned on... | python | def send_mail(recipient, sender, subject="", content="", smtp_host="127.0.0.1", smtp_port=25):
"""
Lightweight mail functionality. Sends an mail from *sender* to *recipient* with *subject* and
*content*. *smtp_host* and *smtp_port* are forwarded to the ``smtplib.SMTP`` constructor. *True*
is returned on... | Lightweight mail functionality. Sends an mail from *sender* to *recipient* with *subject* and
*content*. *smtp_host* and *smtp_port* are forwarded to the ``smtplib.SMTP`` constructor. *True*
is returned on success, *False* otherwise. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/util.py#L746-L762 |
riga/law | law/util.py | open_compat | def open_compat(*args, **kwargs):
"""
Polyfill for python's ``open`` factory, returning the plain ``open`` in python 3, and
``io.open`` in python 2 with a patched ``write`` method that internally handles unicode
conversion of its first argument. All *args* and *kwargs* are forwarded.
"""
if six.... | python | def open_compat(*args, **kwargs):
"""
Polyfill for python's ``open`` factory, returning the plain ``open`` in python 3, and
``io.open`` in python 2 with a patched ``write`` method that internally handles unicode
conversion of its first argument. All *args* and *kwargs* are forwarded.
"""
if six.... | Polyfill for python's ``open`` factory, returning the plain ``open`` in python 3, and
``io.open`` in python 2 with a patched ``write`` method that internally handles unicode
conversion of its first argument. All *args* and *kwargs* are forwarded. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/util.py#L823-L846 |
riga/law | law/util.py | patch_object | def patch_object(obj, attr, value):
"""
Context manager that temporarily patches an object *obj* by replacing its attribute *attr* with
*value*. The original value is set again when the context is closed.
"""
orig = getattr(obj, attr, no_value)
try:
setattr(obj, attr, value)
yi... | python | def patch_object(obj, attr, value):
"""
Context manager that temporarily patches an object *obj* by replacing its attribute *attr* with
*value*. The original value is set again when the context is closed.
"""
orig = getattr(obj, attr, no_value)
try:
setattr(obj, attr, value)
yi... | Context manager that temporarily patches an object *obj* by replacing its attribute *attr* with
*value*. The original value is set again when the context is closed. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/util.py#L850-L868 |
riga/law | law/util.py | TeeStream._flush | def _flush(self):
"""
Flushes all registered consumer streams.
"""
for consumer in self.consumers:
if not getattr(consumer, "closed", False):
consumer.flush() | python | def _flush(self):
"""
Flushes all registered consumer streams.
"""
for consumer in self.consumers:
if not getattr(consumer, "closed", False):
consumer.flush() | Flushes all registered consumer streams. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/util.py#L950-L956 |
riga/law | law/util.py | TeeStream._write | def _write(self, *args, **kwargs):
"""
Writes to all registered consumer streams, passing *args* and *kwargs*.
"""
for consumer in self.consumers:
consumer.write(*args, **kwargs) | python | def _write(self, *args, **kwargs):
"""
Writes to all registered consumer streams, passing *args* and *kwargs*.
"""
for consumer in self.consumers:
consumer.write(*args, **kwargs) | Writes to all registered consumer streams, passing *args* and *kwargs*. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/util.py#L958-L963 |
riga/law | law/util.py | FilteredStream._write | def _write(self, *args, **kwargs):
"""
Writes to the consumer stream when *filter_fn* evaluates to *True*, passing *args* and
*kwargs*.
"""
if self.filter_fn(*args, **kwargs):
self.stream.write(*args, **kwargs) | python | def _write(self, *args, **kwargs):
"""
Writes to the consumer stream when *filter_fn* evaluates to *True*, passing *args* and
*kwargs*.
"""
if self.filter_fn(*args, **kwargs):
self.stream.write(*args, **kwargs) | Writes to the consumer stream when *filter_fn* evaluates to *True*, passing *args* and
*kwargs*. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/util.py#L991-L997 |
riga/law | law/config.py | Config.get_default | def get_default(self, section, option, default=None, type=None, expandvars=False,
expanduser=False):
"""
Returns the config value defined by *section* and *option*. When either the section or the
option does not exist, the *default* value is returned instead. When *type* is set, it m... | python | def get_default(self, section, option, default=None, type=None, expandvars=False,
expanduser=False):
"""
Returns the config value defined by *section* and *option*. When either the section or the
option does not exist, the *default* value is returned instead. When *type* is set, it m... | Returns the config value defined by *section* and *option*. When either the section or the
option does not exist, the *default* value is returned instead. When *type* is set, it must
be either `"str"`, `"int"`, `"float"`, or `"boolean"`. When *expandvars* is *True*,
environment variables are exp... | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/config.py#L198-L216 |
riga/law | law/config.py | Config.get_expanded | def get_expanded(self, *args, **kwargs):
"""
Same as :py:meth:`get_default`, but *expandvars* and *expanduser* arguments are set to
*True* by default.
"""
kwargs.setdefault("expandvars", True)
kwargs.setdefault("expanduser", True)
return self.get_default(*args, **... | python | def get_expanded(self, *args, **kwargs):
"""
Same as :py:meth:`get_default`, but *expandvars* and *expanduser* arguments are set to
*True* by default.
"""
kwargs.setdefault("expandvars", True)
kwargs.setdefault("expanduser", True)
return self.get_default(*args, **... | Same as :py:meth:`get_default`, but *expandvars* and *expanduser* arguments are set to
*True* by default. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/config.py#L218-L225 |
riga/law | law/config.py | Config.update | def update(self, data, overwrite=None, overwrite_sections=True, overwrite_options=True):
"""
Updates the currently stored configuration with new *data*, given as a dictionary. When
*overwrite_sections* is *False*, sections in *data* that are already present in the current
config are skip... | python | def update(self, data, overwrite=None, overwrite_sections=True, overwrite_options=True):
"""
Updates the currently stored configuration with new *data*, given as a dictionary. When
*overwrite_sections* is *False*, sections in *data* that are already present in the current
config are skip... | Updates the currently stored configuration with new *data*, given as a dictionary. When
*overwrite_sections* is *False*, sections in *data* that are already present in the current
config are skipped. When *overwrite_options* is *False*, existing options are not
overwritten. When *overwrite* is n... | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/config.py#L227-L247 |
riga/law | law/config.py | Config.include | def include(self, filename, *args, **kwargs):
"""
Updates the current configc with the config found in *filename*. All *args* and *kwargs* are
forwarded to :py:meth:`update`.
"""
p = self.__class__(filename, skip_defaults=True, skip_fallbacks=True)
self.update(p._sections... | python | def include(self, filename, *args, **kwargs):
"""
Updates the current configc with the config found in *filename*. All *args* and *kwargs* are
forwarded to :py:meth:`update`.
"""
p = self.__class__(filename, skip_defaults=True, skip_fallbacks=True)
self.update(p._sections... | Updates the current configc with the config found in *filename*. All *args* and *kwargs* are
forwarded to :py:meth:`update`. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/config.py#L249-L255 |
riga/law | law/config.py | Config.keys | def keys(self, section, prefix=None):
"""
Returns all keys of a *section* in a list. When *prefix* is set, only keys starting with
that prefix are returned
"""
return [key for key, _ in self.items(section) if (not prefix or key.startswith(prefix))] | python | def keys(self, section, prefix=None):
"""
Returns all keys of a *section* in a list. When *prefix* is set, only keys starting with
that prefix are returned
"""
return [key for key, _ in self.items(section) if (not prefix or key.startswith(prefix))] | Returns all keys of a *section* in a list. When *prefix* is set, only keys starting with
that prefix are returned | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/config.py#L257-L262 |
riga/law | law/config.py | Config.sync_luigi_config | def sync_luigi_config(self, push=True, pull=True, expand=True):
"""
Synchronizes sections starting with ``"luigi_"`` with the luigi configuration parser. First,
when *push* is *True*, options that exist in law but **not** in luigi are stored as defaults
in the luigi config. Then, when *p... | python | def sync_luigi_config(self, push=True, pull=True, expand=True):
"""
Synchronizes sections starting with ``"luigi_"`` with the luigi configuration parser. First,
when *push* is *True*, options that exist in law but **not** in luigi are stored as defaults
in the luigi config. Then, when *p... | Synchronizes sections starting with ``"luigi_"`` with the luigi configuration parser. First,
when *push* is *True*, options that exist in law but **not** in luigi are stored as defaults
in the luigi config. Then, when *pull* is *True*, all luigi-related options in the law
config are overwritten ... | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/config.py#L264-L302 |
riga/law | law/contrib/telegram/notification.py | notify_telegram | def notify_telegram(title, content, token=None, chat=None, mention_user=None, **kwargs):
"""
Sends a telegram notification and returns *True* on success. The communication with the telegram
API might have some delays and is therefore handled by a thread.
"""
# test import
import telegram # noqa... | python | def notify_telegram(title, content, token=None, chat=None, mention_user=None, **kwargs):
"""
Sends a telegram notification and returns *True* on success. The communication with the telegram
API might have some delays and is therefore handled by a thread.
"""
# test import
import telegram # noqa... | Sends a telegram notification and returns *True* on success. The communication with the telegram
API might have some delays and is therefore handled by a thread. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/contrib/telegram/notification.py#L19-L70 |
riga/law | law/workflow/local.py | LocalWorkflowProxy.complete | def complete(self):
"""
When *local_workflow_require_branches* of the task was set to *True*, returns whether the
:py:meth:`run` method has been called before. Otherwise, the call is forwarded to the super
class.
"""
if self.task.local_workflow_require_branches:
... | python | def complete(self):
"""
When *local_workflow_require_branches* of the task was set to *True*, returns whether the
:py:meth:`run` method has been called before. Otherwise, the call is forwarded to the super
class.
"""
if self.task.local_workflow_require_branches:
... | When *local_workflow_require_branches* of the task was set to *True*, returns whether the
:py:meth:`run` method has been called before. Otherwise, the call is forwarded to the super
class. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/workflow/local.py#L29-L38 |
riga/law | law/workflow/local.py | LocalWorkflowProxy.run | def run(self):
"""
When *local_workflow_require_branches* of the task was set to *False*, starts all branch
tasks via dynamic dependencies by yielding them in a list, or simply does nothing otherwise.
"""
if not self._has_yielded and not self.task.local_workflow_require_branches:... | python | def run(self):
"""
When *local_workflow_require_branches* of the task was set to *False*, starts all branch
tasks via dynamic dependencies by yielding them in a list, or simply does nothing otherwise.
"""
if not self._has_yielded and not self.task.local_workflow_require_branches:... | When *local_workflow_require_branches* of the task was set to *False*, starts all branch
tasks via dynamic dependencies by yielding them in a list, or simply does nothing otherwise. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/workflow/local.py#L48-L58 |
riga/law | law/decorator.py | factory | def factory(**default_opts):
"""
Factory function to create decorators for tasks' run methods. Default options for the decorator
function can be given in *default_opts*. The returned decorator can be used with or without
function invocation. Example:
.. code-block:: python
@factory(digits=... | python | def factory(**default_opts):
"""
Factory function to create decorators for tasks' run methods. Default options for the decorator
function can be given in *default_opts*. The returned decorator can be used with or without
function invocation. Example:
.. code-block:: python
@factory(digits=... | Factory function to create decorators for tasks' run methods. Default options for the decorator
function can be given in *default_opts*. The returned decorator can be used with or without
function invocation. Example:
.. code-block:: python
@factory(digits=2)
def runtime(fn, opts, task, *a... | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/decorator.py#L46-L97 |
riga/law | law/decorator.py | log | def log(fn, opts, task, *args, **kwargs):
""" log()
Wraps a bound method of a task and redirects output of both stdout and stderr to the file
defined by the tasks's *log_file* parameter or *default_log_file* attribute. If its value is
``"-"`` or *None*, the output is not redirected.
"""
_task = ... | python | def log(fn, opts, task, *args, **kwargs):
""" log()
Wraps a bound method of a task and redirects output of both stdout and stderr to the file
defined by the tasks's *log_file* parameter or *default_log_file* attribute. If its value is
``"-"`` or *None*, the output is not redirected.
"""
_task = ... | log()
Wraps a bound method of a task and redirects output of both stdout and stderr to the file
defined by the tasks's *log_file* parameter or *default_log_file* attribute. If its value is
``"-"`` or *None*, the output is not redirected. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/decorator.py#L105-L132 |
riga/law | law/decorator.py | safe_output | def safe_output(fn, opts, task, *args, **kwargs):
""" safe_output(skip=None)
Wraps a bound method of a task and guards its execution. If an exception occurs, and it is not
an instance of *skip*, the task's output is removed prior to the actual raising.
"""
try:
return fn(task, *args, **kwarg... | python | def safe_output(fn, opts, task, *args, **kwargs):
""" safe_output(skip=None)
Wraps a bound method of a task and guards its execution. If an exception occurs, and it is not
an instance of *skip*, the task's output is removed prior to the actual raising.
"""
try:
return fn(task, *args, **kwarg... | safe_output(skip=None)
Wraps a bound method of a task and guards its execution. If an exception occurs, and it is not
an instance of *skip*, the task's output is removed prior to the actual raising. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/decorator.py#L136-L147 |
riga/law | law/decorator.py | delay | def delay(fn, opts, task, *args, **kwargs):
""" delay(t=5, stddev=0., pdf="gauss")
Wraps a bound method of a task and delays its execution by *t* seconds.
"""
if opts["stddev"] <= 0:
t = opts["t"]
elif opts["pdf"] == "gauss":
t = random.gauss(opts["t"], opts["stddev"])
elif opts[... | python | def delay(fn, opts, task, *args, **kwargs):
""" delay(t=5, stddev=0., pdf="gauss")
Wraps a bound method of a task and delays its execution by *t* seconds.
"""
if opts["stddev"] <= 0:
t = opts["t"]
elif opts["pdf"] == "gauss":
t = random.gauss(opts["t"], opts["stddev"])
elif opts[... | delay(t=5, stddev=0., pdf="gauss")
Wraps a bound method of a task and delays its execution by *t* seconds. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/decorator.py#L151-L166 |
riga/law | law/decorator.py | notify | def notify(fn, opts, task, *args, **kwargs):
""" notify(on_success=True, on_failure=True, **kwargs)
Wraps a bound method of a task and guards its execution. Information about the execution (task
name, duration, etc) is collected and dispatched to all notification transports registered on
wrapped task vi... | python | def notify(fn, opts, task, *args, **kwargs):
""" notify(on_success=True, on_failure=True, **kwargs)
Wraps a bound method of a task and guards its execution. Information about the execution (task
name, duration, etc) is collected and dispatched to all notification transports registered on
wrapped task vi... | notify(on_success=True, on_failure=True, **kwargs)
Wraps a bound method of a task and guards its execution. Information about the execution (task
name, duration, etc) is collected and dispatched to all notification transports registered on
wrapped task via adding :py:class:`law.NotifyParameter` parameters. ... | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/decorator.py#L170-L248 |
riga/law | law/decorator.py | timeit | def timeit(fn, opts, task, *args, **kwargs):
"""
Wraps a bound method of a task and logs its execution time in a human readable format. Logs in
info mode. When *publish_message* is *True*, the duration is also published as a task message to
the scheduler.
"""
start_time = time.time()
try:
... | python | def timeit(fn, opts, task, *args, **kwargs):
"""
Wraps a bound method of a task and logs its execution time in a human readable format. Logs in
info mode. When *publish_message* is *True*, the duration is also published as a task message to
the scheduler.
"""
start_time = time.time()
try:
... | Wraps a bound method of a task and logs its execution time in a human readable format. Logs in
info mode. When *publish_message* is *True*, the duration is also published as a task message to
the scheduler. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/decorator.py#L252-L270 |
riga/law | law/contrib/wlcg/util.py | get_voms_proxy_user | def get_voms_proxy_user():
"""
Returns the owner of the voms proxy.
"""
out = _voms_proxy_info(["--identity"])[1].strip()
try:
return re.match(r".*\/CN\=([^\/]+).*", out.strip()).group(1)
except:
raise Exception("no valid identity found in voms proxy: {}".format(out)) | python | def get_voms_proxy_user():
"""
Returns the owner of the voms proxy.
"""
out = _voms_proxy_info(["--identity"])[1].strip()
try:
return re.match(r".*\/CN\=([^\/]+).*", out.strip()).group(1)
except:
raise Exception("no valid identity found in voms proxy: {}".format(out)) | Returns the owner of the voms proxy. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/contrib/wlcg/util.py#L44-L52 |
riga/law | law/contrib/wlcg/util.py | check_voms_proxy_validity | def check_voms_proxy_validity(log=False):
"""
Returns *True* when a valid voms proxy exists, *False* otherwise. When *log* is *True*, a
warning will be logged.
"""
valid = _voms_proxy_info(["--exists"], silent=True)[0] == 0
if log and not valid:
logger.warning("no valid voms proxy found"... | python | def check_voms_proxy_validity(log=False):
"""
Returns *True* when a valid voms proxy exists, *False* otherwise. When *log* is *True*, a
warning will be logged.
"""
valid = _voms_proxy_info(["--exists"], silent=True)[0] == 0
if log and not valid:
logger.warning("no valid voms proxy found"... | Returns *True* when a valid voms proxy exists, *False* otherwise. When *log* is *True*, a
warning will be logged. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/contrib/wlcg/util.py#L73-L81 |
riga/law | law/contrib/wlcg/util.py | renew_voms_proxy | def renew_voms_proxy(passwd="", vo=None, lifetime="196:00"):
"""
Renews the voms proxy using a password *passwd*, an optional virtual organization name *vo*, and
a default *lifetime* of 8 days. The password is written to a temporary file first and piped into
the renewal commad to ensure it is not visibl... | python | def renew_voms_proxy(passwd="", vo=None, lifetime="196:00"):
"""
Renews the voms proxy using a password *passwd*, an optional virtual organization name *vo*, and
a default *lifetime* of 8 days. The password is written to a temporary file first and piped into
the renewal commad to ensure it is not visibl... | Renews the voms proxy using a password *passwd*, an optional virtual organization name *vo*, and
a default *lifetime* of 8 days. The password is written to a temporary file first and piped into
the renewal commad to ensure it is not visible in the process list. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/contrib/wlcg/util.py#L84-L100 |
riga/law | law/contrib/wlcg/util.py | delegate_voms_proxy_glite | def delegate_voms_proxy_glite(endpoint, stdout=None, stderr=None, cache=True):
"""
Delegates the voms proxy via gLite to an *endpoint*, e.g.
``grid-ce.physik.rwth-aachen.de:8443``. *stdout* and *stderr* are passed to the *Popen*
constructor for executing the ``glite-ce-delegate-proxy`` command. When *ca... | python | def delegate_voms_proxy_glite(endpoint, stdout=None, stderr=None, cache=True):
"""
Delegates the voms proxy via gLite to an *endpoint*, e.g.
``grid-ce.physik.rwth-aachen.de:8443``. *stdout* and *stderr* are passed to the *Popen*
constructor for executing the ``glite-ce-delegate-proxy`` command. When *ca... | Delegates the voms proxy via gLite to an *endpoint*, e.g.
``grid-ce.physik.rwth-aachen.de:8443``. *stdout* and *stderr* are passed to the *Popen*
constructor for executing the ``glite-ce-delegate-proxy`` command. When *cache* is *True*, a
json file is created alongside the proxy file, which stores the deleg... | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/contrib/wlcg/util.py#L103-L167 |
riga/law | law/target/formatter.py | get_formatter | def get_formatter(name, silent=False):
"""
Returns the formatter class whose name attribute is *name*. When no class could be found and
*silent* is *True*, *None* is returned. Otherwise, an exception is raised.
"""
formatter = FormatterRegister.formatters.get(name)
if formatter or silent:
... | python | def get_formatter(name, silent=False):
"""
Returns the formatter class whose name attribute is *name*. When no class could be found and
*silent* is *True*, *None* is returned. Otherwise, an exception is raised.
"""
formatter = FormatterRegister.formatters.get(name)
if formatter or silent:
... | Returns the formatter class whose name attribute is *name*. When no class could be found and
*silent* is *True*, *None* is returned. Otherwise, an exception is raised. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/target/formatter.py#L48-L57 |
riga/law | law/target/formatter.py | find_formatters | def find_formatters(path, silent=True):
"""
Returns a list of formatter classes which would accept the file given by *path*. When no classes
could be found and *silent* is *True*, an empty list is returned. Otherwise, an exception is
raised.
"""
formatters = [f for f in six.itervalues(FormatterR... | python | def find_formatters(path, silent=True):
"""
Returns a list of formatter classes which would accept the file given by *path*. When no classes
could be found and *silent* is *True*, an empty list is returned. Otherwise, an exception is
raised.
"""
formatters = [f for f in six.itervalues(FormatterR... | Returns a list of formatter classes which would accept the file given by *path*. When no classes
could be found and *silent* is *True*, an empty list is returned. Otherwise, an exception is
raised. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/target/formatter.py#L60-L70 |
riga/law | law/target/formatter.py | find_formatter | def find_formatter(name, path):
"""
Returns the formatter class whose name attribute is *name* when *name* is not *AUTO_FORMATTER*.
Otherwise, the first formatter that accepts *path* is returned. Internally, this method simply
uses :py:func:`get_formatter` or :py:func:`find_formatters` depending on the ... | python | def find_formatter(name, path):
"""
Returns the formatter class whose name attribute is *name* when *name* is not *AUTO_FORMATTER*.
Otherwise, the first formatter that accepts *path* is returned. Internally, this method simply
uses :py:func:`get_formatter` or :py:func:`find_formatters` depending on the ... | Returns the formatter class whose name attribute is *name* when *name* is not *AUTO_FORMATTER*.
Otherwise, the first formatter that accepts *path* is returned. Internally, this method simply
uses :py:func:`get_formatter` or :py:func:`find_formatters` depending on the value of *name*. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/target/formatter.py#L73-L82 |
riga/law | law/job/base.py | JobArguments.encode_list | def encode_list(cls, value):
"""
Encodes a list *value* into a string via base64 encoding.
"""
encoded = base64.b64encode(six.b(" ".join(str(v) for v in value) or "-"))
return encoded.decode("utf-8") if six.PY3 else encoded | python | def encode_list(cls, value):
"""
Encodes a list *value* into a string via base64 encoding.
"""
encoded = base64.b64encode(six.b(" ".join(str(v) for v in value) or "-"))
return encoded.decode("utf-8") if six.PY3 else encoded | Encodes a list *value* into a string via base64 encoding. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/job/base.py#L700-L705 |
riga/law | law/job/base.py | JobArguments.get_args | def get_args(self):
"""
Returns the list of encoded job arguments. The order of this list corresponds to the
arguments expected by the job wrapper script.
"""
return [
self.task_cls.__module__,
self.task_cls.__name__,
self.encode_list(self.task... | python | def get_args(self):
"""
Returns the list of encoded job arguments. The order of this list corresponds to the
arguments expected by the job wrapper script.
"""
return [
self.task_cls.__module__,
self.task_cls.__name__,
self.encode_list(self.task... | Returns the list of encoded job arguments. The order of this list corresponds to the
arguments expected by the job wrapper script. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/job/base.py#L707-L719 |
riga/law | law/contrib/__init__.py | load | def load(*packages):
"""
Loads contrib *packages* and adds members exposed in ``__all__`` to the law main module.
Example:
.. code-block:: python
import law
law.contrib.load("numpy")
print(law.NumpyFormatter)
# -> <class 'law.contrib.numpy.formatter.NumpyFormatter'>
... | python | def load(*packages):
"""
Loads contrib *packages* and adds members exposed in ``__all__`` to the law main module.
Example:
.. code-block:: python
import law
law.contrib.load("numpy")
print(law.NumpyFormatter)
# -> <class 'law.contrib.numpy.formatter.NumpyFormatter'>
... | Loads contrib *packages* and adds members exposed in ``__all__`` to the law main module.
Example:
.. code-block:: python
import law
law.contrib.load("numpy")
print(law.NumpyFormatter)
# -> <class 'law.contrib.numpy.formatter.NumpyFormatter'>
It is ensured that packages ar... | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/contrib/__init__.py#L21-L52 |
riga/law | law/notification.py | notify_mail | def notify_mail(title, message, recipient=None, sender=None, smtp_host=None, smtp_port=None,
**kwargs):
"""
Mail notification method taking a *title* and a string *message*. *recipient*, *sender*,
*smtp_host* and *smtp_port* default to the configuration values in the [notifications] section.
"""... | python | def notify_mail(title, message, recipient=None, sender=None, smtp_host=None, smtp_port=None,
**kwargs):
"""
Mail notification method taking a *title* and a string *message*. *recipient*, *sender*,
*smtp_host* and *smtp_port* default to the configuration values in the [notifications] section.
"""... | Mail notification method taking a *title* and a string *message*. *recipient*, *sender*,
*smtp_host* and *smtp_port* default to the configuration values in the [notifications] section. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/notification.py#L20-L42 |
riga/law | law/patches.py | patch_all | def patch_all():
"""
Runs all patches. This function ensures that a second invocation has no effect.
"""
global _patched
if _patched:
return
_patched = True
patch_default_retcodes()
patch_worker_run_task()
patch_worker_factory()
patch_keepalive_run()
patch_cmdline_p... | python | def patch_all():
"""
Runs all patches. This function ensures that a second invocation has no effect.
"""
global _patched
if _patched:
return
_patched = True
patch_default_retcodes()
patch_worker_run_task()
patch_worker_factory()
patch_keepalive_run()
patch_cmdline_p... | Runs all patches. This function ensures that a second invocation has no effect. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/patches.py#L24-L40 |
riga/law | law/patches.py | patch_default_retcodes | def patch_default_retcodes():
"""
Sets the default luigi return codes in ``luigi.retcodes.retcode`` to:
- already_running: 10
- missing_data: 20
- not_run: 30
- task_failed: 40
- scheduling_error: 50
- unhandled_exception: 60
"""
import luigi.retcodes
... | python | def patch_default_retcodes():
"""
Sets the default luigi return codes in ``luigi.retcodes.retcode`` to:
- already_running: 10
- missing_data: 20
- not_run: 30
- task_failed: 40
- scheduling_error: 50
- unhandled_exception: 60
"""
import luigi.retcodes
... | Sets the default luigi return codes in ``luigi.retcodes.retcode`` to:
- already_running: 10
- missing_data: 20
- not_run: 30
- task_failed: 40
- scheduling_error: 50
- unhandled_exception: 60 | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/patches.py#L43-L63 |
riga/law | law/patches.py | patch_worker_run_task | def patch_worker_run_task():
"""
Patches the ``luigi.worker.Worker._run_task`` method to store the worker id and the id of its
first task in the task. This information is required by the sandboxing mechanism
"""
_run_task = luigi.worker.Worker._run_task
def run_task(self, task_id):
task... | python | def patch_worker_run_task():
"""
Patches the ``luigi.worker.Worker._run_task`` method to store the worker id and the id of its
first task in the task. This information is required by the sandboxing mechanism
"""
_run_task = luigi.worker.Worker._run_task
def run_task(self, task_id):
task... | Patches the ``luigi.worker.Worker._run_task`` method to store the worker id and the id of its
first task in the task. This information is required by the sandboxing mechanism | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/patches.py#L66-L89 |
riga/law | law/patches.py | patch_worker_factory | def patch_worker_factory():
"""
Patches the ``luigi.interface._WorkerSchedulerFactory`` to include sandboxing information when
create a worker instance.
"""
def create_worker(self, scheduler, worker_processes, assistant=False):
worker = luigi.worker.Worker(scheduler=scheduler, worker_process... | python | def patch_worker_factory():
"""
Patches the ``luigi.interface._WorkerSchedulerFactory`` to include sandboxing information when
create a worker instance.
"""
def create_worker(self, scheduler, worker_processes, assistant=False):
worker = luigi.worker.Worker(scheduler=scheduler, worker_process... | Patches the ``luigi.interface._WorkerSchedulerFactory`` to include sandboxing information when
create a worker instance. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/patches.py#L92-L103 |
riga/law | law/patches.py | patch_keepalive_run | def patch_keepalive_run():
"""
Patches the ``luigi.worker.KeepAliveThread.run`` to immediately stop the keep-alive thread when
running within a sandbox.
"""
_run = luigi.worker.KeepAliveThread.run
def run(self):
# do not run the keep-alive loop when sandboxed
if os.getenv("LAW_S... | python | def patch_keepalive_run():
"""
Patches the ``luigi.worker.KeepAliveThread.run`` to immediately stop the keep-alive thread when
running within a sandbox.
"""
_run = luigi.worker.KeepAliveThread.run
def run(self):
# do not run the keep-alive loop when sandboxed
if os.getenv("LAW_S... | Patches the ``luigi.worker.KeepAliveThread.run`` to immediately stop the keep-alive thread when
running within a sandbox. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/patches.py#L106-L120 |
riga/law | law/patches.py | patch_cmdline_parser | def patch_cmdline_parser():
"""
Patches the ``luigi.cmdline_parser.CmdlineParser`` to store the original command line arguments
for later processing in the :py:class:`law.config.Config`.
"""
# store original functions
_init = luigi.cmdline_parser.CmdlineParser.__init__
# patch init
def ... | python | def patch_cmdline_parser():
"""
Patches the ``luigi.cmdline_parser.CmdlineParser`` to store the original command line arguments
for later processing in the :py:class:`law.config.Config`.
"""
# store original functions
_init = luigi.cmdline_parser.CmdlineParser.__init__
# patch init
def ... | Patches the ``luigi.cmdline_parser.CmdlineParser`` to store the original command line arguments
for later processing in the :py:class:`law.config.Config`. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/patches.py#L123-L136 |
riga/law | law/contrib/slack/notification.py | notify_slack | def notify_slack(title, content, attachment_color="#4bb543", short_threshold=40, token=None,
channel=None, mention_user=None, **kwargs):
"""
Sends a slack notification and returns *True* on success. The communication with the slack API
might have some delays and is therefore handled by a thread. The... | python | def notify_slack(title, content, attachment_color="#4bb543", short_threshold=40, token=None,
channel=None, mention_user=None, **kwargs):
"""
Sends a slack notification and returns *True* on success. The communication with the slack API
might have some delays and is therefore handled by a thread. The... | Sends a slack notification and returns *True* on success. The communication with the slack API
might have some delays and is therefore handled by a thread. The format of the notification
depends on *content*. If it is a string, a simple text notification is sent. Otherwise, it
should be a dictionary whose f... | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/contrib/slack/notification.py#L19-L87 |
riga/law | examples/workflows/tasks.py | maybe_wait | def maybe_wait(func):
"""
Wrapper around run() methods that reads the *slow* flag to decide whether to wait some seconds
for illustrative purposes. This is very straight forward, so no need for functools.wraps here.
"""
def wrapper(self, *args, **kwargs):
if self.slow:
time.sleep... | python | def maybe_wait(func):
"""
Wrapper around run() methods that reads the *slow* flag to decide whether to wait some seconds
for illustrative purposes. This is very straight forward, so no need for functools.wraps here.
"""
def wrapper(self, *args, **kwargs):
if self.slow:
time.sleep... | Wrapper around run() methods that reads the *slow* flag to decide whether to wait some seconds
for illustrative purposes. This is very straight forward, so no need for functools.wraps here. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/examples/workflows/tasks.py#L19-L29 |
riga/law | law/contrib/lsf/job.py | LSFJobManager.parse_query_output | def parse_query_output(cls, out):
"""
Example output to parse:
141914132 user_name DONE queue_name exec_host b63cee711a job_name Feb 8 14:54
"""
query_data = {}
for line in out.strip().split("\n"):
parts = line.split()
if len(parts) < 6:
... | python | def parse_query_output(cls, out):
"""
Example output to parse:
141914132 user_name DONE queue_name exec_host b63cee711a job_name Feb 8 14:54
"""
query_data = {}
for line in out.strip().split("\n"):
parts = line.split()
if len(parts) < 6:
... | Example output to parse:
141914132 user_name DONE queue_name exec_host b63cee711a job_name Feb 8 14:54 | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/contrib/lsf/job.py#L144-L165 |
riga/law | law/logger.py | setup_logging | def setup_logging():
"""
Sets up the internal logging mechanism, i.e., it creates the :py:attr:`console_handler`, sets
its formatting, and mounts on on the main ``"law"`` logger. It also sets the levels of all
loggers that are given in the law config.
"""
global console_handler
# make sure ... | python | def setup_logging():
"""
Sets up the internal logging mechanism, i.e., it creates the :py:attr:`console_handler`, sets
its formatting, and mounts on on the main ``"law"`` logger. It also sets the levels of all
loggers that are given in the law config.
"""
global console_handler
# make sure ... | Sets up the internal logging mechanism, i.e., it creates the :py:attr:`console_handler`, sets
its formatting, and mounts on on the main ``"law"`` logger. It also sets the levels of all
loggers that are given in the law config. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/logger.py#L22-L45 |
riga/law | law/cli/config.py | execute | def execute(args):
"""
Executes the *config* subprogram with parsed commandline *args*.
"""
# just print the file location?
if args.location:
print(Config.instance().config_file)
return
# every option below requires the name to be set
if not args.name:
abort("please ... | python | def execute(args):
"""
Executes the *config* subprogram with parsed commandline *args*.
"""
# just print the file location?
if args.location:
print(Config.instance().config_file)
return
# every option below requires the name to be set
if not args.name:
abort("please ... | Executes the *config* subprogram with parsed commandline *args*. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/cli/config.py#L30-L52 |
riga/law | law/cli/config.py | get_config | def get_config(name, expand=False):
"""
Returns the config value that corresponds to *name*, which must have the format
``<section>[.<option>]``. When an option is given and *expand* is *True*, variables are expanded
in the returned value.
"""
cfg = Config.instance()
only_section = "." not i... | python | def get_config(name, expand=False):
"""
Returns the config value that corresponds to *name*, which must have the format
``<section>[.<option>]``. When an option is given and *expand* is *True*, variables are expanded
in the returned value.
"""
cfg = Config.instance()
only_section = "." not i... | Returns the config value that corresponds to *name*, which must have the format
``<section>[.<option>]``. When an option is given and *expand* is *True*, variables are expanded
in the returned value. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/cli/config.py#L55-L71 |
riga/law | law/cli/run.py | setup_parser | def setup_parser(sub_parsers):
"""
Sets up the command line parser for the *run* subprogram and adds it to *sub_parsers*.
"""
parser = sub_parsers.add_parser("run", prog="law run", description="Run a task with"
" configurable parameters. See http://luigi.rtfd.io/en/stable/running_luigi.html for ... | python | def setup_parser(sub_parsers):
"""
Sets up the command line parser for the *run* subprogram and adds it to *sub_parsers*.
"""
parser = sub_parsers.add_parser("run", prog="law run", description="Run a task with"
" configurable parameters. See http://luigi.rtfd.io/en/stable/running_luigi.html for ... | Sets up the command line parser for the *run* subprogram and adds it to *sub_parsers*. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/cli/run.py#L22-L32 |
riga/law | law/cli/run.py | execute | def execute(args):
"""
Executes the *run* subprogram with parsed commandline *args*.
"""
task_family = None
error = None
# try to infer the task module from the passed task family and import it
parts = args.task_family.rsplit(".", 1)
if len(parts) == 2:
modid, cls_name = parts
... | python | def execute(args):
"""
Executes the *run* subprogram with parsed commandline *args*.
"""
task_family = None
error = None
# try to infer the task module from the passed task family and import it
parts = args.task_family.rsplit(".", 1)
if len(parts) == 2:
modid, cls_name = parts
... | Executes the *run* subprogram with parsed commandline *args*. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/cli/run.py#L35-L75 |
riga/law | law/cli/run.py | read_task_from_index | def read_task_from_index(task_family, index_file=None):
"""
Returns module id, task family and space-separated parameters in a tuple for a task given by
*task_family* from the *index_file*. When *None*, the *index_file* refers to the default as
defined in :py:mod:`law.config`. Returns *None* when the ta... | python | def read_task_from_index(task_family, index_file=None):
"""
Returns module id, task family and space-separated parameters in a tuple for a task given by
*task_family* from the *index_file*. When *None*, the *index_file* refers to the default as
defined in :py:mod:`law.config`. Returns *None* when the ta... | Returns module id, task family and space-separated parameters in a tuple for a task given by
*task_family* from the *index_file*. When *None*, the *index_file* refers to the default as
defined in :py:mod:`law.config`. Returns *None* when the task could not be found. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/cli/run.py#L78-L97 |
riga/law | law/cli/cli.py | run | def run():
"""
Entry point to the law cli. Sets up all parsers, parses all arguments, and executes the
requested subprogram.
"""
# setup the main parser and sub parsers
parser = ArgumentParser(prog="law", description="The law command line tool.")
sub_parsers = parser.add_subparsers(help="sub... | python | def run():
"""
Entry point to the law cli. Sets up all parsers, parses all arguments, and executes the
requested subprogram.
"""
# setup the main parser and sub parsers
parser = ArgumentParser(prog="law", description="The law command line tool.")
sub_parsers = parser.add_subparsers(help="sub... | Entry point to the law cli. Sets up all parsers, parses all arguments, and executes the
requested subprogram. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/cli/cli.py#L22-L49 |
riga/law | law/job/dashboard.py | cache_by_status | def cache_by_status(func):
"""
Decorator for :py:meth:`BaseJobDashboard.publish` (and inheriting classes) that caches the last
published status to decide if the a new publication is necessary or not. When the status did not
change since the last call, the actual publish method is not invoked and *None* ... | python | def cache_by_status(func):
"""
Decorator for :py:meth:`BaseJobDashboard.publish` (and inheriting classes) that caches the last
published status to decide if the a new publication is necessary or not. When the status did not
change since the last call, the actual publish method is not invoked and *None* ... | Decorator for :py:meth:`BaseJobDashboard.publish` (and inheriting classes) that caches the last
published status to decide if the a new publication is necessary or not. When the status did not
change since the last call, the actual publish method is not invoked and *None* is returned. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/job/dashboard.py#L19-L39 |
riga/law | law/cli/software.py | setup_parser | def setup_parser(sub_parsers):
"""
Sets up the command line parser for the *software* subprogram and adds it to *sub_parsers*.
"""
parser = sub_parsers.add_parser("software", prog="law software", description="Create or update"
" the law software cache ({}). This is only required for some sandbox... | python | def setup_parser(sub_parsers):
"""
Sets up the command line parser for the *software* subprogram and adds it to *sub_parsers*.
"""
parser = sub_parsers.add_parser("software", prog="law software", description="Create or update"
" the law software cache ({}). This is only required for some sandbox... | Sets up the command line parser for the *software* subprogram and adds it to *sub_parsers*. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/cli/software.py#L30-L41 |
riga/law | law/cli/software.py | execute | def execute(args):
"""
Executes the *software* subprogram with parsed commandline *args*.
"""
sw_dir = get_sw_dir()
# just print the cache location?
if args.location:
print(sw_dir)
return
# just remove the current software cache?
if args.remove:
remove_software_... | python | def execute(args):
"""
Executes the *software* subprogram with parsed commandline *args*.
"""
sw_dir = get_sw_dir()
# just print the cache location?
if args.location:
print(sw_dir)
return
# just remove the current software cache?
if args.remove:
remove_software_... | Executes the *software* subprogram with parsed commandline *args*. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/cli/software.py#L44-L61 |
riga/law | law/cli/software.py | build_software_cache | def build_software_cache(sw_dir=None):
"""
Builds up the software cache directory at *sw_dir* by simply copying all required python
modules. *sw_dir* is evaluated with :py:func:`get_sw_dir`.
"""
# ensure the cache is empty
sw_dir = get_sw_dir(sw_dir)
remove_software_cache(sw_dir)
os.make... | python | def build_software_cache(sw_dir=None):
"""
Builds up the software cache directory at *sw_dir* by simply copying all required python
modules. *sw_dir* is evaluated with :py:func:`get_sw_dir`.
"""
# ensure the cache is empty
sw_dir = get_sw_dir(sw_dir)
remove_software_cache(sw_dir)
os.make... | Builds up the software cache directory at *sw_dir* by simply copying all required python
modules. *sw_dir* is evaluated with :py:func:`get_sw_dir`. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/cli/software.py#L64-L86 |
riga/law | law/cli/software.py | remove_software_cache | def remove_software_cache(sw_dir=None):
"""
Removes the software cache directory at *sw_dir* which is evaluated with :py:func:`get_sw_dir`.
"""
sw_dir = get_sw_dir(sw_dir)
if os.path.exists(sw_dir):
shutil.rmtree(sw_dir) | python | def remove_software_cache(sw_dir=None):
"""
Removes the software cache directory at *sw_dir* which is evaluated with :py:func:`get_sw_dir`.
"""
sw_dir = get_sw_dir(sw_dir)
if os.path.exists(sw_dir):
shutil.rmtree(sw_dir) | Removes the software cache directory at *sw_dir* which is evaluated with :py:func:`get_sw_dir`. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/cli/software.py#L89-L95 |
riga/law | law/cli/software.py | reload_dependencies | def reload_dependencies(force=False):
"""
Reloads all python modules that law depends on. Currently, this is just *luigi* and *six*.
Unless *force* is *True*, multiple calls to this function will not have any effect.
"""
global _reloaded_deps
if _reloaded_deps and not force:
return
... | python | def reload_dependencies(force=False):
"""
Reloads all python modules that law depends on. Currently, this is just *luigi* and *six*.
Unless *force* is *True*, multiple calls to this function will not have any effect.
"""
global _reloaded_deps
if _reloaded_deps and not force:
return
... | Reloads all python modules that law depends on. Currently, this is just *luigi* and *six*.
Unless *force* is *True*, multiple calls to this function will not have any effect. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/cli/software.py#L98-L111 |
riga/law | law/cli/software.py | use_software_cache | def use_software_cache(sw_dir=None, reload_deps=False):
"""
Adjusts ``sys.path`` so that the cached software at *sw_dir* is used. *sw_dir* is evaluated with
:py:func:`get_sw_dir`. When *reload_deps* is *True*, :py:func:`reload_dependencies` is invoked.
"""
sw_dir = get_sw_dir(sw_dir)
if os.path.... | python | def use_software_cache(sw_dir=None, reload_deps=False):
"""
Adjusts ``sys.path`` so that the cached software at *sw_dir* is used. *sw_dir* is evaluated with
:py:func:`get_sw_dir`. When *reload_deps* is *True*, :py:func:`reload_dependencies` is invoked.
"""
sw_dir = get_sw_dir(sw_dir)
if os.path.... | Adjusts ``sys.path`` so that the cached software at *sw_dir* is used. *sw_dir* is evaluated with
:py:func:`get_sw_dir`. When *reload_deps* is *True*, :py:func:`reload_dependencies` is invoked. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/cli/software.py#L114-L124 |
riga/law | law/cli/software.py | get_sw_dir | def get_sw_dir(sw_dir=None):
"""
Returns the software directory defined in the ``config.software_dir`` config. When *sw_dir* is
not *None*, it is expanded and returned instead.
"""
if sw_dir is None:
sw_dir = Config.instance().get("core", "software_dir")
sw_dir = os.path.expandvars(os.p... | python | def get_sw_dir(sw_dir=None):
"""
Returns the software directory defined in the ``config.software_dir`` config. When *sw_dir* is
not *None*, it is expanded and returned instead.
"""
if sw_dir is None:
sw_dir = Config.instance().get("core", "software_dir")
sw_dir = os.path.expandvars(os.p... | Returns the software directory defined in the ``config.software_dir`` config. When *sw_dir* is
not *None*, it is expanded and returned instead. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/cli/software.py#L127-L137 |
riga/law | law/contrib/root/formatter.py | GuardedTFile | def GuardedTFile(*args, **kwargs):
"""
Factory function that lazily creates the guarded TFile class, and creates and returns an
instance with all passed *args* and *kwargs*. This is required as we do not want to import ROOT
in the global scope.
"""
global guarded_tfile_cls
if not guarded_tf... | python | def GuardedTFile(*args, **kwargs):
"""
Factory function that lazily creates the guarded TFile class, and creates and returns an
instance with all passed *args* and *kwargs*. This is required as we do not want to import ROOT
in the global scope.
"""
global guarded_tfile_cls
if not guarded_tf... | Factory function that lazily creates the guarded TFile class, and creates and returns an
instance with all passed *args* and *kwargs*. This is required as we do not want to import ROOT
in the global scope. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/contrib/root/formatter.py#L15-L37 |
riga/law | law/workflow/base.py | workflow_property | def workflow_property(func):
"""
Decorator to declare a property that is stored only on a workflow but makes it also accessible
from branch tasks. Internally, branch tasks are re-instantiated with ``branch=-1``, and its
decorated property is invoked. You might want to use this decorator in case of a pro... | python | def workflow_property(func):
"""
Decorator to declare a property that is stored only on a workflow but makes it also accessible
from branch tasks. Internally, branch tasks are re-instantiated with ``branch=-1``, and its
decorated property is invoked. You might want to use this decorator in case of a pro... | Decorator to declare a property that is stored only on a workflow but makes it also accessible
from branch tasks. Internally, branch tasks are re-instantiated with ``branch=-1``, and its
decorated property is invoked. You might want to use this decorator in case of a property that
is common (and mutable) to... | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/workflow/base.py#L129-L155 |
riga/law | law/workflow/base.py | cached_workflow_property | def cached_workflow_property(func=None, attr=None, setter=True):
"""
Decorator to declare an attribute that is stored only on a workflow and also cached for
subsequent calls. Therefore, the decorated method is expected to (lazily) provide the value to
cache. The resulting value is stored as ``_workflow_... | python | def cached_workflow_property(func=None, attr=None, setter=True):
"""
Decorator to declare an attribute that is stored only on a workflow and also cached for
subsequent calls. Therefore, the decorated method is expected to (lazily) provide the value to
cache. The resulting value is stored as ``_workflow_... | Decorator to declare an attribute that is stored only on a workflow and also cached for
subsequent calls. Therefore, the decorated method is expected to (lazily) provide the value to
cache. The resulting value is stored as ``_workflow_cached_<func.__name__>`` on the workflow,
which can be overwritten by set... | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/workflow/base.py#L158-L199 |
riga/law | law/workflow/base.py | BaseWorkflowProxy.complete | def complete(self):
"""
Custom completion check that invokes the task's *workflow_complete* if it is callable, or
just does the default completion check otherwise.
"""
if callable(self.task.workflow_complete):
return self.task.workflow_complete()
else:
... | python | def complete(self):
"""
Custom completion check that invokes the task's *workflow_complete* if it is callable, or
just does the default completion check otherwise.
"""
if callable(self.task.workflow_complete):
return self.task.workflow_complete()
else:
... | Custom completion check that invokes the task's *workflow_complete* if it is callable, or
just does the default completion check otherwise. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/workflow/base.py#L68-L76 |
riga/law | law/workflow/base.py | BaseWorkflowProxy.requires | def requires(self):
"""
Returns the default workflow requirements in an ordered dictionary, which is updated with
the return value of the task's *workflow_requires* method.
"""
reqs = OrderedDict()
reqs.update(self.task.workflow_requires())
return reqs | python | def requires(self):
"""
Returns the default workflow requirements in an ordered dictionary, which is updated with
the return value of the task's *workflow_requires* method.
"""
reqs = OrderedDict()
reqs.update(self.task.workflow_requires())
return reqs | Returns the default workflow requirements in an ordered dictionary, which is updated with
the return value of the task's *workflow_requires* method. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/workflow/base.py#L78-L85 |
riga/law | law/workflow/base.py | BaseWorkflowProxy.output | def output(self):
"""
Returns the default workflow outputs in an ordered dictionary. At the moment this is just
the collection of outputs of the branch tasks, stored with the key ``"collection"``.
"""
if self.task.target_collection_cls is not None:
cls = self.task.tar... | python | def output(self):
"""
Returns the default workflow outputs in an ordered dictionary. At the moment this is just
the collection of outputs of the branch tasks, stored with the key ``"collection"``.
"""
if self.task.target_collection_cls is not None:
cls = self.task.tar... | Returns the default workflow outputs in an ordered dictionary. At the moment this is just
the collection of outputs of the branch tasks, stored with the key ``"collection"``. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/workflow/base.py#L87-L102 |
riga/law | law/workflow/base.py | BaseWorkflowProxy.threshold | def threshold(self, n=None):
"""
Returns the threshold number of tasks that need to be complete in order to consider the
workflow as being complete itself. This takes into account the
:py:attr:`law.BaseWorkflow.acceptance` parameter of the workflow. The threshold is passed
to the... | python | def threshold(self, n=None):
"""
Returns the threshold number of tasks that need to be complete in order to consider the
workflow as being complete itself. This takes into account the
:py:attr:`law.BaseWorkflow.acceptance` parameter of the workflow. The threshold is passed
to the... | Returns the threshold number of tasks that need to be complete in order to consider the
workflow as being complete itself. This takes into account the
:py:attr:`law.BaseWorkflow.acceptance` parameter of the workflow. The threshold is passed
to the :py:class:`law.TargetCollection` (or :py:class:`... | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/workflow/base.py#L104-L117 |
riga/law | law/workflow/base.py | BaseWorkflowProxy.get_prefixed_config | def get_prefixed_config(self, section, option, **kwargs):
"""
TODO.
"""
cfg = Config.instance()
default = cfg.get_expanded(section, option, **kwargs)
return cfg.get_expanded(section, "{}_{}".format(self.workflow_type, option),
default=default, **kwargs) | python | def get_prefixed_config(self, section, option, **kwargs):
"""
TODO.
"""
cfg = Config.instance()
default = cfg.get_expanded(section, option, **kwargs)
return cfg.get_expanded(section, "{}_{}".format(self.workflow_type, option),
default=default, **kwargs) | TODO. | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/workflow/base.py#L119-L126 |
alexandrovteam/pyimzML | pyimzml/ImzMLParser.py | getionimage | def getionimage(p, mz_value, tol=0.1, z=1, reduce_func=sum):
"""
Get an image representation of the intensity distribution
of the ion with specified m/z value.
By default, the intensity values within the tolerance region are summed.
:param p:
the ImzMLParser (or anything else with similar ... | python | def getionimage(p, mz_value, tol=0.1, z=1, reduce_func=sum):
"""
Get an image representation of the intensity distribution
of the ion with specified m/z value.
By default, the intensity values within the tolerance region are summed.
:param p:
the ImzMLParser (or anything else with similar ... | Get an image representation of the intensity distribution
of the ion with specified m/z value.
By default, the intensity values within the tolerance region are summed.
:param p:
the ImzMLParser (or anything else with similar attributes) for the desired dataset
:param mz_value:
m/z valu... | https://github.com/alexandrovteam/pyimzML/blob/baae0bea7279f9439113d6b2f61be528c0462b3f/pyimzml/ImzMLParser.py#L335-L368 |
alexandrovteam/pyimzML | pyimzml/ImzMLParser.py | ImzMLParser.__iter_read_spectrum_meta | def __iter_read_spectrum_meta(self):
"""
This method should only be called by __init__. Reads the data formats, coordinates and offsets from
the .imzML file and initializes the respective attributes. While traversing the XML tree, the per-spectrum
metadata is pruned, i.e. the <spectrumLi... | python | def __iter_read_spectrum_meta(self):
"""
This method should only be called by __init__. Reads the data formats, coordinates and offsets from
the .imzML file and initializes the respective attributes. While traversing the XML tree, the per-spectrum
metadata is pruned, i.e. the <spectrumLi... | This method should only be called by __init__. Reads the data formats, coordinates and offsets from
the .imzML file and initializes the respective attributes. While traversing the XML tree, the per-spectrum
metadata is pruned, i.e. the <spectrumList> element(s) are left behind empty.
Supported ... | https://github.com/alexandrovteam/pyimzML/blob/baae0bea7279f9439113d6b2f61be528c0462b3f/pyimzml/ImzMLParser.py#L115-L148 |
alexandrovteam/pyimzML | pyimzml/ImzMLParser.py | ImzMLParser.__readimzmlmeta | def __readimzmlmeta(self):
"""
This method should only be called by __init__. Initializes the imzmldict with frequently used metadata from
the .imzML file.
This method reads only a subset of the available meta information and may be extended in the future. The keys
are named sim... | python | def __readimzmlmeta(self):
"""
This method should only be called by __init__. Initializes the imzmldict with frequently used metadata from
the .imzML file.
This method reads only a subset of the available meta information and may be extended in the future. The keys
are named sim... | This method should only be called by __init__. Initializes the imzmldict with frequently used metadata from
the .imzML file.
This method reads only a subset of the available meta information and may be extended in the future. The keys
are named similarly to the imzML names. Currently supported ... | https://github.com/alexandrovteam/pyimzML/blob/baae0bea7279f9439113d6b2f61be528c0462b3f/pyimzml/ImzMLParser.py#L210-L264 |
alexandrovteam/pyimzML | pyimzml/ImzMLParser.py | ImzMLParser.get_physical_coordinates | def get_physical_coordinates(self, i):
"""
For a pixel index i, return the real-world coordinates in nanometers.
This is equivalent to multiplying the image coordinates of the given pixel with the pixel size.
:param i: the pixel index
:return: a tuple of x and y coordinates.
... | python | def get_physical_coordinates(self, i):
"""
For a pixel index i, return the real-world coordinates in nanometers.
This is equivalent to multiplying the image coordinates of the given pixel with the pixel size.
:param i: the pixel index
:return: a tuple of x and y coordinates.
... | For a pixel index i, return the real-world coordinates in nanometers.
This is equivalent to multiplying the image coordinates of the given pixel with the pixel size.
:param i: the pixel index
:return: a tuple of x and y coordinates.
:rtype: Tuple[float]
:raises KeyError: if the... | https://github.com/alexandrovteam/pyimzML/blob/baae0bea7279f9439113d6b2f61be528c0462b3f/pyimzml/ImzMLParser.py#L266-L283 |
alexandrovteam/pyimzML | pyimzml/ImzMLParser.py | ImzMLParser.getspectrum | def getspectrum(self, index):
"""
Reads the spectrum at specified index from the .ibd file.
:param index:
Index of the desired spectrum in the .imzML file
Output:
mz_array: numpy.ndarray
Sequence of m/z values representing the horizontal axis of the des... | python | def getspectrum(self, index):
"""
Reads the spectrum at specified index from the .ibd file.
:param index:
Index of the desired spectrum in the .imzML file
Output:
mz_array: numpy.ndarray
Sequence of m/z values representing the horizontal axis of the des... | Reads the spectrum at specified index from the .ibd file.
:param index:
Index of the desired spectrum in the .imzML file
Output:
mz_array: numpy.ndarray
Sequence of m/z values representing the horizontal axis of the desired mass
spectrum
intensity_a... | https://github.com/alexandrovteam/pyimzML/blob/baae0bea7279f9439113d6b2f61be528c0462b3f/pyimzml/ImzMLParser.py#L285-L303 |
alexandrovteam/pyimzML | pyimzml/ImzMLParser.py | ImzMLParser.get_spectrum_as_string | def get_spectrum_as_string(self, index):
"""
Reads m/z array and intensity array of the spectrum at specified location
from the binary file as a byte string. The string can be unpacked by the struct
module. To get the arrays as numbers, use getspectrum
:param index:
... | python | def get_spectrum_as_string(self, index):
"""
Reads m/z array and intensity array of the spectrum at specified location
from the binary file as a byte string. The string can be unpacked by the struct
module. To get the arrays as numbers, use getspectrum
:param index:
... | Reads m/z array and intensity array of the spectrum at specified location
from the binary file as a byte string. The string can be unpacked by the struct
module. To get the arrays as numbers, use getspectrum
:param index:
Index of the desired spectrum in the .imzML file
:rty... | https://github.com/alexandrovteam/pyimzML/blob/baae0bea7279f9439113d6b2f61be528c0462b3f/pyimzml/ImzMLParser.py#L305-L332 |
alexandrovteam/pyimzML | pyimzml/ImzMLWriter.py | ImzMLWriter._read_mz | def _read_mz(self, mz_offset, mz_len, mz_enc_len):
'''reads a mz array from the currently open ibd file'''
self.ibd.seek(mz_offset)
data = self.ibd.read(mz_enc_len)
self.ibd.seek(0, 2)
data = self.mz_compression.decompress(data)
return tuple(np.fromstring(data, dtype=self... | python | def _read_mz(self, mz_offset, mz_len, mz_enc_len):
'''reads a mz array from the currently open ibd file'''
self.ibd.seek(mz_offset)
data = self.ibd.read(mz_enc_len)
self.ibd.seek(0, 2)
data = self.mz_compression.decompress(data)
return tuple(np.fromstring(data, dtype=self... | reads a mz array from the currently open ibd file | https://github.com/alexandrovteam/pyimzML/blob/baae0bea7279f9439113d6b2f61be528c0462b3f/pyimzml/ImzMLWriter.py#L241-L247 |
alexandrovteam/pyimzML | pyimzml/ImzMLWriter.py | ImzMLWriter._get_previous_mz | def _get_previous_mz(self, mzs):
'''given an mz array, return the mz_data (disk location)
if the mz array was not previously written, write to disk first'''
mzs = tuple(mzs) # must be hashable
if mzs in self.lru_cache:
return self.lru_cache[mzs]
# mz not recognized ... | python | def _get_previous_mz(self, mzs):
'''given an mz array, return the mz_data (disk location)
if the mz array was not previously written, write to disk first'''
mzs = tuple(mzs) # must be hashable
if mzs in self.lru_cache:
return self.lru_cache[mzs]
# mz not recognized ... | given an mz array, return the mz_data (disk location)
if the mz array was not previously written, write to disk first | https://github.com/alexandrovteam/pyimzML/blob/baae0bea7279f9439113d6b2f61be528c0462b3f/pyimzml/ImzMLWriter.py#L249-L269 |
alexandrovteam/pyimzML | pyimzml/ImzMLWriter.py | ImzMLWriter.addSpectrum | def addSpectrum(self, mzs, intensities, coords, userParams=[]):
"""
Add a mass spectrum to the file.
:param mz:
mz array
:param intensities:
intensity array
:param coords:
* 2-tuple of x and y position OR
* 3-tuple of x, y, and z ... | python | def addSpectrum(self, mzs, intensities, coords, userParams=[]):
"""
Add a mass spectrum to the file.
:param mz:
mz array
:param intensities:
intensity array
:param coords:
* 2-tuple of x and y position OR
* 3-tuple of x, y, and z ... | Add a mass spectrum to the file.
:param mz:
mz array
:param intensities:
intensity array
:param coords:
* 2-tuple of x and y position OR
* 3-tuple of x, y, and z position
note some applications want coords to be 1-indexed | https://github.com/alexandrovteam/pyimzML/blob/baae0bea7279f9439113d6b2f61be528c0462b3f/pyimzml/ImzMLWriter.py#L271-L312 |
alexandrovteam/pyimzML | pyimzml/ImzMLWriter.py | ImzMLWriter.finish | def finish(self):
'''alias of close()'''
self.ibd.close()
self._write_xml()
self.xml.close() | python | def finish(self):
'''alias of close()'''
self.ibd.close()
self._write_xml()
self.xml.close() | alias of close() | https://github.com/alexandrovteam/pyimzML/blob/baae0bea7279f9439113d6b2f61be528c0462b3f/pyimzml/ImzMLWriter.py#L321-L325 |
michaeljoseph/changes | changes/__init__.py | initialise | def initialise():
"""
Detects, prompts and initialises the project.
Stores project and tool configuration in the `changes` module.
"""
global settings, project_settings
# Global changes settings
settings = Changes.load()
# Project specific settings
project_settings = Project.load(... | python | def initialise():
"""
Detects, prompts and initialises the project.
Stores project and tool configuration in the `changes` module.
"""
global settings, project_settings
# Global changes settings
settings = Changes.load()
# Project specific settings
project_settings = Project.load(... | Detects, prompts and initialises the project.
Stores project and tool configuration in the `changes` module. | https://github.com/michaeljoseph/changes/blob/a8beb409671c58cdf28ee913bad0a5c7d5374ade/changes/__init__.py#L21-L33 |
michaeljoseph/changes | changes/packaging.py | build_distributions | def build_distributions(context):
"""Builds package distributions"""
rmtree('dist', ignore_errors=True)
build_package_command = 'python setup.py clean sdist bdist_wheel'
result = shell.dry_run(build_package_command, context.dry_run)
packages = Path('dist').files() if not context.dry_run else "nothi... | python | def build_distributions(context):
"""Builds package distributions"""
rmtree('dist', ignore_errors=True)
build_package_command = 'python setup.py clean sdist bdist_wheel'
result = shell.dry_run(build_package_command, context.dry_run)
packages = Path('dist').files() if not context.dry_run else "nothi... | Builds package distributions | https://github.com/michaeljoseph/changes/blob/a8beb409671c58cdf28ee913bad0a5c7d5374ade/changes/packaging.py#L10-L22 |
michaeljoseph/changes | changes/packaging.py | install_package | def install_package(context):
"""Attempts to install the sdist and wheel."""
if not context.dry_run and build_distributions(context):
with util.mktmpdir() as tmp_dir:
venv.create_venv(tmp_dir=tmp_dir)
for distribution in Path('dist').files():
try:
... | python | def install_package(context):
"""Attempts to install the sdist and wheel."""
if not context.dry_run and build_distributions(context):
with util.mktmpdir() as tmp_dir:
venv.create_venv(tmp_dir=tmp_dir)
for distribution in Path('dist').files():
try:
... | Attempts to install the sdist and wheel. | https://github.com/michaeljoseph/changes/blob/a8beb409671c58cdf28ee913bad0a5c7d5374ade/changes/packaging.py#L26-L45 |
michaeljoseph/changes | changes/packaging.py | upload_package | def upload_package(context):
"""Uploads your project packages to pypi with twine."""
if not context.dry_run and build_distributions(context):
upload_args = 'twine upload '
upload_args += ' '.join(Path('dist').files())
if context.pypi:
upload_args += ' -r %s' % context.pypi
... | python | def upload_package(context):
"""Uploads your project packages to pypi with twine."""
if not context.dry_run and build_distributions(context):
upload_args = 'twine upload '
upload_args += ' '.join(Path('dist').files())
if context.pypi:
upload_args += ' -r %s' % context.pypi
... | Uploads your project packages to pypi with twine. | https://github.com/michaeljoseph/changes/blob/a8beb409671c58cdf28ee913bad0a5c7d5374ade/changes/packaging.py#L49-L66 |
michaeljoseph/changes | changes/packaging.py | install_from_pypi | def install_from_pypi(context):
"""Attempts to install your package from pypi."""
tmp_dir = venv.create_venv()
install_cmd = '%s/bin/pip install %s' % (tmp_dir, context.module_name)
package_index = 'pypi'
if context.pypi:
install_cmd += '-i %s' % context.pypi
package_index = contex... | python | def install_from_pypi(context):
"""Attempts to install your package from pypi."""
tmp_dir = venv.create_venv()
install_cmd = '%s/bin/pip install %s' % (tmp_dir, context.module_name)
package_index = 'pypi'
if context.pypi:
install_cmd += '-i %s' % context.pypi
package_index = contex... | Attempts to install your package from pypi. | https://github.com/michaeljoseph/changes/blob/a8beb409671c58cdf28ee913bad0a5c7d5374ade/changes/packaging.py#L69-L94 |
michaeljoseph/changes | changes/probe.py | report_and_raise | def report_and_raise(probe_name, probe_result, failure_msg):
"""Logs the probe result and raises on failure"""
log.info('%s? %s' % (probe_name, probe_result))
if not probe_result:
raise exceptions.ProbeException(failure_msg)
else:
return True | python | def report_and_raise(probe_name, probe_result, failure_msg):
"""Logs the probe result and raises on failure"""
log.info('%s? %s' % (probe_name, probe_result))
if not probe_result:
raise exceptions.ProbeException(failure_msg)
else:
return True | Logs the probe result and raises on failure | https://github.com/michaeljoseph/changes/blob/a8beb409671c58cdf28ee913bad0a5c7d5374ade/changes/probe.py#L30-L36 |
michaeljoseph/changes | changes/probe.py | has_metadata | def has_metadata(python_module):
"""`<module_name>/__init__.py` with `__version__` and `__url__`"""
init_path = '{}/__init__.py'.format(python_module)
has_metadata = (
exists(init_path)
and attributes.has_attribute(python_module, '__version__')
and attributes.has_attribute(python_mod... | python | def has_metadata(python_module):
"""`<module_name>/__init__.py` with `__version__` and `__url__`"""
init_path = '{}/__init__.py'.format(python_module)
has_metadata = (
exists(init_path)
and attributes.has_attribute(python_module, '__version__')
and attributes.has_attribute(python_mod... | `<module_name>/__init__.py` with `__version__` and `__url__` | https://github.com/michaeljoseph/changes/blob/a8beb409671c58cdf28ee913bad0a5c7d5374ade/changes/probe.py#L79-L91 |
michaeljoseph/changes | changes/probe.py | probe_project | def probe_project(python_module):
"""
Check if the project meets `changes` requirements.
Complain and exit otherwise.
"""
log.info('Checking project for changes requirements.')
return (
has_tools()
and has_setup()
and has_metadata(python_module)
and has_test_runne... | python | def probe_project(python_module):
"""
Check if the project meets `changes` requirements.
Complain and exit otherwise.
"""
log.info('Checking project for changes requirements.')
return (
has_tools()
and has_setup()
and has_metadata(python_module)
and has_test_runne... | Check if the project meets `changes` requirements.
Complain and exit otherwise. | https://github.com/michaeljoseph/changes/blob/a8beb409671c58cdf28ee913bad0a5c7d5374ade/changes/probe.py#L98-L111 |
michaeljoseph/changes | changes/flow.py | publish | def publish(context):
"""Publishes the project"""
commit_version_change(context)
if context.github:
# github token
project_settings = project_config(context.module_name)
if not project_settings['gh_token']:
click.echo('You need a GitHub token for changes to create a rele... | python | def publish(context):
"""Publishes the project"""
commit_version_change(context)
if context.github:
# github token
project_settings = project_config(context.module_name)
if not project_settings['gh_token']:
click.echo('You need a GitHub token for changes to create a rele... | Publishes the project | https://github.com/michaeljoseph/changes/blob/a8beb409671c58cdf28ee913bad0a5c7d5374ade/changes/flow.py#L25-L60 |
michaeljoseph/changes | changes/flow.py | perform_release | def perform_release(context):
"""Executes the release process."""
try:
run_tests()
if not context.skip_changelog:
generate_changelog(context)
increment_version(context)
build_distributions(context)
install_package(context)
upload_package(context)
... | python | def perform_release(context):
"""Executes the release process."""
try:
run_tests()
if not context.skip_changelog:
generate_changelog(context)
increment_version(context)
build_distributions(context)
install_package(context)
upload_package(context)
... | Executes the release process. | https://github.com/michaeljoseph/changes/blob/a8beb409671c58cdf28ee913bad0a5c7d5374ade/changes/flow.py#L63-L83 |
michaeljoseph/changes | changes/attributes.py | extract_attribute | def extract_attribute(module_name, attribute_name):
"""Extract metatdata property from a module"""
with open('%s/__init__.py' % module_name) as input_file:
for line in input_file:
if line.startswith(attribute_name):
return ast.literal_eval(line.split('=')[1].strip()) | python | def extract_attribute(module_name, attribute_name):
"""Extract metatdata property from a module"""
with open('%s/__init__.py' % module_name) as input_file:
for line in input_file:
if line.startswith(attribute_name):
return ast.literal_eval(line.split('=')[1].strip()) | Extract metatdata property from a module | https://github.com/michaeljoseph/changes/blob/a8beb409671c58cdf28ee913bad0a5c7d5374ade/changes/attributes.py#L12-L17 |
michaeljoseph/changes | changes/attributes.py | replace_attribute | def replace_attribute(module_name, attribute_name, new_value, dry_run=True):
"""Update a metadata attribute"""
init_file = '%s/__init__.py' % module_name
_, tmp_file = tempfile.mkstemp()
with open(init_file) as input_file:
with open(tmp_file, 'w') as output_file:
for line in input_f... | python | def replace_attribute(module_name, attribute_name, new_value, dry_run=True):
"""Update a metadata attribute"""
init_file = '%s/__init__.py' % module_name
_, tmp_file = tempfile.mkstemp()
with open(init_file) as input_file:
with open(tmp_file, 'w') as output_file:
for line in input_f... | Update a metadata attribute | https://github.com/michaeljoseph/changes/blob/a8beb409671c58cdf28ee913bad0a5c7d5374ade/changes/attributes.py#L20-L36 |
michaeljoseph/changes | changes/attributes.py | has_attribute | def has_attribute(module_name, attribute_name):
"""Is this attribute present?"""
init_file = '%s/__init__.py' % module_name
return any(
[attribute_name in init_line for init_line in open(init_file).readlines()]
) | python | def has_attribute(module_name, attribute_name):
"""Is this attribute present?"""
init_file = '%s/__init__.py' % module_name
return any(
[attribute_name in init_line for init_line in open(init_file).readlines()]
) | Is this attribute present? | https://github.com/michaeljoseph/changes/blob/a8beb409671c58cdf28ee913bad0a5c7d5374ade/changes/attributes.py#L39-L44 |
michaeljoseph/changes | changes/prompt.py | choose_labels | def choose_labels(alternatives):
"""
Prompt the user select several labels from the provided alternatives.
At least one label must be selected.
:param list alternatives: Sequence of options that are available to select from
:return: Several selected labels
"""
if not alternatives:
... | python | def choose_labels(alternatives):
"""
Prompt the user select several labels from the provided alternatives.
At least one label must be selected.
:param list alternatives: Sequence of options that are available to select from
:return: Several selected labels
"""
if not alternatives:
... | Prompt the user select several labels from the provided alternatives.
At least one label must be selected.
:param list alternatives: Sequence of options that are available to select from
:return: Several selected labels | https://github.com/michaeljoseph/changes/blob/a8beb409671c58cdf28ee913bad0a5c7d5374ade/changes/prompt.py#L8-L63 |
michaeljoseph/changes | changes/cli.py | work_in | def work_in(dirname=None):
"""
Context manager version of os.chdir. When exited, returns to the working
directory prior to entering.
"""
curdir = os.getcwd()
try:
if dirname is not None:
os.chdir(dirname)
requests_cache.configure(expire_after=60 * 10 * 10)
ch... | python | def work_in(dirname=None):
"""
Context manager version of os.chdir. When exited, returns to the working
directory prior to entering.
"""
curdir = os.getcwd()
try:
if dirname is not None:
os.chdir(dirname)
requests_cache.configure(expire_after=60 * 10 * 10)
ch... | Context manager version of os.chdir. When exited, returns to the working
directory prior to entering. | https://github.com/michaeljoseph/changes/blob/a8beb409671c58cdf28ee913bad0a5c7d5374ade/changes/cli.py#L20-L36 |
michaeljoseph/changes | changes/cli.py | stage | def stage(draft, discard, repo_directory, release_name, release_description):
"""
Stages a release
"""
with work_in(repo_directory):
if discard:
stage_command.discard(release_name, release_description)
else:
stage_command.stage(draft, release_name, release_descrip... | python | def stage(draft, discard, repo_directory, release_name, release_description):
"""
Stages a release
"""
with work_in(repo_directory):
if discard:
stage_command.discard(release_name, release_description)
else:
stage_command.stage(draft, release_name, release_descrip... | Stages a release | https://github.com/michaeljoseph/changes/blob/a8beb409671c58cdf28ee913bad0a5c7d5374ade/changes/cli.py#L85-L93 |
michaeljoseph/changes | changes/changelog.py | generate_changelog | def generate_changelog(context):
"""Generates an automatic changelog from your commit messages."""
changelog_content = [
'\n## [%s](%s/compare/%s...%s)\n\n'
% (
context.new_version,
context.repo_url,
context.current_version,
context.new_version,
... | python | def generate_changelog(context):
"""Generates an automatic changelog from your commit messages."""
changelog_content = [
'\n## [%s](%s/compare/%s...%s)\n\n'
% (
context.new_version,
context.repo_url,
context.current_version,
context.new_version,
... | Generates an automatic changelog from your commit messages. | https://github.com/michaeljoseph/changes/blob/a8beb409671c58cdf28ee913bad0a5c7d5374ade/changes/changelog.py#L48-L83 |
michaeljoseph/changes | changes/util.py | extract | def extract(dictionary, keys):
"""
Extract only the specified keys from a dict
:param dictionary: source dictionary
:param keys: list of keys to extract
:return dict: extracted dictionary
"""
return dict((k, dictionary[k]) for k in keys if k in dictionary) | python | def extract(dictionary, keys):
"""
Extract only the specified keys from a dict
:param dictionary: source dictionary
:param keys: list of keys to extract
:return dict: extracted dictionary
"""
return dict((k, dictionary[k]) for k in keys if k in dictionary) | Extract only the specified keys from a dict
:param dictionary: source dictionary
:param keys: list of keys to extract
:return dict: extracted dictionary | https://github.com/michaeljoseph/changes/blob/a8beb409671c58cdf28ee913bad0a5c7d5374ade/changes/util.py#L6-L14 |
michaeljoseph/changes | changes/util.py | extract_arguments | def extract_arguments(arguments, long_keys, key_prefix='--'):
"""
:param arguments: dict of command line arguments
"""
long_arguments = extract(arguments, long_keys)
return dict(
[(key.replace(key_prefix, ''), value) for key, value in long_arguments.items()]
) | python | def extract_arguments(arguments, long_keys, key_prefix='--'):
"""
:param arguments: dict of command line arguments
"""
long_arguments = extract(arguments, long_keys)
return dict(
[(key.replace(key_prefix, ''), value) for key, value in long_arguments.items()]
) | :param arguments: dict of command line arguments | https://github.com/michaeljoseph/changes/blob/a8beb409671c58cdf28ee913bad0a5c7d5374ade/changes/util.py#L17-L25 |
michaeljoseph/changes | changes/vcs.py | tag_and_push | def tag_and_push(context):
"""Tags your git repo with the new version number"""
tag_option = '--annotate'
if probe.has_signing_key(context):
tag_option = '--sign'
shell.dry_run(
TAG_TEMPLATE % (tag_option, context.new_version, context.new_version),
context.dry_run,
)
sh... | python | def tag_and_push(context):
"""Tags your git repo with the new version number"""
tag_option = '--annotate'
if probe.has_signing_key(context):
tag_option = '--sign'
shell.dry_run(
TAG_TEMPLATE % (tag_option, context.new_version, context.new_version),
context.dry_run,
)
sh... | Tags your git repo with the new version number | https://github.com/michaeljoseph/changes/blob/a8beb409671c58cdf28ee913bad0a5c7d5374ade/changes/vcs.py#L30-L41 |
michaeljoseph/changes | changes/shell.py | dry_run | def dry_run(command, dry_run):
"""Executes a shell command unless the dry run option is set"""
if not dry_run:
cmd_parts = command.split(' ')
# http://plumbum.readthedocs.org/en/latest/local_commands.html#run-and-popen
return local[cmd_parts[0]](cmd_parts[1:])
else:
log.info(... | python | def dry_run(command, dry_run):
"""Executes a shell command unless the dry run option is set"""
if not dry_run:
cmd_parts = command.split(' ')
# http://plumbum.readthedocs.org/en/latest/local_commands.html#run-and-popen
return local[cmd_parts[0]](cmd_parts[1:])
else:
log.info(... | Executes a shell command unless the dry run option is set | https://github.com/michaeljoseph/changes/blob/a8beb409671c58cdf28ee913bad0a5c7d5374ade/changes/shell.py#L8-L16 |
michaeljoseph/changes | changes/config.py | project_config | def project_config():
"""Deprecated"""
project_name = curdir
config_path = Path(join(project_name, PROJECT_CONFIG_FILE))
if not exists(config_path):
store_settings(DEFAULTS.copy())
return DEFAULTS
return toml.load(io.open(config_path)) or {} | python | def project_config():
"""Deprecated"""
project_name = curdir
config_path = Path(join(project_name, PROJECT_CONFIG_FILE))
if not exists(config_path):
store_settings(DEFAULTS.copy())
return DEFAULTS
return toml.load(io.open(config_path)) or {} | Deprecated | https://github.com/michaeljoseph/changes/blob/a8beb409671c58cdf28ee913bad0a5c7d5374ade/changes/config.py#L195-L205 |
michaeljoseph/changes | changes/version.py | increment | def increment(version, major=False, minor=False, patch=True):
"""
Increment a semantic version
:param version: str of the version to increment
:param major: bool specifying major level version increment
:param minor: bool specifying minor level version increment
:param patch: bool specifying pa... | python | def increment(version, major=False, minor=False, patch=True):
"""
Increment a semantic version
:param version: str of the version to increment
:param major: bool specifying major level version increment
:param minor: bool specifying minor level version increment
:param patch: bool specifying pa... | Increment a semantic version
:param version: str of the version to increment
:param major: bool specifying major level version increment
:param minor: bool specifying minor level version increment
:param patch: bool specifying patch level version increment
:return: str of the incremented version | https://github.com/michaeljoseph/changes/blob/a8beb409671c58cdf28ee913bad0a5c7d5374ade/changes/version.py#L35-L56 |
michaeljoseph/changes | changes/version.py | increment_version | def increment_version(context):
"""Increments the __version__ attribute of your module's __init__."""
attributes.replace_attribute(
context.module_name, '__version__', context.new_version, dry_run=context.dry_run
)
log.info(
'Bumped version from %s to %s' % (context.current_version, con... | python | def increment_version(context):
"""Increments the __version__ attribute of your module's __init__."""
attributes.replace_attribute(
context.module_name, '__version__', context.new_version, dry_run=context.dry_run
)
log.info(
'Bumped version from %s to %s' % (context.current_version, con... | Increments the __version__ attribute of your module's __init__. | https://github.com/michaeljoseph/changes/blob/a8beb409671c58cdf28ee913bad0a5c7d5374ade/changes/version.py#L59-L67 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.