text stringlengths 81 112k |
|---|
Log Level: :attr:COMPLETE
@flag_message: #str flags the message with the given text
using :func:flag
@padding: #str 'top', 'bottom' or 'all', adds a new line to the
specified area with :func:padd
@color: #str colorizes @flag_message using :func:colori... |
Log Level: :attr:NOTICE
@flag_message: #str flags the message with the given text
using :func:flag
@padding: #str 'top', 'bottom' or 'all', adds a new line to the
specified area with :func:padd
@color: #str colorizes @flag_message using :func:colorize... |
Log Level: :attr:WARNING
@flag_message: #str flags the message with the given text
using :func:flag
@padding: #str 'top', 'bottom' or 'all', adds a new line to the
specified area with :func:padd
@color: #str colorizes @flag_message using :func:coloriz... |
Log Level: :attr:ERROR
@flag_message: #str flags the message with the given text
using :func:flag
@padding: #str 'top', 'bottom' or 'all', adds a new line to the
specified area with :func:padd
@color: #str colorizes @flag_message using :func:colorize
... |
Log Level: :attr:TIMING
@flag_message: time-like #float
@padding: #str 'top', 'bottom' or 'all', adds a new line to the
specified area with :func:padd
@force: #bool whether or not to force the message to log in spite
of the assigned log level
... |
Log Level: :attr:COUNT
@flag_message: time-like #float
@padding: #str 'top', 'bottom' or 'all', adds a new line to the
specified area with :func:padd
@force: #bool whether or not to force the message to log in spite
of the assigned log level
... |
Formats a message with :class:Look
def format_message(self, message):
""" Formats a message with :class:Look """
look = Look(message)
return look.pretty(display=False) |
Formats several messages with :class:Look, encodes them
with :func:vital.tools.encoding.stdout_encode
def format_messages(self, messages):
""" Formats several messages with :class:Look, encodes them
with :func:vital.tools.encoding.stdout_encode """
mess = ""
for message ... |
Outputs the message to the terminal
def _print_message(self, flag_message=None, color=None, padding=None,
reverse=False):
""" Outputs the message to the terminal """
if flag_message:
flag_message = stdout_encode(flag(flag_message,
... |
Builds the progress bar
def format_bar(self):
""" Builds the progress bar """
pct = floor(round(self.progress/self.size, 2)*100)
pr = floor(pct*.33)
bar = "".join(
["‒" for x in range(pr)] + ["↦"] +
[" " for o in range(self._barsize-pr-1)])
subprogress = ... |
Resets the progress bar and clears it from the terminal
def finish(self):
""" Resets the progress bar and clears it from the terminal """
pct = floor(round(self.progress/self.size, 2)*100)
pr = floor(pct*.33)
bar = "".join([" " for x in range(pr-1)] + ["↦"])
subprogress = self.f... |
Updates the progress bar with @progress if given, otherwise
increments :prop:progress by 1. Also prints the progress bar.
@progress: #int to assign to :prop:progress
def update(self, progress=0):
""" Updates the progress bar with @progress if given, otherwise
increments :pr... |
Starts the timer
def start(self):
""" Starts the timer """
if not self._start:
self._first_start = time.perf_counter()
self._start = self._first_start
else:
self._start = time.perf_counter() |
Stops the timer, adds it as an interval to :prop:intervals
@precision: #int number of decimal places to round to
-> #str formatted interval time
def stop(self, precision=0):
""" Stops the timer, adds it as an interval to :prop:intervals
@precision: #int number of decimal pl... |
Pretty-formats a given time in a readable manner
@sec: #int or #float seconds
-> #str formatted time
def format_time(self, sec):
""" Pretty-formats a given time in a readable manner
@sec: #int or #float seconds
-> #str formatted time
"""
# µsec
... |
Pretty-formats given bytes size in a readable manner
@bytes: #int or #float bytes
-> #str formatted bytes
def format_size(self, bytes):
""" Pretty-formats given bytes size in a readable manner
@bytes: #int or #float bytes
-> #str formatted bytes
"""
... |
Adds an interval to :prop:intervals
-> #str formatted time
def add_interval(self, precision=0):
""" Adds an interval to :prop:intervals
-> #str formatted time
"""
precision = precision or self.precision
interval = round((self._stop - self._start), precision)
... |
Measures the execution time of :prop:_callable for @intervals
@intervals: #int number of intervals to measure the execution time
of the function for
@*args: arguments to pass to the callable being timed
@**kwargs: arguments to pass to the callable being timed
... |
-> #float :func:numpy.mean of the timing intervals
def mean(self):
""" -> #float :func:numpy.mean of the timing intervals """
return round(np.mean(self.array), self.precision)\
if len(self.array) else None |
-> #float :func:numpy.median of the timing intervals
def median(self):
""" -> #float :func:numpy.median of the timing intervals """
return round(float(np.median(self.array)), self.precision)\
if len(self.array) else None |
-> #float :func:numpy.max of the timing intervals
def max(self):
""" -> #float :func:numpy.max of the timing intervals """
return round(np.max(self.array), self.precision)\
if len(self.array) else None |
-> #float :func:numpy.min of the timing intervals
def min(self):
""" -> #float :func:numpy.min of the timing intervals """
return round(np.min(self.array), self.precision)\
if len(self.array) else None |
-> #float :func:numpy.std of the timing intervals
def stdev(self):
""" -> #float :func:numpy.std of the timing intervals """
return round(np.std(self.array), self.precision)\
if len(self.array) else None |
-> :class:collections.OrderedDict of stats about the time intervals
def stats(self):
""" -> :class:collections.OrderedDict of stats about the time intervals
"""
return OrderedDict([
("Intervals", len(self.array)),
("Mean", self.format_time(self.mean or 0)),
(... |
Calculates and colorizes the percent difference between @best
and @other
def _pct_diff(self, best, other):
""" Calculates and colorizes the percent difference between @best
and @other
"""
return colorize("{}%".format(
round(((best-other)/best)*100, 2)).rjust(... |
Prints and formats the results of the timing
@_print: #bool whether or not to print out to terminal
@verbose: #bool True if you'd like to print the individual timing
results in additions to the comparison results
def info(self, verbose=None):
""" Prints and formats the r... |
Loads Finnish monetary institution codes and BICs in CSV format.
Map which is based on 3 digits as in FIXX<3 digits>.
Can be used to map Finnish IBAN number to bank information.
Format: dict('<3 digits': (BIC, name), ...)
:param filename: CSV file name of the BIC definitions. Columns: National ID, BIC C... |
An LRU cache for asyncio coroutines in Python 3.5
..
@async_lru(1024)
async def slow_coroutine(*args, **kwargs):
return await some_other_slow_coroutine()
..
def async_lru(size=100):
""" An LRU cache for asyncio coroutines in Python 3.5
..
... |
Iterates (value,label) list and returns label matching the choice
:param choices: [(choice1, label1), (choice2, label2), ...]
:param value: Value to find
:return: label or None
def choices_label(choices: tuple, value) -> str:
"""
Iterates (value,label) list and returns label matching the choice
... |
Print sys message to stdout.
System messages should inform about the flow of the script. This should
be a major milestones during the build.
def info(msg, *args, **kw):
# type: (str, *Any, **Any) -> None
""" Print sys message to stdout.
System messages should inform about the flow of the script. ... |
Per step status messages
Use this locally in a command definition to highlight more important
information.
def err(msg, *args, **kw):
# type: (str, *Any, **Any) -> None
""" Per step status messages
Use this locally in a command definition to highlight more important
information.
"""
i... |
Determines whether the @string pattern is username-like
@string: #str being tested
@minlen: minimum required username length
@maxlen: maximum username length
-> #bool
def is_username(string, minlen=1, maxlen=15):
""" Determines whether the @string pattern is username-like
@... |
Converts @val to a string if it is a big integer (|>2**53-1|)
@val: #int or #float
-> #str if @val is a big integer, otherwise @val
def bigint_to_string(val):
""" Converts @val to a string if it is a big integer (|>2**53-1|)
@val: #int or #float
-> #str if @val is a big integer,... |
Recursively converts big integers (|>2**53-1|) to strings
@obj: Any python object
-> @obj, with any big integers converted to #str objects
def rbigint_to_string(obj):
""" Recursively converts big integers (|>2**53-1|) to strings
@obj: Any python object
-> @obj, with any big inte... |
Removes all blank lines in @string
-> #str without blank lines
def remove_blank_lines(string):
""" Removes all blank lines in @string
-> #str without blank lines
"""
return "\n".join(line
for line in string.split("\n")
if len(line.strip())) |
Run django ./manage.py command manually.
This function eliminates the need for having ``manage.py`` (reduces file
clutter).
def _manage_cmd(cmd, settings=None):
# type: () -> None
""" Run django ./manage.py command manually.
This function eliminates the need for having ``manage.py`` (reduces file... |
Return the BranchDetails for the current branch.
Return:
BranchDetails: The details of the current branch.
def current_branch():
# type: () -> BranchDetails
""" Return the BranchDetails for the current branch.
Return:
BranchDetails: The details of the current branch.
"""
cmd =... |
Get the name of the branches that this commit belongs to.
def commit_branches(sha1):
# type: (str) -> List[str]
""" Get the name of the branches that this commit belongs to. """
cmd = 'git branch --contains {}'.format(sha1)
return shell.run(
cmd,
capture=True,
never_pretend=True... |
Try to guess the base branch for the current branch.
Do not trust this guess. git makes it pretty much impossible to guess
the base branch reliably so this function implements few heuristics that
will work on most common use cases but anything a bit crazy will probably
trip this function.
Returns:... |
Return the author of the given commit.
Args:
sha1 (str):
The sha1 of the commit to query. If not given, it will return the
sha1 for the current commit.
Returns:
Author: A named tuple ``(name, email)`` with the commit author details.
def commit_author(sha1=''):
# typ... |
Return a list of unstaged files in the project repository.
Returns:
list[str]: The list of files not tracked by project git repo.
def unstaged():
# type: () -> List[str]
""" Return a list of unstaged files in the project repository.
Returns:
list[str]: The list of files not tracked by... |
Return a list of patterns in the project .gitignore
Returns:
list[str]: List of patterns set to be ignored by git.
def ignore():
# type: () -> List[str]
""" Return a list of patterns in the project .gitignore
Returns:
list[str]: List of patterns set to be ignored by git.
"""
... |
Return a list of branches in the current repo.
Returns:
list[str]: A list of branches in the current repo.
def branches():
# type: () -> List[str]
""" Return a list of branches in the current repo.
Returns:
list[str]: A list of branches in the current repo.
"""
out = shell.run... |
Tag the current commit.
Args:
name (str):
The tag name.
message (str):
The tag message. Same as ``-m`` parameter in ``git tag``.
author (Author):
The commit author. Will default to the author of the commit.
pretend (bool):
If set to **... |
Return the current git configuration.
Returns:
dict[str, Any]: The current git config taken from ``git config --list``.
def config():
# type: () -> dict[str, Any]
""" Return the current git configuration.
Returns:
dict[str, Any]: The current git config taken from ``git config --list``... |
Returns all tags in the repo.
Returns:
list[str]: List of all tags in the repo, sorted as versions.
All tags returned by this function will be parsed as if the contained
versions (using ``v:refname`` sorting).
def tags():
# type: () -> List[str]
""" Returns all tags in the repo.
Retu... |
Verify if the given branch exists.
Args:
branch_name (str):
The name of the branch to check.
Returns:
bool: **True** if a branch with name *branch_name* exits, **False**
otherwise.
def verify_branch(branch_name):
# type: (str) -> bool
""" Verify if the given branch... |
Return branches protected by deletion.
By default those are master and devel branches as configured in pelconf.
Returns:
list[str]: Names of important branches that should not be deleted.
def protected_branches():
# type: () -> list[str]
""" Return branches protected by deletion.
By defa... |
List of all branches this commit is a part of.
def branches(self):
# type: () -> List[str]
""" List of all branches this commit is a part of. """
if self._branches is None:
cmd = 'git branch --contains {}'.format(self.sha1)
out = shell.run(
cmd,
... |
Parents of the this commit.
def parents(self):
# type: () -> List[CommitDetails]
""" Parents of the this commit. """
if self._parents is None:
self._parents = [CommitDetails.get(x) for x in self.parents_sha1]
return self._parents |
Return this commits number.
This is the same as the total number of commits in history up until
this commit.
This value can be useful in some CI scenarios as it allows to track
progress on any given branch (although there can be two commits with the
same number existing on diff... |
Return details about a given commit.
Args:
sha1 (str):
The sha1 of the commit to query. If not given, it will return
the details for the latest commit.
Returns:
CommitDetails: Commit details. You can use the instance of the
class to q... |
Sample usage for this python module
This main method simply illustrates sample usage for this python
module.
:return: None
def main():
"""Sample usage for this python module
This main method simply illustrates sample usage for this python
module.
:return: None
"""
log = logging.... |
Sets the log level for cons3rt assets
This method sets the logging level for cons3rt assets using
pycons3rt. The loglevel is read in from a deployment property
called loglevel and set appropriately.
:type log_level: str
:return: True if log level was set, False otherwise.
def ... |
Searches for a single document in the given index on the 'name' field .
Performs a case-insensitive search by utilizing Elasticsearch's `match_phrase` query.
Args:
index: `str`. The name of an Elasticsearch index (i.e. biosamples).
name: `str`. The value of a document's name... |
Finds an in @obj via a period-delimited string @name.
@obj: (#object)
@name: (#str) |.|-separated keys to search @obj in
..
obj.deep.attr = 'deep value'
getattr_in(obj, 'obj.deep.attr')
..
|'deep value'|
def getattr_in(obj, name):
""" Finds an in @obj... |
Imports a module, class or method from string and unwraps it
if wrapped by functools
@name: (#str) name of the python object
-> imported object
def import_from(name):
""" Imports a module, class or method from string and unwraps it
if wrapped by functools
@name: (#str) na... |
Gets the actual object from a decorated or wrapped function
@obj: (#object) the object to unwrap
def unwrap_obj(obj):
""" Gets the actual object from a decorated or wrapped function
@obj: (#object) the object to unwrap
"""
try:
obj = obj.fget
except (AttributeError, TypeError):
... |
Modality can be appended to the file name (such as 'bold') or use in the
folder (such as "func"). You should always use the specific modality ('bold').
This function converts it to the folder name.
def add_modality(output_path, modality):
"""Modality can be appended to the file name (such as 'bold') or use... |
Load configuration from file.
This will search the directory structure upwards to find the project root
(directory containing ``pelconf.py`` file). Once found it will import the
config file which should initialize all the configuration (using
`peltak.core.conf.init()` function).
You can also have ... |
Load a YAML configuration.
This will not update the configuration but replace it entirely.
Args:
conf_file (str):
Path to the YAML config. This function will not check the file name
or extension and will just crash if the given file does not exist or
is not a valid ... |
Import configuration from a python file.
This will just import the file into python. Sky is the limit. The file
has to deal with the configuration all by itself (i.e. call conf.init()).
You will also need to add your src directory to sys.paths if it's not the
current working directory. This is done aut... |
Load template from file.
The templates are part of the package and must be included as
``package_data`` in project ``setup.py``.
Args:
filename (str):
The template path. Relative to `peltak` package directory.
Returns:
str: The content of the chosen template.
def load_tem... |
Return absolute path to the repo dir (root project directory).
Args:
path (str):
The path relative to the project root (pelconf.yaml).
Returns:
str: The given path converted to an absolute path.
def proj_path(*path_parts):
# type: (str) -> str
""" Return absolute path to t... |
Return an absolute path to the given project relative path.
:param path:
Project relative path that will be converted to the system wide absolute
path.
:return:
Absolute path.
def within_proj_dir(path='.'):
# type: (Optional[str]) -> str
""" Return an absolute path to the given... |
Get config value with the given name and optional default.
Args:
name (str):
The name of the config value.
*default (Any):
If given and the key doesn't not exist, this will be returned
instead. If it's not given and the config value does not exist,
At... |
Get config value as path relative to the project directory.
This allows easily defining the project configuration within the fabfile
as always relative to that fabfile.
Args:
name (str):
The name of the config value containing the path.
*default (Any):
If given and ... |
Find the project path by going up the file tree.
This will look in the current directory and upwards for the pelconf file
(.yaml or .py)
def _find_proj_root():
# type: () -> Optional[str]
""" Find the project path by going up the file tree.
This will look in the current directory and upwards for ... |
Метод должен райзить ошибки
:param verified_entity: сущность
:param verification_key: ключ
:return:
def verify(verified_entity, verification_key):
"""
Метод должен райзить ошибки
:param verified_entity: сущность
:param verification_key: ключ
:return:
... |
Gets XML Element value.
:param el: Element
:param int_tags: List of tags that should be treated as ints
:return: value of the element (int/str)
def _xml_element_value(el: Element, int_tags: list):
"""
Gets XML Element value.
:param el: Element
:param int_tags: List of tags that should be tr... |
Returns tag name and optionally strips namespaces.
:param el: Element
:param strip_namespaces: Strip namespace prefix
:return: str
def _xml_tag_filter(s: str, strip_namespaces: bool) -> str:
"""
Returns tag name and optionally strips namespaces.
:param el: Element
:param strip_namespaces: S... |
Parses XML string to dict. In case of simple elements (no children, no attributes) value is stored as is.
For complex elements value is stored in key '@', attributes '@xxx' and children as sub-dicts.
Optionally strips namespaces.
For example:
<Doc version="1.2">
<A class="x">
... |
Generates XML Element from dict.
Generates complex elements by assuming element attributes are prefixed with '@', and value is stored to plain '@'
in case of complex element. Children are sub-dicts.
For example:
{
'Doc': {
'@version': '1.2',
'A': [{'@clas... |
Property structure which maps within the :func:local() thread
(c)2014, Marcel Hellkamp
def local_property():
""" Property structure which maps within the :func:local() thread
(c)2014, Marcel Hellkamp
"""
ls = local()
def fget(self):
try:
return ls.var
except... |
Module method for downloading from S3
This public module method takes a key and the full path to
the destination directory, assumes that the args have been
validated by the public caller methods, and attempts to
download the specified key to the dest_dir.
:param download_info: (dict) Contains the... |
Finds a list of S3 keys matching the passed regex
Given a regular expression, this method searches the S3 bucket
for matching keys, and returns an array of strings for matched
keys, an empty array if non are found.
:param regex: (str) Regular expression to use is the key search
:param bucket_name:... |
Sample usage for this python module
This main method simply illustrates sample usage for this python
module.
:return: None
def main():
"""Sample usage for this python module
This main method simply illustrates sample usage for this python
module.
:return: None
"""
log = logging.... |
Verify the specified bucket exists
This method validates that the bucket name passed in the S3Util
constructor actually exists.
:return: None
def validate_bucket(self):
"""Verify the specified bucket exists
This method validates that the bucket name passed in the S3Util
... |
Private method for downloading from S3
This private helper method takes a key and the full path to
the destination directory, assumes that the args have been
validated by the public caller methods, and attempts to
download the specified key to the dest_dir.
:param key: (str) S3... |
Downloads a file by key from the specified S3 bucket
This method takes the full 'key' as the arg, and attempts to
download the file to the specified dest_dir as the destination
directory. This method sets the downloaded filename to be the
same as it is on S3.
:param key: (str) ... |
Downloads a file by regex from the specified S3 bucket
This method takes a regular expression as the arg, and attempts
to download the file to the specified dest_dir as the
destination directory. This method sets the downloaded filename
to be the same as it is on S3.
:param reg... |
Attempts to find a single S3 key based on the passed regex
Given a regular expression, this method searches the S3 bucket
for a matching key, and returns it if exactly 1 key matches.
Otherwise, None is returned.
:param regex: (str) Regular expression for an S3 key
:return: (str... |
Finds a list of S3 keys matching the passed regex
Given a regular expression, this method searches the S3 bucket
for matching keys, and returns an array of strings for matched
keys, an empty array if non are found.
:param regex: (str) Regular expression to use is the key search
... |
Uploads a file using the passed S3 key
This method uploads a file specified by the filepath to S3
using the provided S3 key.
:param filepath: (str) Full path to the file to be uploaded
:param key: (str) S3 key to be set for the upload
:return: True if upload is successful, Fals... |
Deletes the specified key
:param key_to_delete:
:return:
def delete_key(self, key_to_delete):
"""Deletes the specified key
:param key_to_delete:
:return:
"""
log = logging.getLogger(self.cls_logger + '.delete_key')
log.info('Attempting to delete key: {... |
Print error and exit if the current branch is not of a given type.
Args:
branch_type (str):
The branch type. This assumes the branch is in the '<type>/<title>`
format.
def assert_branch_type(branch_type):
# type: (str) -> None
""" Print error and exit if the current branch ... |
Print error and exit if *branch_name* is not the current branch.
Args:
branch_name (str):
The supposed name of the current branch.
def assert_on_branch(branch_name):
# type: (str) -> None
""" Print error and exit if *branch_name* is not the current branch.
Args:
branch_nam... |
Delete the given branch.
Args:
branch_name (str):
Name of the branch to delete.
def git_branch_delete(branch_name):
# type: (str) -> None
""" Delete the given branch.
Args:
branch_name (str):
Name of the branch to delete.
"""
if branch_name not in git.p... |
Rename the current branch
Args:
new_name (str):
New name for the current branch.
def git_branch_rename(new_name):
# type: (str) -> None
""" Rename the current branch
Args:
new_name (str):
New name for the current branch.
"""
curr_name = git.current_bran... |
Checkout or create a given branch
Args:
branch_name (str):
The name of the branch to checkout or create.
create (bool):
If set to **True** it will create the branch instead of checking it
out.
def git_checkout(branch_name, create=False):
# type: (str, bool) ... |
Merge *head* into *base*.
Args:
base (str):
The base branch. *head* will be merged into this branch.
head (str):
The branch that will be merged into *base*.
no_ff (bool):
If set to **True** it will force git to create merge commit. If set
to *... |
Return the base branch for the current branch.
This function will first try to guess the base branch and if it can't it
will let the user choose the branch from the list of all local branches.
Returns:
str: The name of the branch the current branch is based on.
def get_base_branch():
# type: ... |
Show the user a menu to pick a branch from the existing ones.
Args:
exclude (list[str]):
List of branch names to exclude from the menu. By default it will
exclude master and develop branches. To show all branches pass an
empty array here.
Returns:
str: The n... |
Call the run method of the decorated class if the current file is the main file
def autorun():
'''
Call the run method of the decorated class if the current file is the main file
'''
def wrapper(cls):
import inspect
if inspect.getmodule(cls).__name__ == "__main__":
cls().ru... |
Removes duplicate elements from given @seq
@seq: a #list or sequence-like object
-> #list
def unique_list(seq):
""" Removes duplicate elements from given @seq
@seq: a #list or sequence-like object
-> #list
"""
seen = set()
seen_add = seen.add
return [x for x in s... |
Flattens a sequence e.g. |[(1, 2), (3, (4, 5))] -> [1, 2, 3, 4, 5]|
@seq: #tuple, #list or :class:UserList
-> yields an iterator
..
l = [(1, 2), (3, 4)]
for x in flatten(l):
print(x)
..
def flatten(*seqs):
""" Flattens a sequence e.g. |[(1,... |
Yields random values from @seq until @seq is empty
def randrange(seq):
""" Yields random values from @seq until @seq is empty """
seq = seq.copy()
choose = rng().choice
remove = seq.remove
for x in range(len(seq)):
y = choose(seq)
remove(y)
yield y |
Return the least-squares solution to a linear matrix equation.
Solves the equation `a x = b` by computing a vector `x` that
minimizes the Euclidean 2-norm `|| b - a x ||^2`. The equation may
be under-, well-, or over- determined (i.e., the number of
linearly independent rows of `a` can be less than, eq... |
Validate the ip_address
:param ip_address: (str) IP address
:return: (bool) True if the ip_address is valid
def validate_ip_address(ip_address):
"""Validate the ip_address
:param ip_address: (str) IP address
:return: (bool) True if the ip_address is valid
"""
# Validate the IP address
... |
Uses the ip addr command to enumerate IP addresses by device
:return: (dict) Containing device: ip_address
def ip_addr():
"""Uses the ip addr command to enumerate IP addresses by device
:return: (dict) Containing device: ip_address
"""
log = logging.getLogger(mod_logger + '.ip_addr')
log.debu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.