id
int32
0
252k
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
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
100
pypyr/pypyr-cli
pypyr/dsl.py
Step.invoke_step
def invoke_step(self, context): """Invoke 'run_step' in the dynamically loaded step module. Don't invoke this from outside the Step class. Use pypyr.dsl.Step.run_step instead. invoke_step just does the bare module step invocation, it does not evaluate any of the decorator logic ...
python
def invoke_step(self, context): logger.debug("starting") logger.debug(f"running step {self.module}") self.run_step_function(context) logger.debug(f"step {self.module} done")
[ "def", "invoke_step", "(", "self", ",", "context", ")", ":", "logger", ".", "debug", "(", "\"starting\"", ")", "logger", ".", "debug", "(", "f\"running step {self.module}\"", ")", "self", ".", "run_step_function", "(", "context", ")", "logger", ".", "debug", ...
Invoke 'run_step' in the dynamically loaded step module. Don't invoke this from outside the Step class. Use pypyr.dsl.Step.run_step instead. invoke_step just does the bare module step invocation, it does not evaluate any of the decorator logic surrounding the step. So unless you...
[ "Invoke", "run_step", "in", "the", "dynamically", "loaded", "step", "module", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/dsl.py#L285-L305
101
pypyr/pypyr-cli
pypyr/dsl.py
Step.run_conditional_decorators
def run_conditional_decorators(self, context): """Evaluate the step decorators to decide whether to run step or not. Use pypyr.dsl.Step.run_step if you intend on executing the step the same way pypyr does. Args: context: (pypyr.context.Context) The pypyr context. This arg w...
python
def run_conditional_decorators(self, context): logger.debug("starting") # The decorator attributes might contain formatting expressions that # change whether they evaluate True or False, thus apply formatting at # last possible instant. run_me = context.get_formatted_as_type(sel...
[ "def", "run_conditional_decorators", "(", "self", ",", "context", ")", ":", "logger", ".", "debug", "(", "\"starting\"", ")", "# The decorator attributes might contain formatting expressions that", "# change whether they evaluate True or False, thus apply formatting at", "# last poss...
Evaluate the step decorators to decide whether to run step or not. Use pypyr.dsl.Step.run_step if you intend on executing the step the same way pypyr does. Args: context: (pypyr.context.Context) The pypyr context. This arg will mutate.
[ "Evaluate", "the", "step", "decorators", "to", "decide", "whether", "to", "run", "step", "or", "not", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/dsl.py#L307-L349
102
pypyr/pypyr-cli
pypyr/dsl.py
Step.run_foreach_or_conditional
def run_foreach_or_conditional(self, context): """Run the foreach sequence or the conditional evaluation. Args: context: (pypyr.context.Context) The pypyr context. This arg will mutate. """ logger.debug("starting") # friendly reminder [] list obj...
python
def run_foreach_or_conditional(self, context): logger.debug("starting") # friendly reminder [] list obj (i.e empty) evals False if self.foreach_items: self.foreach_loop(context) else: # since no looping required, don't pollute output with looping info ...
[ "def", "run_foreach_or_conditional", "(", "self", ",", "context", ")", ":", "logger", ".", "debug", "(", "\"starting\"", ")", "# friendly reminder [] list obj (i.e empty) evals False", "if", "self", ".", "foreach_items", ":", "self", ".", "foreach_loop", "(", "context...
Run the foreach sequence or the conditional evaluation. Args: context: (pypyr.context.Context) The pypyr context. This arg will mutate.
[ "Run", "the", "foreach", "sequence", "or", "the", "conditional", "evaluation", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/dsl.py#L351-L366
103
pypyr/pypyr-cli
pypyr/dsl.py
Step.run_step
def run_step(self, context): """Run a single pipeline step. Args: context: (pypyr.context.Context) The pypyr context. This arg will mutate. """ logger.debug("starting") # the in params should be added to context before step execution. sel...
python
def run_step(self, context): logger.debug("starting") # the in params should be added to context before step execution. self.set_step_input_context(context) if self.while_decorator: self.while_decorator.while_loop(context, self.run...
[ "def", "run_step", "(", "self", ",", "context", ")", ":", "logger", ".", "debug", "(", "\"starting\"", ")", "# the in params should be added to context before step execution.", "self", ".", "set_step_input_context", "(", "context", ")", "if", "self", ".", "while_decor...
Run a single pipeline step. Args: context: (pypyr.context.Context) The pypyr context. This arg will mutate.
[ "Run", "a", "single", "pipeline", "step", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/dsl.py#L368-L385
104
pypyr/pypyr-cli
pypyr/dsl.py
Step.set_step_input_context
def set_step_input_context(self, context): """Append step's 'in' parameters to context, if they exist. Append the[in] dictionary to the context. This will overwrite existing values if the same keys are already in there. I.e if in_parameters has {'eggs': 'boiled'} and key 'eggs' already ...
python
def set_step_input_context(self, context): logger.debug("starting") if self.in_parameters is not None: parameter_count = len(self.in_parameters) if parameter_count > 0: logger.debug( f"Updating context with {parameter_count} 'in' " ...
[ "def", "set_step_input_context", "(", "self", ",", "context", ")", ":", "logger", ".", "debug", "(", "\"starting\"", ")", "if", "self", ".", "in_parameters", "is", "not", "None", ":", "parameter_count", "=", "len", "(", "self", ".", "in_parameters", ")", "...
Append step's 'in' parameters to context, if they exist. Append the[in] dictionary to the context. This will overwrite existing values if the same keys are already in there. I.e if in_parameters has {'eggs': 'boiled'} and key 'eggs' already exists in context, context['eggs'] hereafter w...
[ "Append", "step", "s", "in", "parameters", "to", "context", "if", "they", "exist", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/dsl.py#L387-L409
105
pypyr/pypyr-cli
pypyr/dsl.py
RetryDecorator.exec_iteration
def exec_iteration(self, counter, context, step_method): """Run a single retry iteration. This method abides by the signature invoked by poll.while_until_true, which is to say (counter, *args, **kwargs). In a normal execution chain, this method's args passed by self.retry_loop where con...
python
def exec_iteration(self, counter, context, step_method): logger.debug("starting") context['retryCounter'] = counter logger.info(f"retry: running step with counter {counter}") try: step_method(context) result = True except Exception as ex_info: ...
[ "def", "exec_iteration", "(", "self", ",", "counter", ",", "context", ",", "step_method", ")", ":", "logger", ".", "debug", "(", "\"starting\"", ")", "context", "[", "'retryCounter'", "]", "=", "counter", "logger", ".", "info", "(", "f\"retry: running step wit...
Run a single retry iteration. This method abides by the signature invoked by poll.while_until_true, which is to say (counter, *args, **kwargs). In a normal execution chain, this method's args passed by self.retry_loop where context and step_method set. while_until_true injects counter a...
[ "Run", "a", "single", "retry", "iteration", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/dsl.py#L469-L536
106
pypyr/pypyr-cli
pypyr/dsl.py
RetryDecorator.retry_loop
def retry_loop(self, context, step_method): """Run step inside a retry loop. Args: context: (pypyr.context.Context) The pypyr context. This arg will mutate - after method execution will contain the new updated context. step_method: (meth...
python
def retry_loop(self, context, step_method): logger.debug("starting") context['retryCounter'] = 0 sleep = context.get_formatted_as_type(self.sleep, out_type=float) if self.max: max = context.get_formatted_as_type(self.max, out_type=int) logger.info(f"retry decor...
[ "def", "retry_loop", "(", "self", ",", "context", ",", "step_method", ")", ":", "logger", ".", "debug", "(", "\"starting\"", ")", "context", "[", "'retryCounter'", "]", "=", "0", "sleep", "=", "context", ".", "get_formatted_as_type", "(", "self", ".", "sle...
Run step inside a retry loop. Args: context: (pypyr.context.Context) The pypyr context. This arg will mutate - after method execution will contain the new updated context. step_method: (method/function) This is the method/function that ...
[ "Run", "step", "inside", "a", "retry", "loop", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/dsl.py#L538-L578
107
pypyr/pypyr-cli
pypyr/dsl.py
WhileDecorator.exec_iteration
def exec_iteration(self, counter, context, step_method): """Run a single loop iteration. This method abides by the signature invoked by poll.while_until_true, which is to say (counter, *args, **kwargs). In a normal execution chain, this method's args passed by self.while_loop where cont...
python
def exec_iteration(self, counter, context, step_method): logger.debug("starting") context['whileCounter'] = counter logger.info(f"while: running step with counter {counter}") step_method(context) logger.debug(f"while: done step {counter}") result = False # if no...
[ "def", "exec_iteration", "(", "self", ",", "counter", ",", "context", ",", "step_method", ")", ":", "logger", ".", "debug", "(", "\"starting\"", ")", "context", "[", "'whileCounter'", "]", "=", "counter", "logger", ".", "info", "(", "f\"while: running step wit...
Run a single loop iteration. This method abides by the signature invoked by poll.while_until_true, which is to say (counter, *args, **kwargs). In a normal execution chain, this method's args passed by self.while_loop where context and step_method set. while_until_true injects counter as...
[ "Run", "a", "single", "loop", "iteration", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/dsl.py#L645-L682
108
pypyr/pypyr-cli
pypyr/dsl.py
WhileDecorator.while_loop
def while_loop(self, context, step_method): """Run step inside a while loop. Args: context: (pypyr.context.Context) The pypyr context. This arg will mutate - after method execution will contain the new updated context. step_method: (meth...
python
def while_loop(self, context, step_method): logger.debug("starting") context['whileCounter'] = 0 if self.stop is None and self.max is None: # the ctor already does this check, but guess theoretically # consumer could have messed with the props since ctor log...
[ "def", "while_loop", "(", "self", ",", "context", ",", "step_method", ")", ":", "logger", ".", "debug", "(", "\"starting\"", ")", "context", "[", "'whileCounter'", "]", "=", "0", "if", "self", ".", "stop", "is", "None", "and", "self", ".", "max", "is",...
Run step inside a while loop. Args: context: (pypyr.context.Context) The pypyr context. This arg will mutate - after method execution will contain the new updated context. step_method: (method/function) This is the method/function that ...
[ "Run", "step", "inside", "a", "while", "loop", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/dsl.py#L684-L757
109
pypyr/pypyr-cli
pypyr/steps/fetchyaml.py
run_step
def run_step(context): """Load a yaml file into the pypyr context. Yaml parsed from the file will be merged into the pypyr context. This will overwrite existing values if the same keys are already in there. I.e if file yaml has {'eggs' : 'boiled'} and context {'eggs': 'fried'} already exists, retur...
python
def run_step(context): logger.debug("started") deprecated(context) context.assert_key_has_value(key='fetchYaml', caller=__name__) fetch_yaml_input = context.get_formatted('fetchYaml') if isinstance(fetch_yaml_input, str): file_path = fetch_yaml_input destination_key_expression = ...
[ "def", "run_step", "(", "context", ")", ":", "logger", ".", "debug", "(", "\"started\"", ")", "deprecated", "(", "context", ")", "context", ".", "assert_key_has_value", "(", "key", "=", "'fetchYaml'", ",", "caller", "=", "__name__", ")", "fetch_yaml_input", ...
Load a yaml file into the pypyr context. Yaml parsed from the file will be merged into the pypyr context. This will overwrite existing values if the same keys are already in there. I.e if file yaml has {'eggs' : 'boiled'} and context {'eggs': 'fried'} already exists, returned context['eggs'] will be 'b...
[ "Load", "a", "yaml", "file", "into", "the", "pypyr", "context", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/steps/fetchyaml.py#L10-L81
110
pypyr/pypyr-cli
pypyr/steps/nowutc.py
run_step
def run_step(context): """pypyr step saves current utc datetime to context. Args: context: pypyr.context.Context. Mandatory. The following context key is optional: - nowUtcIn. str. Datetime formatting expression. For full list of possible expressions, ...
python
def run_step(context): logger.debug("started") format_expression = context.get('nowUtcIn', None) if format_expression: formatted_expression = context.get_formatted_string(format_expression) context['nowUtc'] = datetime.now( timezone.utc).strftime(formatted_expression) else:...
[ "def", "run_step", "(", "context", ")", ":", "logger", ".", "debug", "(", "\"started\"", ")", "format_expression", "=", "context", ".", "get", "(", "'nowUtcIn'", ",", "None", ")", "if", "format_expression", ":", "formatted_expression", "=", "context", ".", "...
pypyr step saves current utc datetime to context. Args: context: pypyr.context.Context. Mandatory. The following context key is optional: - nowUtcIn. str. Datetime formatting expression. For full list of possible expressions, check here: ...
[ "pypyr", "step", "saves", "current", "utc", "datetime", "to", "context", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/steps/nowutc.py#L9-L44
111
pypyr/pypyr-cli
pypyr/steps/assert.py
run_step
def run_step(context): """Assert that something is True or equal to something else. Args: context: dictionary-like pypyr.context.Context. context is mandatory. Uses the following context keys in context: - assert - this. mandatory. Any type. If assert['equals'] not s...
python
def run_step(context): logger.debug("started") assert context, f"context must have value for {__name__}" deprecated(context) context.assert_key_has_value('assert', __name__) assert_this = context['assert']['this'] is_equals_there = 'equals' in context['assert'] if is_equals_there: ...
[ "def", "run_step", "(", "context", ")", ":", "logger", ".", "debug", "(", "\"started\"", ")", "assert", "context", ",", "f\"context must have value for {__name__}\"", "deprecated", "(", "context", ")", "context", ".", "assert_key_has_value", "(", "'assert'", ",", ...
Assert that something is True or equal to something else. Args: context: dictionary-like pypyr.context.Context. context is mandatory. Uses the following context keys in context: - assert - this. mandatory. Any type. If assert['equals'] not specified, ev...
[ "Assert", "that", "something", "is", "True", "or", "equal", "to", "something", "else", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/steps/assert.py#L9-L71
112
pypyr/pypyr-cli
pypyr/steps/tar.py
tar_archive
def tar_archive(context): """Archive specified path to a tar archive. Args: context: dictionary-like. context is mandatory. context['tar']['archive'] must exist. It's a dictionary. keys are the paths to archive. values are the destination output paths. Example: ...
python
def tar_archive(context): logger.debug("start") mode = get_file_mode_for_writing(context) for item in context['tar']['archive']: # value is the destination tar. Allow string interpolation. destination = context.get_formatted_string(item['out']) # key is the source to archive ...
[ "def", "tar_archive", "(", "context", ")", ":", "logger", ".", "debug", "(", "\"start\"", ")", "mode", "=", "get_file_mode_for_writing", "(", "context", ")", "for", "item", "in", "context", "[", "'tar'", "]", "[", "'archive'", "]", ":", "# value is the desti...
Archive specified path to a tar archive. Args: context: dictionary-like. context is mandatory. context['tar']['archive'] must exist. It's a dictionary. keys are the paths to archive. values are the destination output paths. Example: tar: archive:...
[ "Archive", "specified", "path", "to", "a", "tar", "archive", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/steps/tar.py#L105-L140
113
pypyr/pypyr-cli
pypyr/steps/tar.py
tar_extract
def tar_extract(context): """Extract all members of tar archive to specified path. Args: context: dictionary-like. context is mandatory. context['tar']['extract'] must exist. It's a dictionary. keys are the path to the tar to extract. values are the destination paths...
python
def tar_extract(context): logger.debug("start") mode = get_file_mode_for_reading(context) for item in context['tar']['extract']: # in is the path to the tar to extract. Allows string interpolation. source = context.get_formatted_string(item['in']) # out is the outdir, dhur. Allows ...
[ "def", "tar_extract", "(", "context", ")", ":", "logger", ".", "debug", "(", "\"start\"", ")", "mode", "=", "get_file_mode_for_reading", "(", "context", ")", "for", "item", "in", "context", "[", "'tar'", "]", "[", "'extract'", "]", ":", "# in is the path to ...
Extract all members of tar archive to specified path. Args: context: dictionary-like. context is mandatory. context['tar']['extract'] must exist. It's a dictionary. keys are the path to the tar to extract. values are the destination paths. Example: tar: ...
[ "Extract", "all", "members", "of", "tar", "archive", "to", "specified", "path", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/steps/tar.py#L143-L178
114
pypyr/pypyr-cli
pypyr/steps/shell.py
run_step
def run_step(context): """Run shell command without shell interpolation. Context is a dictionary or dictionary-like. Context must contain the following keys: cmd: <<cmd string>> (command + args to execute.) OR, as a dict cmd: run: str. mandatory. <<cmd string>> command + args to execu...
python
def run_step(context): logger.debug("started") CmdStep(name=__name__, context=context).run_step(is_shell=True) logger.debug("done")
[ "def", "run_step", "(", "context", ")", ":", "logger", ".", "debug", "(", "\"started\"", ")", "CmdStep", "(", "name", "=", "__name__", ",", "context", "=", "context", ")", ".", "run_step", "(", "is_shell", "=", "True", ")", "logger", ".", "debug", "(",...
Run shell command without shell interpolation. Context is a dictionary or dictionary-like. Context must contain the following keys: cmd: <<cmd string>> (command + args to execute.) OR, as a dict cmd: run: str. mandatory. <<cmd string>> command + args to execute. save: bool. defaul...
[ "Run", "shell", "command", "without", "shell", "interpolation", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/steps/shell.py#L14-L57
115
pypyr/pypyr-cli
pypyr/steps/envget.py
get_args
def get_args(get_item): """Parse env, key, default out of input dict. Args: get_item: dict. contains keys env/key/default Returns: (env, key, has_default, default) tuple, where env: str. env var name. key: str. save env value to this context key. has_def...
python
def get_args(get_item): if not isinstance(get_item, dict): raise ContextError('envGet must contain a list of dicts.') env = get_item.get('env', None) if not env: raise KeyNotInContextError( 'context envGet[env] must exist in context for envGet.') key = get_item.get('key', ...
[ "def", "get_args", "(", "get_item", ")", ":", "if", "not", "isinstance", "(", "get_item", ",", "dict", ")", ":", "raise", "ContextError", "(", "'envGet must contain a list of dicts.'", ")", "env", "=", "get_item", ".", "get", "(", "'env'", ",", "None", ")", ...
Parse env, key, default out of input dict. Args: get_item: dict. contains keys env/key/default Returns: (env, key, has_default, default) tuple, where env: str. env var name. key: str. save env value to this context key. has_default: bool. True if default spe...
[ "Parse", "env", "key", "default", "out", "of", "input", "dict", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/steps/envget.py#L80-L120
116
pypyr/pypyr-cli
pypyr/steps/py.py
run_step
def run_step(context): """Executes dynamic python code. Context is a dictionary or dictionary-like. Context must contain key 'pycode' Will exec context['pycode'] as dynamically interpreted python statements. context is mandatory. When you execute the pipeline, it should look something like thi...
python
def run_step(context): logger.debug("started") context.assert_key_has_value(key='pycode', caller=__name__) logger.debug(f"Executing python string: {context['pycode']}") locals_dictionary = locals() exec(context['pycode'], globals(), locals_dictionary) # It looks like this dance might be unnece...
[ "def", "run_step", "(", "context", ")", ":", "logger", ".", "debug", "(", "\"started\"", ")", "context", ".", "assert_key_has_value", "(", "key", "=", "'pycode'", ",", "caller", "=", "__name__", ")", "logger", ".", "debug", "(", "f\"Executing python string: {c...
Executes dynamic python code. Context is a dictionary or dictionary-like. Context must contain key 'pycode' Will exec context['pycode'] as dynamically interpreted python statements. context is mandatory. When you execute the pipeline, it should look something like this: pipeline-runner [na...
[ "Executes", "dynamic", "python", "code", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/steps/py.py#L11-L35
117
pypyr/pypyr-cli
pypyr/cli.py
get_parser
def get_parser(): """Return ArgumentParser for pypyr cli.""" parser = argparse.ArgumentParser( allow_abbrev=True, description='pypyr pipeline runner') parser.add_argument('pipeline_name', help='Name of pipeline to run. It should exist in the ' ...
python
def get_parser(): parser = argparse.ArgumentParser( allow_abbrev=True, description='pypyr pipeline runner') parser.add_argument('pipeline_name', help='Name of pipeline to run. It should exist in the ' './pipelines directory.') parser.add_argume...
[ "def", "get_parser", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "allow_abbrev", "=", "True", ",", "description", "=", "'pypyr pipeline runner'", ")", "parser", ".", "add_argument", "(", "'pipeline_name'", ",", "help", "=", "'Name of pi...
Return ArgumentParser for pypyr cli.
[ "Return", "ArgumentParser", "for", "pypyr", "cli", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/cli.py#L19-L44
118
pypyr/pypyr-cli
pypyr/cli.py
main
def main(args=None): """Entry point for pypyr cli. The setup_py entry_point wraps this in sys.exit already so this effectively becomes sys.exit(main()). The __main__ entry point similarly wraps sys.exit(). """ if args is None: args = sys.argv[1:] parsed_args = get_args(args) t...
python
def main(args=None): if args is None: args = sys.argv[1:] parsed_args = get_args(args) try: return pypyr.pipelinerunner.main( pipeline_name=parsed_args.pipeline_name, pipeline_context_input=parsed_args.pipeline_context, working_dir=parsed_args.working_di...
[ "def", "main", "(", "args", "=", "None", ")", ":", "if", "args", "is", "None", ":", "args", "=", "sys", ".", "argv", "[", "1", ":", "]", "parsed_args", "=", "get_args", "(", "args", ")", "try", ":", "return", "pypyr", ".", "pipelinerunner", ".", ...
Entry point for pypyr cli. The setup_py entry_point wraps this in sys.exit already so this effectively becomes sys.exit(main()). The __main__ entry point similarly wraps sys.exit().
[ "Entry", "point", "for", "pypyr", "cli", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/cli.py#L47-L80
119
pypyr/pypyr-cli
pypyr/steps/contextclear.py
run_step
def run_step(context): """Remove specified keys from context. Args: Context is a dictionary or dictionary-like. context['contextClear'] must exist. It's a dictionary. Will iterate context['contextClear'] and remove those keys from context. For example, say input context is:...
python
def run_step(context): logger.debug("started") context.assert_key_has_value(key='contextClear', caller=__name__) for k in context['contextClear']: logger.debug(f"removing {k} from context") # slightly unorthodox pop returning None means you don't get a KeyError # if key doesn't exis...
[ "def", "run_step", "(", "context", ")", ":", "logger", ".", "debug", "(", "\"started\"", ")", "context", ".", "assert_key_has_value", "(", "key", "=", "'contextClear'", ",", "caller", "=", "__name__", ")", "for", "k", "in", "context", "[", "'contextClear'", ...
Remove specified keys from context. Args: Context is a dictionary or dictionary-like. context['contextClear'] must exist. It's a dictionary. Will iterate context['contextClear'] and remove those keys from context. For example, say input context is: key1: value1 ...
[ "Remove", "specified", "keys", "from", "context", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/steps/contextclear.py#L13-L46
120
pypyr/pypyr-cli
pypyr/steps/safeshell.py
run_step
def run_step(context): """Run command, program or executable. Context is a dictionary or dictionary-like. Context must contain the following keys: cmd: <<cmd string>> (command + args to execute.) OR, as a dict cmd: run: str. mandatory. <<cmd string>> command + args to execute. ...
python
def run_step(context): logger.debug("started") pypyr.steps.cmd.run_step(context) logger.debug("done")
[ "def", "run_step", "(", "context", ")", ":", "logger", ".", "debug", "(", "\"started\"", ")", "pypyr", ".", "steps", ".", "cmd", ".", "run_step", "(", "context", ")", "logger", ".", "debug", "(", "\"done\"", ")" ]
Run command, program or executable. Context is a dictionary or dictionary-like. Context must contain the following keys: cmd: <<cmd string>> (command + args to execute.) OR, as a dict cmd: run: str. mandatory. <<cmd string>> command + args to execute. save: bool. defaults False. s...
[ "Run", "command", "program", "or", "executable", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/steps/safeshell.py#L16-L55
121
pypyr/pypyr-cli
pypyr/steps/default.py
run_step
def run_step(context): """Set hierarchy into context with substitutions if it doesn't exist yet. context is a dictionary or dictionary-like. context['defaults'] must exist. It's a dictionary. Will iterate context['defaults'] and add these as new values where their keys don't already exist. While i...
python
def run_step(context): logger.debug("started") context.assert_key_has_value(key='defaults', caller=__name__) context.set_defaults(context['defaults']) logger.info(f"set {len(context['defaults'])} context item defaults.") logger.debug("done")
[ "def", "run_step", "(", "context", ")", ":", "logger", ".", "debug", "(", "\"started\"", ")", "context", ".", "assert_key_has_value", "(", "key", "=", "'defaults'", ",", "caller", "=", "__name__", ")", "context", ".", "set_defaults", "(", "context", "[", "...
Set hierarchy into context with substitutions if it doesn't exist yet. context is a dictionary or dictionary-like. context['defaults'] must exist. It's a dictionary. Will iterate context['defaults'] and add these as new values where their keys don't already exist. While it's doing so, it will leave ...
[ "Set", "hierarchy", "into", "context", "with", "substitutions", "if", "it", "doesn", "t", "exist", "yet", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/steps/default.py#L38-L84
122
pypyr/pypyr-cli
pypyr/stepsrunner.py
get_pipeline_steps
def get_pipeline_steps(pipeline, steps_group): """Get the steps attribute of module pipeline. If there is no steps sequence on the pipeline, return None. Guess you could theoretically want to run a pipeline with nothing in it. """ logger.debug("starting") assert pipeline assert steps_group ...
python
def get_pipeline_steps(pipeline, steps_group): logger.debug("starting") assert pipeline assert steps_group logger.debug(f"retrieving {steps_group} steps from pipeline") if steps_group in pipeline: steps = pipeline[steps_group] if steps is None: logger.warn( ...
[ "def", "get_pipeline_steps", "(", "pipeline", ",", "steps_group", ")", ":", "logger", ".", "debug", "(", "\"starting\"", ")", "assert", "pipeline", "assert", "steps_group", "logger", ".", "debug", "(", "f\"retrieving {steps_group} steps from pipeline\"", ")", "if", ...
Get the steps attribute of module pipeline. If there is no steps sequence on the pipeline, return None. Guess you could theoretically want to run a pipeline with nothing in it.
[ "Get", "the", "steps", "attribute", "of", "module", "pipeline", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/stepsrunner.py#L13-L47
123
pypyr/pypyr-cli
pypyr/stepsrunner.py
run_failure_step_group
def run_failure_step_group(pipeline, context): """Run the on_failure step group if it exists. This function will swallow all errors, to prevent obfuscating the error condition that got it here to begin with. """ logger.debug("starting") try: assert pipeline # if no on_failure ex...
python
def run_failure_step_group(pipeline, context): logger.debug("starting") try: assert pipeline # if no on_failure exists, it'll do nothing. run_step_group(pipeline_definition=pipeline, step_group_name='on_failure', context=context) except E...
[ "def", "run_failure_step_group", "(", "pipeline", ",", "context", ")", ":", "logger", ".", "debug", "(", "\"starting\"", ")", "try", ":", "assert", "pipeline", "# if no on_failure exists, it'll do nothing.", "run_step_group", "(", "pipeline_definition", "=", "pipeline",...
Run the on_failure step group if it exists. This function will swallow all errors, to prevent obfuscating the error condition that got it here to begin with.
[ "Run", "the", "on_failure", "step", "group", "if", "it", "exists", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/stepsrunner.py#L50-L67
124
pypyr/pypyr-cli
pypyr/stepsrunner.py
run_step_group
def run_step_group(pipeline_definition, step_group_name, context): """Get the specified step group from the pipeline and run its steps.""" logger.debug(f"starting {step_group_name}") assert step_group_name steps = get_pipeline_steps(pipeline=pipeline_definition, steps_gro...
python
def run_step_group(pipeline_definition, step_group_name, context): logger.debug(f"starting {step_group_name}") assert step_group_name steps = get_pipeline_steps(pipeline=pipeline_definition, steps_group=step_group_name) run_pipeline_steps(steps=steps, context=context) ...
[ "def", "run_step_group", "(", "pipeline_definition", ",", "step_group_name", ",", "context", ")", ":", "logger", ".", "debug", "(", "f\"starting {step_group_name}\"", ")", "assert", "step_group_name", "steps", "=", "get_pipeline_steps", "(", "pipeline", "=", "pipeline...
Get the specified step group from the pipeline and run its steps.
[ "Get", "the", "specified", "step", "group", "from", "the", "pipeline", "and", "run", "its", "steps", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/stepsrunner.py#L96-L106
125
pypyr/pypyr-cli
pypyr/utils/filesystem.py
ensure_dir
def ensure_dir(path): """Create all parent directories of path if they don't exist. Args: path. Path-like object. Create parent dirs to this path. Return: None. """ os.makedirs(os.path.abspath(os.path.dirname(path)), exist_ok=True)
python
def ensure_dir(path): os.makedirs(os.path.abspath(os.path.dirname(path)), exist_ok=True)
[ "def", "ensure_dir", "(", "path", ")", ":", "os", ".", "makedirs", "(", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "dirname", "(", "path", ")", ")", ",", "exist_ok", "=", "True", ")" ]
Create all parent directories of path if they don't exist. Args: path. Path-like object. Create parent dirs to this path. Return: None.
[ "Create", "all", "parent", "directories", "of", "path", "if", "they", "don", "t", "exist", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/utils/filesystem.py#L394-L404
126
pypyr/pypyr-cli
pypyr/utils/filesystem.py
get_glob
def get_glob(path): """Process the input path, applying globbing and formatting. Do note that this will returns files AND directories that match the glob. No tilde expansion is done, but *, ?, and character ranges expressed with [] will be correctly matched. Escape all special characters ('?', '*...
python
def get_glob(path): if isinstance(path, str): return glob.glob(path, recursive=True) if isinstance(path, os.PathLike): # hilariously enough, glob doesn't like path-like. Gotta be str. return glob.glob(str(path), recursive=True) elif isinstance(path, (list, tuple)): # each glo...
[ "def", "get_glob", "(", "path", ")", ":", "if", "isinstance", "(", "path", ",", "str", ")", ":", "return", "glob", ".", "glob", "(", "path", ",", "recursive", "=", "True", ")", "if", "isinstance", "(", "path", ",", "os", ".", "PathLike", ")", ":", ...
Process the input path, applying globbing and formatting. Do note that this will returns files AND directories that match the glob. No tilde expansion is done, but *, ?, and character ranges expressed with [] will be correctly matched. Escape all special characters ('?', '*' and '['). For a literal m...
[ "Process", "the", "input", "path", "applying", "globbing", "and", "formatting", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/utils/filesystem.py#L407-L441
127
pypyr/pypyr-cli
pypyr/utils/filesystem.py
is_same_file
def is_same_file(path1, path2): """Return True if path1 is the same file as path2. The reason for this dance is that samefile throws if either file doesn't exist. Args: path1: str or path-like. path2: str or path-like. Returns: bool. True if the same file, False if not. ...
python
def is_same_file(path1, path2): return ( path1 and path2 and os.path.isfile(path1) and os.path.isfile(path2) and os.path.samefile(path1, path2))
[ "def", "is_same_file", "(", "path1", ",", "path2", ")", ":", "return", "(", "path1", "and", "path2", "and", "os", ".", "path", ".", "isfile", "(", "path1", ")", "and", "os", ".", "path", ".", "isfile", "(", "path2", ")", "and", "os", ".", "path", ...
Return True if path1 is the same file as path2. The reason for this dance is that samefile throws if either file doesn't exist. Args: path1: str or path-like. path2: str or path-like. Returns: bool. True if the same file, False if not.
[ "Return", "True", "if", "path1", "is", "the", "same", "file", "as", "path2", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/utils/filesystem.py#L444-L461
128
pypyr/pypyr-cli
pypyr/utils/filesystem.py
move_file
def move_file(src, dest): """Move source file to destination. Overwrites dest. Args: src: str or path-like. source file dest: str or path-like. destination file Returns: None. Raises: FileNotFoundError: out path parent doesn't exist. OSError: if any IO ope...
python
def move_file(src, dest): try: os.replace(src, dest) except Exception as ex_replace: logger.error(f"error moving file {src} to " f"{dest}. {ex_replace}") raise
[ "def", "move_file", "(", "src", ",", "dest", ")", ":", "try", ":", "os", ".", "replace", "(", "src", ",", "dest", ")", "except", "Exception", "as", "ex_replace", ":", "logger", ".", "error", "(", "f\"error moving file {src} to \"", "f\"{dest}. {ex_replace}\"",...
Move source file to destination. Overwrites dest. Args: src: str or path-like. source file dest: str or path-like. destination file Returns: None. Raises: FileNotFoundError: out path parent doesn't exist. OSError: if any IO operations go wrong.
[ "Move", "source", "file", "to", "destination", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/utils/filesystem.py#L464-L486
129
pypyr/pypyr-cli
pypyr/utils/filesystem.py
move_temp_file
def move_temp_file(src, dest): """Move src to dest. Delete src if something goes wrong. Overwrites dest. Args: src: str or path-like. source file dest: str or path-like. destination file Returns: None. Raises: FileNotFoundError: out path parent doesn't exist. ...
python
def move_temp_file(src, dest): try: move_file(src, dest) except Exception: try: os.remove(src) except Exception as ex_clean: # at this point, something's deeply wrong, so log error. # raising the original error, though, not this error in the ...
[ "def", "move_temp_file", "(", "src", ",", "dest", ")", ":", "try", ":", "move_file", "(", "src", ",", "dest", ")", "except", "Exception", ":", "try", ":", "os", ".", "remove", "(", "src", ")", "except", "Exception", "as", "ex_clean", ":", "# at this po...
Move src to dest. Delete src if something goes wrong. Overwrites dest. Args: src: str or path-like. source file dest: str or path-like. destination file Returns: None. Raises: FileNotFoundError: out path parent doesn't exist. OSError: if any IO operations go w...
[ "Move", "src", "to", "dest", ".", "Delete", "src", "if", "something", "goes", "wrong", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/utils/filesystem.py#L489-L520
130
pypyr/pypyr-cli
pypyr/utils/filesystem.py
FileRewriter.files_in_to_out
def files_in_to_out(self, in_path, out_path=None): """Write in files to out, calling the line_handler on each line. Calls file_in_to_out under the hood to format the in_path payload. The formatting processing is done by the self.formatter instance. Args: in_path: str, path-...
python
def files_in_to_out(self, in_path, out_path=None): in_paths = get_glob(in_path) in_count = len(in_paths) if in_count == 0: logger.debug(f'in path found {in_count} paths.') else: logger.debug(f'in path found {in_count} paths:') for path in in_paths: ...
[ "def", "files_in_to_out", "(", "self", ",", "in_path", ",", "out_path", "=", "None", ")", ":", "in_paths", "=", "get_glob", "(", "in_path", ")", "in_count", "=", "len", "(", "in_paths", ")", "if", "in_count", "==", "0", ":", "logger", ".", "debug", "("...
Write in files to out, calling the line_handler on each line. Calls file_in_to_out under the hood to format the in_path payload. The formatting processing is done by the self.formatter instance. Args: in_path: str, path-like, or an iterable (list/tuple) of stri...
[ "Write", "in", "files", "to", "out", "calling", "the", "line_handler", "on", "each", "line", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/utils/filesystem.py#L56-L156
131
pypyr/pypyr-cli
pypyr/utils/filesystem.py
ObjectRewriter.in_to_out
def in_to_out(self, in_path, out_path=None): """Load file into object, formats, writes object to out. If in_path and out_path point to the same thing it will in-place edit and overwrite the in path. Even easier, if you do want to edit a file in place, don't specify out_path, or set it t...
python
def in_to_out(self, in_path, out_path=None): if is_same_file(in_path, out_path): logger.debug( "in path and out path are the same file. writing to temp " "file and then replacing in path with the temp file.") out_path = None logger.debug(f"opening...
[ "def", "in_to_out", "(", "self", ",", "in_path", ",", "out_path", "=", "None", ")", ":", "if", "is_same_file", "(", "in_path", ",", "out_path", ")", ":", "logger", ".", "debug", "(", "\"in path and out path are the same file. writing to temp \"", "\"file and then re...
Load file into object, formats, writes object to out. If in_path and out_path point to the same thing it will in-place edit and overwrite the in path. Even easier, if you do want to edit a file in place, don't specify out_path, or set it to None. Args: in_path: str or path-...
[ "Load", "file", "into", "object", "formats", "writes", "object", "to", "out", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/utils/filesystem.py#L188-L233
132
pypyr/pypyr-cli
pypyr/utils/filesystem.py
StreamRewriter.in_to_out
def in_to_out(self, in_path, out_path=None): """Write a single file in to out, running self.formatter on each line. If in_path and out_path point to the same thing it will in-place edit and overwrite the in path. Even easier, if you do want to edit a file in place, don't specify out_pat...
python
def in_to_out(self, in_path, out_path=None): is_in_place_edit = False if is_same_file(in_path, out_path): logger.debug( "in path and out path are the same file. writing to temp " "file and then replacing in path with the temp file.") out_path = Non...
[ "def", "in_to_out", "(", "self", ",", "in_path", ",", "out_path", "=", "None", ")", ":", "is_in_place_edit", "=", "False", "if", "is_same_file", "(", "in_path", ",", "out_path", ")", ":", "logger", ".", "debug", "(", "\"in path and out path are the same file. wr...
Write a single file in to out, running self.formatter on each line. If in_path and out_path point to the same thing it will in-place edit and overwrite the in path. Even easier, if you do want to edit a file in place, don't specify out_path, or set it to None. Args: in_path...
[ "Write", "a", "single", "file", "in", "to", "out", "running", "self", ".", "formatter", "on", "each", "line", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/utils/filesystem.py#L252-L303
133
pypyr/pypyr-cli
pypyr/utils/filesystem.py
JsonRepresenter.dump
def dump(self, file, payload): """Dump json oject to open file output. Writes json with 2 spaces indentation. Args: file: Open file-like object. Must be open for writing. payload: The Json object to write to file. Returns: None. """ ...
python
def dump(self, file, payload): json.dump(payload, file, indent=2, ensure_ascii=False)
[ "def", "dump", "(", "self", ",", "file", ",", "payload", ")", ":", "json", ".", "dump", "(", "payload", ",", "file", ",", "indent", "=", "2", ",", "ensure_ascii", "=", "False", ")" ]
Dump json oject to open file output. Writes json with 2 spaces indentation. Args: file: Open file-like object. Must be open for writing. payload: The Json object to write to file. Returns: None.
[ "Dump", "json", "oject", "to", "open", "file", "output", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/utils/filesystem.py#L341-L354
134
pypyr/pypyr-cli
pypyr/steps/filereplace.py
run_step
def run_step(context): """Parse input file and replace a search string. This also does string substitutions from context on the fileReplacePairs. It does this before it search & replaces the in file. Be careful of order. If fileReplacePairs is not an ordered collection, replacements could evaluate...
python
def run_step(context): logger.debug("started") deprecated(context) StreamReplacePairsRewriterStep(__name__, 'fileReplace', context).run_step() logger.debug("done")
[ "def", "run_step", "(", "context", ")", ":", "logger", ".", "debug", "(", "\"started\"", ")", "deprecated", "(", "context", ")", "StreamReplacePairsRewriterStep", "(", "__name__", ",", "'fileReplace'", ",", "context", ")", ".", "run_step", "(", ")", "logger", ...
Parse input file and replace a search string. This also does string substitutions from context on the fileReplacePairs. It does this before it search & replaces the in file. Be careful of order. If fileReplacePairs is not an ordered collection, replacements could evaluate in any given order. If this i...
[ "Parse", "input", "file", "and", "replace", "a", "search", "string", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/steps/filereplace.py#L9-L56
135
pypyr/pypyr-cli
pypyr/log/logger.py
set_logging_config
def set_logging_config(log_level, handlers): """Set python logging library config. Run this ONCE at the start of your process. It formats the python logging module's output. Defaults logging level to INFO = 20) """ logging.basicConfig( format='%(asctime)s %(levelname)s:%(name)s:%(funcNa...
python
def set_logging_config(log_level, handlers): logging.basicConfig( format='%(asctime)s %(levelname)s:%(name)s:%(funcName)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=log_level, handlers=handlers)
[ "def", "set_logging_config", "(", "log_level", ",", "handlers", ")", ":", "logging", ".", "basicConfig", "(", "format", "=", "'%(asctime)s %(levelname)s:%(name)s:%(funcName)s: %(message)s'", ",", "datefmt", "=", "'%Y-%m-%d %H:%M:%S'", ",", "level", "=", "log_level", ","...
Set python logging library config. Run this ONCE at the start of your process. It formats the python logging module's output. Defaults logging level to INFO = 20)
[ "Set", "python", "logging", "library", "config", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/log/logger.py#L8-L19
136
pypyr/pypyr-cli
pypyr/log/logger.py
set_root_logger
def set_root_logger(root_log_level, log_path=None): """Set the root logger 'pypyr'. Do this before you do anything else. Run once and only once at initialization. """ handlers = [] console_handler = logging.StreamHandler() handlers.append(console_handler) if log_path: file_handler ...
python
def set_root_logger(root_log_level, log_path=None): handlers = [] console_handler = logging.StreamHandler() handlers.append(console_handler) if log_path: file_handler = logging.FileHandler(log_path) handlers.append(file_handler) set_logging_config(root_log_level, handlers=handlers)...
[ "def", "set_root_logger", "(", "root_log_level", ",", "log_path", "=", "None", ")", ":", "handlers", "=", "[", "]", "console_handler", "=", "logging", ".", "StreamHandler", "(", ")", "handlers", ".", "append", "(", "console_handler", ")", "if", "log_path", "...
Set the root logger 'pypyr'. Do this before you do anything else. Run once and only once at initialization.
[ "Set", "the", "root", "logger", "pypyr", ".", "Do", "this", "before", "you", "do", "anything", "else", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/log/logger.py#L22-L39
137
pypyr/pypyr-cli
pypyr/pipelinerunner.py
get_parsed_context
def get_parsed_context(pipeline, context_in_string): """Execute get_parsed_context handler if specified. Dynamically load the module specified by the context_parser key in pipeline dict and execute the get_parsed_context function on that module. Args: pipeline: dict. Pipeline object. c...
python
def get_parsed_context(pipeline, context_in_string): logger.debug("starting") if 'context_parser' in pipeline: parser_module_name = pipeline['context_parser'] logger.debug(f"context parser found: {parser_module_name}") parser_module = pypyr.moduleloader.get_module(parser_module_name) ...
[ "def", "get_parsed_context", "(", "pipeline", ",", "context_in_string", ")", ":", "logger", ".", "debug", "(", "\"starting\"", ")", "if", "'context_parser'", "in", "pipeline", ":", "parser_module_name", "=", "pipeline", "[", "'context_parser'", "]", "logger", ".",...
Execute get_parsed_context handler if specified. Dynamically load the module specified by the context_parser key in pipeline dict and execute the get_parsed_context function on that module. Args: pipeline: dict. Pipeline object. context_in_string: string. Argument string used to initialize...
[ "Execute", "get_parsed_context", "handler", "if", "specified", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/pipelinerunner.py#L17-L65
138
pypyr/pypyr-cli
pypyr/pipelinerunner.py
main
def main( pipeline_name, pipeline_context_input, working_dir, log_level, log_path, ): """Entry point for pypyr pipeline runner. Call this once per pypyr run. Call me if you want to run a pypyr pipeline from your own code. This function does some one-off 1st time initialization befor...
python
def main( pipeline_name, pipeline_context_input, working_dir, log_level, log_path, ): pypyr.log.logger.set_root_logger(log_level, log_path) logger.debug("starting pypyr") # pipelines specify steps in python modules that load dynamically. # make it easy for the operator so that the ...
[ "def", "main", "(", "pipeline_name", ",", "pipeline_context_input", ",", "working_dir", ",", "log_level", ",", "log_path", ",", ")", ":", "pypyr", ".", "log", ".", "logger", ".", "set_root_logger", "(", "log_level", ",", "log_path", ")", "logger", ".", "debu...
Entry point for pypyr pipeline runner. Call this once per pypyr run. Call me if you want to run a pypyr pipeline from your own code. This function does some one-off 1st time initialization before running the actual pipeline. pipeline_name.yaml should be in the working_dir/pipelines/ directory. Ar...
[ "Entry", "point", "for", "pypyr", "pipeline", "runner", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/pipelinerunner.py#L68-L108
139
pypyr/pypyr-cli
pypyr/pipelinerunner.py
prepare_context
def prepare_context(pipeline, context_in_string, context): """Prepare context for pipeline run. Args: pipeline: dict. Dictionary representing the pipeline. context_in_string: string. Argument string used to initialize context. context: pypyr.context.Context. Merge any new context genera...
python
def prepare_context(pipeline, context_in_string, context): logger.debug("starting") parsed_context = get_parsed_context( pipeline=pipeline, context_in_string=context_in_string) context.update(parsed_context) logger.debug("done")
[ "def", "prepare_context", "(", "pipeline", ",", "context_in_string", ",", "context", ")", ":", "logger", ".", "debug", "(", "\"starting\"", ")", "parsed_context", "=", "get_parsed_context", "(", "pipeline", "=", "pipeline", ",", "context_in_string", "=", "context_...
Prepare context for pipeline run. Args: pipeline: dict. Dictionary representing the pipeline. context_in_string: string. Argument string used to initialize context. context: pypyr.context.Context. Merge any new context generated from context_in_string into this context inst...
[ "Prepare", "context", "for", "pipeline", "run", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/pipelinerunner.py#L111-L133
140
pypyr/pypyr-cli
pypyr/pipelinerunner.py
load_and_run_pipeline
def load_and_run_pipeline(pipeline_name, pipeline_context_input=None, working_dir=None, context=None, parse_input=True, loader=None): """Load and run the specified pypyr pipeline. T...
python
def load_and_run_pipeline(pipeline_name, pipeline_context_input=None, working_dir=None, context=None, parse_input=True, loader=None): logger.debug(f"you asked to run pipeline: {pipeline_...
[ "def", "load_and_run_pipeline", "(", "pipeline_name", ",", "pipeline_context_input", "=", "None", ",", "working_dir", "=", "None", ",", "context", "=", "None", ",", "parse_input", "=", "True", ",", "loader", "=", "None", ")", ":", "logger", ".", "debug", "("...
Load and run the specified pypyr pipeline. This function runs the actual pipeline by name. If you are running another pipeline from within a pipeline, call this, not main(). Do call main() instead for your 1st pipeline if there are pipelines calling pipelines. By default pypyr uses file loader. This m...
[ "Load", "and", "run", "the", "specified", "pypyr", "pipeline", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/pipelinerunner.py#L136-L215
141
pypyr/pypyr-cli
pypyr/pipelinerunner.py
run_pipeline
def run_pipeline(pipeline, context, pipeline_context_input=None, parse_input=True): """Run the specified pypyr pipeline. This function runs the actual pipeline. If you are running another pipeline from within a pipeline, call this, not main(). Do call main...
python
def run_pipeline(pipeline, context, pipeline_context_input=None, parse_input=True): logger.debug("starting") try: if parse_input: logger.debug("executing context_parser") prepare_context(pipeline=pipeline, ...
[ "def", "run_pipeline", "(", "pipeline", ",", "context", ",", "pipeline_context_input", "=", "None", ",", "parse_input", "=", "True", ")", ":", "logger", ".", "debug", "(", "\"starting\"", ")", "try", ":", "if", "parse_input", ":", "logger", ".", "debug", "...
Run the specified pypyr pipeline. This function runs the actual pipeline. If you are running another pipeline from within a pipeline, call this, not main(). Do call main() instead for your 1st pipeline if there are pipelines calling pipelines. Pipeline and context should be already loaded. Args: ...
[ "Run", "the", "specified", "pypyr", "pipeline", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/pipelinerunner.py#L218-L276
142
pypyr/pypyr-cli
pypyr/steps/filewriteyaml.py
run_step
def run_step(context): """Write payload out to yaml file. Args: context: pypyr.context.Context. Mandatory. The following context keys expected: - fileWriteYaml - path. mandatory. path-like. Write output file to here. Will create...
python
def run_step(context): logger.debug("started") context.assert_child_key_has_value('fileWriteYaml', 'path', __name__) out_path = context.get_formatted_string(context['fileWriteYaml']['path']) # doing it like this to safeguard against accidentally dumping all context # with potentially sensitive valu...
[ "def", "run_step", "(", "context", ")", ":", "logger", ".", "debug", "(", "\"started\"", ")", "context", ".", "assert_child_key_has_value", "(", "'fileWriteYaml'", ",", "'path'", ",", "__name__", ")", "out_path", "=", "context", ".", "get_formatted_string", "(",...
Write payload out to yaml file. Args: context: pypyr.context.Context. Mandatory. The following context keys expected: - fileWriteYaml - path. mandatory. path-like. Write output file to here. Will create directories in path for you. ...
[ "Write", "payload", "out", "to", "yaml", "file", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/steps/filewriteyaml.py#L10-L55
143
pypyr/pypyr-cli
pypyr/steps/debug.py
run_step
def run_step(context): """Print debug info to console. context is a dictionary or dictionary-like. If you use pypyr.steps.debug as a simple step (i.e you do NOT specify the debug input context), it will just dump the entire context to stdout. Configure the debug step with the following optional c...
python
def run_step(context): logger.debug("started") debug = context.get('debug', None) if debug: keys = debug.get('keys', None) format = debug.get('format', False) if keys: logger.debug(f"Writing to output: {keys}") if isinstance(keys, str): payl...
[ "def", "run_step", "(", "context", ")", ":", "logger", ".", "debug", "(", "\"started\"", ")", "debug", "=", "context", ".", "get", "(", "'debug'", ",", "None", ")", "if", "debug", ":", "keys", "=", "debug", ".", "get", "(", "'keys'", ",", "None", "...
Print debug info to console. context is a dictionary or dictionary-like. If you use pypyr.steps.debug as a simple step (i.e you do NOT specify the debug input context), it will just dump the entire context to stdout. Configure the debug step with the following optional context item: debug: ...
[ "Print", "debug", "info", "to", "console", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/steps/debug.py#L23-L64
144
pypyr/pypyr-cli
pypyr/errors.py
get_error_name
def get_error_name(error): """Return canonical error name as string. For builtin errors like ValueError or Exception, will return the bare name, like ValueError or Exception. For all other exceptions, will return modulename.errorname, such as arbpackage.mod.myerror Args: error: Except...
python
def get_error_name(error): error_type = type(error) if error_type.__module__ in ['__main__', 'builtins']: return error_type.__name__ else: return f'{error_type.__module__}.{error_type.__name__}'
[ "def", "get_error_name", "(", "error", ")", ":", "error_type", "=", "type", "(", "error", ")", "if", "error_type", ".", "__module__", "in", "[", "'__main__'", ",", "'builtins'", "]", ":", "return", "error_type", ".", "__name__", "else", ":", "return", "f'{...
Return canonical error name as string. For builtin errors like ValueError or Exception, will return the bare name, like ValueError or Exception. For all other exceptions, will return modulename.errorname, such as arbpackage.mod.myerror Args: error: Exception object. Returns: ...
[ "Return", "canonical", "error", "name", "as", "string", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/errors.py#L7-L27
145
pypyr/pypyr-cli
pypyr/moduleloader.py
get_module
def get_module(module_abs_import): """Use importlib to get the module dynamically. Get instance of the module specified by the module_abs_import. This means that module_abs_import must be resolvable from this package. Args: module_abs_import: string. Absolute name of module to import. Rai...
python
def get_module(module_abs_import): logger.debug("starting") logger.debug(f"loading module {module_abs_import}") try: imported_module = importlib.import_module(module_abs_import) logger.debug("done") return imported_module except ModuleNotFoundError as err: msg = ("The mod...
[ "def", "get_module", "(", "module_abs_import", ")", ":", "logger", ".", "debug", "(", "\"starting\"", ")", "logger", ".", "debug", "(", "f\"loading module {module_abs_import}\"", ")", "try", ":", "imported_module", "=", "importlib", ".", "import_module", "(", "mod...
Use importlib to get the module dynamically. Get instance of the module specified by the module_abs_import. This means that module_abs_import must be resolvable from this package. Args: module_abs_import: string. Absolute name of module to import. Raises: PyModuleNotFoundError: if mod...
[ "Use", "importlib", "to", "get", "the", "module", "dynamically", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/moduleloader.py#L15-L48
146
pypyr/pypyr-cli
pypyr/moduleloader.py
set_working_directory
def set_working_directory(working_directory): """Add working_directory to sys.paths. This allows dynamic loading of arbitrary python modules in cwd. Args: working_directory: string. path to add to sys.paths """ logger.debug("starting") logger.debug(f"adding {working_directory} to sys...
python
def set_working_directory(working_directory): logger.debug("starting") logger.debug(f"adding {working_directory} to sys.paths") sys.path.append(working_directory) logger.debug("done")
[ "def", "set_working_directory", "(", "working_directory", ")", ":", "logger", ".", "debug", "(", "\"starting\"", ")", "logger", ".", "debug", "(", "f\"adding {working_directory} to sys.paths\"", ")", "sys", ".", "path", ".", "append", "(", "working_directory", ")", ...
Add working_directory to sys.paths. This allows dynamic loading of arbitrary python modules in cwd. Args: working_directory: string. path to add to sys.paths
[ "Add", "working_directory", "to", "sys", ".", "paths", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/moduleloader.py#L51-L65
147
pypyr/pypyr-cli
pypyr/context.py
Context.assert_child_key_has_value
def assert_child_key_has_value(self, parent, child, caller): """Assert that context contains key that has child which has a value. Args: parent: parent key child: validate this sub-key of parent exists AND isn't None. caller: string. calling function name - this used...
python
def assert_child_key_has_value(self, parent, child, caller): assert parent, ("parent parameter must be specified.") assert child, ("child parameter must be specified.") self.assert_key_has_value(parent, caller) try: child_exists = child in self[parent] except TypeErr...
[ "def", "assert_child_key_has_value", "(", "self", ",", "parent", ",", "child", ",", "caller", ")", ":", "assert", "parent", ",", "(", "\"parent parameter must be specified.\"", ")", "assert", "child", ",", "(", "\"child parameter must be specified.\"", ")", "self", ...
Assert that context contains key that has child which has a value. Args: parent: parent key child: validate this sub-key of parent exists AND isn't None. caller: string. calling function name - this used to construct error messages Raises: ...
[ "Assert", "that", "context", "contains", "key", "that", "has", "child", "which", "has", "a", "value", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/context.py#L48-L83
148
pypyr/pypyr-cli
pypyr/context.py
Context.assert_key_has_value
def assert_key_has_value(self, key, caller): """Assert that context contains key which also has a value. Args: key: validate this key exists in context AND has a value that isn't None. caller: string. calling function name - this used to construct ...
python
def assert_key_has_value(self, key, caller): assert key, ("key parameter must be specified.") self.assert_key_exists(key, caller) if self[key] is None: raise KeyInContextHasNoValueError( f"context['{key}'] must have a value for {caller}.")
[ "def", "assert_key_has_value", "(", "self", ",", "key", ",", "caller", ")", ":", "assert", "key", ",", "(", "\"key parameter must be specified.\"", ")", "self", ".", "assert_key_exists", "(", "key", ",", "caller", ")", "if", "self", "[", "key", "]", "is", ...
Assert that context contains key which also has a value. Args: key: validate this key exists in context AND has a value that isn't None. caller: string. calling function name - this used to construct error messages Raises: KeyNot...
[ "Assert", "that", "context", "contains", "key", "which", "also", "has", "a", "value", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/context.py#L102-L122
149
pypyr/pypyr-cli
pypyr/context.py
Context.assert_keys_exist
def assert_keys_exist(self, caller, *keys): """Assert that context contains keys. Args: keys: validates that these keys exists in context caller: string. calling function or module name - this used to construct error messages Raises: KeyN...
python
def assert_keys_exist(self, caller, *keys): assert keys, ("*keys parameter must be specified.") for key in keys: self.assert_key_exists(key, caller)
[ "def", "assert_keys_exist", "(", "self", ",", "caller", ",", "*", "keys", ")", ":", "assert", "keys", ",", "(", "\"*keys parameter must be specified.\"", ")", "for", "key", "in", "keys", ":", "self", ".", "assert_key_exists", "(", "key", ",", "caller", ")" ]
Assert that context contains keys. Args: keys: validates that these keys exists in context caller: string. calling function or module name - this used to construct error messages Raises: KeyNotInContextError: When key doesn't exist in context.
[ "Assert", "that", "context", "contains", "keys", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/context.py#L167-L181
150
pypyr/pypyr-cli
pypyr/context.py
Context.assert_keys_have_values
def assert_keys_have_values(self, caller, *keys): """Check that keys list are all in context and all have values. Args: *keys: Will check each of these keys in context caller: string. Calling function name - just used for informational messages Raise...
python
def assert_keys_have_values(self, caller, *keys): for key in keys: self.assert_key_has_value(key, caller)
[ "def", "assert_keys_have_values", "(", "self", ",", "caller", ",", "*", "keys", ")", ":", "for", "key", "in", "keys", ":", "self", ".", "assert_key_has_value", "(", "key", ",", "caller", ")" ]
Check that keys list are all in context and all have values. Args: *keys: Will check each of these keys in context caller: string. Calling function name - just used for informational messages Raises: KeyNotInContextError: Key doesn't exist ...
[ "Check", "that", "keys", "list", "are", "all", "in", "context", "and", "all", "have", "values", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/context.py#L183-L198
151
pypyr/pypyr-cli
pypyr/context.py
Context.get_formatted_iterable
def get_formatted_iterable(self, obj, memo=None): """Recursively loop through obj, formatting as it goes. Interpolates strings from the context dictionary. This is not a full on deepcopy, and it's on purpose not a full on deepcopy. It will handle dict, list, set, tuple for iteration, w...
python
def get_formatted_iterable(self, obj, memo=None): if memo is None: memo = {} obj_id = id(obj) already_done = memo.get(obj_id, None) if already_done is not None: return already_done if isinstance(obj, str): new = self.get_formatted_string(obj)...
[ "def", "get_formatted_iterable", "(", "self", ",", "obj", ",", "memo", "=", "None", ")", ":", "if", "memo", "is", "None", ":", "memo", "=", "{", "}", "obj_id", "=", "id", "(", "obj", ")", "already_done", "=", "memo", ".", "get", "(", "obj_id", ",",...
Recursively loop through obj, formatting as it goes. Interpolates strings from the context dictionary. This is not a full on deepcopy, and it's on purpose not a full on deepcopy. It will handle dict, list, set, tuple for iteration, without any especial cuteness for other types or types...
[ "Recursively", "loop", "through", "obj", "formatting", "as", "it", "goes", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/context.py#L298-L361
152
pypyr/pypyr-cli
pypyr/context.py
Context.get_formatted_string
def get_formatted_string(self, input_string): """Return formatted value for input_string. get_formatted gets a context[key] value. get_formatted_string is for any arbitrary string that is not in the context. Only valid if input_string is a type string. Return a string i...
python
def get_formatted_string(self, input_string): if isinstance(input_string, str): try: return self.get_processed_string(input_string) except KeyNotInContextError as err: # Wrapping the KeyError into a less cryptic error for end-user # friendl...
[ "def", "get_formatted_string", "(", "self", ",", "input_string", ")", ":", "if", "isinstance", "(", "input_string", ",", "str", ")", ":", "try", ":", "return", "self", ".", "get_processed_string", "(", "input_string", ")", "except", "KeyNotInContextError", "as",...
Return formatted value for input_string. get_formatted gets a context[key] value. get_formatted_string is for any arbitrary string that is not in the context. Only valid if input_string is a type string. Return a string interpolated from the context dictionary. If inpu...
[ "Return", "formatted", "value", "for", "input_string", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/context.py#L363-L403
153
pypyr/pypyr-cli
pypyr/context.py
Context.get_formatted_as_type
def get_formatted_as_type(self, value, default=None, out_type=str): """Return formatted value for input value, returns as out_type. Caveat emptor: if out_type is bool and value a string, return will be True if str is 'True'. It will be False for all other cases. Args: ...
python
def get_formatted_as_type(self, value, default=None, out_type=str): if value is None: value = default if isinstance(value, SpecialTagDirective): result = value.get_value(self) return types.cast_to_type(result, out_type) if isinstance(value, str): ...
[ "def", "get_formatted_as_type", "(", "self", ",", "value", ",", "default", "=", "None", ",", "out_type", "=", "str", ")", ":", "if", "value", "is", "None", ":", "value", "=", "default", "if", "isinstance", "(", "value", ",", "SpecialTagDirective", ")", "...
Return formatted value for input value, returns as out_type. Caveat emptor: if out_type is bool and value a string, return will be True if str is 'True'. It will be False for all other cases. Args: value: the value to format default: if value is None, set to thi...
[ "Return", "formatted", "value", "for", "input", "value", "returns", "as", "out_type", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/context.py#L405-L441
154
pypyr/pypyr-cli
pypyr/context.py
Context.get_processed_string
def get_processed_string(self, input_string): """Run token substitution on input_string against context. You probably don't want to call this directly yourself - rather use get_formatted, get_formatted_iterable, or get_formatted_string because these contain more friendly error handling ...
python
def get_processed_string(self, input_string): # arguably, this doesn't really belong here, or at least it makes a # nonsense of the function name. given how py and strings # look and feel pretty much like strings from user's perspective, and # given legacy code back when sic strings were...
[ "def", "get_processed_string", "(", "self", ",", "input_string", ")", ":", "# arguably, this doesn't really belong here, or at least it makes a", "# nonsense of the function name. given how py and strings", "# look and feel pretty much like strings from user's perspective, and", "# given legac...
Run token substitution on input_string against context. You probably don't want to call this directly yourself - rather use get_formatted, get_formatted_iterable, or get_formatted_string because these contain more friendly error handling plumbing and context logic. If you do want to ca...
[ "Run", "token", "substitution", "on", "input_string", "against", "context", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/context.py#L443-L523
155
pypyr/pypyr-cli
pypyr/context.py
Context.keys_of_type_exist
def keys_of_type_exist(self, *keys): """Check if keys exist in context and if types are as expected. Args: *keys: *args for keys to check in context. Each arg is a tuple (str, type) Returns: Tuple of namedtuple ContextItemInfo, same order as *keys. ...
python
def keys_of_type_exist(self, *keys): # k[0] = key name, k[1] = exists, k2 = expected type keys_exist = [(key, key in self.keys(), expected_type) for key, expected_type in keys] return tuple(ContextItemInfo( key=k[0], key_in_context=k[1], ...
[ "def", "keys_of_type_exist", "(", "self", ",", "*", "keys", ")", ":", "# k[0] = key name, k[1] = exists, k2 = expected type", "keys_exist", "=", "[", "(", "key", ",", "key", "in", "self", ".", "keys", "(", ")", ",", "expected_type", ")", "for", "key", ",", "...
Check if keys exist in context and if types are as expected. Args: *keys: *args for keys to check in context. Each arg is a tuple (str, type) Returns: Tuple of namedtuple ContextItemInfo, same order as *keys. ContextItemInfo(key, ...
[ "Check", "if", "keys", "exist", "in", "context", "and", "if", "types", "are", "as", "expected", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/context.py#L560-L593
156
pypyr/pypyr-cli
pypyr/context.py
Context.merge
def merge(self, add_me): """Merge add_me into context and applies interpolation. Bottom-up merge where add_me merges into context. Applies string interpolation where the type is a string. Where a key exists in context already, add_me's value will overwrite what's in context alre...
python
def merge(self, add_me): def merge_recurse(current, add_me): """Walk the current context tree in recursive inner function. On 1st iteration, current = self (i.e root of context) On subsequent recursive iterations, current is wherever you're at in the nested conte...
[ "def", "merge", "(", "self", ",", "add_me", ")", ":", "def", "merge_recurse", "(", "current", ",", "add_me", ")", ":", "\"\"\"Walk the current context tree in recursive inner function.\n\n On 1st iteration, current = self (i.e root of context)\n On subsequent re...
Merge add_me into context and applies interpolation. Bottom-up merge where add_me merges into context. Applies string interpolation where the type is a string. Where a key exists in context already, add_me's value will overwrite what's in context already. Supports nested hierar...
[ "Merge", "add_me", "into", "context", "and", "applies", "interpolation", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/context.py#L595-L675
157
pypyr/pypyr-cli
pypyr/context.py
Context.set_defaults
def set_defaults(self, defaults): """Set defaults in context if keys do not exist already. Adds the input dict (defaults) into the context, only where keys in defaults do not already exist in context. Supports nested hierarchies. Example: Given a context like this: ...
python
def set_defaults(self, defaults): def defaults_recurse(current, defaults): """Walk the current context tree in recursive inner function. On 1st iteration, current = self (i.e root of context) On subsequent recursive iterations, current is wherever you're at in th...
[ "def", "set_defaults", "(", "self", ",", "defaults", ")", ":", "def", "defaults_recurse", "(", "current", ",", "defaults", ")", ":", "\"\"\"Walk the current context tree in recursive inner function.\n\n On 1st iteration, current = self (i.e root of context)\n On...
Set defaults in context if keys do not exist already. Adds the input dict (defaults) into the context, only where keys in defaults do not already exist in context. Supports nested hierarchies. Example: Given a context like this: key1: value1 key2: ...
[ "Set", "defaults", "in", "context", "if", "keys", "do", "not", "exist", "already", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/context.py#L677-L737
158
pypyr/pypyr-cli
pypyr/steps/dsl/fileinoutrewriter.py
FileInRewriterStep.run_step
def run_step(self, rewriter): """Do the file in to out rewrite. Doesn't do anything more crazy than call files_in_to_out on the rewriter. Args: rewriter: pypyr.filesystem.FileRewriter instance. """ assert rewriter, ("FileRewriter instance required to run " ...
python
def run_step(self, rewriter): assert rewriter, ("FileRewriter instance required to run " "FileInRewriterStep.") rewriter.files_in_to_out(in_path=self.path_in, out_path=self.path_out)
[ "def", "run_step", "(", "self", ",", "rewriter", ")", ":", "assert", "rewriter", ",", "(", "\"FileRewriter instance required to run \"", "\"FileInRewriterStep.\"", ")", "rewriter", ".", "files_in_to_out", "(", "in_path", "=", "self", ".", "path_in", ",", "out_path",...
Do the file in to out rewrite. Doesn't do anything more crazy than call files_in_to_out on the rewriter. Args: rewriter: pypyr.filesystem.FileRewriter instance.
[ "Do", "the", "file", "in", "to", "out", "rewrite", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/steps/dsl/fileinoutrewriter.py#L57-L68
159
pypyr/pypyr-cli
pypyr/steps/dsl/fileinoutrewriter.py
ObjectRewriterStep.run_step
def run_step(self, representer): """Do the object in-out rewrite. Args: representer: A pypyr.filesystem.ObjectRepresenter instance. """ assert representer, ("ObjectRepresenter instance required to run " "ObjectRewriterStep.") rewriter = ...
python
def run_step(self, representer): assert representer, ("ObjectRepresenter instance required to run " "ObjectRewriterStep.") rewriter = ObjectRewriter(self.context.get_formatted_iterable, representer) super().run_step(rewriter)
[ "def", "run_step", "(", "self", ",", "representer", ")", ":", "assert", "representer", ",", "(", "\"ObjectRepresenter instance required to run \"", "\"ObjectRewriterStep.\"", ")", "rewriter", "=", "ObjectRewriter", "(", "self", ".", "context", ".", "get_formatted_iterab...
Do the object in-out rewrite. Args: representer: A pypyr.filesystem.ObjectRepresenter instance.
[ "Do", "the", "object", "in", "-", "out", "rewrite", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/steps/dsl/fileinoutrewriter.py#L74-L85
160
pypyr/pypyr-cli
pypyr/steps/dsl/fileinoutrewriter.py
StreamRewriterStep.run_step
def run_step(self): """Do the file in-out rewrite.""" rewriter = StreamRewriter(self.context.iter_formatted_strings) super().run_step(rewriter)
python
def run_step(self): rewriter = StreamRewriter(self.context.iter_formatted_strings) super().run_step(rewriter)
[ "def", "run_step", "(", "self", ")", ":", "rewriter", "=", "StreamRewriter", "(", "self", ".", "context", ".", "iter_formatted_strings", ")", "super", "(", ")", ".", "run_step", "(", "rewriter", ")" ]
Do the file in-out rewrite.
[ "Do", "the", "file", "in", "-", "out", "rewrite", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/steps/dsl/fileinoutrewriter.py#L100-L103
161
pypyr/pypyr-cli
pypyr/steps/dsl/fileinoutrewriter.py
StreamReplacePairsRewriterStep.run_step
def run_step(self): """Write in to out, replacing strings per the replace_pairs.""" formatted_replacements = self.context.get_formatted_iterable( self.replace_pairs) iter = StreamReplacePairsRewriterStep.iter_replace_strings( formatted_replacements) rewriter = St...
python
def run_step(self): formatted_replacements = self.context.get_formatted_iterable( self.replace_pairs) iter = StreamReplacePairsRewriterStep.iter_replace_strings( formatted_replacements) rewriter = StreamRewriter(iter) super().run_step(rewriter)
[ "def", "run_step", "(", "self", ")", ":", "formatted_replacements", "=", "self", ".", "context", ".", "get_formatted_iterable", "(", "self", ".", "replace_pairs", ")", "iter", "=", "StreamReplacePairsRewriterStep", ".", "iter_replace_strings", "(", "formatted_replacem...
Write in to out, replacing strings per the replace_pairs.
[ "Write", "in", "to", "out", "replacing", "strings", "per", "the", "replace_pairs", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/steps/dsl/fileinoutrewriter.py#L133-L141
162
pypyr/pypyr-cli
pypyr/steps/dsl/fileinoutrewriter.py
StreamReplacePairsRewriterStep.iter_replace_strings
def iter_replace_strings(replacements): """Create a function that uses replacement pairs to process a string. The returned function takes an iterator and yields on each processed line. Args: replacements: Dict containing 'find_string': 'replace_string' pairs Return...
python
def iter_replace_strings(replacements): def function_iter_replace_strings(iterable_strings): """Yield a formatted string from iterable_strings using a generator. Args: iterable_strings: Iterable containing strings. E.g a file-like object...
[ "def", "iter_replace_strings", "(", "replacements", ")", ":", "def", "function_iter_replace_strings", "(", "iterable_strings", ")", ":", "\"\"\"Yield a formatted string from iterable_strings using a generator.\n\n Args:\n iterable_strings: Iterable containing string...
Create a function that uses replacement pairs to process a string. The returned function takes an iterator and yields on each processed line. Args: replacements: Dict containing 'find_string': 'replace_string' pairs Returns: function with signature: iterator of...
[ "Create", "a", "function", "that", "uses", "replacement", "pairs", "to", "process", "a", "string", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/steps/dsl/fileinoutrewriter.py#L144-L173
163
pypyr/pypyr-cli
pypyr/steps/contextsetf.py
run_step
def run_step(context): """Set new context keys from formatting expressions with substitutions. Context is a dictionary or dictionary-like. context['contextSetf'] must exist. It's a dictionary. Will iterate context['contextSetf'] and save the values as new keys to the context. For example, say ...
python
def run_step(context): logger.debug("started") context.assert_key_has_value(key='contextSetf', caller=__name__) for k, v in context['contextSetf'].items(): logger.debug(f"setting context {k} to value from context {v}") context[context.get_formatted_iterable( k)] = context.get_fo...
[ "def", "run_step", "(", "context", ")", ":", "logger", ".", "debug", "(", "\"started\"", ")", "context", ".", "assert_key_has_value", "(", "key", "=", "'contextSetf'", ",", "caller", "=", "__name__", ")", "for", "k", ",", "v", "in", "context", "[", "'con...
Set new context keys from formatting expressions with substitutions. Context is a dictionary or dictionary-like. context['contextSetf'] must exist. It's a dictionary. Will iterate context['contextSetf'] and save the values as new keys to the context. For example, say input context is: key1...
[ "Set", "new", "context", "keys", "from", "formatting", "expressions", "with", "substitutions", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/steps/contextsetf.py#L13-L45
164
pypyr/pypyr-cli
pypyr/utils/types.py
cast_to_type
def cast_to_type(obj, out_type): """Cast obj to out_type if it's not out_type already. If the obj happens to be out_type already, it just returns obj as is. Args: obj: input object out_type: type. Returns: obj cast to out_type. Usual python conversion / casting rules apply. ...
python
def cast_to_type(obj, out_type): in_type = type(obj) if out_type is in_type: # no need to cast. return obj else: return out_type(obj)
[ "def", "cast_to_type", "(", "obj", ",", "out_type", ")", ":", "in_type", "=", "type", "(", "obj", ")", "if", "out_type", "is", "in_type", ":", "# no need to cast.", "return", "obj", "else", ":", "return", "out_type", "(", "obj", ")" ]
Cast obj to out_type if it's not out_type already. If the obj happens to be out_type already, it just returns obj as is. Args: obj: input object out_type: type. Returns: obj cast to out_type. Usual python conversion / casting rules apply.
[ "Cast", "obj", "to", "out_type", "if", "it", "s", "not", "out_type", "already", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/utils/types.py#L20-L38
165
pypyr/pypyr-cli
pypyr/yaml.py
get_pipeline_yaml
def get_pipeline_yaml(file): """Return pipeline yaml from open file object. Use specific custom representers to model the custom pypyr pipeline yaml format, to load in special literal types like py and sic strings. If looking to extend the pypyr pipeline syntax with special types, add these to the...
python
def get_pipeline_yaml(file): tag_representers = [PyString, SicString] yaml_loader = get_yaml_parser_safe() for representer in tag_representers: yaml_loader.register_class(representer) pipeline_definition = yaml_loader.load(file) return pipeline_definition
[ "def", "get_pipeline_yaml", "(", "file", ")", ":", "tag_representers", "=", "[", "PyString", ",", "SicString", "]", "yaml_loader", "=", "get_yaml_parser_safe", "(", ")", "for", "representer", "in", "tag_representers", ":", "yaml_loader", ".", "register_class", "("...
Return pipeline yaml from open file object. Use specific custom representers to model the custom pypyr pipeline yaml format, to load in special literal types like py and sic strings. If looking to extend the pypyr pipeline syntax with special types, add these to the tag_representers list. Args: ...
[ "Return", "pipeline", "yaml", "from", "open", "file", "object", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/yaml.py#L7-L31
166
pypyr/pypyr-cli
pypyr/yaml.py
get_yaml_parser_roundtrip
def get_yaml_parser_roundtrip(): """Create the yaml parser object with this factory method. The round-trip parser preserves: - comments - block style and key ordering are kept, so you can diff the round-tripped source - flow style sequences ( ‘a: b, c, d’) (based on request and test by ...
python
def get_yaml_parser_roundtrip(): yaml_writer = yamler.YAML(typ='rt', pure=True) # if this isn't here the yaml doesn't format nicely indented for humans yaml_writer.indent(mapping=2, sequence=4, offset=2) return yaml_writer
[ "def", "get_yaml_parser_roundtrip", "(", ")", ":", "yaml_writer", "=", "yamler", ".", "YAML", "(", "typ", "=", "'rt'", ",", "pure", "=", "True", ")", "# if this isn't here the yaml doesn't format nicely indented for humans", "yaml_writer", ".", "indent", "(", "mapping...
Create the yaml parser object with this factory method. The round-trip parser preserves: - comments - block style and key ordering are kept, so you can diff the round-tripped source - flow style sequences ( ‘a: b, c, d’) (based on request and test by Anthony Sottile) - anchor names that...
[ "Create", "the", "yaml", "parser", "object", "with", "this", "factory", "method", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/yaml.py#L46-L65
167
pypyr/pypyr-cli
pypyr/yaml.py
get_yaml_parser_roundtrip_for_context
def get_yaml_parser_roundtrip_for_context(): """Create a yaml parser that can serialize the pypyr Context. Create yaml parser with get_yaml_parser_roundtrip, adding Context. This allows the yaml parser to serialize the pypyr Context. """ yaml_writer = get_yaml_parser_roundtrip() # Context is a...
python
def get_yaml_parser_roundtrip_for_context(): yaml_writer = get_yaml_parser_roundtrip() # Context is a dict data structure, so can just use a dict representer yaml_writer.Representer.add_representer( Context, yamler.representer.RoundTripRepresenter.represent_dict) return yaml_writer
[ "def", "get_yaml_parser_roundtrip_for_context", "(", ")", ":", "yaml_writer", "=", "get_yaml_parser_roundtrip", "(", ")", "# Context is a dict data structure, so can just use a dict representer", "yaml_writer", ".", "Representer", ".", "add_representer", "(", "Context", ",", "y...
Create a yaml parser that can serialize the pypyr Context. Create yaml parser with get_yaml_parser_roundtrip, adding Context. This allows the yaml parser to serialize the pypyr Context.
[ "Create", "a", "yaml", "parser", "that", "can", "serialize", "the", "pypyr", "Context", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/yaml.py#L68-L81
168
pypyr/pypyr-cli
pypyr/steps/fetchjson.py
run_step
def run_step(context): """Load a json file into the pypyr context. json parsed from the file will be merged into the pypyr context. This will overwrite existing values if the same keys are already in there. I.e if file json has {'eggs' : 'boiled'} and context {'eggs': 'fried'} already exists, retur...
python
def run_step(context): logger.debug("started") deprecated(context) context.assert_key_has_value(key='fetchJson', caller=__name__) fetch_json_input = context.get_formatted('fetchJson') if isinstance(fetch_json_input, str): file_path = fetch_json_input destination_key_expression = ...
[ "def", "run_step", "(", "context", ")", ":", "logger", ".", "debug", "(", "\"started\"", ")", "deprecated", "(", "context", ")", "context", ".", "assert_key_has_value", "(", "key", "=", "'fetchJson'", ",", "caller", "=", "__name__", ")", "fetch_json_input", ...
Load a json file into the pypyr context. json parsed from the file will be merged into the pypyr context. This will overwrite existing values if the same keys are already in there. I.e if file json has {'eggs' : 'boiled'} and context {'eggs': 'fried'} already exists, returned context['eggs'] will be 'b...
[ "Load", "a", "json", "file", "into", "the", "pypyr", "context", "." ]
4003f999cd5eb030b4c7407317de728f5115a80f
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/steps/fetchjson.py#L10-L82
169
bradmontgomery/django-querycount
querycount/middleware.py
QueryCountMiddleware._ignore_request
def _ignore_request(self, path): """Check to see if we should ignore the request.""" return any([ re.match(pattern, path) for pattern in QC_SETTINGS['IGNORE_REQUEST_PATTERNS'] ])
python
def _ignore_request(self, path): return any([ re.match(pattern, path) for pattern in QC_SETTINGS['IGNORE_REQUEST_PATTERNS'] ])
[ "def", "_ignore_request", "(", "self", ",", "path", ")", ":", "return", "any", "(", "[", "re", ".", "match", "(", "pattern", ",", "path", ")", "for", "pattern", "in", "QC_SETTINGS", "[", "'IGNORE_REQUEST_PATTERNS'", "]", "]", ")" ]
Check to see if we should ignore the request.
[ "Check", "to", "see", "if", "we", "should", "ignore", "the", "request", "." ]
61a380d98bc55e926c011367ecc2031102c3484c
https://github.com/bradmontgomery/django-querycount/blob/61a380d98bc55e926c011367ecc2031102c3484c/querycount/middleware.py#L83-L87
170
bradmontgomery/django-querycount
querycount/middleware.py
QueryCountMiddleware._ignore_sql
def _ignore_sql(self, query): """Check to see if we should ignore the sql query.""" return any([ re.search(pattern, query.get('sql')) for pattern in QC_SETTINGS['IGNORE_SQL_PATTERNS'] ])
python
def _ignore_sql(self, query): return any([ re.search(pattern, query.get('sql')) for pattern in QC_SETTINGS['IGNORE_SQL_PATTERNS'] ])
[ "def", "_ignore_sql", "(", "self", ",", "query", ")", ":", "return", "any", "(", "[", "re", ".", "search", "(", "pattern", ",", "query", ".", "get", "(", "'sql'", ")", ")", "for", "pattern", "in", "QC_SETTINGS", "[", "'IGNORE_SQL_PATTERNS'", "]", "]", ...
Check to see if we should ignore the sql query.
[ "Check", "to", "see", "if", "we", "should", "ignore", "the", "sql", "query", "." ]
61a380d98bc55e926c011367ecc2031102c3484c
https://github.com/bradmontgomery/django-querycount/blob/61a380d98bc55e926c011367ecc2031102c3484c/querycount/middleware.py#L89-L93
171
bradmontgomery/django-querycount
querycount/middleware.py
QueryCountMiddleware._duplicate_queries
def _duplicate_queries(self, output): """Appends the most common duplicate queries to the given output.""" if QC_SETTINGS['DISPLAY_DUPLICATES']: for query, count in self.queries.most_common(QC_SETTINGS['DISPLAY_DUPLICATES']): lines = ['\nRepeated {0} times.'.format(count)] ...
python
def _duplicate_queries(self, output): if QC_SETTINGS['DISPLAY_DUPLICATES']: for query, count in self.queries.most_common(QC_SETTINGS['DISPLAY_DUPLICATES']): lines = ['\nRepeated {0} times.'.format(count)] lines += wrap(query) lines = "\n".join(lines) +...
[ "def", "_duplicate_queries", "(", "self", ",", "output", ")", ":", "if", "QC_SETTINGS", "[", "'DISPLAY_DUPLICATES'", "]", ":", "for", "query", ",", "count", "in", "self", ".", "queries", ".", "most_common", "(", "QC_SETTINGS", "[", "'DISPLAY_DUPLICATES'", "]",...
Appends the most common duplicate queries to the given output.
[ "Appends", "the", "most", "common", "duplicate", "queries", "to", "the", "given", "output", "." ]
61a380d98bc55e926c011367ecc2031102c3484c
https://github.com/bradmontgomery/django-querycount/blob/61a380d98bc55e926c011367ecc2031102c3484c/querycount/middleware.py#L142-L150
172
bradmontgomery/django-querycount
querycount/middleware.py
QueryCountMiddleware._calculate_num_queries
def _calculate_num_queries(self): """ Calculate the total number of request and response queries. Used for count header and count table. """ request_totals = self._totals("request") response_totals = self._totals("response") return request_totals[2] + response_to...
python
def _calculate_num_queries(self): request_totals = self._totals("request") response_totals = self._totals("response") return request_totals[2] + response_totals[2]
[ "def", "_calculate_num_queries", "(", "self", ")", ":", "request_totals", "=", "self", ".", "_totals", "(", "\"request\"", ")", "response_totals", "=", "self", ".", "_totals", "(", "\"response\"", ")", "return", "request_totals", "[", "2", "]", "+", "response_...
Calculate the total number of request and response queries. Used for count header and count table.
[ "Calculate", "the", "total", "number", "of", "request", "and", "response", "queries", ".", "Used", "for", "count", "header", "and", "count", "table", "." ]
61a380d98bc55e926c011367ecc2031102c3484c
https://github.com/bradmontgomery/django-querycount/blob/61a380d98bc55e926c011367ecc2031102c3484c/querycount/middleware.py#L193-L201
173
bradmontgomery/django-querycount
querycount/qc_settings.py
_process_settings
def _process_settings(**kwargs): """ Apply user supplied settings. """ # If we are in this method due to a signal, only reload for our settings setting_name = kwargs.get('setting', None) if setting_name is not None and setting_name != 'QUERYCOUNT': return # Support the old-style s...
python
def _process_settings(**kwargs): # If we are in this method due to a signal, only reload for our settings setting_name = kwargs.get('setting', None) if setting_name is not None and setting_name != 'QUERYCOUNT': return # Support the old-style settings if getattr(settings, 'QUERYCOUNT_THRESH...
[ "def", "_process_settings", "(", "*", "*", "kwargs", ")", ":", "# If we are in this method due to a signal, only reload for our settings", "setting_name", "=", "kwargs", ".", "get", "(", "'setting'", ",", "None", ")", "if", "setting_name", "is", "not", "None", "and", ...
Apply user supplied settings.
[ "Apply", "user", "supplied", "settings", "." ]
61a380d98bc55e926c011367ecc2031102c3484c
https://github.com/bradmontgomery/django-querycount/blob/61a380d98bc55e926c011367ecc2031102c3484c/querycount/qc_settings.py#L23-L55
174
xiyouMc/ncmbot
ncmbot/core.py
NCloudBot._get_webapi_requests
def _get_webapi_requests(self): """Update headers of webapi for Requests.""" headers = { 'Accept': '*/*', 'Accept-Language': 'zh-CN,zh;q=0.8,gl;q=0.6,zh-TW;q=0.4', 'Connection': 'keep-alive', 'Content-Type': ...
python
def _get_webapi_requests(self): headers = { 'Accept': '*/*', 'Accept-Language': 'zh-CN,zh;q=0.8,gl;q=0.6,zh-TW;q=0.4', 'Connection': 'keep-alive', 'Content-Type': 'application/x-www-form-urlencoded', 'Ref...
[ "def", "_get_webapi_requests", "(", "self", ")", ":", "headers", "=", "{", "'Accept'", ":", "'*/*'", ",", "'Accept-Language'", ":", "'zh-CN,zh;q=0.8,gl;q=0.6,zh-TW;q=0.4'", ",", "'Connection'", ":", "'keep-alive'", ",", "'Content-Type'", ":", "'application/x-www-form-ur...
Update headers of webapi for Requests.
[ "Update", "headers", "of", "webapi", "for", "Requests", "." ]
c4832f3ee7630ba104a89559f09c1fc366d1547b
https://github.com/xiyouMc/ncmbot/blob/c4832f3ee7630ba104a89559f09c1fc366d1547b/ncmbot/core.py#L104-L124
175
xiyouMc/ncmbot
ncmbot/core.py
NCloudBot._build_response
def _build_response(self, resp): """Build internal Response object from given response.""" # rememberLogin # if self.method is 'LOGIN' and resp.json().get('code') == 200: # cookiesJar.save_cookies(resp, NCloudBot.username) self.response.content = resp.content self.res...
python
def _build_response(self, resp): # rememberLogin # if self.method is 'LOGIN' and resp.json().get('code') == 200: # cookiesJar.save_cookies(resp, NCloudBot.username) self.response.content = resp.content self.response.status_code = resp.status_code self.response.headers...
[ "def", "_build_response", "(", "self", ",", "resp", ")", ":", "# rememberLogin", "# if self.method is 'LOGIN' and resp.json().get('code') == 200:", "# cookiesJar.save_cookies(resp, NCloudBot.username)", "self", ".", "response", ".", "content", "=", "resp", ".", "content", ...
Build internal Response object from given response.
[ "Build", "internal", "Response", "object", "from", "given", "response", "." ]
c4832f3ee7630ba104a89559f09c1fc366d1547b
https://github.com/xiyouMc/ncmbot/blob/c4832f3ee7630ba104a89559f09c1fc366d1547b/ncmbot/core.py#L141-L148
176
xiyouMc/ncmbot
ncmbot/core.py
NCloudBot.send
def send(self): """Sens the request.""" success = False if self.method is None: raise ParamsError() try: if self.method == 'SEARCH': req = self._get_requests() _url = self.__NETEAST_HOST + self._METHODS[self.method] ...
python
def send(self): success = False if self.method is None: raise ParamsError() try: if self.method == 'SEARCH': req = self._get_requests() _url = self.__NETEAST_HOST + self._METHODS[self.method] resp = req.post(_url, data=self....
[ "def", "send", "(", "self", ")", ":", "success", "=", "False", "if", "self", ".", "method", "is", "None", ":", "raise", "ParamsError", "(", ")", "try", ":", "if", "self", ".", "method", "==", "'SEARCH'", ":", "req", "=", "self", ".", "_get_requests",...
Sens the request.
[ "Sens", "the", "request", "." ]
c4832f3ee7630ba104a89559f09c1fc366d1547b
https://github.com/xiyouMc/ncmbot/blob/c4832f3ee7630ba104a89559f09c1fc366d1547b/ncmbot/core.py#L150-L185
177
has2k1/plydata
plydata/options.py
set_option
def set_option(name, value): """ Set plydata option Parameters ---------- name : str Name of the option value : object New value of the option Returns ------- old : object Old value of the option See also -------- :class:`options` """ ol...
python
def set_option(name, value): old = get_option(name) globals()[name] = value return old
[ "def", "set_option", "(", "name", ",", "value", ")", ":", "old", "=", "get_option", "(", "name", ")", "globals", "(", ")", "[", "name", "]", "=", "value", "return", "old" ]
Set plydata option Parameters ---------- name : str Name of the option value : object New value of the option Returns ------- old : object Old value of the option See also -------- :class:`options`
[ "Set", "plydata", "option" ]
d8ca85ff70eee621e96f7c74034e90fec16e8b61
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/options.py#L45-L67
178
has2k1/plydata
plydata/types.py
GroupedDataFrame.group_indices
def group_indices(self): """ Return group indices """ # No groups if not self.plydata_groups: return np.ones(len(self), dtype=int) grouper = self.groupby() indices = np.empty(len(self), dtype=int) for i, (_, idx) in enumerate(sorted(grouper.in...
python
def group_indices(self): # No groups if not self.plydata_groups: return np.ones(len(self), dtype=int) grouper = self.groupby() indices = np.empty(len(self), dtype=int) for i, (_, idx) in enumerate(sorted(grouper.indices.items())): indices[idx] = i ...
[ "def", "group_indices", "(", "self", ")", ":", "# No groups", "if", "not", "self", ".", "plydata_groups", ":", "return", "np", ".", "ones", "(", "len", "(", "self", ")", ",", "dtype", "=", "int", ")", "grouper", "=", "self", ".", "groupby", "(", ")",...
Return group indices
[ "Return", "group", "indices" ]
d8ca85ff70eee621e96f7c74034e90fec16e8b61
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/types.py#L49-L61
179
has2k1/plydata
plydata/dataframe/helpers.py
_make_verb_helper
def _make_verb_helper(verb_func, add_groups=False): """ Create function that prepares verb for the verb function The functions created add expressions to be evaluated to the verb, then call the core verb function Parameters ---------- verb_func : function Core verb function. This i...
python
def _make_verb_helper(verb_func, add_groups=False): @wraps(verb_func) def _verb_func(verb): verb.expressions, new_columns = build_expressions(verb) if add_groups: verb.groups = new_columns return verb_func(verb) return _verb_func
[ "def", "_make_verb_helper", "(", "verb_func", ",", "add_groups", "=", "False", ")", ":", "@", "wraps", "(", "verb_func", ")", "def", "_verb_func", "(", "verb", ")", ":", "verb", ".", "expressions", ",", "new_columns", "=", "build_expressions", "(", "verb", ...
Create function that prepares verb for the verb function The functions created add expressions to be evaluated to the verb, then call the core verb function Parameters ---------- verb_func : function Core verb function. This is the function called after expressions created and adde...
[ "Create", "function", "that", "prepares", "verb", "for", "the", "verb", "function" ]
d8ca85ff70eee621e96f7c74034e90fec16e8b61
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/dataframe/helpers.py#L156-L188
180
has2k1/plydata
plydata/dataframe/common.py
_get_base_dataframe
def _get_base_dataframe(df): """ Remove all columns other than those grouped on """ if isinstance(df, GroupedDataFrame): base_df = GroupedDataFrame( df.loc[:, df.plydata_groups], df.plydata_groups, copy=True) else: base_df = pd.DataFrame(index=df.index) re...
python
def _get_base_dataframe(df): if isinstance(df, GroupedDataFrame): base_df = GroupedDataFrame( df.loc[:, df.plydata_groups], df.plydata_groups, copy=True) else: base_df = pd.DataFrame(index=df.index) return base_df
[ "def", "_get_base_dataframe", "(", "df", ")", ":", "if", "isinstance", "(", "df", ",", "GroupedDataFrame", ")", ":", "base_df", "=", "GroupedDataFrame", "(", "df", ".", "loc", "[", ":", ",", "df", ".", "plydata_groups", "]", ",", "df", ".", "plydata_grou...
Remove all columns other than those grouped on
[ "Remove", "all", "columns", "other", "than", "those", "grouped", "on" ]
d8ca85ff70eee621e96f7c74034e90fec16e8b61
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/dataframe/common.py#L27-L37
181
has2k1/plydata
plydata/dataframe/common.py
_add_group_columns
def _add_group_columns(data, gdf): """ Add group columns to data with a value from the grouped dataframe It is assumed that the grouped dataframe contains a single group >>> data = pd.DataFrame({ ... 'x': [5, 6, 7]}) >>> gdf = GroupedDataFrame({ ... 'g': list('aaa'), ... 'x...
python
def _add_group_columns(data, gdf): n = len(data) if isinstance(gdf, GroupedDataFrame): for i, col in enumerate(gdf.plydata_groups): if col not in data: group_values = [gdf[col].iloc[0]] * n # Need to be careful and maintain the dtypes # of the ...
[ "def", "_add_group_columns", "(", "data", ",", "gdf", ")", ":", "n", "=", "len", "(", "data", ")", "if", "isinstance", "(", "gdf", ",", "GroupedDataFrame", ")", ":", "for", "i", ",", "col", "in", "enumerate", "(", "gdf", ".", "plydata_groups", ")", "...
Add group columns to data with a value from the grouped dataframe It is assumed that the grouped dataframe contains a single group >>> data = pd.DataFrame({ ... 'x': [5, 6, 7]}) >>> gdf = GroupedDataFrame({ ... 'g': list('aaa'), ... 'x': range(3)}, groups=['g']) >>> _add_group_...
[ "Add", "group", "columns", "to", "data", "with", "a", "value", "from", "the", "grouped", "dataframe" ]
d8ca85ff70eee621e96f7c74034e90fec16e8b61
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/dataframe/common.py#L40-L78
182
has2k1/plydata
plydata/dataframe/common.py
_create_column
def _create_column(data, col, value): """ Create column in dataframe Helper method meant to deal with problematic column values. e.g When the series index does not match that of the data. Parameters ---------- data : pandas.DataFrame dataframe in which to insert value col :...
python
def _create_column(data, col, value): with suppress(AttributeError): # If the index of a series and the dataframe # in which the series will be assigned to a # column do not match, missing values/NaNs # are created. We do not want that. if not value.index.equals(data.index): ...
[ "def", "_create_column", "(", "data", ",", "col", ",", "value", ")", ":", "with", "suppress", "(", "AttributeError", ")", ":", "# If the index of a series and the dataframe", "# in which the series will be assigned to a", "# column do not match, missing values/NaNs", "# are cre...
Create column in dataframe Helper method meant to deal with problematic column values. e.g When the series index does not match that of the data. Parameters ---------- data : pandas.DataFrame dataframe in which to insert value col : column label Column name value : obje...
[ "Create", "column", "in", "dataframe" ]
d8ca85ff70eee621e96f7c74034e90fec16e8b61
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/dataframe/common.py#L81-L157
183
has2k1/plydata
plydata/dataframe/common.py
build_expressions
def build_expressions(verb): """ Build expressions for helper verbs Parameters ---------- verb : verb A verb with a *functions* attribute. Returns ------- out : tuple (List of Expressions, New columns). The expressions and the new columns in which the results of...
python
def build_expressions(verb): def partial(func, col, *args, **kwargs): """ Make a function that acts on a column in a dataframe Parameters ---------- func : callable Function col : str Column args : tuple Arguments to pass t...
[ "def", "build_expressions", "(", "verb", ")", ":", "def", "partial", "(", "func", ",", "col", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"\n Make a function that acts on a column in a dataframe\n\n Parameters\n ----------\n func :...
Build expressions for helper verbs Parameters ---------- verb : verb A verb with a *functions* attribute. Returns ------- out : tuple (List of Expressions, New columns). The expressions and the new columns in which the results of those expressions will be stored...
[ "Build", "expressions", "for", "helper", "verbs" ]
d8ca85ff70eee621e96f7c74034e90fec16e8b61
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/dataframe/common.py#L502-L613
184
has2k1/plydata
plydata/dataframe/common.py
Evaluator.process
def process(self): """ Run the expressions Returns ------- out : pandas.DataFrame Resulting data """ # Short cut if self._all_expressions_evaluated(): if self.drop: # Drop extra columns. They do not correspond to ...
python
def process(self): # Short cut if self._all_expressions_evaluated(): if self.drop: # Drop extra columns. They do not correspond to # any expressions. columns = [expr.column for expr in self.expressions] self.data = self.data.loc...
[ "def", "process", "(", "self", ")", ":", "# Short cut", "if", "self", ".", "_all_expressions_evaluated", "(", ")", ":", "if", "self", ".", "drop", ":", "# Drop extra columns. They do not correspond to", "# any expressions.", "columns", "=", "[", "expr", ".", "colu...
Run the expressions Returns ------- out : pandas.DataFrame Resulting data
[ "Run", "the", "expressions" ]
d8ca85ff70eee621e96f7c74034e90fec16e8b61
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/dataframe/common.py#L195-L220
185
has2k1/plydata
plydata/dataframe/common.py
Evaluator._all_expressions_evaluated
def _all_expressions_evaluated(self): """ Return True all expressions match with the columns Saves some processor cycles """ def present(expr): return expr.stmt == expr.column and expr.column in self.data return all(present(expr) for expr in self.expressions)
python
def _all_expressions_evaluated(self): def present(expr): return expr.stmt == expr.column and expr.column in self.data return all(present(expr) for expr in self.expressions)
[ "def", "_all_expressions_evaluated", "(", "self", ")", ":", "def", "present", "(", "expr", ")", ":", "return", "expr", ".", "stmt", "==", "expr", ".", "column", "and", "expr", ".", "column", "in", "self", ".", "data", "return", "all", "(", "present", "...
Return True all expressions match with the columns Saves some processor cycles
[ "Return", "True", "all", "expressions", "match", "with", "the", "columns" ]
d8ca85ff70eee621e96f7c74034e90fec16e8b61
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/dataframe/common.py#L222-L230
186
has2k1/plydata
plydata/dataframe/common.py
Evaluator._get_group_dataframes
def _get_group_dataframes(self): """ Get group dataframes Returns ------- out : tuple or generator Group dataframes """ if isinstance(self.data, GroupedDataFrame): grouper = self.data.groupby() # groupby on categorical columns ...
python
def _get_group_dataframes(self): if isinstance(self.data, GroupedDataFrame): grouper = self.data.groupby() # groupby on categorical columns uses the categories # even if they are not present in the data. This # leads to empty groups. We exclude them. r...
[ "def", "_get_group_dataframes", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "data", ",", "GroupedDataFrame", ")", ":", "grouper", "=", "self", ".", "data", ".", "groupby", "(", ")", "# groupby on categorical columns uses the categories", "# even i...
Get group dataframes Returns ------- out : tuple or generator Group dataframes
[ "Get", "group", "dataframes" ]
d8ca85ff70eee621e96f7c74034e90fec16e8b61
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/dataframe/common.py#L232-L248
187
has2k1/plydata
plydata/dataframe/common.py
Evaluator._evaluate_group_dataframe
def _evaluate_group_dataframe(self, gdf): """ Evaluate a single group dataframe Parameters ---------- gdf : pandas.DataFrame Input group dataframe Returns ------- out : pandas.DataFrame Result data """ gdf._is_copy...
python
def _evaluate_group_dataframe(self, gdf): gdf._is_copy = None result_index = gdf.index if self.keep_index else [] data = pd.DataFrame(index=result_index) for expr in self.expressions: value = expr.evaluate(gdf, self.env) if isinstance(value, pd.DataFrame): ...
[ "def", "_evaluate_group_dataframe", "(", "self", ",", "gdf", ")", ":", "gdf", ".", "_is_copy", "=", "None", "result_index", "=", "gdf", ".", "index", "if", "self", ".", "keep_index", "else", "[", "]", "data", "=", "pd", ".", "DataFrame", "(", "index", ...
Evaluate a single group dataframe Parameters ---------- gdf : pandas.DataFrame Input group dataframe Returns ------- out : pandas.DataFrame Result data
[ "Evaluate", "a", "single", "group", "dataframe" ]
d8ca85ff70eee621e96f7c74034e90fec16e8b61
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/dataframe/common.py#L266-L291
188
has2k1/plydata
plydata/dataframe/common.py
Evaluator._concat
def _concat(self, egdfs): """ Concatenate evaluated group dataframes Parameters ---------- egdfs : iterable Evaluated dataframes Returns ------- edata : pandas.DataFrame Evaluated data """ egdfs = list(egdfs) ...
python
def _concat(self, egdfs): egdfs = list(egdfs) edata = pd.concat(egdfs, axis=0, ignore_index=False, copy=False) # groupby can mixup the rows. We try to maintain the original # order, but we can only do that if the result has a one to # one relationship with the original o...
[ "def", "_concat", "(", "self", ",", "egdfs", ")", ":", "egdfs", "=", "list", "(", "egdfs", ")", "edata", "=", "pd", ".", "concat", "(", "egdfs", ",", "axis", "=", "0", ",", "ignore_index", "=", "False", ",", "copy", "=", "False", ")", "# groupby ca...
Concatenate evaluated group dataframes Parameters ---------- egdfs : iterable Evaluated dataframes Returns ------- edata : pandas.DataFrame Evaluated data
[ "Concatenate", "evaluated", "group", "dataframes" ]
d8ca85ff70eee621e96f7c74034e90fec16e8b61
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/dataframe/common.py#L293-L325
189
has2k1/plydata
plydata/dataframe/common.py
Selector._resolve_slices
def _resolve_slices(data_columns, names): """ Convert any slices into column names Parameters ---------- data_columns : pandas.Index Dataframe columns names : tuple Names (including slices) of columns in the dataframe. Returns...
python
def _resolve_slices(data_columns, names): def _get_slice_cols(sc): """ Convert slice to list of names """ # Just like pandas.DataFrame.loc the stop # column is included idx_start = data_columns.get_loc(sc.start) idx_stop = data_...
[ "def", "_resolve_slices", "(", "data_columns", ",", "names", ")", ":", "def", "_get_slice_cols", "(", "sc", ")", ":", "\"\"\"\n Convert slice to list of names\n \"\"\"", "# Just like pandas.DataFrame.loc the stop", "# column is included", "idx_start", "=", ...
Convert any slices into column names Parameters ---------- data_columns : pandas.Index Dataframe columns names : tuple Names (including slices) of columns in the dataframe. Returns ------- out : tuple Names of colu...
[ "Convert", "any", "slices", "into", "column", "names" ]
d8ca85ff70eee621e96f7c74034e90fec16e8b61
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/dataframe/common.py#L333-L367
190
has2k1/plydata
plydata/dataframe/common.py
Selector.select
def select(cls, verb): """ Return selected columns for the select verb Parameters ---------- verb : object verb with the column selection attributes: - names - startswith - endswith - contains ...
python
def select(cls, verb): columns = verb.data.columns contains = verb.contains matches = verb.matches groups = _get_groups(verb) names = cls._resolve_slices(columns, verb.names) names_set = set(names) groups_set = set(groups) lst = [[]] if names or ...
[ "def", "select", "(", "cls", ",", "verb", ")", ":", "columns", "=", "verb", ".", "data", ".", "columns", "contains", "=", "verb", ".", "contains", "matches", "=", "verb", ".", "matches", "groups", "=", "_get_groups", "(", "verb", ")", "names", "=", "...
Return selected columns for the select verb Parameters ---------- verb : object verb with the column selection attributes: - names - startswith - endswith - contains - matches
[ "Return", "selected", "columns", "for", "the", "select", "verb" ]
d8ca85ff70eee621e96f7c74034e90fec16e8b61
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/dataframe/common.py#L370-L437
191
has2k1/plydata
plydata/dataframe/common.py
Selector._at
def _at(cls, verb): """ A verb with a select text match """ # Named (listed) columns are always included columns = cls.select(verb) final_columns_set = set(cls.select(verb)) groups_set = set(_get_groups(verb)) final_columns_set -= groups_set - set(verb.nam...
python
def _at(cls, verb): # Named (listed) columns are always included columns = cls.select(verb) final_columns_set = set(cls.select(verb)) groups_set = set(_get_groups(verb)) final_columns_set -= groups_set - set(verb.names) def pred(col): if col not in verb.data:...
[ "def", "_at", "(", "cls", ",", "verb", ")", ":", "# Named (listed) columns are always included", "columns", "=", "cls", ".", "select", "(", "verb", ")", "final_columns_set", "=", "set", "(", "cls", ".", "select", "(", "verb", ")", ")", "groups_set", "=", "...
A verb with a select text match
[ "A", "verb", "with", "a", "select", "text", "match" ]
d8ca85ff70eee621e96f7c74034e90fec16e8b61
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/dataframe/common.py#L448-L464
192
has2k1/plydata
plydata/dataframe/common.py
Selector._if
def _if(cls, verb): """ A verb with a predicate function """ pred = verb.predicate data = verb.data groups = set(_get_groups(verb)) # force predicate if isinstance(pred, str): if not pred.endswith('_dtype'): pred = '{}_dtype'.f...
python
def _if(cls, verb): pred = verb.predicate data = verb.data groups = set(_get_groups(verb)) # force predicate if isinstance(pred, str): if not pred.endswith('_dtype'): pred = '{}_dtype'.format(pred) pred = getattr(pdtypes, pred) eli...
[ "def", "_if", "(", "cls", ",", "verb", ")", ":", "pred", "=", "verb", ".", "predicate", "data", "=", "verb", ".", "data", "groups", "=", "set", "(", "_get_groups", "(", "verb", ")", ")", "# force predicate", "if", "isinstance", "(", "pred", ",", "str...
A verb with a predicate function
[ "A", "verb", "with", "a", "predicate", "function" ]
d8ca85ff70eee621e96f7c74034e90fec16e8b61
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/dataframe/common.py#L467-L488
193
has2k1/plydata
plydata/operators.py
get_verb_function
def get_verb_function(data, verb): """ Return function that implements the verb for given data type """ try: module = type_lookup[type(data)] except KeyError: # Some guess work for subclasses for type_, mod in type_lookup.items(): if isinstance(data, type_): ...
python
def get_verb_function(data, verb): try: module = type_lookup[type(data)] except KeyError: # Some guess work for subclasses for type_, mod in type_lookup.items(): if isinstance(data, type_): module = mod break try: return getattr(mod...
[ "def", "get_verb_function", "(", "data", ",", "verb", ")", ":", "try", ":", "module", "=", "type_lookup", "[", "type", "(", "data", ")", "]", "except", "KeyError", ":", "# Some guess work for subclasses", "for", "type_", ",", "mod", "in", "type_lookup", ".",...
Return function that implements the verb for given data type
[ "Return", "function", "that", "implements", "the", "verb", "for", "given", "data", "type" ]
d8ca85ff70eee621e96f7c74034e90fec16e8b61
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/operators.py#L23-L39
194
has2k1/plydata
plydata/expressions.py
Expression
def Expression(*args, **kwargs): """ Return an appropriate Expression given the arguments Parameters ---------- args : tuple Positional arguments passed to the Expression class kwargs : dict Keyword arguments passed to the Expression class """ # dispatch if not hasat...
python
def Expression(*args, **kwargs): # dispatch if not hasattr(args[0], '_Expression'): return BaseExpression(*args, *kwargs) else: return args[0]._Expression(*args, **kwargs)
[ "def", "Expression", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# dispatch", "if", "not", "hasattr", "(", "args", "[", "0", "]", ",", "'_Expression'", ")", ":", "return", "BaseExpression", "(", "*", "args", ",", "*", "kwargs", ")", "else",...
Return an appropriate Expression given the arguments Parameters ---------- args : tuple Positional arguments passed to the Expression class kwargs : dict Keyword arguments passed to the Expression class
[ "Return", "an", "appropriate", "Expression", "given", "the", "arguments" ]
d8ca85ff70eee621e96f7c74034e90fec16e8b61
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/expressions.py#L176-L191
195
has2k1/plydata
plydata/eval.py
EvalEnvironment.with_outer_namespace
def with_outer_namespace(self, outer_namespace): """Return a new EvalEnvironment with an extra namespace added. This namespace will be used only for variables that are not found in any existing namespace, i.e., it is "outside" them all.""" return self.__class__(self._namespaces + [outer_...
python
def with_outer_namespace(self, outer_namespace): return self.__class__(self._namespaces + [outer_namespace], self.flags)
[ "def", "with_outer_namespace", "(", "self", ",", "outer_namespace", ")", ":", "return", "self", ".", "__class__", "(", "self", ".", "_namespaces", "+", "[", "outer_namespace", "]", ",", "self", ".", "flags", ")" ]
Return a new EvalEnvironment with an extra namespace added. This namespace will be used only for variables that are not found in any existing namespace, i.e., it is "outside" them all.
[ "Return", "a", "new", "EvalEnvironment", "with", "an", "extra", "namespace", "added", ".", "This", "namespace", "will", "be", "used", "only", "for", "variables", "that", "are", "not", "found", "in", "any", "existing", "namespace", "i", ".", "e", ".", "it",...
d8ca85ff70eee621e96f7c74034e90fec16e8b61
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/eval.py#L81-L86
196
has2k1/plydata
plydata/eval.py
EvalEnvironment.subset
def subset(self, names): """Creates a new, flat EvalEnvironment that contains only the variables specified.""" vld = VarLookupDict(self._namespaces) new_ns = dict((name, vld[name]) for name in names) return EvalEnvironment([new_ns], self.flags)
python
def subset(self, names): vld = VarLookupDict(self._namespaces) new_ns = dict((name, vld[name]) for name in names) return EvalEnvironment([new_ns], self.flags)
[ "def", "subset", "(", "self", ",", "names", ")", ":", "vld", "=", "VarLookupDict", "(", "self", ".", "_namespaces", ")", "new_ns", "=", "dict", "(", "(", "name", ",", "vld", "[", "name", "]", ")", "for", "name", "in", "names", ")", "return", "EvalE...
Creates a new, flat EvalEnvironment that contains only the variables specified.
[ "Creates", "a", "new", "flat", "EvalEnvironment", "that", "contains", "only", "the", "variables", "specified", "." ]
d8ca85ff70eee621e96f7c74034e90fec16e8b61
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/eval.py#L159-L164
197
has2k1/plydata
plydata/utils.py
Q
def Q(name): """ Quote a variable name A way to 'quote' variable names, especially ones that do not otherwise meet Python's variable name rules. Parameters ---------- name : str Name of variable Returns ------- value : object Value of variable Examples ...
python
def Q(name): env = EvalEnvironment.capture(1) try: return env.namespace[name] except KeyError: raise NameError("No data named {!r} found".format(name))
[ "def", "Q", "(", "name", ")", ":", "env", "=", "EvalEnvironment", ".", "capture", "(", "1", ")", "try", ":", "return", "env", ".", "namespace", "[", "name", "]", "except", "KeyError", ":", "raise", "NameError", "(", "\"No data named {!r} found\"", ".", "...
Quote a variable name A way to 'quote' variable names, especially ones that do not otherwise meet Python's variable name rules. Parameters ---------- name : str Name of variable Returns ------- value : object Value of variable Examples -------- >>> import ...
[ "Quote", "a", "variable", "name" ]
d8ca85ff70eee621e96f7c74034e90fec16e8b61
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/utils.py#L72-L119
198
has2k1/plydata
plydata/utils.py
regular_index
def regular_index(*dfs): """ Change & restore the indices of dataframes Dataframe with duplicate values can be hard to work with. When split and recombined, you cannot restore the row order. This can be the case even if the index has unique but irregular/unordered. This contextmanager resets th...
python
def regular_index(*dfs): original_index = [df.index for df in dfs] have_bad_index = [not isinstance(df.index, pd.RangeIndex) for df in dfs] for df, bad in zip(dfs, have_bad_index): if bad: df.reset_index(drop=True, inplace=True) try: yield dfs fina...
[ "def", "regular_index", "(", "*", "dfs", ")", ":", "original_index", "=", "[", "df", ".", "index", "for", "df", "in", "dfs", "]", "have_bad_index", "=", "[", "not", "isinstance", "(", "df", ".", "index", ",", "pd", ".", "RangeIndex", ")", "for", "df"...
Change & restore the indices of dataframes Dataframe with duplicate values can be hard to work with. When split and recombined, you cannot restore the row order. This can be the case even if the index has unique but irregular/unordered. This contextmanager resets the unordered indices of any datafr...
[ "Change", "&", "restore", "the", "indices", "of", "dataframes" ]
d8ca85ff70eee621e96f7c74034e90fec16e8b61
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/utils.py#L147-L212
199
has2k1/plydata
plydata/utils.py
unique
def unique(lst): """ Return unique elements :class:`pandas.unique` and :class:`numpy.unique` cast mixed type lists to the same type. They are faster, but some times we want to maintain the type. Parameters ---------- lst : list-like List of items Returns ------- ou...
python
def unique(lst): seen = set() def make_seen(x): seen.add(x) return x return [make_seen(x) for x in lst if x not in seen]
[ "def", "unique", "(", "lst", ")", ":", "seen", "=", "set", "(", ")", "def", "make_seen", "(", "x", ")", ":", "seen", ".", "add", "(", "x", ")", "return", "x", "return", "[", "make_seen", "(", "x", ")", "for", "x", "in", "lst", "if", "x", "not...
Return unique elements :class:`pandas.unique` and :class:`numpy.unique` cast mixed type lists to the same type. They are faster, but some times we want to maintain the type. Parameters ---------- lst : list-like List of items Returns ------- out : list Unique items...
[ "Return", "unique", "elements" ]
d8ca85ff70eee621e96f7c74034e90fec16e8b61
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/utils.py#L215-L256