Search is not available for this dataset
text stringlengths 75 104k |
|---|
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... |
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
... |
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:
... |
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 |
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) |
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(
... |
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... |
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 ... |
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]... |
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] |
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) |
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... |
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,
... |
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... |
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] |
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... |
def feature_importance_report(X,
y,
threshold=0.001,
correcting_multiple_hypotesis=True,
method='fdr_bh',
alpha=0.1,
sort_by='pval'):
''... |
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] |
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 |
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, ... |
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
... |
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... |
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... |
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 |
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... |
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... |
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) |
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('... |
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... |
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:
... |
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):
... |
def load_handfile(path, importer=None):
"""
导入传入的 ``handfile`` 文件路径,并返回(docstring, callables)
也就是 handfile 包的 ``__doc__`` 属性 (字符串) 和一个 ``{'name': callable}``
的字典,包含所有通过 mohand 的 command 测试的 callables
:param str path: 待导入的 handfile 文件路径
:param function importer: 可选,包导入函数,默认为 ``__import__``
... |
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... |
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... |
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... |
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... |
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):
... |
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... |
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
... |
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.
... |
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... |
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 ... |
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... |
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)
... |
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_... |
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... |
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... |
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... |
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... |
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... |
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... |
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
... |
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*']))
... |
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... |
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"{... |
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()
... |
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... |
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)... |
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... |
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()
... |
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... |
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... |
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... |
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(
... |
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:
""... |
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... |
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... |
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:... |
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... |
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... |
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 ... |
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):
... |
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... |
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 |
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 |
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... |
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.... |
def _run(self, run_dir):
"""Distributed process"""
# Check to see if the required run_params files exist, if they dont use the tools to generate them
# --------------------------------------------------#
# HERE WE RECREATE OUR RUN_PARAMS OBJECT FROM
# THE RUN FILE WE WROTE TO D... |
def generate_directories(self, overwrite=False):
"""For all possible combinations of 'batchable' parameters. create a unique directory to story outputs
Each directory name is unique and contains the run parameters in the directory name
:param overwrite: If set to True will over write all files... |
def batch_parameters(self, saa, sza, p, x, y, g, s, z):
"""Takes lists for parameters and saves them as class properties
:param saa: <list> Sun Azimuth Angle (deg)
:param sza: <list> Sun Zenith Angle (deg)
:param p: <list> Phytoplankton linear scalling factor
:param x: <list> Sc... |
def read_param_file_to_dict(file_name):
"""Loads a text file to a python dictionary using '=' as the delimiter
:param file_name: the name and path of the text file
"""
data = loadtxt(file_name, delimiter='=', dtype=scipy.string0)
data_dict = dict(data)
for key in data_di... |
def string_to_float_list(string_var):
"""Pull comma separated string values out of a text file and converts them to float list"""
try:
return [float(s) for s in string_var.strip('[').strip(']').split(', ')]
except:
return [float(s) for s in string_var.strip('[').strip(']'... |
def read_pr_report(self, filename):
"""Reads in a PlanarRad generated report
Saves the single line reported parameters as a python dictionary
:param filename: The name and path of the PlanarRad generated file
:returns self.data_dictionary: python dictionary with the key and values from... |
def calc_directional_aop(self, report, parameter, parameter_dir):
"""
Will calcuate the directional AOP (only sub-surface rrs for now) if the direction is defined using @
e.g. rrs@32.0:45 where <zenith-theta>:<azimuth-phi>
:param report: The planarrad report dictionary. should include... |
def write_batch_report(self, input_directory, parameter):
"""
Collect all of the batch reports and concatenate the results. The report should be :
:param input_directory:
:param parameter: This is the parameter in which to report.
"""
# Check to see if there is an @ in... |
def write_batch_to_file(self, filename='batch_test_default.txt'):
"""
This function creates a new file if he doesn't exist already, moves it to 'inputs/batch_file' folder
and writes data and comments associated to them.
Inputs: saa_values : <list> Sun Azimuth Angle (deg)
... |
def update_fields(self, x_data, y_data, num_plot):
"""
This function will update data that we need to display curves, from "data_processing" from "gui_mainLayout"
Inputs : x_data : An array with wavelengths.
y_data : An array with curve's data.
num_plot : The li... |
def display_graphic(self, flag_curves, ui):
"""
This function plots results of a file into the canvas.
Inputs : flag_curves : A boolean to know with we have to plot all curves or not.
ui : The main_Window.
"""
ui.graphic_widget.canvas.picture.clear()
x =... |
def set_handler(self, signals, handler=signal.SIG_DFL):
""" Takes a list of signals and sets a handler for them """
for sig in signals:
self.log.debug("Creating handler for signal: {0}".format(sig))
signal.signal(sig, handler) |
def pseudo_handler(self, signum, frame):
""" Pseudo handler placeholder while signal is beind processed """
self.log.warn("Received sigal {0} but system is already busy processing a previous signal, current frame: {1}".format(signum, str(frame))) |
def default_handler(self, signum, frame):
""" Default handler, a generic callback method for signal processing"""
self.log.debug("Signal handler called with signal: {0}".format(signum))
# 1. If signal is HUP restart the python process
# 2. If signal is TERM, INT or QUIT we try to cleanup... |
def pause(self, signum, seconds=0, callback_function=None):
"""
Pause execution, execution will resume in X seconds or when the
appropriate resume signal is received. Execution will jump to the
callback_function, the default callback function is the handler
method which will run ... |
def abort(self, signum):
""" Run all abort tasks, then all exit tasks, then exit with error
return status"""
self.log.info('Signal handler received abort request')
self._abort(signum)
self._exit(signum)
os._exit(1) |
def status(self, signum):
""" Run all status tasks, then run all tasks in the resume queue"""
self.log.debug('Signal handler got status signal')
new_status_callbacks = []
for status_call in self.status_callbacks:
# If callback is non persistent we remove it
try:
... |
def _unreg_event(self, event_list, event):
""" Tries to remove a registered event without triggering it """
try:
self.log.debug("Removing event {0}({1},{2})".format(event['function'].__name__, event['args'], event['kwargs']))
except AttributeError:
self.log.debug("Removin... |
def reg_on_exit(self, callable_object, *args, **kwargs):
""" Register a function/method to be called on program exit,
will get executed regardless of successs/failure of the program running """
persistent = kwargs.pop('persistent', False)
event = self._create_event(callable_object, 'exit... |
def reg_on_abort(self, callable_object, *args, **kwargs):
""" Register a function/method to be called when execution is aborted"""
persistent = kwargs.pop('persistent', False)
event = self._create_event(callable_object, 'abort', persistent, *args, **kwargs)
self.abort_callbacks.append(ev... |
def reg_on_status(self, callable_object, *args, **kwargs):
""" Register a function/method to be called when a user or another
program asks for an update, when status is done it will start running
any tasks registered with the reg_on_resume method"""
persistent = kwargs.pop('persistent', ... |
def reg_on_resume(self, callable_object, *args, **kwargs):
""" Register a function/method to be called if the system needs to
resume a previously halted or paused execution, including status
requests."""
persistent = kwargs.pop('persistent', False)
event = self._create_event(call... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.