text stringlengths 81 112k |
|---|
Touches the project to trigger refreshing its cauldron.json state.
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(
... |
Returns the synchronization status information for the currently opened
project
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.f... |
downloads the specified project file if it exists
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_direc... |
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
def get_project_source_path(path: str) -> str:
"""
Conve... |
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
def load_project_definiti... |
Simplifies package paths by replacing path prefixes with values specified
in the replacements list
:param path:
:param path_prefixes:
:return:
def simplify_path(path: str, path_prefixes: list = None) -> str:
"""
Simplifies package paths by replacing path prefixes with values specified
in t... |
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:
def module_to_package_data(
name: str,
entry,
path_prefixes: list = None
) -> typing.Un... |
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
def get_system_data() -> ... |
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.
... |
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 t... |
The folder, relative to the project source_directory, where the file
resides
:return:
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:
... |
Determines whether or not a project exists at the specified path
:param response:
:param path:
:return:
def project_exists(response: 'environ.Response', path: str) -> bool:
"""
Determines whether or not a project exists at the specified path
:param response:
:param path:
:return:
... |
:param response:
:param path:
:return:
def update_recent_paths(response, path):
"""
:param response:
:param path:
:return:
"""
try:
recent_paths = environ.configs.fetch('recent_paths', [])
if path in recent_paths:
recent_paths.remove(path)
recent_p... |
Separates the raw line string into two strings: (1) the command and (2) the
argument(s) string
:param line:
:return:
def split_line(line: str) -> typing.Tuple[str, str]:
"""
Separates the raw line string into two strings: (1) the command and (2) the
argument(s) string
:param line:
:re... |
Renders a stop action to the Cauldron 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... |
Identifier for the project.
def id(self) -> typing.Union[str, None]:
"""Identifier for the project."""
return self._project.id if self._project else None |
The display report for the current project.
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
) |
The shared display object associated with this project.
def shared(self) -> typing.Union[None, SharedCache]:
"""The shared display object associated with this project."""
return self._project.shared if self._project else None |
The settings associated with this project.
def settings(self) -> typing.Union[None, SharedCache]:
"""The settings associated with this project."""
return self._project.settings if self._project else None |
The title of this project.
def title(self) -> typing.Union[None, str]:
"""The title of this project."""
return self._project.title if self._project else None |
Modifies the title of the project, which is initially loaded from the
`cauldron.json` file.
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:
... |
Connects this object to the specified source project.
def load(self, project: typing.Union[projects.Project, None]):
"""Connects this object to the specified source project."""
self._project = project |
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
... |
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 t... |
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:
... |
Internal access to the source step. Should not be used outside
of Cauldron development.
:return:
The ProjectStep instance that this ExposedStep represents
def _step(self) -> typing.Union[None, 'projects.ProjectStep']:
"""
Internal access to the source step. Should not be us... |
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... |
Writes the specified message to the console stdout without including
it in the notebook display.
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:
... |
Renders the specified message to the console using Jinja2 template
rendering with the kwargs as render variables. The message will also
be dedented prior to rendering in the same fashion as other Cauldron
template rendering actions.
:param message:
Template string to be rend... |
This will break things if you upgrade Django to 1.8 having already applied this migration in 1.7.
Since this is for a demo site it doesn't really matter (simply blow away the DB if you want to go to 1.8)
Our demo site is a unusual in that we want to run it's tests (for integration testing) in multiple Django v... |
:return:
def create(project: 'projects.Project') -> COMPONENT:
"""
:return:
"""
try:
from bokeh.resources import Resources as BokehResources
bokeh_resources = BokehResources(mode='absolute')
except Exception:
bokeh_resources = None
if bokeh_resources is None:
e... |
The last time at which the report was modified.
def last_update_time(self) -> float:
"""The last time at which the report was modified."""
stdout = self.stdout_interceptor
stderr = self.stderr_interceptor
return max([
self._last_update_time,
stdout.last_write_ti... |
Location where step report is cached between sessions to
prevent loss of display data between runs.
def results_cache_path(self) -> str:
"""
Location where step report is cached between sessions to
prevent loss of display data between runs.
"""
if not self.project:
... |
Clear all user-data stored in this instance and reset it to its
originally loaded state
:return:
The instance that was called for method chaining
def clear(self) -> 'Report':
"""
Clear all user-data stored in this instance and reset it to its
originally loaded state... |
Appends the specified HTML-formatted DOM string to the
currently stored report body for the step.
def append_body(self, dom: str):
"""
Appends the specified HTML-formatted DOM string to the
currently stored report body for the step.
"""
self.flush_stdout()
self.b... |
Reads the current state of the print buffer (if it exists) and returns
a body-ready dom object of those contents without adding them to the
actual report body. This is useful for creating intermediate body
values for display while the method is still executing.
:return:
A do... |
Empties the standard out redirect buffer and renders the
contents to the body as a preformatted text box.
def flush_stdout(self):
"""
Empties the standard out redirect buffer and renders the
contents to the body as a preformatted text box.
"""
try:
contents =... |
Import the named class and return that class
def import_class(klass):
'''Import the named class and return that class'''
mod = __import__(klass.rpartition('.')[0])
for segment in klass.split('.')[1:-1]:
mod = getattr(mod, segment)
return getattr(mod, klass.rpartition('.')[2]) |
Creates a COMPONENT instance for the project component specified by the
include path
:param project:
The project in which the component resides
:param include_path:
The relative path within the project where the component resides
:return:
The created COMPONENT instance
def crea... |
Creates a single COMPONENT instance for all of the specified project
include paths
:param project:
Project where the components reside
:param include_paths:
A list of relative paths within the project directory to files or
directories that should be included in the project
:retu... |
Converts the given file_path into a WEB_INCLUDE instance that represents
the deployed version of this file to be loaded into the results project
page
:param project:
Project in which the file_path resides
:param file_path:
Absolute path to the source file for which the WEB_INCLUDE insta... |
Attempts to write the specified contents to a file and returns None if
successful, or the raised exception if writing failed.
:param path:
The path to the file that will be written
:param contents:
The contents of the file to write
:param mode:
The mode in which the file wil... |
Writes the specified contents to a file, with retry attempts if the write
operation fails. This is useful to prevent OS related write collisions with
files that are regularly written to and read from quickly.
:param path:
The path to the file that will be written
:param contents:
Th... |
Attempts to write the specified JSON content to file.
:param path:
The path to the file where the JSON serialized content will be written.
:param contents:
The JSON data to write to the file
:param mode:
The mode used to open the file where the content will be written.
:r... |
Writes the specified dictionary to a file as a JSON-serialized string,
with retry attempts if the write operation fails. This is useful to prevent
OS related write collisions with files that are regularly written to and
read from quickly.
:param path:
The path to the file that will be wr... |
Formats the source string to strip newlines on both ends and dedents the
the entire string
:param source:
The string to reformat
def reformat(source: str) -> str:
"""
Formats the source string to strip newlines on both ends and dedents the
the entire string
:param source:
The ... |
Returns the jinja2 templating environment updated with the most recent
cauldron environment configurations
:return:
def get_environment() -> Environment:
"""
Returns the jinja2 templating environment updated with the most recent
cauldron environment configurations
:return:
"""
env = ... |
Renders a template string using Jinja2 and the Cauldron templating
environment.
:param template:
The string containing the template to be rendered
:param kwargs:
Any named arguments to pass to Jinja2 for use in rendering
:return:
The rendered template string
def render(template... |
Renders a file at the specified absolute path. The file can reside
anywhere on the local disk as Cauldron's template environment path
searching is ignored.
:param path:
Absolute path to a template file to render
:param kwargs:
Named arguments that should be passed to Jinja2 for renderin... |
Renders the template file with the given filename from within Cauldron's
template environment folder.
:param template_name:
The filename of the template to render. Any path elements should be
relative to Cauldron's root template folder.
:param kwargs:
Any elements passed to Jinja2 f... |
Cleans the specified path by expanding shorthand elements, redirecting to
the real path for symbolic links, and removing any relative components to
return a complete, absolute path to the specified location.
:param path:
The source path to be cleaned
def clean(path: str) -> str:
"""
Cleans... |
Creates an absolute path to a file or folder within the cauldron package
using the relative path elements specified by the args.
:param args:
Zero or more relative path elements that describe a file or folder
within the reporting
def package(*args: str) -> str:
"""
Creates an absolute ... |
Requests confirmation of the specified question and returns that result
:param question:
The question to print to the console for the confirmation
:param default:
The default value if the user hits enter without entering a value
def confirm(question: str, default: bool = True) -> bool:
"""... |
Returns the last opened project path if such a path exists
def fetch_last(response: Response) -> typing.Union[str, None]:
""" Returns the last opened project path if such a path exists """
recent_paths = environ.configs.fetch('recent_paths', [])
if len(recent_paths) < 1:
response.fail(
... |
make sure that the dedicated path exists (create if not exist)
:param file_or_dir:
:return: None
def before_save(file_or_dir):
"""
make sure that the dedicated path exists (create if not exist)
:param file_or_dir:
:return: None
"""
dir_name = os.path.dirname(os.path.abspath(file_or_dir)... |
Run a frequent item mining algorithm to extract candidate rules.
:param x: 2D np.ndarray, categorical data of shape [n_instances, n_features]
:param y: 1D np.ndarray, label array of shape [n_instances, ]
:param data_filename: the path to store data file
:param label_filename: the path to store label fil... |
Convert a 2D int array into a transaction list:
[
['x0=1', 'x1=0', ...],
...
]
:param x:
:return:
def categorical2transactions(x):
# type: (np.ndarray) -> List
"""
Convert a 2D int array into a transaction list:
[
['x0=1', 'x1=0', ...],
... |
return a logical array representing whether entries in x satisfied the rules denoted by features and categories
:param x: a categorical 2D array
:param features: a list of feature indices
:param categories: a list of categories
:return:
def rule_satisfied(x, features, categories):
"""
return a ... |
Returns the file status information for every file within the project
source directory and its shared library folders.
:param project:
The project for which the status information should be generated
:return:
A dictionary containing:
- project: the status information for all fil... |
Returns a dictionary containing status information for the specified file
including when its name relative to the root directory, when it was last
modified and its size.
:param path:
The absolute path to the file for which the status information should
be generated
:param root_directory... |
Returns a dictionary containing status entries recursively for all files
within the specified directory and its descendant directories.
:param directory:
The directory in which to retrieve status information
:param root_directory:
Directory relative to which all file status paths are relate... |
Execute the run command locally within this cauldron environment
:param context:
:param project:
:param project_steps:
:param force:
:param continue_after:
:param single_step:
:param limit:
:param print_status:
:param skip_library_reload:
Whether or not to skip reloading all... |
Loads all demo fixtures.
def loadalldatas():
"""Loads all demo fixtures."""
dependency_order = ['common', 'profiles', 'blog', 'democomments']
for app in dependency_order:
project.recursive_load(os.path.join(paths.project_paths.manage_root, app)) |
...
def project_status():
"""..."""
r = Response()
try:
project = cauldron.project.get_internal_project()
if project:
r.update(project=project.status())
else:
r.update(project=None)
except Exception as err:
r.fail(
code='PROJECT_STATU... |
...
def clean_step(step_name: str):
"""..."""
r = Response()
project = cauldron.project.get_internal_project()
if not project:
return flask.jsonify(r.fail(
code='PROJECT_FETCH_ERROR',
message='No project is currently open'
).response.serialize())
step = pro... |
Appends a timestamp integer to the given slug, yet ensuring the
result is less than the specified max_length.
def _insert_timestamp(self, slug, max_length=255):
"""Appends a timestamp integer to the given slug, yet ensuring the
result is less than the specified max_length.
"""
t... |
Slugify the Entry title, but ensure it's less than the maximum
number of characters. This method also ensures that a slug is unique by
appending a timestamp to any duplicate slugs.
def _slugify_title(self):
"""Slugify the Entry title, but ensure it's less than the maximum
number of char... |
Run jobs, popping one after another
def run(self):
'''Run jobs, popping one after another'''
# Register our signal handlers
self.signals()
with self.listener():
for job in self.jobs():
# If there was no job to be had, we should sleep a little bit
... |
Initializes the cauldron library by confirming that it can be imported
by the importlib library. If the attempt to import it fails, the system
path will be modified and the attempt retried. If both attempts fail, an
import error will be raised.
def initialize():
"""
Initializes the cauldron library... |
Executes the cauldron command
def run(arguments: typing.List[str] = None):
"""Executes the cauldron command"""
initialize()
from cauldron.invoke import parser
from cauldron.invoke import invoker
args = parser.parse(arguments)
exit_code = invoker.run(args.get('command'), args)
sys.exit(exi... |
Returns either the linked or not-linked profile name.
def author_display(author, *args):
"""Returns either the linked or not-linked profile name."""
# Call get_absolute_url or a function returning none if not defined
url = getattr(author, 'get_absolute_url', lambda: None)()
# get_short_name or unicode... |
:param response:
:param project:
:return:
def echo_steps(response: Response, project: Project):
"""
:param response:
:param project:
:return:
"""
if len(project.steps) < 1:
response.update(
steps=[]
).notify(
kind='SUCCESS',
code='ECH... |
Removes any path components from the input filename and returns a
dictionary containing the name of the file without extension and the
extension (if an extension exists)
:param name:
:param scheme:
:return:
def explode_filename(name: str, scheme: str) -> dict:
"""
Removes any path componen... |
:param project:
:return:
def create(project: 'projects.Project') -> COMPONENT:
"""
:param project:
:return:
"""
source_path = get_source_path()
if not source_path:
return COMPONENT([], [])
output_slug = 'components/plotly/plotly.min.js'
output_path = os.path.join(project.o... |
Returns whether or not the current working directory is a Cauldron project
directory, which contains a cauldron.json file.
def in_project_directory() -> bool:
"""
Returns whether or not the current working directory is a Cauldron project
directory, which contains a cauldron.json file.
"""
curre... |
Load shared data from a JSON file stored on disk
def load_shared_data(path: typing.Union[str, None]) -> dict:
"""Load shared data from a JSON file stored on disk"""
if path is None:
return dict()
if not os.path.exists(path):
raise FileNotFoundError('No such shared data file "{}"'.format(p... |
Displays the current version
def run_version(args: dict) -> int:
"""Displays the current version"""
version = environ.package_settings.get('version', 'unknown')
print('VERSION: {}'.format(version))
return 0 |
Runs a batch operation for the given arguments
def run_batch(args: dict) -> int:
"""Runs a batch operation for the given arguments"""
batcher.run_project(
project_directory=args.get('project_directory'),
log_path=args.get('logging_path'),
output_directory=args.get('output_directory'),
... |
Run the shell sub command
def run_shell(args: dict) -> int:
"""Run the shell sub command"""
if args.get('project_directory'):
return run_batch(args)
shell = CauldronShell()
if in_project_directory():
shell.cmdqueue.append('open "{}"'.format(os.path.realpath(os.curdir)))
shell.cm... |
Runs the specified command action and returns the return status code
for exit.
:param action:
The action to run
:param args:
The arguments parsed for the specified action
def run(action: str, args: dict) -> int:
"""
Runs the specified command action and returns the return statu... |
...
def get_running_step_changes(write: bool = False) -> list:
"""..."""
project = cd.project.get_internal_project()
running_steps = list(filter(
lambda step: step.is_running,
project.steps
))
def get_changes(step):
step_data = writing.step_writer.serialize(step)
... |
Parses the arguments for the cauldron server
def parse(
args: typing.List[str] = None,
arg_parser: ArgumentParser = None
) -> dict:
"""Parses the arguments for the cauldron server"""
parser = arg_parser or create_parser()
return vars(parser.parse_args(args)) |
Creates an argument parser populated with the arg formats for the server
command.
def create_parser(arg_parser: ArgumentParser = None) -> ArgumentParser:
"""
Creates an argument parser populated with the arg formats for the server
command.
"""
parser = arg_parser or ArgumentParser()
parser... |
Matches a Tree structure with the given query rules.
Query rules are represented as a dictionary of template to action.
Action is either a function, or a dictionary of subtemplate parameter to rules::
rules = { 'template' : { 'key': rules } }
| { 'template' : {} }
Args:
tree... |
Recursively matches a Tree structure with rules and returns context
Args:
tree (Tree): Parsed tree structure
rules (dict): See match_rules
parent_context (dict): Context of parent call
Returns:
dict: Context matched dictionary of matched rules or
None if no match
def ma... |
Cross product of all contexts
[[a], [b], [c]] -> [[a] x [b] x [c]]
def cross_context(contextss):
"""
Cross product of all contexts
[[a], [b], [c]] -> [[a] x [b] x [c]]
"""
if not contextss:
return []
product = [{}]
for contexts in contextss:
tmp_product = []
f... |
Recursively matches a Tree structure with rules and returns context
Args:
tree (Tree): Parsed tree structure
rules (dict): See match_rules
parent_context (dict): Context of parent call
Returns:
dict: Context matched dictionary of matched rules or
None if no match
def ma... |
Check if match string matches Tree structure
Args:
tree (Tree): Parsed Tree structure of a sentence
template (str): String template to match. Example: "( S ( NP ) )"
Returns:
bool: If they match or not
def match_template(tree, template, args=None):
"""Check if match string matc... |
Check if stack of tokens matches the Tree structure
Special matching rules that can be specified in the template::
':label': Label a token, the token will be returned as part of the context with key 'label'.
'-@': Additional single letter argument determining return format of labeled token. Va... |
Recursively gets tokens from a match list
Args:
tokens : List of tokens ['(', 'S', '(', 'NP', ')', ')']
Returns:
Stack of tokens
def get_tokens(tokens):
"""Recursively gets tokens from a match list
Args:
tokens : List of tokens ['(', 'S', '(', 'NP', ')', ')']
Retur... |
Get the object in the tree object.
Method should remove unnecessary letters and words::
the
a/an
's
Args:
tree (Tree): Parsed tree structure
Returns:
Resulting string of tree ``(Ex: "red car")``
def get_object(tree):
"""Get the object in the tree object.
... |
Get the exact words in lowercase in the tree object.
Args:
tree (Tree): Parsed tree structure
Returns:
Resulting string of tree ``(Ex: "The red car")``
def get_raw(tree):
"""Get the exact words in lowercase in the tree object.
Args:
tree (Tree): Parsed tree structure
... |
Registers and initializes the PySpark library dependencies so that the
pyspark package can be imported and used within the notebook.
If you specify the path to the spark home folder, the PySpark libraries
from that location will be loaded. If a value is omitted, the $SPARK_HOME
environmental variable w... |
Whether or not this project is remote
def is_remote_project(self) -> bool:
"""Whether or not this project is remote"""
project_path = environ.paths.clean(self.source_directory)
return project_path.find('cd-remote-project') != -1 |
The list of directories to all of the library locations
def library_directories(self) -> typing.List[str]:
"""
The list of directories to all of the library locations
"""
def listify(value):
return [value] if isinstance(value, str) else list(value)
# If this is a pr... |
The path where the project results will be written
def results_path(self) -> str:
"""The path where the project results will be written"""
def possible_paths():
yield self._results_path
yield self.settings.fetch('path_results')
yield environ.configs.fetch('results_d... |
Returns the URL that will open this project results file in the browser
:return:
def url(self) -> str:
"""
Returns the URL that will open this project results file in the browser
:return:
"""
return 'file://{path}?id={id}'.format(
path=os.path.join(self.resu... |
Returns the directory where the project results files will be written
def output_directory(self) -> str:
"""
Returns the directory where the project results files will be written
"""
return os.path.join(self.results_path, 'reports', self.uuid, 'latest') |
Loads the cauldron.json definition file for the project and populates
the project with the loaded data. Any existing data will be overwritten,
if the new definition file differs from the previous one.
If the project has already loaded with the most recent version of the
cauldron.json fi... |
Renders preformatted text box
def preformatted_text(source: str) -> str:
"""Renders preformatted text box"""
environ.abort_thread()
if not source:
return ''
source = render_utils.html_escape(source)
return '<pre class="preformatted-textbox">{text}</pre>'.format(
text=str(textwrap... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.