text stringlengths 81 112k |
|---|
Pulls the latest version of the base image
def update_base_image(path: str):
"""Pulls the latest version of the base image"""
with open(path, 'r') as file_handle:
contents = file_handle.read()
regex = re.compile('from\s+(?P<source>[^\s]+)', re.IGNORECASE)
matches = regex.findall(contents)
... |
Builds the container from the specified docker file path
def build(path: str) -> dict:
"""Builds the container from the specified docker file path"""
update_base_image(path)
match = file_pattern.search(os.path.basename(path))
build_id = match.group('id')
tags = [
'{}:{}-{}'.format(HUB_PREFI... |
Publishes the specified build entry to docker hub
def publish(build_entry: dict):
"""Publishes the specified build entry to docker hub"""
for tag in build_entry['tags']:
print('[PUSHING]:', tag)
os.system('docker push {}'.format(tag)) |
Parse command line arguments
def parse() -> dict:
"""Parse command line arguments"""
parser = ArgumentParser()
parser.add_argument('-p', '--publish', action='store_true', default=False)
return vars(parser.parse_args()) |
Execute the build process
def run():
"""Execute the build process"""
args = parse()
build_results = [build(p) for p in glob.iglob(glob_path)]
if not args['publish']:
return
for entry in build_results:
publish(entry) |
Displays the elapsed time since the current step started running.
def elapsed_time(seconds: float) -> str:
"""Displays the elapsed time since the current step started running."""
environ.abort_thread()
parts = (
'{}'.format(timedelta(seconds=seconds))
.rsplit('.', 1)
)
hours, minute... |
Renders an image block
def image(
rendered_path: str,
width: int = None,
height: int = None,
justify: str = None
) -> str:
"""Renders an image block"""
environ.abort_thread()
return templating.render_template(
'image.html',
path=rendered_path,
width=w... |
Information about Cauldron and its Python interpreter.
:return:
A dictionary containing information about the Cauldron and its
Python environment. This information is useful when providing feedback
and bug reports.
def get_environment_info() -> dict:
"""
Information about Cauldron ... |
Run the cauldron http server used to interact with cauldron from a remote
host.
:param port:
The port on which to bind the cauldron server.
:param debug:
Whether or not the server should be run in debug mode. If true, the
server will echo debugging information during operation.
... |
Runs a project as a single command directly within the current Python
interpreter.
:param project_directory:
The fully-qualified path to the directory where the Cauldron project is
located
:param output_directory:
The fully-qualified path to the directory where the results will be
... |
Joins on the thread associated with the response if it exists, or
just returns after a no-op if no thread exists to join.
:param timeout:
Maximum number of seconds to block on the join before given up
and continuing operation. The default `None` value will wait
forev... |
Converts a serialized dictionary response to a Response object
def deserialize(serial_data: dict) -> 'Response':
""" Converts a serialized dictionary response to a Response object """
r = Response(serial_data.get('id'))
r.data.update(serial_data.get('data', {}))
r.ended = serial_data.g... |
This function checks to see if the user has indicated that they want the
currently running execution to stop prematurely by marking the running
thread as aborted. It only applies to operations that are run within
CauldronThreads and not the main thread.
def abort_thread():
"""
This function checks ... |
Specifies whether or not the thread is running
def is_running(self) -> bool:
"""Specifies whether or not the thread is running"""
return (
self._has_started and
self.is_alive() or
self.completed_at is None or
(datetime.utcnow() - self.completed_at).total_... |
Executes the Cauldron command in a thread to prevent long-running
computations from locking the main Cauldron thread, which is needed
to serve and print status information.
def run(self):
"""
Executes the Cauldron command in a thread to prevent long-running
computations from loc... |
Executes a hard abort by shutting down the event loop in this thread
in which the running command was operating. This is carried out using
the asyncio library to prevent the stopped execution from destabilizing
the Python environment.
def abort_running(self) -> bool:
"""
Execute... |
Fetches the arguments for the current Flask application request
def from_request(request=None) -> dict:
""" Fetches the arguments for the current Flask application request """
request = request if request else flask_request
try:
json_args = request.get_json(silent=True)
except Exception:
... |
print the rule in a nice way
:param rule: An instance of Rule
:param feature_names: a list of n_features feature names,
:param category_names: the names of the categories of each feature.
:param label: Can take two values, 'label': just print the label as output, or 'prob': print the prob distribution.
... |
A helper function that converts the resulting string returned from C function to the Rule object
:param rule_str: a string representing the rule
:param prob: the output probability
:return: a Rule object
def rule_str2rule(rule_str, prob):
# type: (str, float) -> Rule
"""
A helper function that... |
:param x_cat: a 2D array of pure categorical data of shape [n_data, n_features]
:return: a bool array of shape [n_data,] representing whether the rule is fired by each input data.
def is_satisfied(self, x_cat):
"""
:param x_cat: a 2D array of pure categorical data of shape [n_data, n_features]
... |
:param x: 2D np.ndarray (n_instances, n_features) should be categorical data, must be of type int
:param y: 1D np.ndarray (n_instances, ) labels
:return:
def fit(self, x, y):
"""
:param x: 2D np.ndarray (n_instances, n_features) should be categorical data, must be of type int
:p... |
A helper function that converts the results returned from C function
:param rule_ids:
:param outputs:
:param raw_rules:
:return:
def from_raw(self, rule_ids, outputs, raw_rules):
"""
A helper function that converts the results returned from C function
:param rule... |
Calculate the support for the rules.
The support of each rule is a list of `n_classes` integers: [l1, l2, ...].
Each integer represents the number of data of label i that is caught by this rule
:param x: 2D np.ndarray (n_instances, n_features) should be categorical data, must be of type int
... |
compute the caught matrix of x
Each rule has an array of bools, showing whether each instances is caught by this rule
:param x: 2D np.ndarray (n_instances, n_features) should be categorical data, must be of type int
:return:
a bool np.ndarray of shape (n_rules, n_instances)
def caug... |
compute the decision path of the rule list on x
:param x: x should be already transformed
:return:
return a np.ndarray of shape [n_rules, n_instances] of type bool,
representing whether an instance has consulted a rule or not
def decision_path(self, x):
# type: (np.ndarr... |
Adds one or more variables to the cache.
:param args:
Variables can be specified by two consecutive arguments where the
first argument is a key and the second one the corresponding value.
For example:
```
put('a', 1, 'b', False)
```
... |
Returns a tuple containing multiple values from the cache specified by
the keys arguments
:param keys:
One or more variable names stored in the cache that should be
returned by the grab function. The order of these arguments are
preserved by the returned tuple.
... |
Retrieves the value of the specified variable from the cache
:param key:
The name of the variable for which the value should be returned
:param default_value:
The value to return if the variable does not exist in the cache
:return:
The value of the specified ... |
The basic training function of the scalable bayesian rule list.
Users are suggested to use SBRL instead of this function.
It takes the paths of the pre-processed data and label files as input,
and return the parameters of the trained rule list.
Check pysbrl.utils:categorical2pysbrl_data to see how to c... |
Returns tree objects from a sentence
Args:
line: Sentence to be parsed into a tree
Returns:
Tree object representing parsed sentence
None if parse fails
def parse(self, line):
"""Returns tree objects from a sentence
Args:
line: Sentence... |
Packs the specified binary source data by compressing it with the Zlib
library and then converting the bytes to a base64 encoded string for
non-binary transmission.
:param source_data:
The data to be converted to a compressed, base64 string
def pack_chunk(source_data: bytes) -> str:
"""
Pa... |
Unpacks a previously packed chunk data back into the original
bytes representation
:param chunk_data:
The compressed, base64 encoded string to convert back to the
source bytes object.
def unpack_chunk(chunk_data: str) -> bytes:
"""
Unpacks a previously packed chunk data back into the o... |
Determines the number of chunks necessary to send the file for the given
chunk size
:param file_path:
The absolute path to the file that will be synchronized in chunks
:param chunk_size:
The maximum size of each chunk in bytes
:return
The number of chunks necessary to send the e... |
Reads the specified file in chunks and returns a generator where
each returned chunk is a compressed base64 encoded string for sync
transmission
:param file_path:
The path to the file to read in chunks
:param chunk_size:
The size, in bytes, of each chunk. The final chunk will be less th... |
Write or append the specified chunk data to the given file path, unpacking
the chunk before writing. If the file does not yet exist, it will be
created. Set the append argument to False if you do not want the chunk
to be appended to an existing file.
:param file_path:
The file where the chunk w... |
Adds the specified path to the output logging paths if it is not
already in the listed paths.
:param path:
The path to add to the logging output paths. If the path is empty
or no path is given, the current working directory will be used
instead.
def add_output_path(path: str = None) ->... |
Removes the specified path from the output logging paths if it is
in the listed paths.
:param path:
The path to remove from the logging output paths. If the path is empty
or no path is given, the current working directory will be used
instead.
def remove_output_path(path: str = None) -... |
Logs a message to the console with the formatting support beyond a simple
print statement or logger statement.
:param message:
The primary log message for the entry
:param whitespace:
The number of lines of whitespace to append to the beginning and end
of the log message when printe... |
Adds data to the message object
def add_to_message(data, indent_level=0) -> list:
"""Adds data to the message object"""
message = []
if isinstance(data, str):
message.append(indent(
dedent(data.strip('\n')).strip(),
indent_level * ' '
))
return message
... |
Adds the specified mode identifier to the list of active modes and returns
a copy of the currently active modes list.
def add(mode_id: str) -> list:
"""
Adds the specified mode identifier to the list of active modes and returns
a copy of the currently active modes list.
"""
if not has(mode_id)... |
Removes the specified mode identifier from the active modes and returns
whether or not a remove operation was carried out. If the mode identifier
is not in the currently active modes, it does need to be removed.
def remove(mode_id: str) -> bool:
"""
Removes the specified mode identifier from the active... |
Clone the redis client to be slowlog-compatible
def clone(client):
'''Clone the redis client to be slowlog-compatible'''
kwargs = client.redis.connection_pool.connection_kwargs
kwargs['parser_class'] = redis.connection.PythonParser
pool = redis.connection.ConnectionPool(**kwargs)
... |
Print timing stats
def pretty(timings, label):
'''Print timing stats'''
results = [(sum(values), len(values), key)
for key, values in timings.items()]
print(label)
print('=' * 65)
print('%20s => %13s | %8s | %13s' % (
'Command', 'Average', '# Calls', 'Tot... |
Get ready for a profiling run
def start(self):
'''Get ready for a profiling run'''
self._configs = self._client.config_get('slow-*')
self._client.config_set('slowlog-max-len', 100000)
self._client.config_set('slowlog-log-slower-than', 0)
self._client.execute_command('slowlog', '... |
Set everything back to normal and collect our data
def stop(self):
'''Set everything back to normal and collect our data'''
for key, value in self._configs.items():
self._client.config_set(key, value)
logs = self._client.execute_command('slowlog', 'get', 100000)
current = {
... |
Print the results of this profiling
def display(self):
'''Print the results of this profiling'''
self.pretty(self._timings, 'Raw Redis Commands')
print()
for key, value in self._commands.items():
self.pretty(value, 'Qless "%s" Command' % key)
print() |
Populates the sub parser with the shell arguments
def add_shell_action(sub_parser: ArgumentParser) -> ArgumentParser:
"""Populates the sub parser with the shell arguments"""
sub_parser.add_argument(
'-p', '--project',
dest='project_directory',
type=str,
default=None
)
... |
Parses the command line arguments and returns a dictionary containing the
results.
:param args:
The command line arguments to parse. If None, the system command line
arguments will be used instead.
def parse(args: list = None) -> dict:
"""
Parses the command line arguments and retu... |
Return all the currently-running jobs
def running(self, offset=0, count=25):
'''Return all the currently-running jobs'''
return self.client('jobs', 'running', self.name, offset, count) |
Return all the currently-stalled jobs
def stalled(self, offset=0, count=25):
'''Return all the currently-stalled jobs'''
return self.client('jobs', 'stalled', self.name, offset, count) |
Return all the currently-scheduled jobs
def scheduled(self, offset=0, count=25):
'''Return all the currently-scheduled jobs'''
return self.client('jobs', 'scheduled', self.name, offset, count) |
Return all the currently dependent jobs
def depends(self, offset=0, count=25):
'''Return all the currently dependent jobs'''
return self.client('jobs', 'depends', self.name, offset, count) |
Return all the recurring jobs
def recurring(self, offset=0, count=25):
'''Return all the recurring jobs'''
return self.client('jobs', 'recurring', self.name, offset, count) |
Return a string representative of the class
def class_string(self, klass):
'''Return a string representative of the class'''
if isinstance(klass, string_types):
return klass
return klass.__module__ + '.' + klass.__name__ |
Either create a new job in the provided queue with the provided
attributes, or move that job into that queue. If the job is being
serviced by a worker, subsequent attempts by that worker to either
`heartbeat` or `complete` the job should fail and return `false`.
The `priority` argument ... |
Place a recurring job in this queue
def recur(self, klass, data, interval, offset=0, priority=None, tags=None,
retries=None, jid=None):
'''Place a recurring job in this queue'''
return self.client('recur', self.name,
jid or uuid.uuid4().hex,
self.class_string(klass),
... |
Passing in the queue from which to pull items, the current time,
when the locks for these returned items should expire, and the number
of items to be popped off.
def pop(self, count=None):
'''Passing in the queue from which to pull items, the current time,
when the locks for these retur... |
Similar to the pop command, except that it merely peeks at the next
items
def peek(self, count=None):
'''Similar to the pop command, except that it merely peeks at the next
items'''
results = [Job(self.client, **rec) for rec in json.loads(
self.client('peek', self.name, coun... |
Return the current statistics for a given queue on a given date.
The results are returned are a JSON blob::
{
'total' : ...,
'mean' : ...,
'variance' : ...,
'histogram': [
...
]
}
... |
Runs the markdown file and renders the contents to the notebook display
:param project:
:param step:
:return:
A run response dictionary containing
def run(
project: 'projects.Project',
step: 'projects.ProjectStep'
) -> dict:
"""
Runs the markdown file and renders the conten... |
Returns a dictionary containing all of the available Cauldron commands
currently registered. This data is cached for performance. Unless the
reload argument is set to True, the command list will only be generated
the first time this function is called.
:param reload:
Whether or not to disregard... |
Returns the execution command to use for the specified module, which may
be different depending upon remote connection
:param command_module:
:param remote_connection:
:return:
def get_command_from_module(
command_module,
remote_connection: environ.RemoteConnection
):
"""
Retur... |
Prints the basic command help to the console
def show_help(command_name: str = None, raw_args: str = '') -> Response:
""" Prints the basic command help to the console """
response = Response()
cmds = fetch()
if command_name and command_name in cmds:
parser, result = parse.get_parser(
... |
1) Get a reference to the module
2) Check the file that module's imported from
3) If that file's been updated, force a reload of that module
return it
def _import(klass):
'''1) Get a reference to the module
2) Check the file that module's imported from
... |
Load the module containing your class, and run the appropriate
method. For example, if this job was popped from the queue
``testing``, then this would invoke the ``testing`` staticmethod of
your class.
def process(self):
'''Load the module containing your class, and run the appropriate
... |
Move this job out of its existing state and into another queue. If
a worker has been given this job, then that worker's attempts to
heartbeat that job will fail. Like ``Queue.put``, this accepts a
delay, and dependencies
def move(self, queue, delay=0, depends=None):
'''Move this job out... |
Turn this job in as complete, optionally advancing it to another
queue. Like ``Queue.put`` and ``move``, it accepts a delay, and
dependencies
def complete(self, nextq=None, delay=None, depends=None):
'''Turn this job in as complete, optionally advancing it to another
queue. Like ``Queue... |
Renew the heartbeat, if possible, and optionally update the job's
user data.
def heartbeat(self):
'''Renew the heartbeat, if possible, and optionally update the job's
user data.'''
logger.debug('Heartbeating %s (ttl = %s)', self.jid, self.ttl)
try:
self.expires_at = ... |
Mark the particular job as failed, with the provided type, and a
more specific message. By `type`, we mean some phrase that might be
one of several categorical modes of failure. The `message` is
something more job-specific, like perhaps a traceback.
This method should __not__ be used to... |
Retry this job in a little bit, in the same queue. This is meant
for the times when you detect a transient failure yourself
def retry(self, delay=0, group=None, message=None):
'''Retry this job in a little bit, in the same queue. This is meant
for the times when you detect a transient failure y... |
Remove specific (or all) job dependencies from this job:
job.remove(jid1, jid2)
job.remove(all=True)
def undepend(self, *args, **kwargs):
'''Remove specific (or all) job dependencies from this job:
job.remove(jid1, jid2)
job.remove(all=True)'''
if kwarg... |
Checks to see if the given file path ends with any of the specified file
extensions. If a file extension does not begin with a '.' it will be added
automatically
:param file_path:
The path on which the extensions will be tested for a match
:param args:
One or more extensions to test for... |
Retrieves the documentation string from the target object and returns it
after removing insignificant whitespace
:param target:
The object for which the doc string should be retrieved
:return:
The cleaned documentation string for the target. If no doc string
exists an empty string w... |
Gets the lines of documentation from the given target, which are formatted
so that each line is a documentation entry.
:param target:
:return:
A list of strings containing the documentation block entries
def get_doc_entries(target: typing.Callable) -> list:
"""
Gets the lines of documentat... |
Parses the documentation for a function, which is specified by the name of
the function and the function itself.
:param name:
Name of the function to parse
:param target:
The function to parse into documentation
:return:
A dictionary containing documentation for the specified fu... |
:param name:
:param target:
:return:
def variable(name: str, target: property) -> typing.Union[None, dict]:
"""
:param name:
:param target:
:return:
"""
if hasattr(target, 'fget'):
doc = parse_function(name, target.fget)
if doc:
doc['read_only'] = bool(targe... |
Reads the current state of the buffer and returns a string those
contents
:return:
A string for the current state of the print buffer contents
def read_all(self) -> str:
"""
Reads the current state of the buffer and returns a string those
contents
:return:
... |
:return:
def flush_all(self) -> str:
"""
:return:
"""
# self.bytes_buffer.seek(0)
# contents = self.bytes_buffer.read()
# self.bytes_buffer.truncate(0)
# self.bytes_buffer.seek(0)
# if contents is None:
# return ''
contents... |
Creates the data object that stores the step information in the notebook
results JavaScript file.
:param step:
Project step for which to create the data
:return:
Step data tuple containing scaffold data structure for the step output.
The dictionary must then be populated with data f... |
Attempts to load and return the cached step data for the specified step. If
not cached data exists, or the cached data is corrupt, a None value is
returned instead.
:param step:
The step for which the cached data should be loaded
:return:
Either a step data structure containing the cac... |
Initializes the logging path for running the project. If no logging path
is specified, the current directory will be used instead.
:param path:
Path to initialize for logging. Can be either a path to a file or
a path to a directory. If a directory is specified, the log file
written will... |
Opens, executes and closes a Cauldron project in a single command in
production mode (non-interactive).
:param project_directory:
Directory where the project to run is located
:param output_directory:
Directory where the project display data will be saved
:param log_path:
Path t... |
Stop all the workers, and then wait for them
def stop(self, sig=signal.SIGINT):
'''Stop all the workers, and then wait for them'''
for cpid in self.sandboxes:
logger.warn('Stopping %i...' % cpid)
try:
os.kill(cpid, sig)
except OSError: # pragma: no c... |
Return a new worker for a child process
def spawn(self, **kwargs):
'''Return a new worker for a child process'''
copy = dict(self.kwargs)
copy.update(kwargs)
# Apparently there's an issue with importing gevent in the parent
# process and then using it int he child. This is meant... |
Run this worker
def run(self):
'''Run this worker'''
self.signals(('TERM', 'INT', 'QUIT'))
# Divide up the jobs that we have to divy up between the workers. This
# produces evenly-sized groups of jobs
resume = self.divide(self.resume, self.count)
for index in range(self.... |
Signal handler for this process
def handler(self, signum, frame): # pragma: no cover
'''Signal handler for this process'''
if signum in (signal.SIGTERM, signal.SIGINT, signal.SIGQUIT):
self.stop(signum)
os._exit(0) |
Returns a list of the current stack frames, which are pruned focus on the
Cauldron code where the relevant information resides.
def get_stack_frames(error_stack: bool = True) -> list:
"""
Returns a list of the current stack frames, which are pruned focus on the
Cauldron code where the relevant informat... |
Formats a raw stack frame into a dictionary formatted for render
templating and enriched with information from the currently open project.
:param stack_frame:
A raw stack frame to turn into an enriched version for templating.
:param project:
The currently open project, which is used to con... |
Returns a list of the stack frames formatted for user display that has
been enriched by the project-specific data.
:param project:
The currently open project used to enrich the stack data.
:param error_stack:
Whether or not to return the error stack. When True the stack of the
... |
Converts the argument type to a string
:param arg_type:
:return:
String representation of the argument type. Multiple return types are
turned into a comma delimited list of type names
def arg_type_to_string(arg_type) -> str:
"""
Converts the argument type to a string
:param arg_ty... |
Merges multiple COMPONENT instances into a single one by merging the
lists of includes and files. Has support for elements of the components
arguments list to be lists or tuples of COMPONENT instances as well.
:param components:
:return:
def merge_components(
*components: typing.List[typing.Un... |
Flattens a list of COMPONENT instances to remove any lists or tuples
of COMPONENTS contained within the list
:param flattened_list:
The existing flattened list that has been populated from previous
calls of this reducer function
:param entry:
An entry to be reduced. Either a COMPONE... |
Reducer function to combine the lists for the specified key into a
single, flat list
:param key:
The key on the COMPONENT instances to operate upon
:param merged_list:
The accumulated list of values populated by previous calls to this
reducer function
:param component:
T... |
Listen for events as they come in
def listen(self):
'''Listen for events as they come in'''
try:
self._pubsub.subscribe(self._channels)
for message in self._pubsub.listen():
if message['type'] == 'message':
yield message
finally:
... |
Run in a thread
def thread(self):
'''Run in a thread'''
thread = threading.Thread(target=self.listen)
thread.start()
try:
yield self
finally:
self.unlisten()
thread.join() |
Listen for events
def listen(self):
'''Listen for events'''
for message in Listener.listen(self):
logger.debug('Message: %s', message)
# Strip off the 'namespace' from the channel
channel = message['channel'][len(self.namespace):]
func = self._callbacks.g... |
Set a callback handler for a pubsub event
def on(self, evt, func):
'''Set a callback handler for a pubsub event'''
if evt not in self._callbacks:
raise NotImplementedError('callback "%s"' % evt)
else:
self._callbacks[evt] = func |
Get a particular option, or the default if it's missing
def get(self, option, default=None):
'''Get a particular option, or the default if it's missing'''
val = self[option]
return (val is None and default) or val |
Just like `dict.pop`
def pop(self, option, default=None):
'''Just like `dict.pop`'''
val = self[option]
del self[option]
return (val is None and default) or val |
Just like `dict.update`
def update(self, other=(), **kwargs):
'''Just like `dict.update`'''
_kwargs = dict(kwargs)
_kwargs.update(other)
for key, value in _kwargs.items():
self[key] = value |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.