INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Iterates over the actions and executes them in order. | def execute_actions(self, cwd):
"""Iterates over the actions and executes them in order."""
self._execute_globals(cwd)
for action in self.actions:
logger.info("executing {}".format(action))
p = subprocess.Popen(action, shell=True, cwd=cwd)
p.wait() |
Creates a new instance of a rule by merging two dictionaries. | def from_yaml(cls, defaults, **kwargs):
"""Creates a new instance of a rule by merging two dictionaries.
This allows for independant configuration files to be merged
into the defaults."""
# TODO: I hate myself for this. Fix it later mmkay?
if "token" not in defaults:
... |
: param formatted_address: A string like email | def parse_address(formatted_address):
"""
:param formatted_address: A string like "email@address.com" or "My Email <email@address.com>"
:return: Tuple: (address, name)
"""
if email_regex.match(formatted_address):
# Just a raw address
return (formatted_address, None)
mat... |
: param recipient_list: List of recipients i. e. [ testing | def send_mail(recipient_list, subject, body, html=False, from_address=None):
"""
:param recipient_list: List of recipients i.e. ['testing@fig14.com', 'Stephen Brown <steve@fig14.com>']
:param subject: The subject
:param body: The email body
:param html: Is this a html email? Defaults to False
:p... |
Add extra details to the message. Separate so that it can be overridden | def add_details(self, message):
"""
Add extra details to the message. Separate so that it can be overridden
"""
msg = message
# Try to append Flask request details
try:
from flask import request
url = request.url
method = request.metho... |
Emit a record. | def emit(self, record):
"""
Emit a record.
Format the record and send it to the specified addressees.
"""
try:
# First, remove all records from the rate limiter list that are over a minute old
now = timetool.unix_time()
one_minute_ago = now - ... |
Ensure image_rendition is added to the global context. | def get_context(self, value):
"""Ensure `image_rendition` is added to the global context."""
context = super(RenditionAwareStructBlock, self).get_context(value)
context['image_rendition'] = self.rendition.\
image_rendition or 'original'
return context |
Log an attempt against key incrementing the number of attempts for that key and potentially adding a lock to the lock table | def log_attempt(self, key):
"""
Log an attempt against key, incrementing the number of attempts for that key and potentially adding a lock to
the lock table
"""
with self.lock:
if key not in self.attempts:
self.attempts[key] = 1
else:
... |
Decrease the countdowns and remove any expired locks. Should be called once every <decrease_every > seconds. | def service(self):
"""
Decrease the countdowns, and remove any expired locks. Should be called once every <decrease_every> seconds.
"""
with self.lock:
# Decrement / remove all attempts
for key in list(self.attempts.keys()):
log.debug('Decrementin... |
Adds an URL to the download queue. | def add_to_queue(self, url):
"""
Adds an URL to the download queue.
:param str url: URL to the music service track
"""
if self.connection_handler.current_music is None:
log.error('Music service is not initialized. URL was not added to queue.')
elif self.conn... |
Sets the current music service to service_name.: param str service_name: Name of the music service: param str api_key: Optional API key if necessary | def use_music_service(self, service_name, api_key=None):
"""
Sets the current music service to service_name.
:param str service_name: Name of the music service
:param str api_key: Optional API key if necessary
"""
self.connection_handler.use_music_service(servic... |
Sets the current storage service to service_name and attempts to connect to it.: param str service_name: Name of the storage service: param str custom_path: Custom path where to download tracks for local storage ( optional and must already exist use absolute paths only ) | def use_storage_service(self, service_name, custom_path=None):
"""
Sets the current storage service to service_name and attempts to connect to it.
:param str service_name: Name of the storage service
:param str custom_path: Custom path where to download tracks for local storage ... |
Creates and starts the workers as well as attaching a handler to terminate them gracefully when a SIGINT signal is received. | def start_workers(self, workers_per_task=1):
"""
Creates and starts the workers, as well as attaching a handler to terminate them gracefully when a SIGINT signal is received.
:param int workers_per_task: Number of workers to create for each task in the pipeline
"""
if not self.... |
Add or update a key value pair to the database | def set(self, k, v):
"""Add or update a key, value pair to the database"""
k = k.lstrip('/')
url = '{}/{}'.format(self.endpoint, k)
r = requests.put(url, data=str(v))
if r.status_code != 200 or r.json() is not True:
raise KVStoreError('PUT returned {}'.format(r.status... |
Get the value of a given key | def get(self, k, wait=False, wait_index=False, timeout='5m'):
"""Get the value of a given key"""
k = k.lstrip('/')
url = '{}/{}'.format(self.endpoint, k)
params = {}
if wait:
params['index'] = wait_index
params['wait'] = timeout
r = requests.get(ur... |
Recursively get the tree below the given key | def recurse(self, k, wait=False, wait_index=None, timeout='5m'):
"""Recursively get the tree below the given key"""
k = k.lstrip('/')
url = '{}/{}'.format(self.endpoint, k)
params = {}
params['recurse'] = 'true'
if wait:
params['wait'] = timeout
if... |
Get the current index of the key or the subtree. This is needed for later creating long polling requests | def index(self, k, recursive=False):
"""Get the current index of the key or the subtree.
This is needed for later creating long polling requests
"""
k = k.lstrip('/')
url = '{}/{}'.format(self.endpoint, k)
params = {}
if recursive:
params['recurse'] = ... |
Delete a given key or recursively delete the tree below it | def delete(self, k, recursive=False):
"""Delete a given key or recursively delete the tree below it"""
k = k.lstrip('/')
url = '{}/{}'.format(self.endpoint, k)
params = {}
if recursive:
params['recurse'] = ''
r = requests.delete(url, params=params)
if ... |
Render an internal error page. The following variables will be populated when rendering the template: title: The page title message: The body of the error message to display to the user preformat: Boolean stating whether to wrap the error message in a pre | def internal_error(exception, template_path, is_admin, db=None):
"""
Render an "internal error" page. The following variables will be populated when rendering the
template:
title: The page title
message: The body of the error message to display to the user
preformat: Boolean stating whethe... |
Plot heatmap which shows features with classes. | def plot_heatmap(X, y, top_n=10, metric='correlation', method='complete'):
'''
Plot heatmap which shows features with classes.
:param X: list of dict
:param y: labels
:param top_n: most important n feature
:param metric: metric which will be used for clustering
:param method: method which w... |
获取打包使用的版本号,符合 PYPI 官方推荐的版本号方案 | def get_setup_version():
"""
获取打包使用的版本号,符合 PYPI 官方推荐的版本号方案
:return: PYPI 打包版本号
:rtype: str
"""
ver = '.'.join(map(str, VERSION[:3]))
# 若后缀描述字串为 None ,则直接返回主版本号
if not VERSION[3]:
return ver
# 否则,追加版本号后缀
hyphen = ''
suffix = hyphen.join(map(str, VERSION[-2:]))
i... |
获取终端命令版本号,若存在VERSION文件则使用其中的版本号, 否则使用: meth:. get_setup_version | def get_cli_version():
"""
获取终端命令版本号,若存在VERSION文件则使用其中的版本号,
否则使用 :meth:`.get_setup_version`
:return: 终端命令版本号
:rtype: str
"""
directory = os.path.dirname(os.path.abspath(__file__))
version_path = os.path.join(directory, 'VERSION')
if os.path.exists(version_path):
with open(ve... |
Add a number of months to a timestamp | def add_months(months, timestamp=datetime.datetime.utcnow()):
"""Add a number of months to a timestamp"""
month = timestamp.month
new_month = month + months
years = 0
while new_month < 1:
new_month += 12
years -= 1
while new_month > 12:
new_month -= 12
y... |
Add a number of months to a date | def add_months_to_date(months, date):
"""Add a number of months to a date"""
month = date.month
new_month = month + months
years = 0
while new_month < 1:
new_month += 12
years -= 1
while new_month > 12:
new_month -= 12
years += 1
# month = timestamp.month
... |
Generate a unix style timestamp ( in seconds ) | def unix_time(dt=None, as_int=False):
"""Generate a unix style timestamp (in seconds)"""
if dt is None:
dt = datetime.datetime.utcnow()
if type(dt) is datetime.date:
dt = date_to_datetime(dt)
epoch = datetime.datetime.utcfromtimestamp(0)
delta = dt - epoch
if as_int:
... |
Is this the christmas period? | def is_christmas_period():
"""Is this the christmas period?"""
now = datetime.date.today()
if now.month != 12:
return False
if now.day < 15:
return False
if now.day > 27:
return False
return True |
Given a date or a datetime return a datetime at 23: 59: 59 on that day | def get_end_of_day(timestamp):
"""
Given a date or a datetime, return a datetime at 23:59:59 on that day
"""
return datetime.datetime(timestamp.year, timestamp.month, timestamp.day, 23, 59, 59) |
: param X: features. | def transform(self, X):
'''
:param X: features.
'''
inverser_tranformer = self.dict_vectorizer_
if self.feature_selection:
inverser_tranformer = self.clone_dict_vectorizer_
return inverser_tranformer.inverse_transform(
self.transformer.transform(
... |
Sets the current music service to service_name. | def use_music_service(self, service_name, api_key):
"""
Sets the current music service to service_name.
:param str service_name: Name of the music service
:param str api_key: Optional API key if necessary
"""
try:
self.current_music = self.music_services[ser... |
Sets the current storage service to service_name and runs the connect method on the service. | def use_storage_service(self, service_name, custom_path):
"""
Sets the current storage service to service_name and runs the connect method on the service.
:param str service_name: Name of the storage service
:param str custom_path: Custom path where to download tracks for local storage ... |
Read dataset from csv. | def from_csv(self, label_column='labels'):
'''
Read dataset from csv.
'''
df = pd.read_csv(self.path, header=0)
X = df.loc[:, df.columns != label_column].to_dict('records')
X = map_dict_list(X, if_func=lambda k, v: v and math.isfinite(v))
y = list(df[label_column]... |
Reads dataset from json. | def from_json(self):
'''
Reads dataset from json.
'''
with gzip.open('%s.gz' % self.path,
'rt') if self.gz else open(self.path) as file:
return list(map(list, zip(*json.load(file))))[::-1] |
Reads dataset to csv. | def to_json(self, X, y):
'''
Reads dataset to csv.
:param X: dataset as list of dict.
:param y: labels.
'''
with gzip.open('%s.gz' % self.path, 'wt') if self.gz else open(
self.path, 'w') as file:
json.dump(list(zip(y, X)), file) |
Select items with label from dataset. | def filter_by_label(X, y, ref_label, reverse=False):
'''
Select items with label from dataset.
:param X: dataset
:param y: labels
:param ref_label: reference label
:param bool reverse: if false selects ref_labels else eliminates
'''
check_reference_label(y, ref_label)
return list(z... |
Calculates average dictinary from list of dictionary for give label | def average_by_label(X, y, ref_label):
'''
Calculates average dictinary from list of dictionary for give label
:param List[Dict] X: dataset
:param list y: labels
:param ref_label: reference label
'''
# TODO: consider to delete defaultdict
return defaultdict(float,
... |
: param dict d: dictionary: param func key_func: func which will run on key.: param func value_func: func which will run on values. | def map_dict(d, key_func=None, value_func=None, if_func=None):
'''
:param dict d: dictionary
:param func key_func: func which will run on key.
:param func value_func: func which will run on values.
'''
key_func = key_func or (lambda k, v: k)
value_func = value_func or (lambda k, v: v)
if... |
: param List [ Dict ] ds: list of dict: param func key_func: func which will run on key.: param func value_func: func which will run on values. | def map_dict_list(ds, key_func=None, value_func=None, if_func=None):
'''
:param List[Dict] ds: list of dict
:param func key_func: func which will run on key.
:param func value_func: func which will run on values.
'''
return [map_dict(d, key_func, value_func, if_func) for d in ds] |
: param list y: label: param ref_label: reference label | def check_reference_label(y, ref_label):
'''
:param list y: label
:param ref_label: reference label
'''
set_y = set(y)
if ref_label not in set_y:
raise ValueError('There is not reference label in dataset. '
"Reference label: '%s' "
'Label... |
Provide signifance for features in dataset with anova using multiple hypostesis testing | def feature_importance_report(X,
y,
threshold=0.001,
correcting_multiple_hypotesis=True,
method='fdr_bh',
alpha=0.1,
sort_by='pval'):
''... |
Restore the data dict - update the flask session and this object | def restore_data(self, data_dict):
"""
Restore the data dict - update the flask session and this object
"""
session[self._base_key] = data_dict
self._data_dict = session[self._base_key] |
Recusively merge the 2 dicts. | def _mergedict(a, b):
"""Recusively merge the 2 dicts.
Destructive on argument 'a'.
"""
for p, d1 in b.items():
if p in a:
if not isinstance(d1, dict):
continue
_mergedict(a[p], d1)
else:
a[p] = d1
return a |
A decorator for a function to dispatch on. | def multi(dispatch_fn, default=None):
"""A decorator for a function to dispatch on.
The value returned by the dispatch function is used to look up the
implementation function based on its dispatch key.
The dispatch function is available using the `dispatch_fn` function.
"""
def _inner(*args, ... |
A decorator for a function implementing dispatch_fn for dispatch_key. | def method(dispatch_fn, dispatch_key=None):
"""A decorator for a function implementing dispatch_fn for dispatch_key.
If no dispatch_key is specified, the function is used as the
default dispacth function.
"""
def apply_decorator(fn):
if dispatch_key is None:
# Default case
... |
Auto - discover INSTALLED_APPS registered_blocks. py modules and fail silently when not present. This forces an import on them thereby registering their blocks. | def find_blocks():
"""
Auto-discover INSTALLED_APPS registered_blocks.py modules and fail
silently when not present. This forces an import on them thereby
registering their blocks.
This is a near 1-to-1 copy of how django's admin application registers
models.
"""
for app in settings.IN... |
Verifies a block prior to registration. | def _verify_block(self, block_type, block):
"""
Verifies a block prior to registration.
"""
if block_type in self._registry:
raise AlreadyRegistered(
"A block has already been registered to the {} `block_type` "
"in the registry. Either unregis... |
Registers block to block_type in the registry. | def register_block(self, block_type, block):
"""
Registers `block` to `block_type` in the registry.
"""
self._verify_block(block_type, block)
self._registry[block_type] = block |
Unregisters the block associated with block_type from the registry. | def unregister_block(self, block_type):
"""
Unregisters the block associated with `block_type` from the registry.
If no block is registered to `block_type`, NotRegistered will raise.
"""
if block_type not in self._registry:
raise NotRegistered(
'There... |
Converts the file associated with the file_name passed into a MP3 file. | def convert_to_mp3(file_name, delete_queue):
"""
Converts the file associated with the file_name passed into a MP3 file.
:param str file_name: Filename of the original file in local storage
:param Queue delete_queue: Delete queue to add the original file to after conversion is done
:return str: Fil... |
Deletes the file associated with the file_name passed from local storage.: param str file_name: Filename of the file to be deleted: return str: Filename of the file that was just deleted | def delete_local_file(file_name):
"""
Deletes the file associated with the file_name passed from local storage.
:param str file_name: Filename of the file to be deleted
:return str: Filename of the file that was just deleted
"""
try:
os.remove(file_name)
log.info(f"Deletion... |
通用自动化处理工具 | def cli(*args, **kwargs):
"""
通用自动化处理工具
详情参考 `GitHub <https://github.com/littlemo/mohand>`_
"""
log.debug('cli: {} {}'.format(args, kwargs))
# 使用终端传入的 option 更新 env 中的配置值
env.update(kwargs) |
判断传入的路径是否为一个 Python 模块包 | def _is_package(path):
"""
判断传入的路径是否为一个 Python 模块包
:param str path: 待判断的路径
:return: 返回是,则传入 path 为一个 Python 包,否则不是
:rtype: bool
"""
def _exists(s):
return os.path.exists(os.path.join(path, s))
return (
os.path.isdir(path) and
(_exists('__init__.py') or _exists('... |
尝试定位 handfile 文件,明确指定或逐级搜索父路径 | def find_handfile(names=None):
"""
尝试定位 ``handfile`` 文件,明确指定或逐级搜索父路径
:param str names: 可选,待查找的文件名,主要用于调试,默认使用终端传入的配置
:return: ``handfile`` 文件所在的绝对路径,默认为 None
:rtype: str
"""
# 如果没有明确指定,则包含 env 中的值
names = names or [env.handfile]
# 若无 ``.py`` 扩展名,则作为待查询名称,追加到 names 末尾
if not nam... |
从传入的 imported 中获取所有 click. core. Command | def get_commands_from_module(imported):
"""
从传入的 ``imported`` 中获取所有 ``click.core.Command``
:param module imported: 导入的Python包
:return: 包描述文档,仅含终端命令函数的对象字典
:rtype: (str, dict(str, object))
"""
# 如果存在 <module>.__all__ ,则遵守
imported_vars = vars(imported)
if "__all__" in imported_vars:
... |
从传入的变量列表中提取命令 ( click. core. Command ) 对象 | def extract_commands(imported_vars):
"""
从传入的变量列表中提取命令( ``click.core.Command`` )对象
:param dict_items imported_vars: 字典的键值条目列表
:return: 判定为终端命令的对象字典
:rtype: dict(str, object)
"""
commands = dict()
for tup in imported_vars:
name, obj = tup
if is_command_object(obj):
... |
导入传入的 handfile 文件路径,并返回 ( docstring callables ) | def load_handfile(path, importer=None):
"""
导入传入的 ``handfile`` 文件路径,并返回(docstring, callables)
也就是 handfile 包的 ``__doc__`` 属性 (字符串) 和一个 ``{'name': callable}``
的字典,包含所有通过 mohand 的 command 测试的 callables
:param str path: 待导入的 handfile 文件路径
:param function importer: 可选,包导入函数,默认为 ``__import__``
... |
Determine whether the desired version is a reasonable next version. | def reasonable_desired_version(self, desired_version, allow_equal=False,
allow_patch_skip=False):
"""
Determine whether the desired version is a reasonable next version.
Parameters
----------
desired_version: str
the proposed next ve... |
Check if a route needs ssl and redirect it if not. Also redirects back to http for non - ssl routes. Static routes are served as both http and https | def handle_ssl_redirect():
"""
Check if a route needs ssl, and redirect it if not. Also redirects back to http for non-ssl routes. Static routes
are served as both http and https
:return: A response to be returned or None
"""
if request.endpoint and request.endpoint not in ['static', 'fileman... |
Initialise this library. The following config variables need to be in your Flask config: | def init(app):
"""
Initialise this library. The following config variables need to be in your Flask config:
REDIS_HOST: The host of the Redis server
REDIS_PORT: The port of the Redis server
REDIS_PASSWORD: The password used to connect to Redis or None
REDIS_GLOBAL_KEY_PREFIX: A short string un... |
Use this to enable error reporting. You need to put the following in your tasks. py or wherever you want to create your celery instance: | def get_enable_celery_error_reporting_function(site_name, from_address):
"""
Use this to enable error reporting. You need to put the following in your tasks.py or wherever you
want to create your celery instance:
celery = Celery(__name__)
enable_celery_email_logging = get_enable_celery_error_repo... |
Initialise Celery and set up logging | def init_celery(app, celery):
"""
Initialise Celery and set up logging
:param app: Flask app
:param celery: Celery instance
"""
celery.conf.update(app.config)
TaskBase = celery.Task
class ContextTask(TaskBase):
abstract = True
def __call__(self, *args, **kwargs):
... |
Add a mail to the queue to be sent. | def queue_email(to_addresses, from_address, subject, body, commit=True, html=True, session=None):
"""
Add a mail to the queue to be sent.
WARNING: Commits by default!
:param to_addresses: The names and addresses to send the email to, i.e. "Steve<steve@fig14.com>, info@fig14.com"
:param from_addres... |
Parse an HTTP accept - like header. | def parse_accept(header_value):
"""Parse an HTTP accept-like header.
:param str header_value: the header value to parse
:return: a :class:`list` of :class:`.ContentType` instances
in decreasing quality order. Each instance is augmented
with the associated quality as a ``float`` property
... |
Parse a Cache - Control _ header returning a dictionary of key - value pairs. | def parse_cache_control(header_value):
"""
Parse a `Cache-Control`_ header, returning a dictionary of key-value pairs.
Any of the ``Cache-Control`` parameters that do not have directives, such
as ``public`` or ``no-cache`` will be returned with a value of ``True``
if they are set in the header.
... |
Parse a content type like header. | def parse_content_type(content_type, normalize_parameter_values=True):
"""Parse a content type like header.
:param str content_type: the string to parse as a content type
:param bool normalize_parameter_values:
setting this to ``False`` will enable strict RFC2045 compliance
in which content... |
Parse RFC7239 Forwarded header. | def parse_forwarded(header_value, only_standard_parameters=False):
"""
Parse RFC7239 Forwarded header.
:param str header_value: value to parse
:keyword bool only_standard_parameters: if this keyword is specified
and given a *truthy* value, then a non-standard parameter name
will result ... |
Parse a HTTP Link header. | def parse_link(header_value, strict=True):
"""
Parse a HTTP Link header.
:param str header_value: the header value to parse
:param bool strict: set this to ``False`` to disable semantic
checking. Syntactical errors will still raise an exception.
Use this if you want to receive all para... |
Parse a comma - separated list header. | def parse_list(value):
"""
Parse a comma-separated list header.
:param str value: header value to split into elements
:return: list of header elements as strings
"""
segments = _QUOTED_SEGMENT_RE.findall(value)
for segment in segments:
left, match, right = value.partition(segment)
... |
Parse a named parameter list in the common format. | def _parse_parameter_list(parameter_list,
normalized_parameter_values=_DEF_PARAM_VALUE,
normalize_parameter_names=False,
normalize_parameter_values=True):
"""
Parse a named parameter list in the "common" format.
:param parameter_... |
Parse a header value returning a sorted list of values based upon the quality rules specified in https:// tools. ietf. org/ html/ rfc7231 for the Accept - * headers. | def _parse_qualified_list(value):
"""
Parse a header value, returning a sorted list of values based upon
the quality rules specified in https://tools.ietf.org/html/rfc7231 for
the Accept-* headers.
:param str value: The value to parse into a list
:rtype: list
"""
found_wildcard = False... |
Parse a HTTP Link header. | def parse_link_header(header_value, strict=True):
"""
Parse a HTTP Link header.
:param str header_value: the header value to parse
:param bool strict: set this to ``False`` to disable semantic
checking. Syntactical errors will still raise an exception.
Use this if you want to receive a... |
Resize the image to fit inside dest rectangle. Resultant image may be smaller than target: param image: PIL. Image: param dest_w: Target width: param dest_h: Target height: return: Scaled image | def resize_image_to_fit(image, dest_w, dest_h):
"""
Resize the image to fit inside dest rectangle. Resultant image may be smaller than target
:param image: PIL.Image
:param dest_w: Target width
:param dest_h: Target height
:return: Scaled image
"""
dest_w = float(dest_w)
dest_h = fl... |
: param image: PIL. Image: param dest_w: Target width: param dest_h: Target height: return: Scaled and cropped image | def resize_crop_image(image, dest_w, dest_h, pad_when_tall=False):
"""
:param image: PIL.Image
:param dest_w: Target width
:param dest_h: Target height
:return: Scaled and cropped image
"""
# Now we need to resize it
dest_w = float(dest_w)
dest_h = float(dest_h)
dest_ratio = des... |
Resize the image and pad to the correct aspect ratio.: param image: PIL. Image: param dest_w: Target width: param dest_h: Target height: param pad_with_transparent: If True make additional padding transparent | def resize_pad_image(image, dest_w, dest_h, pad_with_transparent=False):
"""
Resize the image and pad to the correct aspect ratio.
:param image: PIL.Image
:param dest_w: Target width
:param dest_h: Target height
:param pad_with_transparent: If True, make additional padding transparent
:retu... |
Resize and image to fit the passed in width keeping the aspect ratio the same | def resize_image_to_fit_width(image, dest_w):
"""
Resize and image to fit the passed in width, keeping the aspect ratio the same
:param image: PIL.Image
:param dest_w: The desired width
"""
scale_factor = dest_w / image.size[0]
dest_h = image.size[1] * scale_factor
scaled_image = i... |
Add a new value to the list. | def add_value(self, name, value):
"""
Add a new value to the list.
:param str name: name of the value that is being parsed
:param str value: value that is being parsed
:raises ietfparse.errors.MalformedLinkValue:
if *strict mode* is enabled and a validation error
... |
The name/ value mapping that was parsed. | def values(self):
"""
The name/value mapping that was parsed.
:returns: a sequence of name/value pairs.
"""
values = self._values[:]
if self.strict:
if self._rfc_values['title*']:
values.append(('title*', self._rfc_values['title*']))
... |
Downloads a MP4 or WebM file that is associated with the video at the URL passed. | def download(self, url):
"""
Downloads a MP4 or WebM file that is associated with the video at the URL passed.
:param str url: URL of the video to be downloaded
:return str: Filename of the file in local storage
"""
try:
yt = YouTube(url)
except Rege... |
Downloads a MP3 file that is associated with the track at the URL passed.: param str url: URL of the track to be downloaded | def download(self, url):
"""
Downloads a MP3 file that is associated with the track at the URL passed.
:param str url: URL of the track to be downloaded
"""
try:
track = self.client.get('/resolve', url=url)
except HTTPError:
log.error(f"{... |
Creates connection to the Google Drive API sets the connection attribute to make requests and creates the Music folder if it doesn t exist. | def connect(self):
"""Creates connection to the Google Drive API, sets the connection attribute to make requests, and creates the Music folder if it doesn't exist."""
SCOPES = 'https://www.googleapis.com/auth/drive'
store = file.Storage('drive_credentials.json')
creds = store.get()
... |
Uploads the file associated with the file_name passed to Google Drive in the Music folder. | def upload(self, file_name):
"""
Uploads the file associated with the file_name passed to Google Drive in the Music folder.
:param str file_name: Filename of the file to be uploaded
:return str: Original filename passed as an argument (in order for the worker to send it to the delete qu... |
Initializes the connection attribute with the path to the user home folder s Music folder and creates it if it doesn t exist. | def connect(self):
"""Initializes the connection attribute with the path to the user home folder's Music folder, and creates it if it doesn't exist."""
if self.music_folder is None:
music_folder = os.path.join(os.path.expanduser('~'), 'Music')
if not os.path.exists(music_folder)... |
Moves the file associated with the file_name passed to the Music folder in the local storage.: param str file_name: Filename of the file to be uploaded | def upload(self, file_name):
"""
Moves the file associated with the file_name passed to the Music folder in the local storage.
:param str file_name: Filename of the file to be uploaded
"""
log.info(f"Upload for {file_name} has started")
start_time = time... |
All of the class properties are written to a text file | def write_run_parameters_to_file(self):
"""All of the class properties are written to a text file
Each property is on a new line with the key and value seperated with an equals sign '='
This is the mane planarrad properties file used by slabtool
"""
self.update_filenames()
... |
Writes the params to file that skytool_Free needs to generate the sky radiance distribution. | def write_sky_params_to_file(self):
"""Writes the params to file that skytool_Free needs to generate the sky radiance distribution."""
inp_file = self.sky_file + '_params.txt'
lg.info('Writing Inputs to file : ' + inp_file)
f = open(inp_file, 'w')
f.write('verbose= ' + str(sel... |
Write the params to file that surftool_Free needs to generate the surface facets | def write_surf_params_to_file(self):
"""Write the params to file that surftool_Free needs to generate the surface facets"""
inp_file = self.water_surface_file + '_params.txt'
lg.info('Writing Inputs to file : ' + inp_file)
if self.surf_state == 'flat': # this is the only one that curr... |
Write the params to file that surftool_Free needs to generate the surface facets | def write_phase_params_to_file(self):
"""Write the params to file that surftool_Free needs to generate the surface facets"""
inp_file = os.path.join(os.path.join(self.input_path, 'phase_files'), self.phase_function_file) + '_params.txt'
lg.info('Writing Inputs to file : ' + inp_file)
if... |
Does nothing currently. May not need this method | def update_filenames(self):
"""Does nothing currently. May not need this method"""
self.sky_file = os.path.abspath(os.path.join(os.path.join(self.input_path, 'sky_files'),
'sky_' + self.sky_state + '_z' + str(
... |
Builds the particle backscattering function: math: X ( \\ frac { 550 } { \\ lambda } ) ^Y | def build_bbp(self, x, y, wave_const=550):
"""
Builds the particle backscattering function :math:`X(\\frac{550}{\\lambda})^Y`
:param x: function coefficient
:param y: order of the power function
:param wave_const: wave constant default 550 (nm)
:returns null:
""... |
Builds the CDOM absorption function::: math: G \ exp ( - S ( \ lambda - 400 )) | def build_a_cdom(self, g, s, wave_const=400):
"""
Builds the CDOM absorption function :: :math:`G \exp (-S(\lambda - 400))`
:param g: function coefficient
:param s: slope factor
:param wave_const: wave constant default = 400 (nm)
:returns null:
"""
lg.inf... |
Read the phytoplankton absorption file from a csv formatted file | def read_aphi_from_file(self, file_name):
"""Read the phytoplankton absorption file from a csv formatted file
:param file_name: filename and path of the csv file
"""
lg.info('Reading ahpi absorption')
try:
self.a_phi = self._read_iop_from_file(file_name)
exce... |
Scale the spectra by multiplying by linear scaling factor | def scale_aphi(self, scale_parameter):
"""Scale the spectra by multiplying by linear scaling factor
:param scale_parameter: Linear scaling factor
"""
lg.info('Scaling a_phi by :: ' + str(scale_parameter))
try:
self.a_phi = self.a_phi * scale_parameter
except:... |
Read the pure water absorption from a csv formatted file | def read_pure_water_absorption_from_file(self, file_name):
"""Read the pure water absorption from a csv formatted file
:param file_name: filename and path of the csv file
"""
lg.info('Reading water absorption from file')
try:
self.a_water = self._read_iop_from_file(f... |
Read the pure water scattering from a csv formatted file | def read_pure_water_scattering_from_file(self, file_name):
"""Read the pure water scattering from a csv formatted file
:param file_name: filename and path of the csv file
"""
lg.info('Reading water scattering from file')
try:
self.b_water = self._read_iop_from_file(f... |
Generic IOP reader that interpolates the iop to the common wavelengths defined in the constructor | def _read_iop_from_file(self, file_name):
"""
Generic IOP reader that interpolates the iop to the common wavelengths defined in the constructor
:param file_name: filename and path of the csv file
:returns interpolated iop
"""
lg.info('Reading :: ' + file_name + ' :: and ... |
Generic iop file writer | def _write_iop_to_file(self, iop, file_name):
"""Generic iop file writer
:param iop numpy array to write to file
:param file_name the file and path to write the IOP to
"""
lg.info('Writing :: ' + file_name)
f = open(file_name, 'w')
for i in scipy.nditer(iop):
... |
Calculates the total scattering from back - scattering | def build_b(self, scattering_fraction=0.01833):
"""Calculates the total scattering from back-scattering
:param scattering_fraction: the fraction of back-scattering to total scattering default = 0.01833
b = ( bb[sea water] + bb[p] ) /0.01833
"""
lg.info('Building b with scatteri... |
Calculates the total absorption from water phytoplankton and CDOM | def build_a(self):
"""Calculates the total absorption from water, phytoplankton and CDOM
a = awater + acdom + aphi
"""
lg.info('Building total absorption')
self.a = self.a_water + self.a_cdom + self.a_phi |
Calculates the total attenuation from the total absorption and total scattering | def build_c(self):
"""Calculates the total attenuation from the total absorption and total scattering
c = a + b
"""
lg.info('Building total attenuation C')
self.c = self.a + self.b |
Meta method that calls all of the build methods in the correct order | def build_all_iop(self):
"""Meta method that calls all of the build methods in the correct order
self.build_a()
self.build_bb()
self.build_b()
self.build_c()
"""
lg.info('Building all b and c from IOPs')
self.build_a()
self.build_bb()
sel... |
Distributes the work across the CPUs. It actually uses _run () | def run(self):
"""Distributes the work across the CPUs. It actually uses _run()"""
done = False
dir_list = []
tic = time.clock()
lg.info('Starting batch run at :: ' + str(tic))
if self.run_params.num_cpus == -1: # user hasn't set a throttle
self.run_params.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.