Search is not available for this dataset
text stringlengths 75 104k |
|---|
def make_root(self, name): # noqa: D302
r"""
Make a sub-node the root node of the tree.
All nodes not belonging to the sub-tree are deleted
:param name: New root node name
:type name: :ref:`NodeName`
:raises:
* RuntimeError (Argument \`name\` is not valid)
... |
def print_node(self, name): # noqa: D302
r"""
Print node information (parent, children and data).
:param name: Node name
:type name: :ref:`NodeName`
:raises:
* RuntimeError (Argument \`name\` is not valid)
* RuntimeError (Node *[name]* not in tree)
... |
def rename_node(self, name, new_name): # noqa: D302
r"""
Rename a tree node.
It is typical to have a root node name with more than one hierarchy
level after using :py:meth:`ptrie.Trie.make_root`. In this instance the
root node *can* be renamed as long as the new root name has t... |
def search_tree(self, name): # noqa: D302
r"""
Search tree for all nodes with a specific name.
:param name: Node name to search for
:type name: :ref:`NodeName`
:raises: RuntimeError (Argument \`name\` is not valid)
For example:
>>> from __future__ import... |
def find_root(filename, target='bids'):
"""Find base directory (root) for a filename.
Parameters
----------
filename : instance of Path
search the root for this file
target: str
'bids' (the directory containing 'participants.tsv'), 'subject' (the
directory starting with 'sub... |
def find_in_bids(filename, pattern=None, generator=False, upwards=False,
wildcard=True, **kwargs):
"""Find nearest file matching some criteria.
Parameters
----------
filename : instance of Path
search the root for this file
pattern : str
glob string for search crite... |
def define_format(self, plotStyle, plotSize):
#Default sizes for computer
sizing_dict = {}
sizing_dict['figure.figsize'] = (14, 8)
sizing_dict['legend.fontsize'] = 15
sizing_dict['axes.labelsize'] = 20
sizing_dict['axes.titlesize'] = 24
sizing_dict['xtick.labelsi... |
def get_xyz(self, list_of_names=None):
"""Get xyz coordinates for these electrodes
Parameters
----------
list_of_names : list of str
list of electrode names to use
Returns
-------
list of tuples of 3 floats (x, y, z)
list of xyz coordinat... |
def bces(y1,y1err,y2,y2err,cerr):
"""
Does the entire regression calculation for 4 slopes:
OLS(Y|X), OLS(X|Y), bisector, orthogonal.
Fitting form: Y=AX+B.
Usage:
>>> a,b,aerr,berr,covab=bces(x,xerr,y,yerr,cov)
Output:
- a,b : best-fit parameters a,b of the linear regression
- aerr,berr : the standard deviations i... |
def bootstrap(v):
"""
Constructs Monte Carlo simulated data set using the
Bootstrap algorithm.
Usage:
>>> bootstrap(x)
where x is either an array or a list of arrays. If it is a
list, the code returns the corresponding list of bootst... |
def bcesboot(y1,y1err,y2,y2err,cerr,nsim=10000):
"""
Does the BCES with bootstrapping.
Usage:
>>> a,b,aerr,berr,covab=bcesboot(x,xerr,y,yerr,cov,nsim)
:param x,y: data
:param xerr,yerr: measurement errors affecting x and y
:param cov: covariance between the measurement errors (all are arrays)
:param ns... |
def bcesboot_backup(y1,y1err,y2,y2err,cerr,nsim=10000):
"""
Does the BCES with bootstrapping.
Usage:
>>> a,b,aerr,berr,covab=bcesboot(x,xerr,y,yerr,cov,nsim)
:param x,y: data
:param xerr,yerr: measurement errors affecting x and y
:param cov: covariance between the measurement errors (all are arrays)
:param nsim: n... |
def ab(x):
"""
This method is the big bottleneck of the parallel BCES code. That's the
reason why I put these calculations in a separate method, in order to
distribute this among the cores. In the original BCES method, this is
inside the main routine.
Argument:
[y1,y1err,y2,y2err,cerr,nsim]
where nsim is the numb... |
def bcesp(y1,y1err,y2,y2err,cerr,nsim=10000):
"""
Parallel implementation of the BCES with bootstrapping.
Divide the bootstraps equally among the threads (cores) of
the machine. It will automatically detect the number of
cores available.
Usage:
>>> a,b,aerr,berr,covab=bcesp(x,xerr,y,yerr,cov,nsim)
:param x,y: data
... |
def mean(data):
"""Return the sample arithmetic mean of data."""
#: http://stackoverflow.com/a/27758326
n = len(data)
if n < 1:
raise ValueError('mean requires at least one data point')
return sum(data)/n |
def pstdev(data):
"""Calculates the population standard deviation."""
#: http://stackoverflow.com/a/27758326
n = len(data)
if n < 2:
raise ValueError('variance requires at least two data points')
ss = _ss(data)
pvar = ss/n # the population variance
return pvar**0.5 |
def median(lst):
""" Calcuates the median value in a @lst """
#: http://stackoverflow.com/a/24101534
sortedLst = sorted(lst)
lstLen = len(lst)
index = (lstLen - 1) // 2
if (lstLen % 2):
return sortedLst[index]
else:
return (sortedLst[index] + sortedLst[index + 1])/2.0 |
def send_email(recipients: list, subject: str, text: str, html: str='', sender: str='', files: list=[], exceptions: bool=False):
"""
:param recipients: List of recipients; or single email (str); or comma-separated email list (str); or list of name-email pairs (e.g. settings.ADMINS)
:param subject: Subject o... |
def remove_whitespace(s):
""" Unsafely attempts to remove HTML whitespace. This is not an HTML parser
which is why its considered 'unsafe', but it should work for most
implementations. Just use on at your own risk.
@s: #str
-> HTML with whitespace removed, ignoring <pre>, script, t... |
def hashtag_links(uri, s):
""" Turns hashtag-like strings into HTML links
@uri: /uri/ root for the hashtag-like
@s: the #str string you're looking for |#|hashtags in
-> #str HTML link |<a href="/uri/hashtag">hashtag</a>|
"""
for tag, after in hashtag_re.findall(s):
_uri = '... |
def mentions_links(uri, s):
""" Turns mentions-like strings into HTML links,
@uri: /uri/ root for the hashtag-like
@s: the #str string you're looking for |@|mentions in
-> #str HTML link |<a href="/uri/mention">mention</a>|
"""
for username, after in mentions_re.findall(s):
... |
def filter(self, query: Query):
"""Return a new filtered query.
Use the tree to filter the query and return a new query "filtered".
This query can be filtered again using another tree or even a manual
filter.
To manually filter query see :
- https://docs.sqlalch... |
def print_progress_bar(iteration, total, prefix='', suffix='', decimals=1, length=100, fill='█'):
"""
Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : total iterations (Int)
prefix - Optional : p... |
def print_progress_bar_multi_threads(nb_threads, suffix='', decimals=1, length=15,
fill='█'):
"""
Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : total iterations (Int)
... |
def upload(target):
# type: (str) -> None
""" Upload the release to a pypi server.
TODO: Make sure the git directory is clean before allowing a release.
Args:
target (str):
pypi target as defined in ~/.pypirc
"""
log.info("Uploading to pypi server <33>{}".format(target))
... |
def gen_pypirc(username=None, password=None):
# type: (str, str) -> None
""" Generate ~/.pypirc with the given credentials.
Useful for CI builds. Can also get credentials through env variables
``PYPI_USER`` and ``PYPI_PASS``.
Args:
username (str):
pypi username. If not given it... |
def pick_sdf(filename, directory=None):
"""Returns a full path to the chosen SDF file. The supplied file
is not expected to contain a recognised SDF extension, this is added
automatically.
If a file with the extension `.sdf.gz` or `.sdf` is found the path to it
(excluding the extension) is returned.... |
def main():
"""Handles external calling for this module
Execute this python module and provide the args shown below to
external call this module to send Slack messages with attachments!
:return: None
"""
log = logging.getLogger(mod_logger + '.main')
parser = argparse.ArgumentParser(descrip... |
def set_text(self, text):
"""Sets the text attribute of the payload
:param text: (str) Text of the message
:return: None
"""
log = logging.getLogger(self.cls_logger + '.set_text')
if not isinstance(text, basestring):
msg = 'text arg must be a string'
... |
def set_icon(self, icon_url):
"""Sets the icon_url for the message
:param icon_url: (str) Icon URL
:return: None
"""
log = logging.getLogger(self.cls_logger + '.set_icon')
if not isinstance(icon_url, basestring):
msg = 'icon_url arg must be a string'
... |
def add_attachment(self, attachment):
"""Adds an attachment to the SlackMessage payload
This public method adds a slack message to the attachment
list.
:param attachment: SlackAttachment object
:return: None
"""
log = logging.getLogger(self.cls_logger + '.add_at... |
def send(self):
"""Sends the Slack message
This public method sends the Slack message along with any
attachments, then clears the attachments array.
:return: None
:raises: OSError
"""
log = logging.getLogger(self.cls_logger + '.send')
if self.attachment... |
def send_cons3rt_agent_logs(self):
"""Sends a Slack message with an attachment for each cons3rt agent log
:return:
"""
log = logging.getLogger(self.cls_logger + '.send_cons3rt_agent_logs')
log.debug('Searching for log files in directory: {d}'.format(d=self.dep.cons3rt_agent_log... |
def send_text_file(self, text_file):
"""Sends a Slack message with the contents of a text file
:param: test_file: (str) Full path to text file to send
:return: None
:raises: Cons3rtSlackerError
"""
log = logging.getLogger(self.cls_logger + '.send_text_file')
if ... |
def deploy(project, version, promote, quiet):
""" Deploy the app to the target environment.
The target environments can be configured using the ENVIRONMENTS conf
variable. This will also collect all static files and compile translation
messages
"""
from . import logic
logic.deploy(project,... |
def devserver(port, admin_port, clear):
# type: (int, int, bool) -> None
""" Run devserver. """
from . import logic
logic.devserver(port, admin_port, clear) |
def gaussian_filter1d_ppxf(spec, sig):
"""
Convolve a spectrum by a Gaussian with different sigma for every pixel.
If all sigma are the same this routine produces the same output as
scipy.ndimage.gaussian_filter1d, except for the border treatment.
Here the first/last p pixels are filled with zeros.
... |
def call_plugins(self, step):
'''
For each plugins, check if a "step" method exist on it, and call it
Args:
step (str): The method to search and call on each plugin
'''
for plugin in self.plugins:
try:
getattr(plugin, step)()
e... |
def run(self):
"""
Run the application
"""
self.call_plugins("on_run")
if vars(self.arguments).get("version", None):
self.logger.info("{app_name}: {version}".format(app_name=self.app_name, version=self.version))
else:
if self.arguments.command == "... |
def pretend_option(fn):
# type: (FunctionType) -> FunctionType
""" Decorator to add a --pretend option to any click command.
The value won't be passed down to the command, but rather handled in the
callback. The value will be accessible through `peltak.core.context` under
'pretend' if the command n... |
def verbose_option(fn):
""" Decorator to add a --verbose option to any click command.
The value won't be passed down to the command, but rather handled in the
callback. The value will be accessible through `peltak.core.context` under
'verbose' if the command needs it. To get the current value you can d... |
def changelog():
# type: () -> str
""" Print change log since last release. """
# Skip 'v' prefix
versions = [x for x in git.tags() if versioning.is_valid(x[1:])]
cmd = 'git log --format=%H'
if versions:
cmd += ' {}..HEAD'.format(versions[-1])
hashes = shell.run(cmd, capture=True).... |
def extract_changelog_items(text, tags):
# type: (str) -> Dict[str, List[str]]
""" Extract all tagged items from text.
Args:
text (str):
Text to extract the tagged items from. Each tagged item is a
paragraph that starts with a tag. It can also be a text list item.
Retur... |
def _(mcs, cls_name="Object", with_meta=None):
""" Method to generate real metaclass to be used::
mc = ExtensibleType._("MyClass") # note this line
@six.add_metaclass(mc)
class MyClassBase(object):
pass
:param str cls_name: name ... |
def get_class(mcs):
""" Generates new class to gether logic of all available extensions
::
mc = ExtensibleType._("MyClass")
@six.add_metaclass(mc)
class MyClassBase(object):
pass
# get class with all extensions ena... |
def _add_base_class(mcs, cls):
""" Adds new class *cls* to base classes
"""
# Do all magic only if subclass had defined required attributes
if getattr(mcs, '_base_classes_hash', None) is not None:
meta = getattr(cls, 'Meta', None)
_hash = getattr(meta, mcs._hashat... |
def _(mcs, cls_name='Object', with_meta=None, hashattr='_name'):
""" Method to generate real metaclass to be used
::
# Create metaclass *mc*
mc = ExtensibleByHashType._("MyClass", hashattr='name')
# Create class using *mc* as metaclass
... |
def get_class(mcs, name, default=False):
""" Generates new class to gether logic of all available extensions
::
# Create metaclass *mc*
mc = ExtensibleByHashType._("MyClass", hashattr='name')
# Use metaclass *mc* to create base class for extensions
... |
def get_registered_names(mcs):
""" Return's list of names (keys) registered in this tree.
For each name specific classes exists
"""
return [k for k, v in six.iteritems(mcs._base_classes_hash) if v] |
def get_last_day_of_month(t: datetime) -> int:
"""
Returns day number of the last day of the month
:param t: datetime
:return: int
"""
tn = t + timedelta(days=32)
tn = datetime(year=tn.year, month=tn.month, day=1)
tt = tn - timedelta(hours=1)
return tt.day |
def localize_time_range(begin: datetime, end: datetime, tz=None) -> (datetime, datetime):
"""
Localizes time range. Uses pytz.utc if None provided.
:param begin: Begin datetime
:param end: End datetime
:param tz: pytz timezone or None (default UTC)
:return: begin, end
"""
if not tz:
... |
def this_week(today: datetime=None, tz=None):
"""
Returns this week begin (inclusive) and end (exclusive).
:param today: Some date (defaults current datetime)
:param tz: Timezone (defaults pytz UTC)
:return: begin (inclusive), end (exclusive)
"""
if today is None:
today = datetime.ut... |
def this_month(today: datetime=None, tz=None):
"""
Returns current month begin (inclusive) and end (exclusive).
:param today: Some date in the month (defaults current datetime)
:param tz: Timezone (defaults pytz UTC)
:return: begin (inclusive), end (exclusive)
"""
if today is None:
t... |
def next_month(today: datetime=None, tz=None):
"""
Returns next month begin (inclusive) and end (exclusive).
:param today: Some date in the month (defaults current datetime)
:param tz: Timezone (defaults pytz UTC)
:return: begin (inclusive), end (exclusive)
"""
if today is None:
toda... |
def last_year(today: datetime=None, tz=None):
"""
Returns last year begin (inclusive) and end (exclusive).
:param today: Some date (defaults current datetime)
:param tz: Timezone (defaults pytz UTC)
:return: begin (inclusive), end (exclusive)
"""
if today is None:
today = datetime.ut... |
def add_month(t: datetime, n: int=1) -> datetime:
"""
Adds +- n months to datetime.
Clamps to number of days in given month.
:param t: datetime
:param n: count
:return: datetime
"""
t2 = t
for count in range(abs(n)):
if n > 0:
t2 = datetime(year=t2.year, month=t2.... |
def per_delta(start: datetime, end: datetime, delta: timedelta):
"""
Iterates over time range in steps specified in delta.
:param start: Start of time range (inclusive)
:param end: End of time range (exclusive)
:param delta: Step interval
:return: Iterable collection of [(start+td*0, start+td*... |
def per_month(start: datetime, end: datetime, n: int=1):
"""
Iterates over time range in one month steps.
Clamps to number of days in given month.
:param start: Start of time range (inclusive)
:param end: End of time range (exclusive)
:param n: Number of months to step. Default is 1.
:retu... |
def get_requirements() -> List[str]:
"""Return the requirements as a list of string."""
requirements_path = os.path.join(
os.path.dirname(__file__), 'requirements.txt'
)
with open(requirements_path) as f:
return f.read().split() |
def project_dev_requirements():
""" List requirements for peltak commands configured for the project.
This list is dynamic and depends on the commands you have configured in
your project's pelconf.yaml. This will be the combined list of packages
needed to be installed in order for all the configured co... |
def get_func_params(method, called_params):
"""
:type method: function
:type called_params: dict
:return:
"""
insp = inspect.getfullargspec(method)
if not isinstance(called_params, dict):
raise UserWarning()
_called_params = called_params.copy()
params = {}
arg_count = le... |
def parse_dsn(dsn, default_port=5432, protocol='http://'):
"""
Разбирает строку подключения к БД и возвращает список из (host, port,
username, password, dbname)
:param dsn: Строка подключения. Например: username@localhost:5432/dname
:type: str
:param default_port: Порт по-умолчанию
:type de... |
def build_images():
# type: () -> None
""" Build all docker images for the project. """
registry = conf.get('docker.registry')
docker_images = conf.get('docker.images', [])
for image in docker_images:
build_image(registry, image) |
def push_images():
# type: () -> None
""" Push all project docker images to a remote registry. """
registry = conf.get('docker.registry')
docker_images = conf.get('docker.images', [])
if registry is None:
log.err("You must define docker.registry conf variable to push images")
sys.ex... |
def docker_list(registry_pass):
# type: (str) -> None
""" List docker images stored in the remote registry.
Args:
registry_pass (str):
Remote docker registry password.
"""
registry = conf.get('docker.registry', None)
if registry is None:
log.err("You must define doc... |
def build_image(registry, image):
# type: (str, Dict[str, Any]) -> None
""" Build docker image.
Args:
registry (str):
The name of the registry this image belongs to. If not given, the
resulting image will have a name without the registry.
image (dict[str, Any]):
... |
def push_image(registry, image):
# type: (str, Dict[str, Any]) -> None
""" Push the given image to selected repository.
Args:
registry (str):
The name of the registry we're pushing to. This is the address of
the repository without the protocol specification (no http(s)://)
... |
def _build_opr_data(self, data, store):
"""Returns a well formatted OPR data"""
return {
"invoice_data": {
"invoice": {
"total_amount": data.get("total_amount"),
"description": data.get("description")
},
... |
def create(self, data={}, store=None):
"""Initiazes an OPR
First step in the OPR process is to create the OPR request.
Returns the OPR token
"""
_store = store or self.store
_data = self._build_opr_data(data, _store) if data else self._opr_data
return self._proce... |
def charge(self, data):
"""Second stage of an OPR request"""
token = data.get("token", self._response["token"])
data = {
"token": token,
"confirm_token": data.get("confirm_token")
}
return self._process('opr/charge', data) |
def get_value(self, field, quick):
# type: (Field, bool) -> Any
""" Ask user the question represented by this instance.
Args:
field (Field):
The field we're asking the user to provide the value for.
quick (bool):
Enable quick mode. In quic... |
def update_image(self, ami_id, instance_id):
"""Replaces an existing AMI ID with an image created from the provided
instance ID
:param ami_id: (str) ID of the AMI to delete and replace
:param instance_id: (str) ID of the instance ID to create an image from
:return: None... |
def create_cons3rt_template(self, instance_id, name, description='CONS3RT OS template'):
"""Created a new CONS3RT-ready template from an instance ID
:param instance_id: (str) Instance ID to create the image from
:param name: (str) Name of the new image
:param description: (str) ... |
def copy_cons3rt_template(self, ami_id):
"""
:param ami_id:
:return:
"""
log = logging.getLogger(self.cls_logger + '.copy_cons3rt_template')
# Get the current AMI info
try:
ami_info = self.ec2.describe_images(DryRun=False, ImageIds=[ami_id],... |
def uniorbytes(s, result=str, enc="utf-8", err="strict"):
"""
This function was made to avoid byte / str type errors received in
packages like base64. Accepts all input types and will recursively
encode entire lists and dicts.
@s: the #bytes or #str item you are attempting to encode or decode
@... |
def recode_unicode(s, encoding='utf-8'):
""" Inputs are encoded to utf-8 and then decoded to the desired
output encoding
@encoding: the desired encoding
-> #str with the desired @encoding
"""
if isinstance(s, str):
return s.encode().decode(encoding)
return s |
def fix_bad_unicode(text):
u"""Copyright:
http://blog.luminoso.com/2012/08/20/fix-unicode-mistakes-with-python/
Something you will find all over the place, in real-world text, is text
that's mistakenly encoded as utf-8, decoded in some ugly format like
latin-1 or even Windows codepage 1252, and... |
def text_badness(text):
u'''
Look for red flags that text is encoded incorrectly:
Obvious problems:
- The replacement character \ufffd, indicating a decoding error
- Unassigned or private-use Unicode characters
Very weird things:
- Adjacent letters from two different scripts
- Letters ... |
def get_pycons3rt_home_dir():
"""Returns the pycons3rt home directory based on OS
:return: (str) Full path to pycons3rt home
:raises: OSError
"""
if platform.system() == 'Linux':
return os.path.join(os.path.sep, 'etc', 'pycons3rt')
elif platform.system() == 'Windows':
return os.... |
def initialize_pycons3rt_dirs():
"""Initializes the pycons3rt directories
:return: None
:raises: OSError
"""
for pycons3rt_dir in [get_pycons3rt_home_dir(),
get_pycons3rt_user_dir(),
get_pycons3rt_conf_dir(),
get_pycons3r... |
def main():
# Create the pycons3rt directories
try:
initialize_pycons3rt_dirs()
except OSError as ex:
traceback.print_exc()
return 1
# Replace log directory paths
log_dir_path = get_pycons3rt_log_dir() + os.path.sep
conf_contents = default_logging_conf_file_contents.re... |
def add_hooks():
# type: () -> None
""" Add git hooks for commit and push to run linting and tests. """
# Detect virtualenv the hooks should use
# Detect virtualenv
virtual_env = conf.getenv('VIRTUAL_ENV')
if virtual_env is None:
log.err("You are not inside a virtualenv")
confi... |
def start(name):
# type: (str) -> None
""" Start working on a new feature by branching off develop.
This will create a new branch off develop called feature/<name>.
Args:
name (str):
The name of the new feature.
"""
feature_name = 'feature/' + common.to_branch_name(name)
... |
def update():
# type: () -> None
""" Update the feature with updates committed to develop.
This will merge current develop into the current branch.
"""
branch = git.current_branch(refresh=True)
develop = conf.get('git.devel_branch', 'develop')
common.assert_branch_type('feature')
commo... |
def merged():
# type: () -> None
""" Cleanup a remotely merged branch. """
develop = conf.get('git.devel_branch', 'develop')
branch = git.current_branch(refresh=True)
common.assert_branch_type('feature')
# Pull develop with the merged feature
common.git_checkout(develop)
common.git_pul... |
def clean(exclude):
# type: (bool, List[str]) -> None
""" Remove all unnecessary files.
Args:
pretend (bool):
If set to **True**, do not delete any files, just show what would be
deleted.
exclude (list[str]):
A list of path patterns to exclude from deleti... |
def init(quick):
# type: () -> None
""" Create an empty pelconf.yaml from template """
config_file = 'pelconf.yaml'
prompt = "-- <35>{} <32>already exists. Wipe it?<0>".format(config_file)
if exists(config_file) and not click.confirm(shell.fmt(prompt)):
log.info("Canceled")
return
... |
def tracebacks_from_lines(lines_iter):
"""Generator that yields tracebacks found in a lines iterator
The lines iterator can be:
- a file-like object
- a list (or deque) of lines.
- any other iterable sequence of strings
"""
tbgrep = TracebackGrep()
for line in lines_iter:
tb ... |
def tracebacks_from_file(fileobj, reverse=False):
"""Generator that yields tracebacks found in a file object
With reverse=True, searches backwards from the end of the file.
"""
if reverse:
lines = deque()
for line in BackwardsReader(fileobj):
lines.appendleft(line)
... |
def BackwardsReader(file, BLKSIZE = 4096):
"""Read a file line by line, backwards"""
buf = ""
file.seek(0, 2)
lastchar = file.read(1)
trailing_newline = (lastchar == "\n")
while 1:
newline_pos = buf.rfind("\n")
pos = file.tell()
if newline_pos != -1:
# Foun... |
def inversefunc(func,
y_values=None,
domain=None,
image=None,
open_domain=None,
args=(),
accuracy=2):
r"""Obtain the inverse of a function.
Returns the numerical inverse of the function `f`. It may return a callable... |
def progressed_bar(count, total=100, status=None, suffix=None, bar_len=10):
"""render a progressed.io like progress bar"""
status = status or ''
suffix = suffix or '%'
assert isinstance(count, int)
count_normalized = count if count <= total else total
filled_len = int(round(bar_len * count_norma... |
def prettify(string):
"""
replace markup emoji and progressbars with actual things
# Example
```python
from habitipy.util import prettify
print(prettify('Write thesis :book: '))
```
```
Write thesis 📖 ██████████0%
```
"""
... |
def assert_secure_file(file):
"""checks if a file is stored securely"""
if not is_secure_file(file):
msg = """
File {0} can be read by other users.
This is not secure. Please run 'chmod 600 "{0}"'"""
raise SecurityError(dedent(msg).replace('\n', ' ').format(file))
return True |
def get_translation_for(package_name: str) -> gettext.NullTranslations:
"""find and return gettext translation for package"""
localedir = None
for localedir in pkg_resources.resource_filename(package_name, 'i18n'), None:
localefile = gettext.find(package_name, localedir) # type: ignore
if l... |
def get_translation_functions(package_name: str, names: Tuple[str, ...] = ('gettext',)):
"""finds and installs translation functions for package"""
translation = get_translation_for(package_name)
return [getattr(translation, x) for x in names] |
def escape_keywords(arr):
"""append _ to all python keywords"""
for i in arr:
i = i if i not in kwlist else i + '_'
i = i if '-' not in i else i.replace('-', '_')
yield i |
def download_api(branch=None) -> str:
"""download API documentation from _branch_ of Habitica\'s repo on Github"""
habitica_github_api = 'https://api.github.com/repos/HabitRPG/habitica'
if not branch:
branch = requests.get(habitica_github_api + '/releases/latest').json()['tag_name']
curl = local... |
def save_apidoc(text: str) -> None:
"""save `text` to apidoc cache"""
apidoc_local = local.path(APIDOC_LOCAL_FILE)
if not apidoc_local.dirname.exists():
apidoc_local.dirname.mkdir()
with open(apidoc_local, 'w') as f:
f.write(text) |
def parse_apidoc(
file_or_branch,
from_github=False,
save_github_version=True
) -> List['ApiEndpoint']:
"""read file and parse apiDoc lines"""
apis = [] # type: List[ApiEndpoint]
regex = r'(?P<group>\([^)]*\)){0,1} *(?P<type_>{[^}]*}){0,1} *'
regex += r'(?P<field>[^ ]*) *(?P<description>.*)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.