repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
sernst/cauldron
cauldron/__init__.py
run_project
def run_project( project_directory: str, output_directory: str = None, logging_path: str = None, reader_path: str = None, reload_project_libraries: bool = False, **kwargs ) -> ExecutionResult: """ 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 written. All of the results files will be written within this directory. If the directory does not exist, it will be created. :param logging_path: The fully-qualified path to a file that will be used for logging. If a directory is specified instead of a file, a file will be created using the default filename of cauldron_run.log. If a file already exists at that location it will be removed and a new file created in its place. :param reader_path: Specifies a path where a reader file will be saved after the project has finished running. If no path is specified, no reader file will be saved. If the path is a directory, a reader file will be saved in that directory with the project name as the file name. :param reload_project_libraries: Whether or not to reload all project libraries prior to execution of the project. By default this is False, but can be enabled in cases where refreshing the project libraries before execution is needed. :param kwargs: Any variables to be available in the cauldron.shared object during execution of the project can be specified here as keyword arguments. :return: A response object that contains information about the run process and the shared data from the final state of the project. """ from cauldron.cli import batcher return batcher.run_project( project_directory=project_directory, output_directory=output_directory, log_path=logging_path, reader_path=reader_path, reload_project_libraries=reload_project_libraries, shared_data=kwargs )
python
def run_project( project_directory: str, output_directory: str = None, logging_path: str = None, reader_path: str = None, reload_project_libraries: bool = False, **kwargs ) -> ExecutionResult: """ 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 written. All of the results files will be written within this directory. If the directory does not exist, it will be created. :param logging_path: The fully-qualified path to a file that will be used for logging. If a directory is specified instead of a file, a file will be created using the default filename of cauldron_run.log. If a file already exists at that location it will be removed and a new file created in its place. :param reader_path: Specifies a path where a reader file will be saved after the project has finished running. If no path is specified, no reader file will be saved. If the path is a directory, a reader file will be saved in that directory with the project name as the file name. :param reload_project_libraries: Whether or not to reload all project libraries prior to execution of the project. By default this is False, but can be enabled in cases where refreshing the project libraries before execution is needed. :param kwargs: Any variables to be available in the cauldron.shared object during execution of the project can be specified here as keyword arguments. :return: A response object that contains information about the run process and the shared data from the final state of the project. """ from cauldron.cli import batcher return batcher.run_project( project_directory=project_directory, output_directory=output_directory, log_path=logging_path, reader_path=reader_path, reload_project_libraries=reload_project_libraries, shared_data=kwargs )
[ "def", "run_project", "(", "project_directory", ":", "str", ",", "output_directory", ":", "str", "=", "None", ",", "logging_path", ":", "str", "=", "None", ",", "reader_path", ":", "str", "=", "None", ",", "reload_project_libraries", ":", "bool", "=", "False...
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 written. All of the results files will be written within this directory. If the directory does not exist, it will be created. :param logging_path: The fully-qualified path to a file that will be used for logging. If a directory is specified instead of a file, a file will be created using the default filename of cauldron_run.log. If a file already exists at that location it will be removed and a new file created in its place. :param reader_path: Specifies a path where a reader file will be saved after the project has finished running. If no path is specified, no reader file will be saved. If the path is a directory, a reader file will be saved in that directory with the project name as the file name. :param reload_project_libraries: Whether or not to reload all project libraries prior to execution of the project. By default this is False, but can be enabled in cases where refreshing the project libraries before execution is needed. :param kwargs: Any variables to be available in the cauldron.shared object during execution of the project can be specified here as keyword arguments. :return: A response object that contains information about the run process and the shared data from the final state of the project.
[ "Runs", "a", "project", "as", "a", "single", "command", "directly", "within", "the", "current", "Python", "interpreter", "." ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/__init__.py#L61-L109
train
44,600
sernst/cauldron
cauldron/environ/response.py
Response.join
def join(self, timeout: float = None) -> bool: """ 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 forever. :return: A boolean indicating whether or not a thread existed to join upon. """ try: self.thread.join(timeout) return True except AttributeError: return False
python
def join(self, timeout: float = None) -> bool: """ 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 forever. :return: A boolean indicating whether or not a thread existed to join upon. """ try: self.thread.join(timeout) return True except AttributeError: return False
[ "def", "join", "(", "self", ",", "timeout", ":", "float", "=", "None", ")", "->", "bool", ":", "try", ":", "self", ".", "thread", ".", "join", "(", "timeout", ")", "return", "True", "except", "AttributeError", ":", "return", "False" ]
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 forever. :return: A boolean indicating whether or not a thread existed to join upon.
[ "Joins", "on", "the", "thread", "associated", "with", "the", "response", "if", "it", "exists", "or", "just", "returns", "after", "a", "no", "-", "op", "if", "no", "thread", "exists", "to", "join", "." ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/environ/response.py#L194-L211
train
44,601
sernst/cauldron
cauldron/environ/response.py
Response.deserialize
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.get('ended', False) r.failed = not serial_data.get('success', True) def load_messages(message_type: str): messages = [ ResponseMessage(**data) for data in serial_data.get(message_type, []) ] setattr(r, message_type, getattr(r, message_type) + messages) load_messages('errors') load_messages('warnings') load_messages('messages') return r
python
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.get('ended', False) r.failed = not serial_data.get('success', True) def load_messages(message_type: str): messages = [ ResponseMessage(**data) for data in serial_data.get(message_type, []) ] setattr(r, message_type, getattr(r, message_type) + messages) load_messages('errors') load_messages('warnings') load_messages('messages') return r
[ "def", "deserialize", "(", "serial_data", ":", "dict", ")", "->", "'Response'", ":", "r", "=", "Response", "(", "serial_data", ".", "get", "(", "'id'", ")", ")", "r", ".", "data", ".", "update", "(", "serial_data", ".", "get", "(", "'data'", ",", "{"...
Converts a serialized dictionary response to a Response object
[ "Converts", "a", "serialized", "dictionary", "response", "to", "a", "Response", "object" ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/environ/response.py#L455-L474
train
44,602
sernst/cauldron
cauldron/cli/threads.py
abort_thread
def abort_thread(): """ 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. """ thread = threading.current_thread() if not isinstance(thread, CauldronThread): return if thread.is_executing and thread.abort: raise ThreadAbortError('User Aborted Execution')
python
def abort_thread(): """ 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. """ thread = threading.current_thread() if not isinstance(thread, CauldronThread): return if thread.is_executing and thread.abort: raise ThreadAbortError('User Aborted Execution')
[ "def", "abort_thread", "(", ")", ":", "thread", "=", "threading", ".", "current_thread", "(", ")", "if", "not", "isinstance", "(", "thread", ",", "CauldronThread", ")", ":", "return", "if", "thread", ".", "is_executing", "and", "thread", ".", "abort", ":",...
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.
[ "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", "onl...
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/cli/threads.py#L105-L119
train
44,603
sernst/cauldron
cauldron/cli/threads.py
CauldronThread.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_seconds() < 0.5 )
python
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_seconds() < 0.5 )
[ "def", "is_running", "(", "self", ")", "->", "bool", ":", "return", "(", "self", ".", "_has_started", "and", "self", ".", "is_alive", "(", ")", "or", "self", ".", "completed_at", "is", "None", "or", "(", "datetime", ".", "utcnow", "(", ")", "-", "sel...
Specifies whether or not the thread is running
[ "Specifies", "whether", "or", "not", "the", "thread", "is", "running" ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/cli/threads.py#L42-L49
train
44,604
sernst/cauldron
cauldron/cli/threads.py
CauldronThread.run
def run(self): """ 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. """ async def run_command(): try: self.result = self.command( context=self.context, **self.kwargs ) except Exception as error: self.exception = error print(error) import traceback traceback.print_exc() import sys self.context.response.fail( code='COMMAND_EXECUTION_ERROR', message='Failed to execute command due to internal error', error=error ).console( whitespace=1 ) self._has_started = True self._loop = asyncio.new_event_loop() self._loop.run_until_complete(run_command()) self._loop.close() self._loop = None self.completed_at = datetime.utcnow()
python
def run(self): """ 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. """ async def run_command(): try: self.result = self.command( context=self.context, **self.kwargs ) except Exception as error: self.exception = error print(error) import traceback traceback.print_exc() import sys self.context.response.fail( code='COMMAND_EXECUTION_ERROR', message='Failed to execute command due to internal error', error=error ).console( whitespace=1 ) self._has_started = True self._loop = asyncio.new_event_loop() self._loop.run_until_complete(run_command()) self._loop.close() self._loop = None self.completed_at = datetime.utcnow()
[ "def", "run", "(", "self", ")", ":", "async", "def", "run_command", "(", ")", ":", "try", ":", "self", ".", "result", "=", "self", ".", "command", "(", "context", "=", "self", ".", "context", ",", "*", "*", "self", ".", "kwargs", ")", "except", "...
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.
[ "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", "."...
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/cli/threads.py#L51-L83
train
44,605
sernst/cauldron
cauldron/cli/threads.py
CauldronThread.abort_running
def abort_running(self) -> bool: """ 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. """ if not self._loop: return False try: self._loop.stop() return True except Exception: return False finally: self.completed_at = datetime.utcnow()
python
def abort_running(self) -> bool: """ 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. """ if not self._loop: return False try: self._loop.stop() return True except Exception: return False finally: self.completed_at = datetime.utcnow()
[ "def", "abort_running", "(", "self", ")", "->", "bool", ":", "if", "not", "self", ".", "_loop", ":", "return", "False", "try", ":", "self", ".", "_loop", ".", "stop", "(", ")", "return", "True", "except", "Exception", ":", "return", "False", "finally",...
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.
[ "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", "pr...
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/cli/threads.py#L85-L102
train
44,606
sernst/cauldron
cauldron/cli/server/arguments.py
from_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: json_args = None try: get_args = request.values except Exception: get_args = None arg_sources = list(filter( lambda arg: arg is not None, [json_args, get_args, {}] )) return arg_sources[0]
python
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: json_args = None try: get_args = request.values except Exception: get_args = None arg_sources = list(filter( lambda arg: arg is not None, [json_args, get_args, {}] )) return arg_sources[0]
[ "def", "from_request", "(", "request", "=", "None", ")", "->", "dict", ":", "request", "=", "request", "if", "request", "else", "flask_request", "try", ":", "json_args", "=", "request", ".", "get_json", "(", "silent", "=", "True", ")", "except", "Exception...
Fetches the arguments for the current Flask application request
[ "Fetches", "the", "arguments", "for", "the", "current", "Flask", "application", "request" ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/cli/server/arguments.py#L4-L24
train
44,607
myaooo/pysbrl
pysbrl/rule_list.py
rule_str2rule
def rule_str2rule(rule_str, prob): # type: (str, float) -> Rule """ 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 """ if rule_str == "default": return Rule([], prob) raw_rules = rule_str[1:-1].split(",") clauses = [] for raw_rule in raw_rules: idx = raw_rule.find("=") if idx == -1: raise ValueError("No \"=\" find in the rule!") clauses.append(Clause(int(raw_rule[1:idx]), int(raw_rule[(idx + 1):]))) return Rule(clauses, prob)
python
def rule_str2rule(rule_str, prob): # type: (str, float) -> Rule """ 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 """ if rule_str == "default": return Rule([], prob) raw_rules = rule_str[1:-1].split(",") clauses = [] for raw_rule in raw_rules: idx = raw_rule.find("=") if idx == -1: raise ValueError("No \"=\" find in the rule!") clauses.append(Clause(int(raw_rule[1:idx]), int(raw_rule[(idx + 1):]))) return Rule(clauses, prob)
[ "def", "rule_str2rule", "(", "rule_str", ",", "prob", ")", ":", "# type: (str, float) -> Rule", "if", "rule_str", "==", "\"default\"", ":", "return", "Rule", "(", "[", "]", ",", "prob", ")", "raw_rules", "=", "rule_str", "[", "1", ":", "-", "1", "]", "."...
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
[ "A", "helper", "function", "that", "converts", "the", "resulting", "string", "returned", "from", "C", "function", "to", "the", "Rule", "object" ]
74bba8c6913a7f82e32313108f8c3e025b89d9c7
https://github.com/myaooo/pysbrl/blob/74bba8c6913a7f82e32313108f8c3e025b89d9c7/pysbrl/rule_list.py#L106-L125
train
44,608
sernst/cauldron
cauldron/session/caching.py
SharedCache.put
def put(self, *args, **kwargs) -> 'SharedCache': """ 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) ``` would add two variables to the cache where the value of _a_ would be 1 and the value of _b_ would be False. :param kwargs: Keyword arguments to be added to the cache, which are name value pairs like standard keyword named arguments in Python. For example: ``` put(a=1, b=False) ``` would add two variables to the cache where the value of _a_ would be 1 and the value of _b_ would be False. """ environ.abort_thread() index = 0 while index < (len(args) - 1): key = args[index] value = args[index + 1] self._shared_cache_data[key] = value index += 2 for key, value in kwargs.items(): if value is None and key in self._shared_cache_data: del self._shared_cache_data[key] else: self._shared_cache_data[key] = value return self
python
def put(self, *args, **kwargs) -> 'SharedCache': """ 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) ``` would add two variables to the cache where the value of _a_ would be 1 and the value of _b_ would be False. :param kwargs: Keyword arguments to be added to the cache, which are name value pairs like standard keyword named arguments in Python. For example: ``` put(a=1, b=False) ``` would add two variables to the cache where the value of _a_ would be 1 and the value of _b_ would be False. """ environ.abort_thread() index = 0 while index < (len(args) - 1): key = args[index] value = args[index + 1] self._shared_cache_data[key] = value index += 2 for key, value in kwargs.items(): if value is None and key in self._shared_cache_data: del self._shared_cache_data[key] else: self._shared_cache_data[key] = value return self
[ "def", "put", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "'SharedCache'", ":", "environ", ".", "abort_thread", "(", ")", "index", "=", "0", "while", "index", "<", "(", "len", "(", "args", ")", "-", "1", ")", ":", "key", ...
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) ``` would add two variables to the cache where the value of _a_ would be 1 and the value of _b_ would be False. :param kwargs: Keyword arguments to be added to the cache, which are name value pairs like standard keyword named arguments in Python. For example: ``` put(a=1, b=False) ``` would add two variables to the cache where the value of _a_ would be 1 and the value of _b_ would be False.
[ "Adds", "one", "or", "more", "variables", "to", "the", "cache", "." ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/caching.py#L25-L67
train
44,609
sernst/cauldron
cauldron/session/caching.py
SharedCache.grab
def grab( self, *keys: typing.List[str], default_value=None ) -> typing.Tuple: """ 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. :param default_value: If one or more of the keys is not found within the cache, this value will be returned as the missing value. :return: A tuple containing values for each of the keys specified in the arguments """ return tuple([self.fetch(k, default_value) for k in keys])
python
def grab( self, *keys: typing.List[str], default_value=None ) -> typing.Tuple: """ 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. :param default_value: If one or more of the keys is not found within the cache, this value will be returned as the missing value. :return: A tuple containing values for each of the keys specified in the arguments """ return tuple([self.fetch(k, default_value) for k in keys])
[ "def", "grab", "(", "self", ",", "*", "keys", ":", "typing", ".", "List", "[", "str", "]", ",", "default_value", "=", "None", ")", "->", "typing", ".", "Tuple", ":", "return", "tuple", "(", "[", "self", ".", "fetch", "(", "k", ",", "default_value",...
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. :param default_value: If one or more of the keys is not found within the cache, this value will be returned as the missing value. :return: A tuple containing values for each of the keys specified in the arguments
[ "Returns", "a", "tuple", "containing", "multiple", "values", "from", "the", "cache", "specified", "by", "the", "keys", "arguments" ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/caching.py#L69-L90
train
44,610
sernst/cauldron
cauldron/session/caching.py
SharedCache.fetch
def fetch(self, key: typing.Union[str, None], default_value=None): """ 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 key if it exists in the cache or the default_Value if it does not """ environ.abort_thread() if key is None: return self._shared_cache_data return self._shared_cache_data.get(key, default_value)
python
def fetch(self, key: typing.Union[str, None], default_value=None): """ 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 key if it exists in the cache or the default_Value if it does not """ environ.abort_thread() if key is None: return self._shared_cache_data return self._shared_cache_data.get(key, default_value)
[ "def", "fetch", "(", "self", ",", "key", ":", "typing", ".", "Union", "[", "str", ",", "None", "]", ",", "default_value", "=", "None", ")", ":", "environ", ".", "abort_thread", "(", ")", "if", "key", "is", "None", ":", "return", "self", ".", "_shar...
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 key if it exists in the cache or the default_Value if it does not
[ "Retrieves", "the", "value", "of", "the", "specified", "variable", "from", "the", "cache" ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/caching.py#L92-L110
train
44,611
myaooo/pysbrl
pysbrl/train.py
train_sbrl
def train_sbrl(data_file, label_file, lambda_=20, eta=2, max_iters=300000, n_chains=20, alpha=1, seed=None, verbose=0): """ 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 convert categorical data to the required format :param data_file: The data file :param label_file: The label file :param lambda_: A hyper parameter, the prior representing the expected length of the rule list :param eta: A hyper parameter, the prior representing the expected length of each rule :param max_iters: The maximum iteration of the algo :param n_chains: The number of markov chains to run :param alpha: The prior of the output probability distribution, see the paper for more detail. :return: A tuple of (`rule_ids`, `outputs`, `rule_strings`) `rule_ids`: the list of ids of rules `outputs`: the outputs matrix (prob distribution as a vector per rule) `rule_strings`: the whole list of rules in the format of strings like `u'{c2=x,c4=o,c5=b}'`. """ if isinstance(alpha, int): alphas = np.array([alpha], dtype=np.int32) elif isinstance(alpha, list): for a in alpha: assert isinstance(a, int) alphas = np.array(alpha, dtype=np.int32) else: raise ValueError('the argument alpha can only be int or List[int]') if seed is None: seed = -1 if not os.path.isfile(data_file): raise FileNotFoundError('data file %s does not exists!' % data_file) if not os.path.isfile(label_file): raise FileNotFoundError('label file %s does not exists!' % label_file) return _train(data_file, label_file, lambda_, eta, max_iters, n_chains, alphas, seed, verbose)
python
def train_sbrl(data_file, label_file, lambda_=20, eta=2, max_iters=300000, n_chains=20, alpha=1, seed=None, verbose=0): """ 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 convert categorical data to the required format :param data_file: The data file :param label_file: The label file :param lambda_: A hyper parameter, the prior representing the expected length of the rule list :param eta: A hyper parameter, the prior representing the expected length of each rule :param max_iters: The maximum iteration of the algo :param n_chains: The number of markov chains to run :param alpha: The prior of the output probability distribution, see the paper for more detail. :return: A tuple of (`rule_ids`, `outputs`, `rule_strings`) `rule_ids`: the list of ids of rules `outputs`: the outputs matrix (prob distribution as a vector per rule) `rule_strings`: the whole list of rules in the format of strings like `u'{c2=x,c4=o,c5=b}'`. """ if isinstance(alpha, int): alphas = np.array([alpha], dtype=np.int32) elif isinstance(alpha, list): for a in alpha: assert isinstance(a, int) alphas = np.array(alpha, dtype=np.int32) else: raise ValueError('the argument alpha can only be int or List[int]') if seed is None: seed = -1 if not os.path.isfile(data_file): raise FileNotFoundError('data file %s does not exists!' % data_file) if not os.path.isfile(label_file): raise FileNotFoundError('label file %s does not exists!' % label_file) return _train(data_file, label_file, lambda_, eta, max_iters, n_chains, alphas, seed, verbose)
[ "def", "train_sbrl", "(", "data_file", ",", "label_file", ",", "lambda_", "=", "20", ",", "eta", "=", "2", ",", "max_iters", "=", "300000", ",", "n_chains", "=", "20", ",", "alpha", "=", "1", ",", "seed", "=", "None", ",", "verbose", "=", "0", ")",...
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 convert categorical data to the required format :param data_file: The data file :param label_file: The label file :param lambda_: A hyper parameter, the prior representing the expected length of the rule list :param eta: A hyper parameter, the prior representing the expected length of each rule :param max_iters: The maximum iteration of the algo :param n_chains: The number of markov chains to run :param alpha: The prior of the output probability distribution, see the paper for more detail. :return: A tuple of (`rule_ids`, `outputs`, `rule_strings`) `rule_ids`: the list of ids of rules `outputs`: the outputs matrix (prob distribution as a vector per rule) `rule_strings`: the whole list of rules in the format of strings like `u'{c2=x,c4=o,c5=b}'`.
[ "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...
74bba8c6913a7f82e32313108f8c3e025b89d9c7
https://github.com/myaooo/pysbrl/blob/74bba8c6913a7f82e32313108f8c3e025b89d9c7/pysbrl/train.py#L11-L46
train
44,612
ayoungprogrammer/Lango
lango/parser.py
OldStanfordLibParser.parse
def parse(self, line): """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 """ tree = list(self.parser.raw_parse(line))[0] tree = tree[0] return tree
python
def parse(self, line): """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 """ tree = list(self.parser.raw_parse(line))[0] tree = tree[0] return tree
[ "def", "parse", "(", "self", ",", "line", ")", ":", "tree", "=", "list", "(", "self", ".", "parser", ".", "raw_parse", "(", "line", ")", ")", "[", "0", "]", "tree", "=", "tree", "[", "0", "]", "return", "tree" ]
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
[ "Returns", "tree", "objects", "from", "a", "sentence" ]
0c4284c153abc2d8de4b03a86731bd84385e6afa
https://github.com/ayoungprogrammer/Lango/blob/0c4284c153abc2d8de4b03a86731bd84385e6afa/lango/parser.py#L22-L34
train
44,613
sernst/cauldron
cauldron/cli/sync/sync_io.py
pack_chunk
def pack_chunk(source_data: bytes) -> str: """ 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 """ if not source_data: return '' chunk_compressed = zlib.compress(source_data) return binascii.b2a_base64(chunk_compressed).decode('utf-8')
python
def pack_chunk(source_data: bytes) -> str: """ 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 """ if not source_data: return '' chunk_compressed = zlib.compress(source_data) return binascii.b2a_base64(chunk_compressed).decode('utf-8')
[ "def", "pack_chunk", "(", "source_data", ":", "bytes", ")", "->", "str", ":", "if", "not", "source_data", ":", "return", "''", "chunk_compressed", "=", "zlib", ".", "compress", "(", "source_data", ")", "return", "binascii", ".", "b2a_base64", "(", "chunk_com...
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
[ "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", "." ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/cli/sync/sync_io.py#L12-L25
train
44,614
sernst/cauldron
cauldron/cli/sync/sync_io.py
unpack_chunk
def unpack_chunk(chunk_data: str) -> bytes: """ 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. """ if not chunk_data: return b'' chunk_compressed = binascii.a2b_base64(chunk_data.encode('utf-8')) return zlib.decompress(chunk_compressed)
python
def unpack_chunk(chunk_data: str) -> bytes: """ 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. """ if not chunk_data: return b'' chunk_compressed = binascii.a2b_base64(chunk_data.encode('utf-8')) return zlib.decompress(chunk_compressed)
[ "def", "unpack_chunk", "(", "chunk_data", ":", "str", ")", "->", "bytes", ":", "if", "not", "chunk_data", ":", "return", "b''", "chunk_compressed", "=", "binascii", ".", "a2b_base64", "(", "chunk_data", ".", "encode", "(", "'utf-8'", ")", ")", "return", "z...
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.
[ "Unpacks", "a", "previously", "packed", "chunk", "data", "back", "into", "the", "original", "bytes", "representation" ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/cli/sync/sync_io.py#L28-L42
train
44,615
sernst/cauldron
cauldron/cli/sync/sync_io.py
get_file_chunk_count
def get_file_chunk_count( file_path: str, chunk_size: int = DEFAULT_CHUNK_SIZE ) -> int: """ 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 entire contents of the specified file for the given chunk size """ if not os.path.exists(file_path): return 0 file_size = os.path.getsize(file_path) return max(1, int(math.ceil(file_size / chunk_size)))
python
def get_file_chunk_count( file_path: str, chunk_size: int = DEFAULT_CHUNK_SIZE ) -> int: """ 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 entire contents of the specified file for the given chunk size """ if not os.path.exists(file_path): return 0 file_size = os.path.getsize(file_path) return max(1, int(math.ceil(file_size / chunk_size)))
[ "def", "get_file_chunk_count", "(", "file_path", ":", "str", ",", "chunk_size", ":", "int", "=", "DEFAULT_CHUNK_SIZE", ")", "->", "int", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "file_path", ")", ":", "return", "0", "file_size", "=", "os"...
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 entire contents of the specified file for the given chunk size
[ "Determines", "the", "number", "of", "chunks", "necessary", "to", "send", "the", "file", "for", "the", "given", "chunk", "size" ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/cli/sync/sync_io.py#L45-L65
train
44,616
sernst/cauldron
cauldron/cli/sync/sync_io.py
read_file_chunks
def read_file_chunks( file_path: str, chunk_size: int = DEFAULT_CHUNK_SIZE ) -> bytes: """ 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 than or equal to this size as the remainder. """ chunk_count = get_file_chunk_count(file_path, chunk_size) if chunk_count < 1: return '' with open(file_path, mode='rb') as fp: for chunk_index in range(chunk_count): source = fp.read(chunk_size) chunk = pack_chunk(source) yield chunk
python
def read_file_chunks( file_path: str, chunk_size: int = DEFAULT_CHUNK_SIZE ) -> bytes: """ 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 than or equal to this size as the remainder. """ chunk_count = get_file_chunk_count(file_path, chunk_size) if chunk_count < 1: return '' with open(file_path, mode='rb') as fp: for chunk_index in range(chunk_count): source = fp.read(chunk_size) chunk = pack_chunk(source) yield chunk
[ "def", "read_file_chunks", "(", "file_path", ":", "str", ",", "chunk_size", ":", "int", "=", "DEFAULT_CHUNK_SIZE", ")", "->", "bytes", ":", "chunk_count", "=", "get_file_chunk_count", "(", "file_path", ",", "chunk_size", ")", "if", "chunk_count", "<", "1", ":"...
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 than or equal to this size as the remainder.
[ "Reads", "the", "specified", "file", "in", "chunks", "and", "returns", "a", "generator", "where", "each", "returned", "chunk", "is", "a", "compressed", "base64", "encoded", "string", "for", "sync", "transmission" ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/cli/sync/sync_io.py#L68-L92
train
44,617
sernst/cauldron
cauldron/cli/sync/sync_io.py
write_file_chunk
def write_file_chunk( file_path: str, packed_chunk: str, append: bool = True, offset: int = -1 ): """ 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 will be written or appended :param packed_chunk: The packed chunk data to write to the file. It will be unpacked before the file is written. :param append: Whether or not the chunk should be appended to the existing file. If False the chunk data will overwrite the existing file. :param offset: The byte offset in the file where the chunk should be written. If the value is less than zero, the chunk will be written or appended based on the `append` argument. Note that if you indicate an append write mode and an offset, the mode will be forced to write instead of append. """ mode = 'ab' if append else 'wb' contents = unpack_chunk(packed_chunk) writer.write_file(file_path, contents, mode=mode, offset=offset)
python
def write_file_chunk( file_path: str, packed_chunk: str, append: bool = True, offset: int = -1 ): """ 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 will be written or appended :param packed_chunk: The packed chunk data to write to the file. It will be unpacked before the file is written. :param append: Whether or not the chunk should be appended to the existing file. If False the chunk data will overwrite the existing file. :param offset: The byte offset in the file where the chunk should be written. If the value is less than zero, the chunk will be written or appended based on the `append` argument. Note that if you indicate an append write mode and an offset, the mode will be forced to write instead of append. """ mode = 'ab' if append else 'wb' contents = unpack_chunk(packed_chunk) writer.write_file(file_path, contents, mode=mode, offset=offset)
[ "def", "write_file_chunk", "(", "file_path", ":", "str", ",", "packed_chunk", ":", "str", ",", "append", ":", "bool", "=", "True", ",", "offset", ":", "int", "=", "-", "1", ")", ":", "mode", "=", "'ab'", "if", "append", "else", "'wb'", "contents", "=...
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 will be written or appended :param packed_chunk: The packed chunk data to write to the file. It will be unpacked before the file is written. :param append: Whether or not the chunk should be appended to the existing file. If False the chunk data will overwrite the existing file. :param offset: The byte offset in the file where the chunk should be written. If the value is less than zero, the chunk will be written or appended based on the `append` argument. Note that if you indicate an append write mode and an offset, the mode will be forced to write instead of append.
[ "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...
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/cli/sync/sync_io.py#L95-L124
train
44,618
sernst/cauldron
cauldron/environ/logger.py
add_output_path
def add_output_path(path: str = None) -> str: """ 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. """ cleaned = paths.clean(path or os.getcwd()) if cleaned not in _logging_paths: _logging_paths.append(cleaned) return cleaned
python
def add_output_path(path: str = None) -> str: """ 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. """ cleaned = paths.clean(path or os.getcwd()) if cleaned not in _logging_paths: _logging_paths.append(cleaned) return cleaned
[ "def", "add_output_path", "(", "path", ":", "str", "=", "None", ")", "->", "str", ":", "cleaned", "=", "paths", ".", "clean", "(", "path", "or", "os", ".", "getcwd", "(", ")", ")", "if", "cleaned", "not", "in", "_logging_paths", ":", "_logging_paths", ...
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.
[ "Adds", "the", "specified", "path", "to", "the", "output", "logging", "paths", "if", "it", "is", "not", "already", "in", "the", "listed", "paths", "." ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/environ/logger.py#L14-L27
train
44,619
sernst/cauldron
cauldron/environ/logger.py
remove_output_path
def remove_output_path(path: str = None) -> str: """ 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. """ cleaned = paths.clean(path or os.getcwd()) if cleaned in _logging_paths: _logging_paths.remove(path) return cleaned
python
def remove_output_path(path: str = None) -> str: """ 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. """ cleaned = paths.clean(path or os.getcwd()) if cleaned in _logging_paths: _logging_paths.remove(path) return cleaned
[ "def", "remove_output_path", "(", "path", ":", "str", "=", "None", ")", "->", "str", ":", "cleaned", "=", "paths", ".", "clean", "(", "path", "or", "os", ".", "getcwd", "(", ")", ")", "if", "cleaned", "in", "_logging_paths", ":", "_logging_paths", ".",...
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.
[ "Removes", "the", "specified", "path", "from", "the", "output", "logging", "paths", "if", "it", "is", "in", "the", "listed", "paths", "." ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/environ/logger.py#L30-L43
train
44,620
sernst/cauldron
cauldron/environ/logger.py
log
def log( message: typing.Union[str, typing.List[str]], whitespace: int = 0, whitespace_top: int = 0, whitespace_bottom: int = 0, indent_by: int = 0, trace: bool = True, file_path: str = None, append_to_file: bool = True, **kwargs ) -> str: """ 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 printed to the console :param whitespace_top: The number of lines of whitespace to append to the beginning only of the log message when printed to the console. If whitespace_top and whitespace are both specified, the larger of the two values will be used. :param whitespace_bottom: The number of lines of whitespace to append to the end of the log message when printed to the console. If whitespace_bottom and whitespace are both specified, the larger of hte two values will be used. :param indent_by: The number of spaces that each line of text should be indented :param trace: Whether or not to trace the output to the console :param file_path: A path to a logging file where the output should be written :param append_to_file: Whether or not the log entry should be overwritten or appended to the log file specified in the file_path argument :param kwargs: """ m = add_to_message(message) for key, value in kwargs.items(): m.append('{key}: {value}'.format(key=key, value=value)) pre_whitespace = int(max(whitespace, whitespace_top)) post_whitespace = int(max(whitespace, whitespace_bottom)) if pre_whitespace: m.insert(0, max(0, pre_whitespace - 1) * '\n') if post_whitespace: m.append(max(0, post_whitespace - 1) * '\n') message = indent('\n'.join(m), ' ' * indent_by) raw( message=message, trace=trace, file_path=file_path, append_to_file=append_to_file ) return message
python
def log( message: typing.Union[str, typing.List[str]], whitespace: int = 0, whitespace_top: int = 0, whitespace_bottom: int = 0, indent_by: int = 0, trace: bool = True, file_path: str = None, append_to_file: bool = True, **kwargs ) -> str: """ 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 printed to the console :param whitespace_top: The number of lines of whitespace to append to the beginning only of the log message when printed to the console. If whitespace_top and whitespace are both specified, the larger of the two values will be used. :param whitespace_bottom: The number of lines of whitespace to append to the end of the log message when printed to the console. If whitespace_bottom and whitespace are both specified, the larger of hte two values will be used. :param indent_by: The number of spaces that each line of text should be indented :param trace: Whether or not to trace the output to the console :param file_path: A path to a logging file where the output should be written :param append_to_file: Whether or not the log entry should be overwritten or appended to the log file specified in the file_path argument :param kwargs: """ m = add_to_message(message) for key, value in kwargs.items(): m.append('{key}: {value}'.format(key=key, value=value)) pre_whitespace = int(max(whitespace, whitespace_top)) post_whitespace = int(max(whitespace, whitespace_bottom)) if pre_whitespace: m.insert(0, max(0, pre_whitespace - 1) * '\n') if post_whitespace: m.append(max(0, post_whitespace - 1) * '\n') message = indent('\n'.join(m), ' ' * indent_by) raw( message=message, trace=trace, file_path=file_path, append_to_file=append_to_file ) return message
[ "def", "log", "(", "message", ":", "typing", ".", "Union", "[", "str", ",", "typing", ".", "List", "[", "str", "]", "]", ",", "whitespace", ":", "int", "=", "0", ",", "whitespace_top", ":", "int", "=", "0", ",", "whitespace_bottom", ":", "int", "="...
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 printed to the console :param whitespace_top: The number of lines of whitespace to append to the beginning only of the log message when printed to the console. If whitespace_top and whitespace are both specified, the larger of the two values will be used. :param whitespace_bottom: The number of lines of whitespace to append to the end of the log message when printed to the console. If whitespace_bottom and whitespace are both specified, the larger of hte two values will be used. :param indent_by: The number of spaces that each line of text should be indented :param trace: Whether or not to trace the output to the console :param file_path: A path to a logging file where the output should be written :param append_to_file: Whether or not the log entry should be overwritten or appended to the log file specified in the file_path argument :param kwargs:
[ "Logs", "a", "message", "to", "the", "console", "with", "the", "formatting", "support", "beyond", "a", "simple", "print", "statement", "or", "logger", "statement", "." ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/environ/logger.py#L128-L188
train
44,621
sernst/cauldron
cauldron/environ/logger.py
add_to_message
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 for line in data: offset = 0 if isinstance(line, str) else 1 message += add_to_message(line, indent_level + offset) return message
python
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 for line in data: offset = 0 if isinstance(line, str) else 1 message += add_to_message(line, indent_level + offset) return message
[ "def", "add_to_message", "(", "data", ",", "indent_level", "=", "0", ")", "->", "list", ":", "message", "=", "[", "]", "if", "isinstance", "(", "data", ",", "str", ")", ":", "message", ".", "append", "(", "indent", "(", "dedent", "(", "data", ".", ...
Adds data to the message object
[ "Adds", "data", "to", "the", "message", "object" ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/environ/logger.py#L226-L240
train
44,622
sernst/cauldron
cauldron/environ/modes.py
add
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): _current_modes.append(mode_id) return _current_modes.copy()
python
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): _current_modes.append(mode_id) return _current_modes.copy()
[ "def", "add", "(", "mode_id", ":", "str", ")", "->", "list", ":", "if", "not", "has", "(", "mode_id", ")", ":", "_current_modes", ".", "append", "(", "mode_id", ")", "return", "_current_modes", ".", "copy", "(", ")" ]
Adds the specified mode identifier to the list of active modes and returns a copy of the currently active modes list.
[ "Adds", "the", "specified", "mode", "identifier", "to", "the", "list", "of", "active", "modes", "and", "returns", "a", "copy", "of", "the", "currently", "active", "modes", "list", "." ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/environ/modes.py#L20-L28
train
44,623
sernst/cauldron
cauldron/environ/modes.py
remove
def remove(mode_id: str) -> bool: """ 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. """ had_mode = has(mode_id) if had_mode: _current_modes.remove(mode_id) return had_mode
python
def remove(mode_id: str) -> bool: """ 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. """ had_mode = has(mode_id) if had_mode: _current_modes.remove(mode_id) return had_mode
[ "def", "remove", "(", "mode_id", ":", "str", ")", "->", "bool", ":", "had_mode", "=", "has", "(", "mode_id", ")", "if", "had_mode", ":", "_current_modes", ".", "remove", "(", "mode_id", ")", "return", "had_mode" ]
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.
[ "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...
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/environ/modes.py#L31-L43
train
44,624
seomoz/qless-py
qless/profile.py
Profiler.clone
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) return redis.Redis(connection_pool=pool)
python
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) return redis.Redis(connection_pool=pool)
[ "def", "clone", "(", "client", ")", ":", "kwargs", "=", "client", ".", "redis", ".", "connection_pool", ".", "connection_kwargs", "kwargs", "[", "'parser_class'", "]", "=", "redis", ".", "connection", ".", "PythonParser", "pool", "=", "redis", ".", "connecti...
Clone the redis client to be slowlog-compatible
[ "Clone", "the", "redis", "client", "to", "be", "slowlog", "-", "compatible" ]
3eda4ffcd4c0016c9a7e44f780d6155e1a354dda
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/profile.py#L12-L17
train
44,625
seomoz/qless-py
qless/profile.py
Profiler.pretty
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', 'Total time')) print('-' * 65) for total, length, key in sorted(results, reverse=True): print('%20s => %10.5f us | %8i | %10i us' % ( key, float(total) / length, length, total))
python
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', 'Total time')) print('-' * 65) for total, length, key in sorted(results, reverse=True): print('%20s => %10.5f us | %8i | %10i us' % ( key, float(total) / length, length, total))
[ "def", "pretty", "(", "timings", ",", "label", ")", ":", "results", "=", "[", "(", "sum", "(", "values", ")", ",", "len", "(", "values", ")", ",", "key", ")", "for", "key", ",", "values", "in", "timings", ".", "items", "(", ")", "]", "print", "...
Print timing stats
[ "Print", "timing", "stats" ]
3eda4ffcd4c0016c9a7e44f780d6155e1a354dda
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/profile.py#L20-L31
train
44,626
seomoz/qless-py
qless/profile.py
Profiler.start
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', 'reset')
python
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', 'reset')
[ "def", "start", "(", "self", ")", ":", "self", ".", "_configs", "=", "self", ".", "_client", ".", "config_get", "(", "'slow-*'", ")", "self", ".", "_client", ".", "config_set", "(", "'slowlog-max-len'", ",", "100000", ")", "self", ".", "_client", ".", ...
Get ready for a profiling run
[ "Get", "ready", "for", "a", "profiling", "run" ]
3eda4ffcd4c0016c9a7e44f780d6155e1a354dda
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/profile.py#L39-L44
train
44,627
seomoz/qless-py
qless/profile.py
Profiler.stop
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 = { 'name': None, 'accumulated': defaultdict(list) } for _, _, duration, request in logs: command = request[0] if command == 'slowlog': continue if 'eval' in command.lower(): subcommand = request[3] self._timings['qless-%s' % subcommand].append(duration) if current['name']: if current['name'] not in self._commands: self._commands[current['name']] = defaultdict(list) for key, values in current['accumulated'].items(): self._commands[current['name']][key].extend(values) current = { 'name': subcommand, 'accumulated': defaultdict(list) } else: self._timings[command].append(duration) if current['name']: current['accumulated'][command].append(duration) # Include the last if current['name']: if current['name'] not in self._commands: self._commands[current['name']] = defaultdict(list) for key, values in current['accumulated'].items(): self._commands[current['name']][key].extend(values)
python
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 = { 'name': None, 'accumulated': defaultdict(list) } for _, _, duration, request in logs: command = request[0] if command == 'slowlog': continue if 'eval' in command.lower(): subcommand = request[3] self._timings['qless-%s' % subcommand].append(duration) if current['name']: if current['name'] not in self._commands: self._commands[current['name']] = defaultdict(list) for key, values in current['accumulated'].items(): self._commands[current['name']][key].extend(values) current = { 'name': subcommand, 'accumulated': defaultdict(list) } else: self._timings[command].append(duration) if current['name']: current['accumulated'][command].append(duration) # Include the last if current['name']: if current['name'] not in self._commands: self._commands[current['name']] = defaultdict(list) for key, values in current['accumulated'].items(): self._commands[current['name']][key].extend(values)
[ "def", "stop", "(", "self", ")", ":", "for", "key", ",", "value", "in", "self", ".", "_configs", ".", "items", "(", ")", ":", "self", ".", "_client", ".", "config_set", "(", "key", ",", "value", ")", "logs", "=", "self", ".", "_client", ".", "exe...
Set everything back to normal and collect our data
[ "Set", "everything", "back", "to", "normal", "and", "collect", "our", "data" ]
3eda4ffcd4c0016c9a7e44f780d6155e1a354dda
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/profile.py#L46-L78
train
44,628
seomoz/qless-py
qless/profile.py
Profiler.display
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()
python
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()
[ "def", "display", "(", "self", ")", ":", "self", ".", "pretty", "(", "self", ".", "_timings", ",", "'Raw Redis Commands'", ")", "print", "(", ")", "for", "key", ",", "value", "in", "self", ".", "_commands", ".", "items", "(", ")", ":", "self", ".", ...
Print the results of this profiling
[ "Print", "the", "results", "of", "this", "profiling" ]
3eda4ffcd4c0016c9a7e44f780d6155e1a354dda
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/profile.py#L80-L86
train
44,629
sernst/cauldron
cauldron/invoke/parser.py
add_shell_action
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 ) sub_parser.add_argument( '-l', '--log', dest='logging_path', type=str, default=None ) sub_parser.add_argument( '-o', '--output', dest='output_directory', type=str, default=None ) sub_parser.add_argument( '-s', '--shared', dest='shared_data_path', type=str, default=None ) return sub_parser
python
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 ) sub_parser.add_argument( '-l', '--log', dest='logging_path', type=str, default=None ) sub_parser.add_argument( '-o', '--output', dest='output_directory', type=str, default=None ) sub_parser.add_argument( '-s', '--shared', dest='shared_data_path', type=str, default=None ) return sub_parser
[ "def", "add_shell_action", "(", "sub_parser", ":", "ArgumentParser", ")", "->", "ArgumentParser", ":", "sub_parser", ".", "add_argument", "(", "'-p'", ",", "'--project'", ",", "dest", "=", "'project_directory'", ",", "type", "=", "str", ",", "default", "=", "N...
Populates the sub parser with the shell arguments
[ "Populates", "the", "sub", "parser", "with", "the", "shell", "arguments" ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/invoke/parser.py#L11-L42
train
44,630
seomoz/qless-py
qless/queue.py
Jobs.running
def running(self, offset=0, count=25): '''Return all the currently-running jobs''' return self.client('jobs', 'running', self.name, offset, count)
python
def running(self, offset=0, count=25): '''Return all the currently-running jobs''' return self.client('jobs', 'running', self.name, offset, count)
[ "def", "running", "(", "self", ",", "offset", "=", "0", ",", "count", "=", "25", ")", ":", "return", "self", ".", "client", "(", "'jobs'", ",", "'running'", ",", "self", ".", "name", ",", "offset", ",", "count", ")" ]
Return all the currently-running jobs
[ "Return", "all", "the", "currently", "-", "running", "jobs" ]
3eda4ffcd4c0016c9a7e44f780d6155e1a354dda
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/queue.py#L19-L21
train
44,631
seomoz/qless-py
qless/queue.py
Jobs.stalled
def stalled(self, offset=0, count=25): '''Return all the currently-stalled jobs''' return self.client('jobs', 'stalled', self.name, offset, count)
python
def stalled(self, offset=0, count=25): '''Return all the currently-stalled jobs''' return self.client('jobs', 'stalled', self.name, offset, count)
[ "def", "stalled", "(", "self", ",", "offset", "=", "0", ",", "count", "=", "25", ")", ":", "return", "self", ".", "client", "(", "'jobs'", ",", "'stalled'", ",", "self", ".", "name", ",", "offset", ",", "count", ")" ]
Return all the currently-stalled jobs
[ "Return", "all", "the", "currently", "-", "stalled", "jobs" ]
3eda4ffcd4c0016c9a7e44f780d6155e1a354dda
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/queue.py#L23-L25
train
44,632
seomoz/qless-py
qless/queue.py
Jobs.scheduled
def scheduled(self, offset=0, count=25): '''Return all the currently-scheduled jobs''' return self.client('jobs', 'scheduled', self.name, offset, count)
python
def scheduled(self, offset=0, count=25): '''Return all the currently-scheduled jobs''' return self.client('jobs', 'scheduled', self.name, offset, count)
[ "def", "scheduled", "(", "self", ",", "offset", "=", "0", ",", "count", "=", "25", ")", ":", "return", "self", ".", "client", "(", "'jobs'", ",", "'scheduled'", ",", "self", ".", "name", ",", "offset", ",", "count", ")" ]
Return all the currently-scheduled jobs
[ "Return", "all", "the", "currently", "-", "scheduled", "jobs" ]
3eda4ffcd4c0016c9a7e44f780d6155e1a354dda
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/queue.py#L27-L29
train
44,633
seomoz/qless-py
qless/queue.py
Jobs.depends
def depends(self, offset=0, count=25): '''Return all the currently dependent jobs''' return self.client('jobs', 'depends', self.name, offset, count)
python
def depends(self, offset=0, count=25): '''Return all the currently dependent jobs''' return self.client('jobs', 'depends', self.name, offset, count)
[ "def", "depends", "(", "self", ",", "offset", "=", "0", ",", "count", "=", "25", ")", ":", "return", "self", ".", "client", "(", "'jobs'", ",", "'depends'", ",", "self", ".", "name", ",", "offset", ",", "count", ")" ]
Return all the currently dependent jobs
[ "Return", "all", "the", "currently", "dependent", "jobs" ]
3eda4ffcd4c0016c9a7e44f780d6155e1a354dda
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/queue.py#L31-L33
train
44,634
seomoz/qless-py
qless/queue.py
Jobs.recurring
def recurring(self, offset=0, count=25): '''Return all the recurring jobs''' return self.client('jobs', 'recurring', self.name, offset, count)
python
def recurring(self, offset=0, count=25): '''Return all the recurring jobs''' return self.client('jobs', 'recurring', self.name, offset, count)
[ "def", "recurring", "(", "self", ",", "offset", "=", "0", ",", "count", "=", "25", ")", ":", "return", "self", ".", "client", "(", "'jobs'", ",", "'recurring'", ",", "self", ".", "name", ",", "offset", ",", "count", ")" ]
Return all the recurring jobs
[ "Return", "all", "the", "recurring", "jobs" ]
3eda4ffcd4c0016c9a7e44f780d6155e1a354dda
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/queue.py#L35-L37
train
44,635
seomoz/qless-py
qless/queue.py
Queue.class_string
def class_string(self, klass): '''Return a string representative of the class''' if isinstance(klass, string_types): return klass return klass.__module__ + '.' + klass.__name__
python
def class_string(self, klass): '''Return a string representative of the class''' if isinstance(klass, string_types): return klass return klass.__module__ + '.' + klass.__name__
[ "def", "class_string", "(", "self", ",", "klass", ")", ":", "if", "isinstance", "(", "klass", ",", "string_types", ")", ":", "return", "klass", "return", "klass", ".", "__module__", "+", "'.'", "+", "klass", ".", "__name__" ]
Return a string representative of the class
[ "Return", "a", "string", "representative", "of", "the", "class" ]
3eda4ffcd4c0016c9a7e44f780d6155e1a354dda
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/queue.py#L66-L70
train
44,636
seomoz/qless-py
qless/queue.py
Queue.put
def put(self, klass, data, priority=None, tags=None, delay=None, retries=None, jid=None, depends=None): '''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 should be negative to be run sooner rather than later, and positive if it's less important. The `tags` argument should be a JSON array of the tags associated with the instance and the `valid after` argument should be in how many seconds the instance should be considered actionable.''' return self.client('put', self.worker_name, self.name, jid or uuid.uuid4().hex, self.class_string(klass), json.dumps(data), delay or 0, 'priority', priority or 0, 'tags', json.dumps(tags or []), 'retries', retries or 5, 'depends', json.dumps(depends or []) )
python
def put(self, klass, data, priority=None, tags=None, delay=None, retries=None, jid=None, depends=None): '''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 should be negative to be run sooner rather than later, and positive if it's less important. The `tags` argument should be a JSON array of the tags associated with the instance and the `valid after` argument should be in how many seconds the instance should be considered actionable.''' return self.client('put', self.worker_name, self.name, jid or uuid.uuid4().hex, self.class_string(klass), json.dumps(data), delay or 0, 'priority', priority or 0, 'tags', json.dumps(tags or []), 'retries', retries or 5, 'depends', json.dumps(depends or []) )
[ "def", "put", "(", "self", ",", "klass", ",", "data", ",", "priority", "=", "None", ",", "tags", "=", "None", ",", "delay", "=", "None", ",", "retries", "=", "None", ",", "jid", "=", "None", ",", "depends", "=", "None", ")", ":", "return", "self"...
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 should be negative to be run sooner rather than later, and positive if it's less important. The `tags` argument should be a JSON array of the tags associated with the instance and the `valid after` argument should be in how many seconds the instance should be considered actionable.
[ "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", ...
3eda4ffcd4c0016c9a7e44f780d6155e1a354dda
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/queue.py#L78-L100
train
44,637
seomoz/qless-py
qless/queue.py
Queue.recur
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), json.dumps(data), 'interval', interval, offset, 'priority', priority or 0, 'tags', json.dumps(tags or []), 'retries', retries or 5 )
python
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), json.dumps(data), 'interval', interval, offset, 'priority', priority or 0, 'tags', json.dumps(tags or []), 'retries', retries or 5 )
[ "def", "recur", "(", "self", ",", "klass", ",", "data", ",", "interval", ",", "offset", "=", "0", ",", "priority", "=", "None", ",", "tags", "=", "None", ",", "retries", "=", "None", ",", "jid", "=", "None", ")", ":", "return", "self", ".", "clie...
Place a recurring job in this queue
[ "Place", "a", "recurring", "job", "in", "this", "queue" ]
3eda4ffcd4c0016c9a7e44f780d6155e1a354dda
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/queue.py#L118-L129
train
44,638
seomoz/qless-py
qless/queue.py
Queue.pop
def pop(self, count=None): '''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.''' results = [Job(self.client, **job) for job in json.loads( self.client('pop', self.name, self.worker_name, count or 1))] if count is None: return (len(results) and results[0]) or None return results
python
def pop(self, count=None): '''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.''' results = [Job(self.client, **job) for job in json.loads( self.client('pop', self.name, self.worker_name, count or 1))] if count is None: return (len(results) and results[0]) or None return results
[ "def", "pop", "(", "self", ",", "count", "=", "None", ")", ":", "results", "=", "[", "Job", "(", "self", ".", "client", ",", "*", "*", "job", ")", "for", "job", "in", "json", ".", "loads", "(", "self", ".", "client", "(", "'pop'", ",", "self", ...
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.
[ "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", "." ]
3eda4ffcd4c0016c9a7e44f780d6155e1a354dda
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/queue.py#L131-L139
train
44,639
seomoz/qless-py
qless/queue.py
Queue.peek
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, count or 1))] if count is None: return (len(results) and results[0]) or None return results
python
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, count or 1))] if count is None: return (len(results) and results[0]) or None return results
[ "def", "peek", "(", "self", ",", "count", "=", "None", ")", ":", "results", "=", "[", "Job", "(", "self", ".", "client", ",", "*", "*", "rec", ")", "for", "rec", "in", "json", ".", "loads", "(", "self", ".", "client", "(", "'peek'", ",", "self"...
Similar to the pop command, except that it merely peeks at the next items
[ "Similar", "to", "the", "pop", "command", "except", "that", "it", "merely", "peeks", "at", "the", "next", "items" ]
3eda4ffcd4c0016c9a7e44f780d6155e1a354dda
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/queue.py#L141-L148
train
44,640
sernst/cauldron
cauldron/runner/markdown_file.py
run
def run( project: 'projects.Project', step: 'projects.ProjectStep' ) -> dict: """ Runs the markdown file and renders the contents to the notebook display :param project: :param step: :return: A run response dictionary containing """ with open(step.source_path, 'r') as f: code = f.read() try: cauldron.display.markdown(code, **project.shared.fetch(None)) return {'success': True} except Exception as err: return dict( success=False, html_message=templating.render_template( 'markdown-error.html', error=err ) )
python
def run( project: 'projects.Project', step: 'projects.ProjectStep' ) -> dict: """ Runs the markdown file and renders the contents to the notebook display :param project: :param step: :return: A run response dictionary containing """ with open(step.source_path, 'r') as f: code = f.read() try: cauldron.display.markdown(code, **project.shared.fetch(None)) return {'success': True} except Exception as err: return dict( success=False, html_message=templating.render_template( 'markdown-error.html', error=err ) )
[ "def", "run", "(", "project", ":", "'projects.Project'", ",", "step", ":", "'projects.ProjectStep'", ")", "->", "dict", ":", "with", "open", "(", "step", ".", "source_path", ",", "'r'", ")", "as", "f", ":", "code", "=", "f", ".", "read", "(", ")", "t...
Runs the markdown file and renders the contents to the notebook display :param project: :param step: :return: A run response dictionary containing
[ "Runs", "the", "markdown", "file", "and", "renders", "the", "contents", "to", "the", "notebook", "display" ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/runner/markdown_file.py#L6-L32
train
44,641
sernst/cauldron
cauldron/cli/commander.py
fetch
def fetch(reload: bool = False) -> dict: """ 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 any cached command data and generate a new dictionary of available commands. :return: A dictionary where the keys are the name of the commands and the values are the modules for the command . """ if len(list(COMMANDS.keys())) > 0 and not reload: return COMMANDS COMMANDS.clear() for key in dir(commands): e = getattr(commands, key) if e and hasattr(e, 'NAME') and hasattr(e, 'DESCRIPTION'): COMMANDS[e.NAME] = e return dict(COMMANDS.items())
python
def fetch(reload: bool = False) -> dict: """ 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 any cached command data and generate a new dictionary of available commands. :return: A dictionary where the keys are the name of the commands and the values are the modules for the command . """ if len(list(COMMANDS.keys())) > 0 and not reload: return COMMANDS COMMANDS.clear() for key in dir(commands): e = getattr(commands, key) if e and hasattr(e, 'NAME') and hasattr(e, 'DESCRIPTION'): COMMANDS[e.NAME] = e return dict(COMMANDS.items())
[ "def", "fetch", "(", "reload", ":", "bool", "=", "False", ")", "->", "dict", ":", "if", "len", "(", "list", "(", "COMMANDS", ".", "keys", "(", ")", ")", ")", ">", "0", "and", "not", "reload", ":", "return", "COMMANDS", "COMMANDS", ".", "clear", "...
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 any cached command data and generate a new dictionary of available commands. :return: A dictionary where the keys are the name of the commands and the values are the modules for the command .
[ "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", "t...
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/cli/commander.py#L35-L61
train
44,642
sernst/cauldron
cauldron/cli/commander.py
get_command_from_module
def get_command_from_module( command_module, remote_connection: environ.RemoteConnection ): """ 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: """ use_remote = ( remote_connection.active and hasattr(command_module, 'execute_remote') ) return ( command_module.execute_remote if use_remote else command_module.execute )
python
def get_command_from_module( command_module, remote_connection: environ.RemoteConnection ): """ 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: """ use_remote = ( remote_connection.active and hasattr(command_module, 'execute_remote') ) return ( command_module.execute_remote if use_remote else command_module.execute )
[ "def", "get_command_from_module", "(", "command_module", ",", "remote_connection", ":", "environ", ".", "RemoteConnection", ")", ":", "use_remote", "=", "(", "remote_connection", ".", "active", "and", "hasattr", "(", "command_module", ",", "'execute_remote'", ")", "...
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:
[ "Returns", "the", "execution", "command", "to", "use", "for", "the", "specified", "module", "which", "may", "be", "different", "depending", "upon", "remote", "connection" ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/cli/commander.py#L64-L85
train
44,643
seomoz/qless-py
qless/job.py
BaseJob._import
def _import(klass): '''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''' mod = __import__(klass.rpartition('.')[0]) for segment in klass.split('.')[1:-1]: mod = getattr(mod, segment) # Alright, now check the file associated with it. Note that clases # defined in __main__ don't have a __file__ attribute if klass not in BaseJob._loaded: BaseJob._loaded[klass] = time.time() if hasattr(mod, '__file__'): try: mtime = os.stat(mod.__file__).st_mtime if BaseJob._loaded[klass] < mtime: mod = reload_module(mod) except OSError: logger.warn('Could not check modification time of %s', mod.__file__) return getattr(mod, klass.rpartition('.')[2])
python
def _import(klass): '''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''' mod = __import__(klass.rpartition('.')[0]) for segment in klass.split('.')[1:-1]: mod = getattr(mod, segment) # Alright, now check the file associated with it. Note that clases # defined in __main__ don't have a __file__ attribute if klass not in BaseJob._loaded: BaseJob._loaded[klass] = time.time() if hasattr(mod, '__file__'): try: mtime = os.stat(mod.__file__).st_mtime if BaseJob._loaded[klass] < mtime: mod = reload_module(mod) except OSError: logger.warn('Could not check modification time of %s', mod.__file__) return getattr(mod, klass.rpartition('.')[2])
[ "def", "_import", "(", "klass", ")", ":", "mod", "=", "__import__", "(", "klass", ".", "rpartition", "(", "'.'", ")", "[", "0", "]", ")", "for", "segment", "in", "klass", ".", "split", "(", "'.'", ")", "[", "1", ":", "-", "1", "]", ":", "mod", ...
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
[ "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", "...
3eda4ffcd4c0016c9a7e44f780d6155e1a354dda
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/job.py#L59-L81
train
44,644
seomoz/qless-py
qless/job.py
Job.process
def process(self): '''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.''' try: method = getattr(self.klass, self.queue_name, getattr(self.klass, 'process', None)) except Exception as exc: # We failed to import the module containing this class logger.exception('Failed to import %s', self.klass_name) return self.fail(self.queue_name + '-' + exc.__class__.__name__, 'Failed to import %s' % self.klass_name) if method: if isinstance(method, types.FunctionType): try: logger.info('Processing %s in %s', self.jid, self.queue_name) method(self) logger.info('Completed %s in %s', self.jid, self.queue_name) except Exception as exc: # Make error type based on exception type logger.exception('Failed %s in %s: %s', self.jid, self.queue_name, repr(method)) self.fail(self.queue_name + '-' + exc.__class__.__name__, traceback.format_exc()) else: # Or fail with a message to that effect logger.error('Failed %s in %s : %s is not static', self.jid, self.queue_name, repr(method)) self.fail(self.queue_name + '-method-type', repr(method) + ' is not static') else: # Or fail with a message to that effect logger.error( 'Failed %s : %s is missing a method "%s" or "process"', self.jid, self.klass_name, self.queue_name) self.fail(self.queue_name + '-method-missing', self.klass_name + ' is missing a method "' + self.queue_name + '" or "process"')
python
def process(self): '''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.''' try: method = getattr(self.klass, self.queue_name, getattr(self.klass, 'process', None)) except Exception as exc: # We failed to import the module containing this class logger.exception('Failed to import %s', self.klass_name) return self.fail(self.queue_name + '-' + exc.__class__.__name__, 'Failed to import %s' % self.klass_name) if method: if isinstance(method, types.FunctionType): try: logger.info('Processing %s in %s', self.jid, self.queue_name) method(self) logger.info('Completed %s in %s', self.jid, self.queue_name) except Exception as exc: # Make error type based on exception type logger.exception('Failed %s in %s: %s', self.jid, self.queue_name, repr(method)) self.fail(self.queue_name + '-' + exc.__class__.__name__, traceback.format_exc()) else: # Or fail with a message to that effect logger.error('Failed %s in %s : %s is not static', self.jid, self.queue_name, repr(method)) self.fail(self.queue_name + '-method-type', repr(method) + ' is not static') else: # Or fail with a message to that effect logger.error( 'Failed %s : %s is missing a method "%s" or "process"', self.jid, self.klass_name, self.queue_name) self.fail(self.queue_name + '-method-missing', self.klass_name + ' is missing a method "' + self.queue_name + '" or "process"')
[ "def", "process", "(", "self", ")", ":", "try", ":", "method", "=", "getattr", "(", "self", ".", "klass", ",", "self", ".", "queue_name", ",", "getattr", "(", "self", ".", "klass", ",", "'process'", ",", "None", ")", ")", "except", "Exception", "as",...
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.
[ "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", "static...
3eda4ffcd4c0016c9a7e44f780d6155e1a354dda
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/job.py#L133-L173
train
44,645
seomoz/qless-py
qless/job.py
Job.move
def move(self, queue, delay=0, depends=None): '''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''' logger.info('Moving %s to %s from %s', self.jid, queue, self.queue_name) return self.client('put', self.worker_name, queue, self.jid, self.klass_name, json.dumps(self.data), delay, 'depends', json.dumps(depends or []) )
python
def move(self, queue, delay=0, depends=None): '''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''' logger.info('Moving %s to %s from %s', self.jid, queue, self.queue_name) return self.client('put', self.worker_name, queue, self.jid, self.klass_name, json.dumps(self.data), delay, 'depends', json.dumps(depends or []) )
[ "def", "move", "(", "self", ",", "queue", ",", "delay", "=", "0", ",", "depends", "=", "None", ")", ":", "logger", ".", "info", "(", "'Moving %s to %s from %s'", ",", "self", ".", "jid", ",", "queue", ",", "self", ".", "queue_name", ")", "return", "s...
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
[ "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...
3eda4ffcd4c0016c9a7e44f780d6155e1a354dda
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/job.py#L175-L185
train
44,646
seomoz/qless-py
qless/job.py
Job.complete
def complete(self, nextq=None, delay=None, depends=None): '''Turn this job in as complete, optionally advancing it to another queue. Like ``Queue.put`` and ``move``, it accepts a delay, and dependencies''' if nextq: logger.info('Advancing %s to %s from %s', self.jid, nextq, self.queue_name) return self.client('complete', self.jid, self.client.worker_name, self.queue_name, json.dumps(self.data), 'next', nextq, 'delay', delay or 0, 'depends', json.dumps(depends or [])) or False else: logger.info('Completing %s', self.jid) return self.client('complete', self.jid, self.client.worker_name, self.queue_name, json.dumps(self.data)) or False
python
def complete(self, nextq=None, delay=None, depends=None): '''Turn this job in as complete, optionally advancing it to another queue. Like ``Queue.put`` and ``move``, it accepts a delay, and dependencies''' if nextq: logger.info('Advancing %s to %s from %s', self.jid, nextq, self.queue_name) return self.client('complete', self.jid, self.client.worker_name, self.queue_name, json.dumps(self.data), 'next', nextq, 'delay', delay or 0, 'depends', json.dumps(depends or [])) or False else: logger.info('Completing %s', self.jid) return self.client('complete', self.jid, self.client.worker_name, self.queue_name, json.dumps(self.data)) or False
[ "def", "complete", "(", "self", ",", "nextq", "=", "None", ",", "delay", "=", "None", ",", "depends", "=", "None", ")", ":", "if", "nextq", ":", "logger", ".", "info", "(", "'Advancing %s to %s from %s'", ",", "self", ".", "jid", ",", "nextq", ",", "...
Turn this job in as complete, optionally advancing it to another queue. Like ``Queue.put`` and ``move``, it accepts a delay, and dependencies
[ "Turn", "this", "job", "in", "as", "complete", "optionally", "advancing", "it", "to", "another", "queue", ".", "Like", "Queue", ".", "put", "and", "move", "it", "accepts", "a", "delay", "and", "dependencies" ]
3eda4ffcd4c0016c9a7e44f780d6155e1a354dda
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/job.py#L187-L201
train
44,647
seomoz/qless-py
qless/job.py
Job.heartbeat
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 = float(self.client('heartbeat', self.jid, self.client.worker_name, json.dumps(self.data)) or 0) except QlessException: raise LostLockException(self.jid) logger.debug('Heartbeated %s (ttl = %s)', self.jid, self.ttl) return self.expires_at
python
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 = float(self.client('heartbeat', self.jid, self.client.worker_name, json.dumps(self.data)) or 0) except QlessException: raise LostLockException(self.jid) logger.debug('Heartbeated %s (ttl = %s)', self.jid, self.ttl) return self.expires_at
[ "def", "heartbeat", "(", "self", ")", ":", "logger", ".", "debug", "(", "'Heartbeating %s (ttl = %s)'", ",", "self", ".", "jid", ",", "self", ".", "ttl", ")", "try", ":", "self", ".", "expires_at", "=", "float", "(", "self", ".", "client", "(", "'heart...
Renew the heartbeat, if possible, and optionally update the job's user data.
[ "Renew", "the", "heartbeat", "if", "possible", "and", "optionally", "update", "the", "job", "s", "user", "data", "." ]
3eda4ffcd4c0016c9a7e44f780d6155e1a354dda
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/job.py#L203-L213
train
44,648
seomoz/qless-py
qless/job.py
Job.fail
def fail(self, group, message): '''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 note that a job has been dropped or has failed in a transient way. This method __should__ be used to note that a job has something really wrong with it that must be remedied. The motivation behind the `type` is so that similar errors can be grouped together. Optionally, updated data can be provided for the job. A job in any state can be marked as failed. If it has been given to a worker as a job, then its subsequent requests to heartbeat or complete that job will fail. Failed jobs are kept until they are canceled or completed. __Returns__ the id of the failed job if successful, or `False` on failure.''' logger.warn('Failing %s (%s): %s', self.jid, group, message) return self.client('fail', self.jid, self.client.worker_name, group, message, json.dumps(self.data)) or False
python
def fail(self, group, message): '''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 note that a job has been dropped or has failed in a transient way. This method __should__ be used to note that a job has something really wrong with it that must be remedied. The motivation behind the `type` is so that similar errors can be grouped together. Optionally, updated data can be provided for the job. A job in any state can be marked as failed. If it has been given to a worker as a job, then its subsequent requests to heartbeat or complete that job will fail. Failed jobs are kept until they are canceled or completed. __Returns__ the id of the failed job if successful, or `False` on failure.''' logger.warn('Failing %s (%s): %s', self.jid, group, message) return self.client('fail', self.jid, self.client.worker_name, group, message, json.dumps(self.data)) or False
[ "def", "fail", "(", "self", ",", "group", ",", "message", ")", ":", "logger", ".", "warn", "(", "'Failing %s (%s): %s'", ",", "self", ".", "jid", ",", "group", ",", "message", ")", "return", "self", ".", "client", "(", "'fail'", ",", "self", ".", "ji...
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 note that a job has been dropped or has failed in a transient way. This method __should__ be used to note that a job has something really wrong with it that must be remedied. The motivation behind the `type` is so that similar errors can be grouped together. Optionally, updated data can be provided for the job. A job in any state can be marked as failed. If it has been given to a worker as a job, then its subsequent requests to heartbeat or complete that job will fail. Failed jobs are kept until they are canceled or completed. __Returns__ the id of the failed job if successful, or `False` on failure.
[ "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"...
3eda4ffcd4c0016c9a7e44f780d6155e1a354dda
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/job.py#L215-L235
train
44,649
seomoz/qless-py
qless/job.py
Job.retry
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 yourself''' args = ['retry', self.jid, self.queue_name, self.worker_name, delay] if group is not None and message is not None: args.append(group) args.append(message) return self.client(*args)
python
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 yourself''' args = ['retry', self.jid, self.queue_name, self.worker_name, delay] if group is not None and message is not None: args.append(group) args.append(message) return self.client(*args)
[ "def", "retry", "(", "self", ",", "delay", "=", "0", ",", "group", "=", "None", ",", "message", "=", "None", ")", ":", "args", "=", "[", "'retry'", ",", "self", ".", "jid", ",", "self", ".", "queue_name", ",", "self", ".", "worker_name", ",", "de...
Retry this job in a little bit, in the same queue. This is meant for the times when you detect a transient failure yourself
[ "Retry", "this", "job", "in", "a", "little", "bit", "in", "the", "same", "queue", ".", "This", "is", "meant", "for", "the", "times", "when", "you", "detect", "a", "transient", "failure", "yourself" ]
3eda4ffcd4c0016c9a7e44f780d6155e1a354dda
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/job.py#L245-L252
train
44,650
sernst/cauldron
cauldron/runner/source.py
has_extension
def has_extension(file_path: str, *args: typing.Tuple[str]) -> bool: """ 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 a match with the file_path argument :return: Whether or not the file_path argument ended with one or more of the specified extensions """ def add_dot(extension): return ( extension if extension.startswith('.') else '.{}'.format(extension) ) return any([ file_path.endswith(add_dot(extension)) for extension in args ])
python
def has_extension(file_path: str, *args: typing.Tuple[str]) -> bool: """ 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 a match with the file_path argument :return: Whether or not the file_path argument ended with one or more of the specified extensions """ def add_dot(extension): return ( extension if extension.startswith('.') else '.{}'.format(extension) ) return any([ file_path.endswith(add_dot(extension)) for extension in args ])
[ "def", "has_extension", "(", "file_path", ":", "str", ",", "*", "args", ":", "typing", ".", "Tuple", "[", "str", "]", ")", "->", "bool", ":", "def", "add_dot", "(", "extension", ")", ":", "return", "(", "extension", "if", "extension", ".", "startswith"...
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 a match with the file_path argument :return: Whether or not the file_path argument ended with one or more of the specified extensions
[ "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...
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/runner/source.py#L39-L64
train
44,651
sernst/cauldron
cauldron/docgen/parsing.py
get_docstring
def get_docstring(target) -> str: """ 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 will be returned instead. """ raw = getattr(target, '__doc__') if raw is None: return '' return textwrap.dedent(raw)
python
def get_docstring(target) -> str: """ 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 will be returned instead. """ raw = getattr(target, '__doc__') if raw is None: return '' return textwrap.dedent(raw)
[ "def", "get_docstring", "(", "target", ")", "->", "str", ":", "raw", "=", "getattr", "(", "target", ",", "'__doc__'", ")", "if", "raw", "is", "None", ":", "return", "''", "return", "textwrap", ".", "dedent", "(", "raw", ")" ]
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 will be returned instead.
[ "Retrieves", "the", "documentation", "string", "from", "the", "target", "object", "and", "returns", "it", "after", "removing", "insignificant", "whitespace" ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/docgen/parsing.py#L9-L26
train
44,652
sernst/cauldron
cauldron/docgen/parsing.py
get_doc_entries
def get_doc_entries(target: typing.Callable) -> list: """ 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 """ raw = get_docstring(target) if not raw: return [] raw_lines = [ line.strip() for line in raw.replace('\r', '').split('\n') ] def compactify(compacted: list, entry: str) -> list: chars = entry.strip() if not chars: return compacted if len(compacted) < 1 or chars.startswith(':'): compacted.append(entry.rstrip()) else: compacted[-1] = '{}\n{}'.format(compacted[-1], entry.rstrip()) return compacted return [ textwrap.dedent(block).strip() for block in functools.reduce(compactify, raw_lines, []) ]
python
def get_doc_entries(target: typing.Callable) -> list: """ 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 """ raw = get_docstring(target) if not raw: return [] raw_lines = [ line.strip() for line in raw.replace('\r', '').split('\n') ] def compactify(compacted: list, entry: str) -> list: chars = entry.strip() if not chars: return compacted if len(compacted) < 1 or chars.startswith(':'): compacted.append(entry.rstrip()) else: compacted[-1] = '{}\n{}'.format(compacted[-1], entry.rstrip()) return compacted return [ textwrap.dedent(block).strip() for block in functools.reduce(compactify, raw_lines, []) ]
[ "def", "get_doc_entries", "(", "target", ":", "typing", ".", "Callable", ")", "->", "list", ":", "raw", "=", "get_docstring", "(", "target", ")", "if", "not", "raw", ":", "return", "[", "]", "raw_lines", "=", "[", "line", ".", "strip", "(", ")", "for...
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
[ "Gets", "the", "lines", "of", "documentation", "from", "the", "given", "target", "which", "are", "formatted", "so", "that", "each", "line", "is", "a", "documentation", "entry", "." ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/docgen/parsing.py#L29-L65
train
44,653
sernst/cauldron
cauldron/docgen/parsing.py
parse_function
def parse_function( name: str, target: typing.Callable ) -> typing.Union[None, dict]: """ 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 function, or None if the target was not a function. """ if not hasattr(target, '__code__'): return None lines = get_doc_entries(target) docs = ' '.join(filter(lambda line: not line.startswith(':'), lines)) params = parse_params(target, lines) returns = parse_returns(target, lines) return dict( name=getattr(target, '__name__'), doc=docs, params=params, returns=returns )
python
def parse_function( name: str, target: typing.Callable ) -> typing.Union[None, dict]: """ 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 function, or None if the target was not a function. """ if not hasattr(target, '__code__'): return None lines = get_doc_entries(target) docs = ' '.join(filter(lambda line: not line.startswith(':'), lines)) params = parse_params(target, lines) returns = parse_returns(target, lines) return dict( name=getattr(target, '__name__'), doc=docs, params=params, returns=returns )
[ "def", "parse_function", "(", "name", ":", "str", ",", "target", ":", "typing", ".", "Callable", ")", "->", "typing", ".", "Union", "[", "None", ",", "dict", "]", ":", "if", "not", "hasattr", "(", "target", ",", "'__code__'", ")", ":", "return", "Non...
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 function, or None if the target was not a function.
[ "Parses", "the", "documentation", "for", "a", "function", "which", "is", "specified", "by", "the", "name", "of", "the", "function", "and", "the", "function", "itself", "." ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/docgen/parsing.py#L68-L98
train
44,654
sernst/cauldron
cauldron/session/buffering.py
RedirectBuffer.read_all
def read_all(self) -> str: """ 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 """ try: buffered_bytes = self.bytes_buffer.getvalue() if buffered_bytes is None: return '' return buffered_bytes.decode(self.source_encoding) except Exception as err: return 'Redirect Buffer Error: {}'.format(err)
python
def read_all(self) -> str: """ 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 """ try: buffered_bytes = self.bytes_buffer.getvalue() if buffered_bytes is None: return '' return buffered_bytes.decode(self.source_encoding) except Exception as err: return 'Redirect Buffer Error: {}'.format(err)
[ "def", "read_all", "(", "self", ")", "->", "str", ":", "try", ":", "buffered_bytes", "=", "self", ".", "bytes_buffer", ".", "getvalue", "(", ")", "if", "buffered_bytes", "is", "None", ":", "return", "''", "return", "buffered_bytes", ".", "decode", "(", "...
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
[ "Reads", "the", "current", "state", "of", "the", "buffer", "and", "returns", "a", "string", "those", "contents" ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/buffering.py#L31-L46
train
44,655
sernst/cauldron
cauldron/session/writing/step.py
create_data
def create_data(step: 'projects.ProjectStep') -> STEP_DATA: """ 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 from the step to correctly reflect the current state of the step. This is essentially a "blank" step dictionary, which is what the step would look like if it had not yet run """ return STEP_DATA( name=step.definition.name, status=step.status(), has_error=False, body=None, data=dict(), includes=[], cauldron_version=list(environ.version_info), file_writes=[] )
python
def create_data(step: 'projects.ProjectStep') -> STEP_DATA: """ 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 from the step to correctly reflect the current state of the step. This is essentially a "blank" step dictionary, which is what the step would look like if it had not yet run """ return STEP_DATA( name=step.definition.name, status=step.status(), has_error=False, body=None, data=dict(), includes=[], cauldron_version=list(environ.version_info), file_writes=[] )
[ "def", "create_data", "(", "step", ":", "'projects.ProjectStep'", ")", "->", "STEP_DATA", ":", "return", "STEP_DATA", "(", "name", "=", "step", ".", "definition", ".", "name", ",", "status", "=", "step", ".", "status", "(", ")", ",", "has_error", "=", "F...
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 from the step to correctly reflect the current state of the step. This is essentially a "blank" step dictionary, which is what the step would look like if it had not yet run
[ "Creates", "the", "data", "object", "that", "stores", "the", "step", "information", "in", "the", "notebook", "results", "JavaScript", "file", "." ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/writing/step.py#L23-L48
train
44,656
sernst/cauldron
cauldron/session/writing/step.py
get_cached_data
def get_cached_data( step: 'projects.ProjectStep' ) -> typing.Union[None, STEP_DATA]: """ 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 cached step data or None if no cached data exists for the step """ cache_path = step.report.results_cache_path if not os.path.exists(cache_path): return None out = create_data(step) try: with open(cache_path, 'r') as f: cached_data = json.load(f) except Exception: return None file_writes = [ file_io.entry_from_dict(fw) for fw in cached_data['file_writes'] ] return out \ ._replace(**cached_data) \ ._replace(file_writes=file_writes)
python
def get_cached_data( step: 'projects.ProjectStep' ) -> typing.Union[None, STEP_DATA]: """ 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 cached step data or None if no cached data exists for the step """ cache_path = step.report.results_cache_path if not os.path.exists(cache_path): return None out = create_data(step) try: with open(cache_path, 'r') as f: cached_data = json.load(f) except Exception: return None file_writes = [ file_io.entry_from_dict(fw) for fw in cached_data['file_writes'] ] return out \ ._replace(**cached_data) \ ._replace(file_writes=file_writes)
[ "def", "get_cached_data", "(", "step", ":", "'projects.ProjectStep'", ")", "->", "typing", ".", "Union", "[", "None", ",", "STEP_DATA", "]", ":", "cache_path", "=", "step", ".", "report", ".", "results_cache_path", "if", "not", "os", ".", "path", ".", "exi...
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 cached step data or None if no cached data exists for the step
[ "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", ...
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/writing/step.py#L51-L86
train
44,657
sernst/cauldron
cauldron/cli/batcher.py
initialize_logging_path
def initialize_logging_path(path: str = None) -> str: """ 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 be called "cauldron_run.log". :return: The absolute path to the log file that will be used when this project is executed. """ path = environ.paths.clean(path if path else '.') if os.path.isdir(path) and os.path.exists(path): path = os.path.join(path, 'cauldron_run.log') elif os.path.exists(path): os.remove(path) directory = os.path.dirname(path) if not os.path.exists(directory): os.makedirs(directory) return path
python
def initialize_logging_path(path: str = None) -> str: """ 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 be called "cauldron_run.log". :return: The absolute path to the log file that will be used when this project is executed. """ path = environ.paths.clean(path if path else '.') if os.path.isdir(path) and os.path.exists(path): path = os.path.join(path, 'cauldron_run.log') elif os.path.exists(path): os.remove(path) directory = os.path.dirname(path) if not os.path.exists(directory): os.makedirs(directory) return path
[ "def", "initialize_logging_path", "(", "path", ":", "str", "=", "None", ")", "->", "str", ":", "path", "=", "environ", ".", "paths", ".", "clean", "(", "path", "if", "path", "else", "'.'", ")", "if", "os", ".", "path", ".", "isdir", "(", "path", ")...
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 be called "cauldron_run.log". :return: The absolute path to the log file that will be used when this project is executed.
[ "Initializes", "the", "logging", "path", "for", "running", "the", "project", ".", "If", "no", "logging", "path", "is", "specified", "the", "current", "directory", "will", "be", "used", "instead", "." ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/cli/batcher.py#L16-L40
train
44,658
seomoz/qless-py
qless/workers/forking.py
ForkingWorker.stop
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 cover logger.exception('Error stopping %s...' % cpid) # While we still have children running, wait for them # We edit the dictionary during the loop, so we need to copy its keys for cpid in list(self.sandboxes): try: logger.info('Waiting for %i...' % cpid) pid, status = os.waitpid(cpid, 0) logger.warn('%i stopped with status %i' % (pid, status >> 8)) except OSError: # pragma: no cover logger.exception('Error waiting for %i...' % cpid) finally: self.sandboxes.pop(cpid, None)
python
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 cover logger.exception('Error stopping %s...' % cpid) # While we still have children running, wait for them # We edit the dictionary during the loop, so we need to copy its keys for cpid in list(self.sandboxes): try: logger.info('Waiting for %i...' % cpid) pid, status = os.waitpid(cpid, 0) logger.warn('%i stopped with status %i' % (pid, status >> 8)) except OSError: # pragma: no cover logger.exception('Error waiting for %i...' % cpid) finally: self.sandboxes.pop(cpid, None)
[ "def", "stop", "(", "self", ",", "sig", "=", "signal", ".", "SIGINT", ")", ":", "for", "cpid", "in", "self", ".", "sandboxes", ":", "logger", ".", "warn", "(", "'Stopping %i...'", "%", "cpid", ")", "try", ":", "os", ".", "kill", "(", "cpid", ",", ...
Stop all the workers, and then wait for them
[ "Stop", "all", "the", "workers", "and", "then", "wait", "for", "them" ]
3eda4ffcd4c0016c9a7e44f780d6155e1a354dda
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/workers/forking.py#L33-L52
train
44,659
seomoz/qless-py
qless/workers/forking.py
ForkingWorker.spawn
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 to relieve that # problem by allowing `klass` to be specified as a string. if isinstance(self.klass, string_types): self.klass = util.import_class(self.klass) return self.klass(self.queues, self.client, **copy)
python
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 to relieve that # problem by allowing `klass` to be specified as a string. if isinstance(self.klass, string_types): self.klass = util.import_class(self.klass) return self.klass(self.queues, self.client, **copy)
[ "def", "spawn", "(", "self", ",", "*", "*", "kwargs", ")", ":", "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 ...
Return a new worker for a child process
[ "Return", "a", "new", "worker", "for", "a", "child", "process" ]
3eda4ffcd4c0016c9a7e44f780d6155e1a354dda
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/workers/forking.py#L54-L63
train
44,660
seomoz/qless-py
qless/workers/forking.py
ForkingWorker.run
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.count): # The sandbox for the child worker sandbox = os.path.join( os.getcwd(), 'qless-py-workers', 'sandbox-%s' % index) cpid = os.fork() if cpid: logger.info('Spawned worker %i' % cpid) self.sandboxes[cpid] = sandbox else: # pragma: no cover # Move to the sandbox as the current working directory with Worker.sandbox(sandbox): os.chdir(sandbox) try: self.spawn(resume=resume[index], sandbox=sandbox).run() except: logger.exception('Exception in spawned worker') finally: os._exit(0) try: while not self.shutdown: pid, status = os.wait() logger.warn('Worker %i died with status %i from signal %i' % ( pid, status >> 8, status & 0xff)) sandbox = self.sandboxes.pop(pid) cpid = os.fork() if cpid: logger.info('Spawned replacement worker %i' % cpid) self.sandboxes[cpid] = sandbox else: # pragma: no cover with Worker.sandbox(sandbox): os.chdir(sandbox) try: self.spawn(sandbox=sandbox).run() except: logger.exception('Exception in spawned worker') finally: os._exit(0) finally: self.stop(signal.SIGKILL)
python
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.count): # The sandbox for the child worker sandbox = os.path.join( os.getcwd(), 'qless-py-workers', 'sandbox-%s' % index) cpid = os.fork() if cpid: logger.info('Spawned worker %i' % cpid) self.sandboxes[cpid] = sandbox else: # pragma: no cover # Move to the sandbox as the current working directory with Worker.sandbox(sandbox): os.chdir(sandbox) try: self.spawn(resume=resume[index], sandbox=sandbox).run() except: logger.exception('Exception in spawned worker') finally: os._exit(0) try: while not self.shutdown: pid, status = os.wait() logger.warn('Worker %i died with status %i from signal %i' % ( pid, status >> 8, status & 0xff)) sandbox = self.sandboxes.pop(pid) cpid = os.fork() if cpid: logger.info('Spawned replacement worker %i' % cpid) self.sandboxes[cpid] = sandbox else: # pragma: no cover with Worker.sandbox(sandbox): os.chdir(sandbox) try: self.spawn(sandbox=sandbox).run() except: logger.exception('Exception in spawned worker') finally: os._exit(0) finally: self.stop(signal.SIGKILL)
[ "def", "run", "(", "self", ")", ":", "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", ".", "div...
Run this worker
[ "Run", "this", "worker" ]
3eda4ffcd4c0016c9a7e44f780d6155e1a354dda
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/workers/forking.py#L65-L110
train
44,661
sernst/cauldron
cauldron/render/stack.py
get_stack_frames
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 information resides. """ cauldron_path = environ.paths.package() resources_path = environ.paths.resources() frames = ( list(traceback.extract_tb(sys.exc_info()[-1])) if error_stack else traceback.extract_stack() ).copy() def is_cauldron_code(test_filename: str) -> bool: if not test_filename or not test_filename.startswith(cauldron_path): return False if test_filename.startswith(resources_path): return False return True while len(frames) > 1 and is_cauldron_code(frames[0].filename): frames.pop(0) return frames
python
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 information resides. """ cauldron_path = environ.paths.package() resources_path = environ.paths.resources() frames = ( list(traceback.extract_tb(sys.exc_info()[-1])) if error_stack else traceback.extract_stack() ).copy() def is_cauldron_code(test_filename: str) -> bool: if not test_filename or not test_filename.startswith(cauldron_path): return False if test_filename.startswith(resources_path): return False return True while len(frames) > 1 and is_cauldron_code(frames[0].filename): frames.pop(0) return frames
[ "def", "get_stack_frames", "(", "error_stack", ":", "bool", "=", "True", ")", "->", "list", ":", "cauldron_path", "=", "environ", ".", "paths", ".", "package", "(", ")", "resources_path", "=", "environ", ".", "paths", ".", "resources", "(", ")", "frames", ...
Returns a list of the current stack frames, which are pruned focus on the Cauldron code where the relevant information resides.
[ "Returns", "a", "list", "of", "the", "current", "stack", "frames", "which", "are", "pruned", "focus", "on", "the", "Cauldron", "code", "where", "the", "relevant", "information", "resides", "." ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/render/stack.py#L8-L34
train
44,662
sernst/cauldron
cauldron/render/stack.py
format_stack_frame
def format_stack_frame(stack_frame, project: 'projects.Project') -> dict: """ 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 contextualize stack information with project-specific information. :return: A dictionary containing the enriched stack frame data. """ filename = stack_frame.filename if filename.startswith(project.source_directory): filename = filename[len(project.source_directory) + 1:] location = stack_frame.name if location == '<module>': location = None return dict( filename=filename, location=location, line_number=stack_frame.lineno, line=stack_frame.line )
python
def format_stack_frame(stack_frame, project: 'projects.Project') -> dict: """ 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 contextualize stack information with project-specific information. :return: A dictionary containing the enriched stack frame data. """ filename = stack_frame.filename if filename.startswith(project.source_directory): filename = filename[len(project.source_directory) + 1:] location = stack_frame.name if location == '<module>': location = None return dict( filename=filename, location=location, line_number=stack_frame.lineno, line=stack_frame.line )
[ "def", "format_stack_frame", "(", "stack_frame", ",", "project", ":", "'projects.Project'", ")", "->", "dict", ":", "filename", "=", "stack_frame", ".", "filename", "if", "filename", ".", "startswith", "(", "project", ".", "source_directory", ")", ":", "filename...
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 contextualize stack information with project-specific information. :return: A dictionary containing the enriched stack frame data.
[ "Formats", "a", "raw", "stack", "frame", "into", "a", "dictionary", "formatted", "for", "render", "templating", "and", "enriched", "with", "information", "from", "the", "currently", "open", "project", "." ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/render/stack.py#L37-L64
train
44,663
sernst/cauldron
cauldron/docgen/conversions.py
arg_type_to_string
def arg_type_to_string(arg_type) -> str: """ 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 """ union_params = ( getattr(arg_type, '__union_params__', None) or getattr(arg_type, '__args__', None) ) if union_params and isinstance(union_params, (list, tuple)): return ', '.join([arg_type_to_string(item) for item in union_params]) try: return arg_type.__name__ except AttributeError: return '{}'.format(arg_type)
python
def arg_type_to_string(arg_type) -> str: """ 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 """ union_params = ( getattr(arg_type, '__union_params__', None) or getattr(arg_type, '__args__', None) ) if union_params and isinstance(union_params, (list, tuple)): return ', '.join([arg_type_to_string(item) for item in union_params]) try: return arg_type.__name__ except AttributeError: return '{}'.format(arg_type)
[ "def", "arg_type_to_string", "(", "arg_type", ")", "->", "str", ":", "union_params", "=", "(", "getattr", "(", "arg_type", ",", "'__union_params__'", ",", "None", ")", "or", "getattr", "(", "arg_type", ",", "'__args__'", ",", "None", ")", ")", "if", "union...
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
[ "Converts", "the", "argument", "type", "to", "a", "string" ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/docgen/conversions.py#L1-L22
train
44,664
sernst/cauldron
cauldron/session/writing/components/definitions.py
merge_components
def merge_components( *components: typing.List[typing.Union[list, tuple, COMPONENT]] ) -> COMPONENT: """ 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: """ flat_components = functools.reduce(flatten_reducer, components, []) return COMPONENT( includes=functools.reduce( functools.partial(combine_lists_reducer, 'includes'), flat_components, [] ), files=functools.reduce( functools.partial(combine_lists_reducer, 'files'), flat_components, [] ) )
python
def merge_components( *components: typing.List[typing.Union[list, tuple, COMPONENT]] ) -> COMPONENT: """ 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: """ flat_components = functools.reduce(flatten_reducer, components, []) return COMPONENT( includes=functools.reduce( functools.partial(combine_lists_reducer, 'includes'), flat_components, [] ), files=functools.reduce( functools.partial(combine_lists_reducer, 'files'), flat_components, [] ) )
[ "def", "merge_components", "(", "*", "components", ":", "typing", ".", "List", "[", "typing", ".", "Union", "[", "list", ",", "tuple", ",", "COMPONENT", "]", "]", ")", "->", "COMPONENT", ":", "flat_components", "=", "functools", ".", "reduce", "(", "flat...
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:
[ "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", "o...
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/writing/components/definitions.py#L9-L33
train
44,665
sernst/cauldron
cauldron/session/writing/components/definitions.py
flatten_reducer
def flatten_reducer( flattened_list: list, entry: typing.Union[list, tuple, COMPONENT] ) -> list: """ 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 COMPONENT instance or a list/tuple of COMPONENT instances :return: The flattened list with the entry flatly added to it """ if hasattr(entry, 'includes') and hasattr(entry, 'files'): flattened_list.append(entry) elif entry: flattened_list.extend(entry) return flattened_list
python
def flatten_reducer( flattened_list: list, entry: typing.Union[list, tuple, COMPONENT] ) -> list: """ 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 COMPONENT instance or a list/tuple of COMPONENT instances :return: The flattened list with the entry flatly added to it """ if hasattr(entry, 'includes') and hasattr(entry, 'files'): flattened_list.append(entry) elif entry: flattened_list.extend(entry) return flattened_list
[ "def", "flatten_reducer", "(", "flattened_list", ":", "list", ",", "entry", ":", "typing", ".", "Union", "[", "list", ",", "tuple", ",", "COMPONENT", "]", ")", "->", "list", ":", "if", "hasattr", "(", "entry", ",", "'includes'", ")", "and", "hasattr", ...
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 COMPONENT instance or a list/tuple of COMPONENT instances :return: The flattened list with the entry flatly added to it
[ "Flattens", "a", "list", "of", "COMPONENT", "instances", "to", "remove", "any", "lists", "or", "tuples", "of", "COMPONENTS", "contained", "within", "the", "list" ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/writing/components/definitions.py#L36-L58
train
44,666
sernst/cauldron
cauldron/session/writing/components/definitions.py
combine_lists_reducer
def combine_lists_reducer( key: str, merged_list: list, component: COMPONENT ) -> list: """ 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: The COMPONENT instance from which to append values to the merged_list :return: The updated merged_list with the values for the COMPONENT added onto it """ merged_list.extend(getattr(component, key)) return merged_list
python
def combine_lists_reducer( key: str, merged_list: list, component: COMPONENT ) -> list: """ 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: The COMPONENT instance from which to append values to the merged_list :return: The updated merged_list with the values for the COMPONENT added onto it """ merged_list.extend(getattr(component, key)) return merged_list
[ "def", "combine_lists_reducer", "(", "key", ":", "str", ",", "merged_list", ":", "list", ",", "component", ":", "COMPONENT", ")", "->", "list", ":", "merged_list", ".", "extend", "(", "getattr", "(", "component", ",", "key", ")", ")", "return", "merged_lis...
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: The COMPONENT instance from which to append values to the merged_list :return: The updated merged_list with the values for the COMPONENT added onto it
[ "Reducer", "function", "to", "combine", "the", "lists", "for", "the", "specified", "key", "into", "a", "single", "flat", "list" ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/writing/components/definitions.py#L61-L84
train
44,667
seomoz/qless-py
qless/listener.py
Listener.listen
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: self._channels = []
python
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: self._channels = []
[ "def", "listen", "(", "self", ")", ":", "try", ":", "self", ".", "_pubsub", ".", "subscribe", "(", "self", ".", "_channels", ")", "for", "message", "in", "self", ".", "_pubsub", ".", "listen", "(", ")", ":", "if", "message", "[", "'type'", "]", "==...
Listen for events as they come in
[ "Listen", "for", "events", "as", "they", "come", "in" ]
3eda4ffcd4c0016c9a7e44f780d6155e1a354dda
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/listener.py#L17-L25
train
44,668
seomoz/qless-py
qless/listener.py
Listener.thread
def thread(self): '''Run in a thread''' thread = threading.Thread(target=self.listen) thread.start() try: yield self finally: self.unlisten() thread.join()
python
def thread(self): '''Run in a thread''' thread = threading.Thread(target=self.listen) thread.start() try: yield self finally: self.unlisten() thread.join()
[ "def", "thread", "(", "self", ")", ":", "thread", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "listen", ")", "thread", ".", "start", "(", ")", "try", ":", "yield", "self", "finally", ":", "self", ".", "unlisten", "(", ")", "th...
Run in a thread
[ "Run", "in", "a", "thread" ]
3eda4ffcd4c0016c9a7e44f780d6155e1a354dda
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/listener.py#L32-L40
train
44,669
seomoz/qless-py
qless/listener.py
Events.listen
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.get(channel) if func: func(message['data'])
python
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.get(channel) if func: func(message['data'])
[ "def", "listen", "(", "self", ")", ":", "for", "message", "in", "Listener", ".", "listen", "(", "self", ")", ":", "logger", ".", "debug", "(", "'Message: %s'", ",", "message", ")", "# Strip off the 'namespace' from the channel", "channel", "=", "message", "[",...
Listen for events
[ "Listen", "for", "events" ]
3eda4ffcd4c0016c9a7e44f780d6155e1a354dda
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/listener.py#L56-L64
train
44,670
seomoz/qless-py
qless/listener.py
Events.on
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
python
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
[ "def", "on", "(", "self", ",", "evt", ",", "func", ")", ":", "if", "evt", "not", "in", "self", ".", "_callbacks", ":", "raise", "NotImplementedError", "(", "'callback \"%s\"'", "%", "evt", ")", "else", ":", "self", ".", "_callbacks", "[", "evt", "]", ...
Set a callback handler for a pubsub event
[ "Set", "a", "callback", "handler", "for", "a", "pubsub", "event" ]
3eda4ffcd4c0016c9a7e44f780d6155e1a354dda
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/listener.py#L66-L71
train
44,671
seomoz/qless-py
qless/config.py
Config.get
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
python
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
[ "def", "get", "(", "self", ",", "option", ",", "default", "=", "None", ")", ":", "val", "=", "self", "[", "option", "]", "return", "(", "val", "is", "None", "and", "default", ")", "or", "val" ]
Get a particular option, or the default if it's missing
[ "Get", "a", "particular", "option", "or", "the", "default", "if", "it", "s", "missing" ]
3eda4ffcd4c0016c9a7e44f780d6155e1a354dda
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/config.py#L45-L48
train
44,672
seomoz/qless-py
qless/config.py
Config.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
python
def pop(self, option, default=None): '''Just like `dict.pop`''' val = self[option] del self[option] return (val is None and default) or val
[ "def", "pop", "(", "self", ",", "option", ",", "default", "=", "None", ")", ":", "val", "=", "self", "[", "option", "]", "del", "self", "[", "option", "]", "return", "(", "val", "is", "None", "and", "default", ")", "or", "val" ]
Just like `dict.pop`
[ "Just", "like", "dict", ".", "pop" ]
3eda4ffcd4c0016c9a7e44f780d6155e1a354dda
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/config.py#L58-L62
train
44,673
seomoz/qless-py
qless/config.py
Config.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
python
def update(self, other=(), **kwargs): '''Just like `dict.update`''' _kwargs = dict(kwargs) _kwargs.update(other) for key, value in _kwargs.items(): self[key] = value
[ "def", "update", "(", "self", ",", "other", "=", "(", ")", ",", "*", "*", "kwargs", ")", ":", "_kwargs", "=", "dict", "(", "kwargs", ")", "_kwargs", ".", "update", "(", "other", ")", "for", "key", ",", "value", "in", "_kwargs", ".", "items", "(",...
Just like `dict.update`
[ "Just", "like", "dict", ".", "update" ]
3eda4ffcd4c0016c9a7e44f780d6155e1a354dda
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/config.py#L64-L69
train
44,674
sernst/cauldron
cauldron/cli/server/routes/synchronize/__init__.py
touch_project
def touch_project(): """ Touches the project to trigger refreshing its cauldron.json state. """ r = Response() project = cd.project.get_internal_project() if project: project.refresh() else: r.fail( code='NO_PROJECT', message='No open project to refresh' ) return r.update( sync_time=sync_status.get('time', 0) ).flask_serialize()
python
def touch_project(): """ Touches the project to trigger refreshing its cauldron.json state. """ r = Response() project = cd.project.get_internal_project() if project: project.refresh() else: r.fail( code='NO_PROJECT', message='No open project to refresh' ) return r.update( sync_time=sync_status.get('time', 0) ).flask_serialize()
[ "def", "touch_project", "(", ")", ":", "r", "=", "Response", "(", ")", "project", "=", "cd", ".", "project", ".", "get_internal_project", "(", ")", "if", "project", ":", "project", ".", "refresh", "(", ")", "else", ":", "r", ".", "fail", "(", "code",...
Touches the project to trigger refreshing its cauldron.json state.
[ "Touches", "the", "project", "to", "trigger", "refreshing", "its", "cauldron", ".", "json", "state", "." ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/cli/server/routes/synchronize/__init__.py#L28-L45
train
44,675
sernst/cauldron
cauldron/cli/server/routes/synchronize/__init__.py
fetch_synchronize_status
def fetch_synchronize_status(): """ Returns the synchronization status information for the currently opened project """ r = Response() project = cd.project.get_internal_project() if not project: r.fail( code='NO_PROJECT', message='No open project on which to retrieve status' ) else: with open(project.source_path, 'r') as f: definition = json.load(f) result = status.of_project(project) r.update( sync_time=sync_status.get('time', 0), source_directory=project.source_directory, remote_source_directory=project.remote_source_directory, status=result, definition=definition ) return r.flask_serialize()
python
def fetch_synchronize_status(): """ Returns the synchronization status information for the currently opened project """ r = Response() project = cd.project.get_internal_project() if not project: r.fail( code='NO_PROJECT', message='No open project on which to retrieve status' ) else: with open(project.source_path, 'r') as f: definition = json.load(f) result = status.of_project(project) r.update( sync_time=sync_status.get('time', 0), source_directory=project.source_directory, remote_source_directory=project.remote_source_directory, status=result, definition=definition ) return r.flask_serialize()
[ "def", "fetch_synchronize_status", "(", ")", ":", "r", "=", "Response", "(", ")", "project", "=", "cd", ".", "project", ".", "get_internal_project", "(", ")", "if", "not", "project", ":", "r", ".", "fail", "(", "code", "=", "'NO_PROJECT'", ",", "message"...
Returns the synchronization status information for the currently opened project
[ "Returns", "the", "synchronization", "status", "information", "for", "the", "currently", "opened", "project" ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/cli/server/routes/synchronize/__init__.py#L50-L76
train
44,676
sernst/cauldron
cauldron/cli/server/routes/synchronize/__init__.py
download_file
def download_file(filename: str): """ downloads the specified project file if it exists """ project = cd.project.get_internal_project() source_directory = project.source_directory if project else None if not filename or not project or not source_directory: return '', 204 path = os.path.realpath(os.path.join( source_directory, '..', '__cauldron_downloads', filename )) if not os.path.exists(path): return '', 204 return flask.send_file(path, mimetype=mimetypes.guess_type(path)[0])
python
def download_file(filename: str): """ downloads the specified project file if it exists """ project = cd.project.get_internal_project() source_directory = project.source_directory if project else None if not filename or not project or not source_directory: return '', 204 path = os.path.realpath(os.path.join( source_directory, '..', '__cauldron_downloads', filename )) if not os.path.exists(path): return '', 204 return flask.send_file(path, mimetype=mimetypes.guess_type(path)[0])
[ "def", "download_file", "(", "filename", ":", "str", ")", ":", "project", "=", "cd", ".", "project", ".", "get_internal_project", "(", ")", "source_directory", "=", "project", ".", "source_directory", "if", "project", "else", "None", "if", "not", "filename", ...
downloads the specified project file if it exists
[ "downloads", "the", "specified", "project", "file", "if", "it", "exists" ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/cli/server/routes/synchronize/__init__.py#L198-L217
train
44,677
sernst/cauldron
cauldron/session/projects/definitions.py
get_project_source_path
def get_project_source_path(path: str) -> str: """ Converts the given path into a project source path, to the cauldron.json file. If the path already points to a cauldron.json file, the path is returned without modification. :param path: The path to convert into a project source path """ path = environ.paths.clean(path) if not path.endswith('cauldron.json'): return os.path.join(path, 'cauldron.json') return path
python
def get_project_source_path(path: str) -> str: """ Converts the given path into a project source path, to the cauldron.json file. If the path already points to a cauldron.json file, the path is returned without modification. :param path: The path to convert into a project source path """ path = environ.paths.clean(path) if not path.endswith('cauldron.json'): return os.path.join(path, 'cauldron.json') return path
[ "def", "get_project_source_path", "(", "path", ":", "str", ")", "->", "str", ":", "path", "=", "environ", ".", "paths", ".", "clean", "(", "path", ")", "if", "not", "path", ".", "endswith", "(", "'cauldron.json'", ")", ":", "return", "os", ".", "path",...
Converts the given path into a project source path, to the cauldron.json file. If the path already points to a cauldron.json file, the path is returned without modification. :param path: The path to convert into a project source path
[ "Converts", "the", "given", "path", "into", "a", "project", "source", "path", "to", "the", "cauldron", ".", "json", "file", ".", "If", "the", "path", "already", "points", "to", "a", "cauldron", ".", "json", "file", "the", "path", "is", "returned", "witho...
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/projects/definitions.py#L7-L22
train
44,678
sernst/cauldron
cauldron/session/projects/definitions.py
load_project_definition
def load_project_definition(path: str) -> dict: """ Load the cauldron.json project definition file for the given path. The path can be either a source path to the cauldron.json file or the source directory where a cauldron.json file resides. :param path: The source path or directory where the definition file will be loaded """ source_path = get_project_source_path(path) if not os.path.exists(source_path): raise FileNotFoundError('Missing project file: {}'.format(source_path)) with open(source_path, 'r') as f: out = json.load(f) project_folder = os.path.split(os.path.dirname(source_path))[-1] if 'id' not in out or not out['id']: out['id'] = project_folder return out
python
def load_project_definition(path: str) -> dict: """ Load the cauldron.json project definition file for the given path. The path can be either a source path to the cauldron.json file or the source directory where a cauldron.json file resides. :param path: The source path or directory where the definition file will be loaded """ source_path = get_project_source_path(path) if not os.path.exists(source_path): raise FileNotFoundError('Missing project file: {}'.format(source_path)) with open(source_path, 'r') as f: out = json.load(f) project_folder = os.path.split(os.path.dirname(source_path))[-1] if 'id' not in out or not out['id']: out['id'] = project_folder return out
[ "def", "load_project_definition", "(", "path", ":", "str", ")", "->", "dict", ":", "source_path", "=", "get_project_source_path", "(", "path", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "source_path", ")", ":", "raise", "FileNotFoundError", "("...
Load the cauldron.json project definition file for the given path. The path can be either a source path to the cauldron.json file or the source directory where a cauldron.json file resides. :param path: The source path or directory where the definition file will be loaded
[ "Load", "the", "cauldron", ".", "json", "project", "definition", "file", "for", "the", "given", "path", ".", "The", "path", "can", "be", "either", "a", "source", "path", "to", "the", "cauldron", ".", "json", "file", "or", "the", "source", "directory", "w...
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/projects/definitions.py#L25-L46
train
44,679
sernst/cauldron
cauldron/environ/systems.py
simplify_path
def simplify_path(path: str, path_prefixes: list = None) -> str: """ Simplifies package paths by replacing path prefixes with values specified in the replacements list :param path: :param path_prefixes: :return: """ test_path = '{}'.format(path if path else '') replacements = (path_prefixes if path_prefixes else []).copy() replacements.append(('~', os.path.expanduser('~'))) for key, value in replacements: if test_path.startswith(value): return '{}{}'.format(key, test_path[len(value):]) return test_path
python
def simplify_path(path: str, path_prefixes: list = None) -> str: """ Simplifies package paths by replacing path prefixes with values specified in the replacements list :param path: :param path_prefixes: :return: """ test_path = '{}'.format(path if path else '') replacements = (path_prefixes if path_prefixes else []).copy() replacements.append(('~', os.path.expanduser('~'))) for key, value in replacements: if test_path.startswith(value): return '{}{}'.format(key, test_path[len(value):]) return test_path
[ "def", "simplify_path", "(", "path", ":", "str", ",", "path_prefixes", ":", "list", "=", "None", ")", "->", "str", ":", "test_path", "=", "'{}'", ".", "format", "(", "path", "if", "path", "else", "''", ")", "replacements", "=", "(", "path_prefixes", "i...
Simplifies package paths by replacing path prefixes with values specified in the replacements list :param path: :param path_prefixes: :return:
[ "Simplifies", "package", "paths", "by", "replacing", "path", "prefixes", "with", "values", "specified", "in", "the", "replacements", "list" ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/environ/systems.py#L20-L38
train
44,680
sernst/cauldron
cauldron/environ/systems.py
module_to_package_data
def module_to_package_data( name: str, entry, path_prefixes: list = None ) -> typing.Union[dict, None]: """ Converts a module entry into a package data dictionary with information about the module. including version and location on disk :param name: :param entry: :param path_prefixes: :return: """ if name.find('.') > -1: # Not interested in sub-packages, only root ones return None version = getattr(entry, '__version__', None) version = version if not hasattr(version, 'version') else version.version location = getattr(entry, '__file__', sys.exec_prefix) if version is None or location.startswith(sys.exec_prefix): # Not interested in core packages. They obviously are standard and # don't need to be included in an output. return None return dict( name=name, version=version, location=simplify_path(location, path_prefixes) )
python
def module_to_package_data( name: str, entry, path_prefixes: list = None ) -> typing.Union[dict, None]: """ Converts a module entry into a package data dictionary with information about the module. including version and location on disk :param name: :param entry: :param path_prefixes: :return: """ if name.find('.') > -1: # Not interested in sub-packages, only root ones return None version = getattr(entry, '__version__', None) version = version if not hasattr(version, 'version') else version.version location = getattr(entry, '__file__', sys.exec_prefix) if version is None or location.startswith(sys.exec_prefix): # Not interested in core packages. They obviously are standard and # don't need to be included in an output. return None return dict( name=name, version=version, location=simplify_path(location, path_prefixes) )
[ "def", "module_to_package_data", "(", "name", ":", "str", ",", "entry", ",", "path_prefixes", ":", "list", "=", "None", ")", "->", "typing", ".", "Union", "[", "dict", ",", "None", "]", ":", "if", "name", ".", "find", "(", "'.'", ")", ">", "-", "1"...
Converts a module entry into a package data dictionary with information about the module. including version and location on disk :param name: :param entry: :param path_prefixes: :return:
[ "Converts", "a", "module", "entry", "into", "a", "package", "data", "dictionary", "with", "information", "about", "the", "module", ".", "including", "version", "and", "location", "on", "disk" ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/environ/systems.py#L41-L73
train
44,681
sernst/cauldron
cauldron/environ/systems.py
get_system_data
def get_system_data() -> typing.Union[None, dict]: """ Returns information about the system in which Cauldron is running. If the information cannot be found, None is returned instead. :return: Dictionary containing information about the Cauldron system, whic includes: * name * location * version """ site_packages = get_site_packages() path_prefixes = [('[SP]', p) for p in site_packages] path_prefixes.append(('[CORE]', sys.exec_prefix)) packages = [ module_to_package_data(name, entry, path_prefixes) for name, entry in list(sys.modules.items()) ] python_data = dict( version=list(sys.version_info), executable=simplify_path(sys.executable), directory=simplify_path(sys.exec_prefix), site_packages=[simplify_path(sp) for sp in site_packages] ) return dict( python=python_data, packages=[p for p in packages if p is not None] )
python
def get_system_data() -> typing.Union[None, dict]: """ Returns information about the system in which Cauldron is running. If the information cannot be found, None is returned instead. :return: Dictionary containing information about the Cauldron system, whic includes: * name * location * version """ site_packages = get_site_packages() path_prefixes = [('[SP]', p) for p in site_packages] path_prefixes.append(('[CORE]', sys.exec_prefix)) packages = [ module_to_package_data(name, entry, path_prefixes) for name, entry in list(sys.modules.items()) ] python_data = dict( version=list(sys.version_info), executable=simplify_path(sys.executable), directory=simplify_path(sys.exec_prefix), site_packages=[simplify_path(sp) for sp in site_packages] ) return dict( python=python_data, packages=[p for p in packages if p is not None] )
[ "def", "get_system_data", "(", ")", "->", "typing", ".", "Union", "[", "None", ",", "dict", "]", ":", "site_packages", "=", "get_site_packages", "(", ")", "path_prefixes", "=", "[", "(", "'[SP]'", ",", "p", ")", "for", "p", "in", "site_packages", "]", ...
Returns information about the system in which Cauldron is running. If the information cannot be found, None is returned instead. :return: Dictionary containing information about the Cauldron system, whic includes: * name * location * version
[ "Returns", "information", "about", "the", "system", "in", "which", "Cauldron", "is", "running", ".", "If", "the", "information", "cannot", "be", "found", "None", "is", "returned", "instead", "." ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/environ/systems.py#L76-L108
train
44,682
sernst/cauldron
cauldron/environ/systems.py
remove
def remove(path: str, max_retries: int = 3) -> bool: """ Removes the specified path from the local filesystem if it exists. Directories will be removed along with all files and folders within them as well as files. :param path: The location of the file or folder to remove. :param max_retries: The number of times to retry before giving up. :return: A boolean indicating whether or not the removal was successful. """ if not path: return False if not os.path.exists(path): return True remover = os.remove if os.path.isfile(path) else shutil.rmtree for attempt in range(max_retries): try: remover(path) return True except Exception: # Pause briefly in case there's a race condition on lock # for the target. time.sleep(0.02) return False
python
def remove(path: str, max_retries: int = 3) -> bool: """ Removes the specified path from the local filesystem if it exists. Directories will be removed along with all files and folders within them as well as files. :param path: The location of the file or folder to remove. :param max_retries: The number of times to retry before giving up. :return: A boolean indicating whether or not the removal was successful. """ if not path: return False if not os.path.exists(path): return True remover = os.remove if os.path.isfile(path) else shutil.rmtree for attempt in range(max_retries): try: remover(path) return True except Exception: # Pause briefly in case there's a race condition on lock # for the target. time.sleep(0.02) return False
[ "def", "remove", "(", "path", ":", "str", ",", "max_retries", ":", "int", "=", "3", ")", "->", "bool", ":", "if", "not", "path", ":", "return", "False", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "return", "True", "remo...
Removes the specified path from the local filesystem if it exists. Directories will be removed along with all files and folders within them as well as files. :param path: The location of the file or folder to remove. :param max_retries: The number of times to retry before giving up. :return: A boolean indicating whether or not the removal was successful.
[ "Removes", "the", "specified", "path", "from", "the", "local", "filesystem", "if", "it", "exists", ".", "Directories", "will", "be", "removed", "along", "with", "all", "files", "and", "folders", "within", "them", "as", "well", "as", "files", "." ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/environ/systems.py#L123-L153
train
44,683
sernst/cauldron
cauldron/environ/systems.py
end
def end(code: int): """ Ends the application with the specified error code, adding whitespace to the end of the console log output for clarity :param code: The integer status code to apply on exit. If the value is non-zero, indicating an error, a message will be printed to the console to inform the user that the application exited in error """ print('\n') if code != 0: log('Failed with status code: {}'.format(code), whitespace=1) sys.exit(code)
python
def end(code: int): """ Ends the application with the specified error code, adding whitespace to the end of the console log output for clarity :param code: The integer status code to apply on exit. If the value is non-zero, indicating an error, a message will be printed to the console to inform the user that the application exited in error """ print('\n') if code != 0: log('Failed with status code: {}'.format(code), whitespace=1) sys.exit(code)
[ "def", "end", "(", "code", ":", "int", ")", ":", "print", "(", "'\\n'", ")", "if", "code", "!=", "0", ":", "log", "(", "'Failed with status code: {}'", ".", "format", "(", "code", ")", ",", "whitespace", "=", "1", ")", "sys", ".", "exit", "(", "cod...
Ends the application with the specified error code, adding whitespace to the end of the console log output for clarity :param code: The integer status code to apply on exit. If the value is non-zero, indicating an error, a message will be printed to the console to inform the user that the application exited in error
[ "Ends", "the", "application", "with", "the", "specified", "error", "code", "adding", "whitespace", "to", "the", "end", "of", "the", "console", "log", "output", "for", "clarity" ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/environ/systems.py#L156-L170
train
44,684
sernst/cauldron
cauldron/session/definitions.py
FileDefinition.folder
def folder(self) -> typing.Union[str, None]: """ The folder, relative to the project source_directory, where the file resides :return: """ if 'folder' in self.data: return self.data.get('folder') elif self.project_folder: if callable(self.project_folder): return self.project_folder() else: return self.project_folder return None
python
def folder(self) -> typing.Union[str, None]: """ The folder, relative to the project source_directory, where the file resides :return: """ if 'folder' in self.data: return self.data.get('folder') elif self.project_folder: if callable(self.project_folder): return self.project_folder() else: return self.project_folder return None
[ "def", "folder", "(", "self", ")", "->", "typing", ".", "Union", "[", "str", ",", "None", "]", ":", "if", "'folder'", "in", "self", ".", "data", ":", "return", "self", ".", "data", ".", "get", "(", "'folder'", ")", "elif", "self", ".", "project_fol...
The folder, relative to the project source_directory, where the file resides :return:
[ "The", "folder", "relative", "to", "the", "project", "source_directory", "where", "the", "file", "resides" ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/definitions.py#L91-L106
train
44,685
sernst/cauldron
cauldron/session/exposed.py
render_stop_display
def render_stop_display(step: 'projects.ProjectStep', message: str): """Renders a stop action to the Cauldron display.""" stack = render_stack.get_formatted_stack_frame( project=step.project, error_stack=False ) try: names = [frame['filename'] for frame in stack] index = names.index(os.path.realpath(__file__)) frame = stack[index - 1] except Exception: frame = {} stop_message = ( '{}'.format(message) if message else 'This step was explicitly stopped prior to its completion' ) dom = templating.render_template( 'step-stop.html', message=stop_message, frame=frame ) step.report.append_body(dom)
python
def render_stop_display(step: 'projects.ProjectStep', message: str): """Renders a stop action to the Cauldron display.""" stack = render_stack.get_formatted_stack_frame( project=step.project, error_stack=False ) try: names = [frame['filename'] for frame in stack] index = names.index(os.path.realpath(__file__)) frame = stack[index - 1] except Exception: frame = {} stop_message = ( '{}'.format(message) if message else 'This step was explicitly stopped prior to its completion' ) dom = templating.render_template( 'step-stop.html', message=stop_message, frame=frame ) step.report.append_body(dom)
[ "def", "render_stop_display", "(", "step", ":", "'projects.ProjectStep'", ",", "message", ":", "str", ")", ":", "stack", "=", "render_stack", ".", "get_formatted_stack_frame", "(", "project", "=", "step", ".", "project", ",", "error_stack", "=", "False", ")", ...
Renders a stop action to the Cauldron display.
[ "Renders", "a", "stop", "action", "to", "the", "Cauldron", "display", "." ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/exposed.py#L283-L308
train
44,686
sernst/cauldron
cauldron/session/exposed.py
ExposedProject.id
def id(self) -> typing.Union[str, None]: """Identifier for the project.""" return self._project.id if self._project else None
python
def id(self) -> typing.Union[str, None]: """Identifier for the project.""" return self._project.id if self._project else None
[ "def", "id", "(", "self", ")", "->", "typing", ".", "Union", "[", "str", ",", "None", "]", ":", "return", "self", ".", "_project", ".", "id", "if", "self", ".", "_project", "else", "None" ]
Identifier for the project.
[ "Identifier", "for", "the", "project", "." ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/exposed.py#L36-L38
train
44,687
sernst/cauldron
cauldron/session/exposed.py
ExposedProject.display
def display(self) -> typing.Union[None, report.Report]: """The display report for the current project.""" return ( self._project.current_step.report if self._project and self._project.current_step else None )
python
def display(self) -> typing.Union[None, report.Report]: """The display report for the current project.""" return ( self._project.current_step.report if self._project and self._project.current_step else None )
[ "def", "display", "(", "self", ")", "->", "typing", ".", "Union", "[", "None", ",", "report", ".", "Report", "]", ":", "return", "(", "self", ".", "_project", ".", "current_step", ".", "report", "if", "self", ".", "_project", "and", "self", ".", "_pr...
The display report for the current project.
[ "The", "display", "report", "for", "the", "current", "project", "." ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/exposed.py#L41-L47
train
44,688
sernst/cauldron
cauldron/session/exposed.py
ExposedProject.shared
def shared(self) -> typing.Union[None, SharedCache]: """The shared display object associated with this project.""" return self._project.shared if self._project else None
python
def shared(self) -> typing.Union[None, SharedCache]: """The shared display object associated with this project.""" return self._project.shared if self._project else None
[ "def", "shared", "(", "self", ")", "->", "typing", ".", "Union", "[", "None", ",", "SharedCache", "]", ":", "return", "self", ".", "_project", ".", "shared", "if", "self", ".", "_project", "else", "None" ]
The shared display object associated with this project.
[ "The", "shared", "display", "object", "associated", "with", "this", "project", "." ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/exposed.py#L50-L52
train
44,689
sernst/cauldron
cauldron/session/exposed.py
ExposedProject.settings
def settings(self) -> typing.Union[None, SharedCache]: """The settings associated with this project.""" return self._project.settings if self._project else None
python
def settings(self) -> typing.Union[None, SharedCache]: """The settings associated with this project.""" return self._project.settings if self._project else None
[ "def", "settings", "(", "self", ")", "->", "typing", ".", "Union", "[", "None", ",", "SharedCache", "]", ":", "return", "self", ".", "_project", ".", "settings", "if", "self", ".", "_project", "else", "None" ]
The settings associated with this project.
[ "The", "settings", "associated", "with", "this", "project", "." ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/exposed.py#L55-L57
train
44,690
sernst/cauldron
cauldron/session/exposed.py
ExposedProject.title
def title(self) -> typing.Union[None, str]: """The title of this project.""" return self._project.title if self._project else None
python
def title(self) -> typing.Union[None, str]: """The title of this project.""" return self._project.title if self._project else None
[ "def", "title", "(", "self", ")", "->", "typing", ".", "Union", "[", "None", ",", "str", "]", ":", "return", "self", ".", "_project", ".", "title", "if", "self", ".", "_project", "else", "None" ]
The title of this project.
[ "The", "title", "of", "this", "project", "." ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/exposed.py#L60-L62
train
44,691
sernst/cauldron
cauldron/session/exposed.py
ExposedProject.title
def title(self, value: typing.Union[None, str]): """ Modifies the title of the project, which is initially loaded from the `cauldron.json` file. """ if not self._project: raise RuntimeError('Failed to assign title to an unloaded project') self._project.title = value
python
def title(self, value: typing.Union[None, str]): """ Modifies the title of the project, which is initially loaded from the `cauldron.json` file. """ if not self._project: raise RuntimeError('Failed to assign title to an unloaded project') self._project.title = value
[ "def", "title", "(", "self", ",", "value", ":", "typing", ".", "Union", "[", "None", ",", "str", "]", ")", ":", "if", "not", "self", ".", "_project", ":", "raise", "RuntimeError", "(", "'Failed to assign title to an unloaded project'", ")", "self", ".", "_...
Modifies the title of the project, which is initially loaded from the `cauldron.json` file.
[ "Modifies", "the", "title", "of", "the", "project", "which", "is", "initially", "loaded", "from", "the", "cauldron", ".", "json", "file", "." ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/exposed.py#L65-L72
train
44,692
sernst/cauldron
cauldron/session/exposed.py
ExposedProject.load
def load(self, project: typing.Union[projects.Project, None]): """Connects this object to the specified source project.""" self._project = project
python
def load(self, project: typing.Union[projects.Project, None]): """Connects this object to the specified source project.""" self._project = project
[ "def", "load", "(", "self", ",", "project", ":", "typing", ".", "Union", "[", "projects", ".", "Project", ",", "None", "]", ")", ":", "self", ".", "_project", "=", "project" ]
Connects this object to the specified source project.
[ "Connects", "this", "object", "to", "the", "specified", "source", "project", "." ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/exposed.py#L74-L76
train
44,693
sernst/cauldron
cauldron/session/exposed.py
ExposedProject.path
def path(self, *args: typing.List[str]) -> typing.Union[None, str]: """ Creates an absolute path in the project source directory from the relative path components. :param args: Relative components for creating a path within the project source directory :return: An absolute path to the specified file or directory within the project source directory. """ if not self._project: return None return environ.paths.clean(os.path.join( self._project.source_directory, *args ))
python
def path(self, *args: typing.List[str]) -> typing.Union[None, str]: """ Creates an absolute path in the project source directory from the relative path components. :param args: Relative components for creating a path within the project source directory :return: An absolute path to the specified file or directory within the project source directory. """ if not self._project: return None return environ.paths.clean(os.path.join( self._project.source_directory, *args ))
[ "def", "path", "(", "self", ",", "*", "args", ":", "typing", ".", "List", "[", "str", "]", ")", "->", "typing", ".", "Union", "[", "None", ",", "str", "]", ":", "if", "not", "self", ".", "_project", ":", "return", "None", "return", "environ", "."...
Creates an absolute path in the project source directory from the relative path components. :param args: Relative components for creating a path within the project source directory :return: An absolute path to the specified file or directory within the project source directory.
[ "Creates", "an", "absolute", "path", "in", "the", "project", "source", "directory", "from", "the", "relative", "path", "components", "." ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/exposed.py#L82-L100
train
44,694
sernst/cauldron
cauldron/session/exposed.py
ExposedProject.stop
def stop(self, message: str = None, silent: bool = False): """ Stops the execution of the project at the current step immediately without raising an error. Use this to abort running the project in situations where some critical branching action should prevent the project from continuing to run. :param message: A custom display message to include in the display for the stop action. This message is ignored if silent is set to True. :param silent: When True nothing will be shown in the notebook display when the step is stopped. When False, the notebook display will include information relating to the stopped action. """ me = self.get_internal_project() if not me or not me.current_step: return if not silent: render_stop_display(me.current_step, message) raise UserAbortError(halt=True)
python
def stop(self, message: str = None, silent: bool = False): """ Stops the execution of the project at the current step immediately without raising an error. Use this to abort running the project in situations where some critical branching action should prevent the project from continuing to run. :param message: A custom display message to include in the display for the stop action. This message is ignored if silent is set to True. :param silent: When True nothing will be shown in the notebook display when the step is stopped. When False, the notebook display will include information relating to the stopped action. """ me = self.get_internal_project() if not me or not me.current_step: return if not silent: render_stop_display(me.current_step, message) raise UserAbortError(halt=True)
[ "def", "stop", "(", "self", ",", "message", ":", "str", "=", "None", ",", "silent", ":", "bool", "=", "False", ")", ":", "me", "=", "self", ".", "get_internal_project", "(", ")", "if", "not", "me", "or", "not", "me", ".", "current_step", ":", "retu...
Stops the execution of the project at the current step immediately without raising an error. Use this to abort running the project in situations where some critical branching action should prevent the project from continuing to run. :param message: A custom display message to include in the display for the stop action. This message is ignored if silent is set to True. :param silent: When True nothing will be shown in the notebook display when the step is stopped. When False, the notebook display will include information relating to the stopped action.
[ "Stops", "the", "execution", "of", "the", "project", "at", "the", "current", "step", "immediately", "without", "raising", "an", "error", ".", "Use", "this", "to", "abort", "running", "the", "project", "in", "situations", "where", "some", "critical", "branching...
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/exposed.py#L102-L123
train
44,695
sernst/cauldron
cauldron/session/exposed.py
ExposedProject.get_internal_project
def get_internal_project( self, timeout: float = 1 ) -> typing.Union['projects.Project', None]: """ Attempts to return the internally loaded project. This function prevents race condition issues where projects are loaded via threads because the internal loop will try to continuously load the internal project until it is available or until the timeout is reached. :param timeout: Maximum number of seconds to wait before giving up and returning None. """ count = int(timeout / 0.1) for _ in range(count): project = self.internal_project if project: return project time.sleep(0.1) return self.internal_project
python
def get_internal_project( self, timeout: float = 1 ) -> typing.Union['projects.Project', None]: """ Attempts to return the internally loaded project. This function prevents race condition issues where projects are loaded via threads because the internal loop will try to continuously load the internal project until it is available or until the timeout is reached. :param timeout: Maximum number of seconds to wait before giving up and returning None. """ count = int(timeout / 0.1) for _ in range(count): project = self.internal_project if project: return project time.sleep(0.1) return self.internal_project
[ "def", "get_internal_project", "(", "self", ",", "timeout", ":", "float", "=", "1", ")", "->", "typing", ".", "Union", "[", "'projects.Project'", ",", "None", "]", ":", "count", "=", "int", "(", "timeout", "/", "0.1", ")", "for", "_", "in", "range", ...
Attempts to return the internally loaded project. This function prevents race condition issues where projects are loaded via threads because the internal loop will try to continuously load the internal project until it is available or until the timeout is reached. :param timeout: Maximum number of seconds to wait before giving up and returning None.
[ "Attempts", "to", "return", "the", "internally", "loaded", "project", ".", "This", "function", "prevents", "race", "condition", "issues", "where", "projects", "are", "loaded", "via", "threads", "because", "the", "internal", "loop", "will", "try", "to", "continuo...
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/exposed.py#L125-L146
train
44,696
sernst/cauldron
cauldron/session/exposed.py
ExposedStep._step
def _step(self) -> typing.Union[None, 'projects.ProjectStep']: """ Internal access to the source step. Should not be used outside of Cauldron development. :return: The ProjectStep instance that this ExposedStep represents """ import cauldron try: return cauldron.project.get_internal_project().current_step except Exception: return None
python
def _step(self) -> typing.Union[None, 'projects.ProjectStep']: """ Internal access to the source step. Should not be used outside of Cauldron development. :return: The ProjectStep instance that this ExposedStep represents """ import cauldron try: return cauldron.project.get_internal_project().current_step except Exception: return None
[ "def", "_step", "(", "self", ")", "->", "typing", ".", "Union", "[", "None", ",", "'projects.ProjectStep'", "]", ":", "import", "cauldron", "try", ":", "return", "cauldron", ".", "project", ".", "get_internal_project", "(", ")", ".", "current_step", "except"...
Internal access to the source step. Should not be used outside of Cauldron development. :return: The ProjectStep instance that this ExposedStep represents
[ "Internal", "access", "to", "the", "source", "step", ".", "Should", "not", "be", "used", "outside", "of", "Cauldron", "development", "." ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/exposed.py#L156-L168
train
44,697
sernst/cauldron
cauldron/session/exposed.py
ExposedStep.stop
def stop( self, message: str = None, silent: bool = False, halt: bool = False ): """ Stops the execution of the current step immediately without raising an error. Use this to abort the step running process if you want to return early. :param message: A custom display message to include in the display for the stop action. This message is ignored if silent is set to True. :param silent: When True nothing will be shown in the notebook display when the step is stopped. When False, the notebook display will include information relating to the stopped action. :param halt: Whether or not to keep running other steps in the project after this step has been stopped. By default this is False and after this stops running, future steps in the project will continue running if they've been queued to run. If you want stop execution entirely, set this value to True and the current run command will be aborted entirely. """ step = self._step if not step: return if not silent: render_stop_display(step, message) raise UserAbortError(halt=halt)
python
def stop( self, message: str = None, silent: bool = False, halt: bool = False ): """ Stops the execution of the current step immediately without raising an error. Use this to abort the step running process if you want to return early. :param message: A custom display message to include in the display for the stop action. This message is ignored if silent is set to True. :param silent: When True nothing will be shown in the notebook display when the step is stopped. When False, the notebook display will include information relating to the stopped action. :param halt: Whether or not to keep running other steps in the project after this step has been stopped. By default this is False and after this stops running, future steps in the project will continue running if they've been queued to run. If you want stop execution entirely, set this value to True and the current run command will be aborted entirely. """ step = self._step if not step: return if not silent: render_stop_display(step, message) raise UserAbortError(halt=halt)
[ "def", "stop", "(", "self", ",", "message", ":", "str", "=", "None", ",", "silent", ":", "bool", "=", "False", ",", "halt", ":", "bool", "=", "False", ")", ":", "step", "=", "self", ".", "_step", "if", "not", "step", ":", "return", "if", "not", ...
Stops the execution of the current step immediately without raising an error. Use this to abort the step running process if you want to return early. :param message: A custom display message to include in the display for the stop action. This message is ignored if silent is set to True. :param silent: When True nothing will be shown in the notebook display when the step is stopped. When False, the notebook display will include information relating to the stopped action. :param halt: Whether or not to keep running other steps in the project after this step has been stopped. By default this is False and after this stops running, future steps in the project will continue running if they've been queued to run. If you want stop execution entirely, set this value to True and the current run command will be aborted entirely.
[ "Stops", "the", "execution", "of", "the", "current", "step", "immediately", "without", "raising", "an", "error", ".", "Use", "this", "to", "abort", "the", "step", "running", "process", "if", "you", "want", "to", "return", "early", "." ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/exposed.py#L212-L244
train
44,698
sernst/cauldron
cauldron/session/exposed.py
ExposedStep.write_to_console
def write_to_console(self, message: str): """ Writes the specified message to the console stdout without including it in the notebook display. """ if not self._step: raise ValueError( 'Cannot write to the console stdout on an uninitialized step' ) interceptor = self._step.report.stdout_interceptor interceptor.write_source('{}'.format(message))
python
def write_to_console(self, message: str): """ Writes the specified message to the console stdout without including it in the notebook display. """ if not self._step: raise ValueError( 'Cannot write to the console stdout on an uninitialized step' ) interceptor = self._step.report.stdout_interceptor interceptor.write_source('{}'.format(message))
[ "def", "write_to_console", "(", "self", ",", "message", ":", "str", ")", ":", "if", "not", "self", ".", "_step", ":", "raise", "ValueError", "(", "'Cannot write to the console stdout on an uninitialized step'", ")", "interceptor", "=", "self", ".", "_step", ".", ...
Writes the specified message to the console stdout without including it in the notebook display.
[ "Writes", "the", "specified", "message", "to", "the", "console", "stdout", "without", "including", "it", "in", "the", "notebook", "display", "." ]
4086aec9c038c402ea212c79fe8bd0d27104f9cf
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/exposed.py#L255-L265
train
44,699