repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
tensorflow/skflow
scripts/docs/docs.py
Library.write_other_members
def write_other_members(self, f, catch_all=False): """Writes the leftover members to `f`. Args: f: File to write to. catch_all: If true, document all missing symbols from any module. Otherwise, document missing symbols from just this module. """ if catch_all: names = self._members.items() else: names = inspect.getmembers(self._module) leftovers = [] for name, _ in names: if name in self._members and name not in self._documented: leftovers.append(name) if leftovers: print("%s: undocumented members: %d" % (self._title, len(leftovers))) print("\n## Other Functions and Classes", file=f) for name in sorted(leftovers): print(" %s" % name) self._documented.add(name) self._mentioned.add(name) self._write_member_markdown_to_file(f, "###", *self._members[name])
python
def write_other_members(self, f, catch_all=False): """Writes the leftover members to `f`. Args: f: File to write to. catch_all: If true, document all missing symbols from any module. Otherwise, document missing symbols from just this module. """ if catch_all: names = self._members.items() else: names = inspect.getmembers(self._module) leftovers = [] for name, _ in names: if name in self._members and name not in self._documented: leftovers.append(name) if leftovers: print("%s: undocumented members: %d" % (self._title, len(leftovers))) print("\n## Other Functions and Classes", file=f) for name in sorted(leftovers): print(" %s" % name) self._documented.add(name) self._mentioned.add(name) self._write_member_markdown_to_file(f, "###", *self._members[name])
[ "def", "write_other_members", "(", "self", ",", "f", ",", "catch_all", "=", "False", ")", ":", "if", "catch_all", ":", "names", "=", "self", ".", "_members", ".", "items", "(", ")", "else", ":", "names", "=", "inspect", ".", "getmembers", "(", "self", ".", "_module", ")", "leftovers", "=", "[", "]", "for", "name", ",", "_", "in", "names", ":", "if", "name", "in", "self", ".", "_members", "and", "name", "not", "in", "self", ".", "_documented", ":", "leftovers", ".", "append", "(", "name", ")", "if", "leftovers", ":", "print", "(", "\"%s: undocumented members: %d\"", "%", "(", "self", ".", "_title", ",", "len", "(", "leftovers", ")", ")", ")", "print", "(", "\"\\n## Other Functions and Classes\"", ",", "file", "=", "f", ")", "for", "name", "in", "sorted", "(", "leftovers", ")", ":", "print", "(", "\" %s\"", "%", "name", ")", "self", ".", "_documented", ".", "add", "(", "name", ")", "self", ".", "_mentioned", ".", "add", "(", "name", ")", "self", ".", "_write_member_markdown_to_file", "(", "f", ",", "\"###\"", ",", "*", "self", ".", "_members", "[", "name", "]", ")" ]
Writes the leftover members to `f`. Args: f: File to write to. catch_all: If true, document all missing symbols from any module. Otherwise, document missing symbols from just this module.
[ "Writes", "the", "leftover", "members", "to", "f", "." ]
f8da498a1abb7562f57dfc7010941578103061b6
https://github.com/tensorflow/skflow/blob/f8da498a1abb7562f57dfc7010941578103061b6/scripts/docs/docs.py#L478-L501
train
tensorflow/skflow
scripts/docs/docs.py
Library.assert_no_leftovers
def assert_no_leftovers(self): """Generate an error if there are leftover members.""" leftovers = [] for name in self._members.keys(): if name in self._members and name not in self._documented: leftovers.append(name) if leftovers: raise RuntimeError("%s: undocumented members: %s" % (self._title, ", ".join(leftovers)))
python
def assert_no_leftovers(self): """Generate an error if there are leftover members.""" leftovers = [] for name in self._members.keys(): if name in self._members and name not in self._documented: leftovers.append(name) if leftovers: raise RuntimeError("%s: undocumented members: %s" % (self._title, ", ".join(leftovers)))
[ "def", "assert_no_leftovers", "(", "self", ")", ":", "leftovers", "=", "[", "]", "for", "name", "in", "self", ".", "_members", ".", "keys", "(", ")", ":", "if", "name", "in", "self", ".", "_members", "and", "name", "not", "in", "self", ".", "_documented", ":", "leftovers", ".", "append", "(", "name", ")", "if", "leftovers", ":", "raise", "RuntimeError", "(", "\"%s: undocumented members: %s\"", "%", "(", "self", ".", "_title", ",", "\", \"", ".", "join", "(", "leftovers", ")", ")", ")" ]
Generate an error if there are leftover members.
[ "Generate", "an", "error", "if", "there", "are", "leftover", "members", "." ]
f8da498a1abb7562f57dfc7010941578103061b6
https://github.com/tensorflow/skflow/blob/f8da498a1abb7562f57dfc7010941578103061b6/scripts/docs/docs.py#L503-L511
train
rycus86/prometheus_flask_exporter
prometheus_flask_exporter/multiprocess.py
MultiprocessPrometheusMetrics.start_http_server
def start_http_server(self, port, host='0.0.0.0', endpoint=None): """ Start an HTTP server for exposing the metrics, if the `should_start_http_server` function says we should, otherwise just return. Uses the implementation from `prometheus_client` rather than a Flask app. :param port: the HTTP port to expose the metrics endpoint on :param host: the HTTP host to listen on (default: `0.0.0.0`) :param endpoint: **ignored**, the HTTP server will respond on any path """ if self.should_start_http_server(): pc_start_http_server(port, host, registry=self.registry)
python
def start_http_server(self, port, host='0.0.0.0', endpoint=None): """ Start an HTTP server for exposing the metrics, if the `should_start_http_server` function says we should, otherwise just return. Uses the implementation from `prometheus_client` rather than a Flask app. :param port: the HTTP port to expose the metrics endpoint on :param host: the HTTP host to listen on (default: `0.0.0.0`) :param endpoint: **ignored**, the HTTP server will respond on any path """ if self.should_start_http_server(): pc_start_http_server(port, host, registry=self.registry)
[ "def", "start_http_server", "(", "self", ",", "port", ",", "host", "=", "'0.0.0.0'", ",", "endpoint", "=", "None", ")", ":", "if", "self", ".", "should_start_http_server", "(", ")", ":", "pc_start_http_server", "(", "port", ",", "host", ",", "registry", "=", "self", ".", "registry", ")" ]
Start an HTTP server for exposing the metrics, if the `should_start_http_server` function says we should, otherwise just return. Uses the implementation from `prometheus_client` rather than a Flask app. :param port: the HTTP port to expose the metrics endpoint on :param host: the HTTP host to listen on (default: `0.0.0.0`) :param endpoint: **ignored**, the HTTP server will respond on any path
[ "Start", "an", "HTTP", "server", "for", "exposing", "the", "metrics", "if", "the", "should_start_http_server", "function", "says", "we", "should", "otherwise", "just", "return", ".", "Uses", "the", "implementation", "from", "prometheus_client", "rather", "than", "a", "Flask", "app", "." ]
678dbf3097e82a0ddb697268406004cc1f4a26bc
https://github.com/rycus86/prometheus_flask_exporter/blob/678dbf3097e82a0ddb697268406004cc1f4a26bc/prometheus_flask_exporter/multiprocess.py#L75-L87
train
rycus86/prometheus_flask_exporter
prometheus_flask_exporter/__init__.py
PrometheusMetrics.init_app
def init_app(self, app): """ This callback can be used to initialize an application for the use with this prometheus reporter setup. This is usually used with a flask "app factory" configuration. Please see: http://flask.pocoo.org/docs/1.0/patterns/appfactories/ Note, that you need to use `PrometheusMetrics(app=None, ...)` for this mode, otherwise it is called automatically. :param app: the Flask application """ if self.path: self.register_endpoint(self.path, app) if self._export_defaults: self.export_defaults( self.buckets, self.group_by, self._defaults_prefix, app )
python
def init_app(self, app): """ This callback can be used to initialize an application for the use with this prometheus reporter setup. This is usually used with a flask "app factory" configuration. Please see: http://flask.pocoo.org/docs/1.0/patterns/appfactories/ Note, that you need to use `PrometheusMetrics(app=None, ...)` for this mode, otherwise it is called automatically. :param app: the Flask application """ if self.path: self.register_endpoint(self.path, app) if self._export_defaults: self.export_defaults( self.buckets, self.group_by, self._defaults_prefix, app )
[ "def", "init_app", "(", "self", ",", "app", ")", ":", "if", "self", ".", "path", ":", "self", ".", "register_endpoint", "(", "self", ".", "path", ",", "app", ")", "if", "self", ".", "_export_defaults", ":", "self", ".", "export_defaults", "(", "self", ".", "buckets", ",", "self", ".", "group_by", ",", "self", ".", "_defaults_prefix", ",", "app", ")" ]
This callback can be used to initialize an application for the use with this prometheus reporter setup. This is usually used with a flask "app factory" configuration. Please see: http://flask.pocoo.org/docs/1.0/patterns/appfactories/ Note, that you need to use `PrometheusMetrics(app=None, ...)` for this mode, otherwise it is called automatically. :param app: the Flask application
[ "This", "callback", "can", "be", "used", "to", "initialize", "an", "application", "for", "the", "use", "with", "this", "prometheus", "reporter", "setup", "." ]
678dbf3097e82a0ddb697268406004cc1f4a26bc
https://github.com/rycus86/prometheus_flask_exporter/blob/678dbf3097e82a0ddb697268406004cc1f4a26bc/prometheus_flask_exporter/__init__.py#L133-L154
train
rycus86/prometheus_flask_exporter
prometheus_flask_exporter/__init__.py
PrometheusMetrics.register_endpoint
def register_endpoint(self, path, app=None): """ Register the metrics endpoint on the Flask application. :param path: the path of the endpoint :param app: the Flask application to register the endpoint on (by default it is the application registered with this class) """ if is_running_from_reloader() and not os.environ.get('DEBUG_METRICS'): return if app is None: app = self.app or current_app @app.route(path) @self.do_not_track() def prometheus_metrics(): # import these here so they don't clash with our own multiprocess module from prometheus_client import multiprocess, CollectorRegistry if 'prometheus_multiproc_dir' in os.environ: registry = CollectorRegistry() else: registry = self.registry if 'name[]' in request.args: registry = registry.restricted_registry(request.args.getlist('name[]')) if 'prometheus_multiproc_dir' in os.environ: multiprocess.MultiProcessCollector(registry) headers = {'Content-Type': CONTENT_TYPE_LATEST} return generate_latest(registry), 200, headers
python
def register_endpoint(self, path, app=None): """ Register the metrics endpoint on the Flask application. :param path: the path of the endpoint :param app: the Flask application to register the endpoint on (by default it is the application registered with this class) """ if is_running_from_reloader() and not os.environ.get('DEBUG_METRICS'): return if app is None: app = self.app or current_app @app.route(path) @self.do_not_track() def prometheus_metrics(): # import these here so they don't clash with our own multiprocess module from prometheus_client import multiprocess, CollectorRegistry if 'prometheus_multiproc_dir' in os.environ: registry = CollectorRegistry() else: registry = self.registry if 'name[]' in request.args: registry = registry.restricted_registry(request.args.getlist('name[]')) if 'prometheus_multiproc_dir' in os.environ: multiprocess.MultiProcessCollector(registry) headers = {'Content-Type': CONTENT_TYPE_LATEST} return generate_latest(registry), 200, headers
[ "def", "register_endpoint", "(", "self", ",", "path", ",", "app", "=", "None", ")", ":", "if", "is_running_from_reloader", "(", ")", "and", "not", "os", ".", "environ", ".", "get", "(", "'DEBUG_METRICS'", ")", ":", "return", "if", "app", "is", "None", ":", "app", "=", "self", ".", "app", "or", "current_app", "@", "app", ".", "route", "(", "path", ")", "@", "self", ".", "do_not_track", "(", ")", "def", "prometheus_metrics", "(", ")", ":", "# import these here so they don't clash with our own multiprocess module", "from", "prometheus_client", "import", "multiprocess", ",", "CollectorRegistry", "if", "'prometheus_multiproc_dir'", "in", "os", ".", "environ", ":", "registry", "=", "CollectorRegistry", "(", ")", "else", ":", "registry", "=", "self", ".", "registry", "if", "'name[]'", "in", "request", ".", "args", ":", "registry", "=", "registry", ".", "restricted_registry", "(", "request", ".", "args", ".", "getlist", "(", "'name[]'", ")", ")", "if", "'prometheus_multiproc_dir'", "in", "os", ".", "environ", ":", "multiprocess", ".", "MultiProcessCollector", "(", "registry", ")", "headers", "=", "{", "'Content-Type'", ":", "CONTENT_TYPE_LATEST", "}", "return", "generate_latest", "(", "registry", ")", ",", "200", ",", "headers" ]
Register the metrics endpoint on the Flask application. :param path: the path of the endpoint :param app: the Flask application to register the endpoint on (by default it is the application registered with this class)
[ "Register", "the", "metrics", "endpoint", "on", "the", "Flask", "application", "." ]
678dbf3097e82a0ddb697268406004cc1f4a26bc
https://github.com/rycus86/prometheus_flask_exporter/blob/678dbf3097e82a0ddb697268406004cc1f4a26bc/prometheus_flask_exporter/__init__.py#L156-L189
train
rycus86/prometheus_flask_exporter
prometheus_flask_exporter/__init__.py
PrometheusMetrics.start_http_server
def start_http_server(self, port, host='0.0.0.0', endpoint='/metrics'): """ Start an HTTP server for exposing the metrics. This will be an individual Flask application, not the one registered with this class. :param port: the HTTP port to expose the metrics endpoint on :param host: the HTTP host to listen on (default: `0.0.0.0`) :param endpoint: the URL path to expose the endpoint on (default: `/metrics`) """ if is_running_from_reloader(): return app = Flask('prometheus-flask-exporter-%d' % port) self.register_endpoint(endpoint, app) def run_app(): app.run(host=host, port=port) thread = threading.Thread(target=run_app) thread.setDaemon(True) thread.start()
python
def start_http_server(self, port, host='0.0.0.0', endpoint='/metrics'): """ Start an HTTP server for exposing the metrics. This will be an individual Flask application, not the one registered with this class. :param port: the HTTP port to expose the metrics endpoint on :param host: the HTTP host to listen on (default: `0.0.0.0`) :param endpoint: the URL path to expose the endpoint on (default: `/metrics`) """ if is_running_from_reloader(): return app = Flask('prometheus-flask-exporter-%d' % port) self.register_endpoint(endpoint, app) def run_app(): app.run(host=host, port=port) thread = threading.Thread(target=run_app) thread.setDaemon(True) thread.start()
[ "def", "start_http_server", "(", "self", ",", "port", ",", "host", "=", "'0.0.0.0'", ",", "endpoint", "=", "'/metrics'", ")", ":", "if", "is_running_from_reloader", "(", ")", ":", "return", "app", "=", "Flask", "(", "'prometheus-flask-exporter-%d'", "%", "port", ")", "self", ".", "register_endpoint", "(", "endpoint", ",", "app", ")", "def", "run_app", "(", ")", ":", "app", ".", "run", "(", "host", "=", "host", ",", "port", "=", "port", ")", "thread", "=", "threading", ".", "Thread", "(", "target", "=", "run_app", ")", "thread", ".", "setDaemon", "(", "True", ")", "thread", ".", "start", "(", ")" ]
Start an HTTP server for exposing the metrics. This will be an individual Flask application, not the one registered with this class. :param port: the HTTP port to expose the metrics endpoint on :param host: the HTTP host to listen on (default: `0.0.0.0`) :param endpoint: the URL path to expose the endpoint on (default: `/metrics`)
[ "Start", "an", "HTTP", "server", "for", "exposing", "the", "metrics", ".", "This", "will", "be", "an", "individual", "Flask", "application", "not", "the", "one", "registered", "with", "this", "class", "." ]
678dbf3097e82a0ddb697268406004cc1f4a26bc
https://github.com/rycus86/prometheus_flask_exporter/blob/678dbf3097e82a0ddb697268406004cc1f4a26bc/prometheus_flask_exporter/__init__.py#L191-L214
train
rycus86/prometheus_flask_exporter
prometheus_flask_exporter/__init__.py
PrometheusMetrics.histogram
def histogram(self, name, description, labels=None, **kwargs): """ Use a Histogram to track the execution time and invocation count of the method. :param name: the name of the metric :param description: the description of the metric :param labels: a dictionary of `{labelname: callable_or_value}` for labels :param kwargs: additional keyword arguments for creating the Histogram """ return self._track( Histogram, lambda metric, time: metric.observe(time), kwargs, name, description, labels, registry=self.registry )
python
def histogram(self, name, description, labels=None, **kwargs): """ Use a Histogram to track the execution time and invocation count of the method. :param name: the name of the metric :param description: the description of the metric :param labels: a dictionary of `{labelname: callable_or_value}` for labels :param kwargs: additional keyword arguments for creating the Histogram """ return self._track( Histogram, lambda metric, time: metric.observe(time), kwargs, name, description, labels, registry=self.registry )
[ "def", "histogram", "(", "self", ",", "name", ",", "description", ",", "labels", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_track", "(", "Histogram", ",", "lambda", "metric", ",", "time", ":", "metric", ".", "observe", "(", "time", ")", ",", "kwargs", ",", "name", ",", "description", ",", "labels", ",", "registry", "=", "self", ".", "registry", ")" ]
Use a Histogram to track the execution time and invocation count of the method. :param name: the name of the metric :param description: the description of the metric :param labels: a dictionary of `{labelname: callable_or_value}` for labels :param kwargs: additional keyword arguments for creating the Histogram
[ "Use", "a", "Histogram", "to", "track", "the", "execution", "time", "and", "invocation", "count", "of", "the", "method", "." ]
678dbf3097e82a0ddb697268406004cc1f4a26bc
https://github.com/rycus86/prometheus_flask_exporter/blob/678dbf3097e82a0ddb697268406004cc1f4a26bc/prometheus_flask_exporter/__init__.py#L317-L333
train
rycus86/prometheus_flask_exporter
prometheus_flask_exporter/__init__.py
PrometheusMetrics.summary
def summary(self, name, description, labels=None, **kwargs): """ Use a Summary to track the execution time and invocation count of the method. :param name: the name of the metric :param description: the description of the metric :param labels: a dictionary of `{labelname: callable_or_value}` for labels :param kwargs: additional keyword arguments for creating the Summary """ return self._track( Summary, lambda metric, time: metric.observe(time), kwargs, name, description, labels, registry=self.registry )
python
def summary(self, name, description, labels=None, **kwargs): """ Use a Summary to track the execution time and invocation count of the method. :param name: the name of the metric :param description: the description of the metric :param labels: a dictionary of `{labelname: callable_or_value}` for labels :param kwargs: additional keyword arguments for creating the Summary """ return self._track( Summary, lambda metric, time: metric.observe(time), kwargs, name, description, labels, registry=self.registry )
[ "def", "summary", "(", "self", ",", "name", ",", "description", ",", "labels", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_track", "(", "Summary", ",", "lambda", "metric", ",", "time", ":", "metric", ".", "observe", "(", "time", ")", ",", "kwargs", ",", "name", ",", "description", ",", "labels", ",", "registry", "=", "self", ".", "registry", ")" ]
Use a Summary to track the execution time and invocation count of the method. :param name: the name of the metric :param description: the description of the metric :param labels: a dictionary of `{labelname: callable_or_value}` for labels :param kwargs: additional keyword arguments for creating the Summary
[ "Use", "a", "Summary", "to", "track", "the", "execution", "time", "and", "invocation", "count", "of", "the", "method", "." ]
678dbf3097e82a0ddb697268406004cc1f4a26bc
https://github.com/rycus86/prometheus_flask_exporter/blob/678dbf3097e82a0ddb697268406004cc1f4a26bc/prometheus_flask_exporter/__init__.py#L335-L351
train
rycus86/prometheus_flask_exporter
prometheus_flask_exporter/__init__.py
PrometheusMetrics.gauge
def gauge(self, name, description, labels=None, **kwargs): """ Use a Gauge to track the number of invocations in progress for the method. :param name: the name of the metric :param description: the description of the metric :param labels: a dictionary of `{labelname: callable_or_value}` for labels :param kwargs: additional keyword arguments for creating the Gauge """ return self._track( Gauge, lambda metric, time: metric.dec(), kwargs, name, description, labels, registry=self.registry, before=lambda metric: metric.inc() )
python
def gauge(self, name, description, labels=None, **kwargs): """ Use a Gauge to track the number of invocations in progress for the method. :param name: the name of the metric :param description: the description of the metric :param labels: a dictionary of `{labelname: callable_or_value}` for labels :param kwargs: additional keyword arguments for creating the Gauge """ return self._track( Gauge, lambda metric, time: metric.dec(), kwargs, name, description, labels, registry=self.registry, before=lambda metric: metric.inc() )
[ "def", "gauge", "(", "self", ",", "name", ",", "description", ",", "labels", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_track", "(", "Gauge", ",", "lambda", "metric", ",", "time", ":", "metric", ".", "dec", "(", ")", ",", "kwargs", ",", "name", ",", "description", ",", "labels", ",", "registry", "=", "self", ".", "registry", ",", "before", "=", "lambda", "metric", ":", "metric", ".", "inc", "(", ")", ")" ]
Use a Gauge to track the number of invocations in progress for the method. :param name: the name of the metric :param description: the description of the metric :param labels: a dictionary of `{labelname: callable_or_value}` for labels :param kwargs: additional keyword arguments for creating the Gauge
[ "Use", "a", "Gauge", "to", "track", "the", "number", "of", "invocations", "in", "progress", "for", "the", "method", "." ]
678dbf3097e82a0ddb697268406004cc1f4a26bc
https://github.com/rycus86/prometheus_flask_exporter/blob/678dbf3097e82a0ddb697268406004cc1f4a26bc/prometheus_flask_exporter/__init__.py#L353-L370
train
rycus86/prometheus_flask_exporter
prometheus_flask_exporter/__init__.py
PrometheusMetrics.counter
def counter(self, name, description, labels=None, **kwargs): """ Use a Counter to track the total number of invocations of the method. :param name: the name of the metric :param description: the description of the metric :param labels: a dictionary of `{labelname: callable_or_value}` for labels :param kwargs: additional keyword arguments for creating the Counter """ return self._track( Counter, lambda metric, time: metric.inc(), kwargs, name, description, labels, registry=self.registry )
python
def counter(self, name, description, labels=None, **kwargs): """ Use a Counter to track the total number of invocations of the method. :param name: the name of the metric :param description: the description of the metric :param labels: a dictionary of `{labelname: callable_or_value}` for labels :param kwargs: additional keyword arguments for creating the Counter """ return self._track( Counter, lambda metric, time: metric.inc(), kwargs, name, description, labels, registry=self.registry )
[ "def", "counter", "(", "self", ",", "name", ",", "description", ",", "labels", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_track", "(", "Counter", ",", "lambda", "metric", ",", "time", ":", "metric", ".", "inc", "(", ")", ",", "kwargs", ",", "name", ",", "description", ",", "labels", ",", "registry", "=", "self", ".", "registry", ")" ]
Use a Counter to track the total number of invocations of the method. :param name: the name of the metric :param description: the description of the metric :param labels: a dictionary of `{labelname: callable_or_value}` for labels :param kwargs: additional keyword arguments for creating the Counter
[ "Use", "a", "Counter", "to", "track", "the", "total", "number", "of", "invocations", "of", "the", "method", "." ]
678dbf3097e82a0ddb697268406004cc1f4a26bc
https://github.com/rycus86/prometheus_flask_exporter/blob/678dbf3097e82a0ddb697268406004cc1f4a26bc/prometheus_flask_exporter/__init__.py#L372-L387
train
rycus86/prometheus_flask_exporter
prometheus_flask_exporter/__init__.py
PrometheusMetrics._track
def _track(metric_type, metric_call, metric_kwargs, name, description, labels, registry, before=None): """ Internal method decorator logic. :param metric_type: the type of the metric from the `prometheus_client` library :param metric_call: the invocation to execute as a callable with `(metric, time)` :param metric_kwargs: additional keyword arguments for creating the metric :param name: the name of the metric :param description: the description of the metric :param labels: a dictionary of `{labelname: callable_or_value}` for labels :param before: an optional callable to invoke before executing the request handler method accepting the single `metric` argument :param registry: the Prometheus Registry to use """ if labels is not None and not isinstance(labels, dict): raise TypeError('labels needs to be a dictionary of {labelname: callable}') label_names = labels.keys() if labels else tuple() parent_metric = metric_type( name, description, labelnames=label_names, registry=registry, **metric_kwargs ) def argspec(func): if hasattr(inspect, 'getfullargspec'): return inspect.getfullargspec(func) else: return inspect.getargspec(func) def label_value(f): if not callable(f): return lambda x: f if argspec(f).args: return lambda x: f(x) else: return lambda x: f() label_generator = tuple( (key, label_value(call)) for key, call in labels.items() ) if labels else tuple() def get_metric(response): if label_names: return parent_metric.labels( **{key: call(response) for key, call in label_generator} ) else: return parent_metric def decorator(f): @functools.wraps(f) def func(*args, **kwargs): if before: metric = get_metric(None) before(metric) else: metric = None start_time = default_timer() try: response = f(*args, **kwargs) except HTTPException as ex: response = ex except Exception as ex: response = make_response('Exception: %s' % ex, 500) total_time = max(default_timer() - start_time, 0) if not metric: response_for_metric = response if not isinstance(response, Response): if request.endpoint == f.__name__: # we are in a request handler method response_for_metric = make_response(response) metric = get_metric(response_for_metric) metric_call(metric, time=total_time) return response return func return decorator
python
def _track(metric_type, metric_call, metric_kwargs, name, description, labels, registry, before=None): """ Internal method decorator logic. :param metric_type: the type of the metric from the `prometheus_client` library :param metric_call: the invocation to execute as a callable with `(metric, time)` :param metric_kwargs: additional keyword arguments for creating the metric :param name: the name of the metric :param description: the description of the metric :param labels: a dictionary of `{labelname: callable_or_value}` for labels :param before: an optional callable to invoke before executing the request handler method accepting the single `metric` argument :param registry: the Prometheus Registry to use """ if labels is not None and not isinstance(labels, dict): raise TypeError('labels needs to be a dictionary of {labelname: callable}') label_names = labels.keys() if labels else tuple() parent_metric = metric_type( name, description, labelnames=label_names, registry=registry, **metric_kwargs ) def argspec(func): if hasattr(inspect, 'getfullargspec'): return inspect.getfullargspec(func) else: return inspect.getargspec(func) def label_value(f): if not callable(f): return lambda x: f if argspec(f).args: return lambda x: f(x) else: return lambda x: f() label_generator = tuple( (key, label_value(call)) for key, call in labels.items() ) if labels else tuple() def get_metric(response): if label_names: return parent_metric.labels( **{key: call(response) for key, call in label_generator} ) else: return parent_metric def decorator(f): @functools.wraps(f) def func(*args, **kwargs): if before: metric = get_metric(None) before(metric) else: metric = None start_time = default_timer() try: response = f(*args, **kwargs) except HTTPException as ex: response = ex except Exception as ex: response = make_response('Exception: %s' % ex, 500) total_time = max(default_timer() - start_time, 0) if not metric: response_for_metric = response if not isinstance(response, Response): if request.endpoint == f.__name__: # we are in a request handler method response_for_metric = make_response(response) metric = get_metric(response_for_metric) metric_call(metric, time=total_time) return response return func return decorator
[ "def", "_track", "(", "metric_type", ",", "metric_call", ",", "metric_kwargs", ",", "name", ",", "description", ",", "labels", ",", "registry", ",", "before", "=", "None", ")", ":", "if", "labels", "is", "not", "None", "and", "not", "isinstance", "(", "labels", ",", "dict", ")", ":", "raise", "TypeError", "(", "'labels needs to be a dictionary of {labelname: callable}'", ")", "label_names", "=", "labels", ".", "keys", "(", ")", "if", "labels", "else", "tuple", "(", ")", "parent_metric", "=", "metric_type", "(", "name", ",", "description", ",", "labelnames", "=", "label_names", ",", "registry", "=", "registry", ",", "*", "*", "metric_kwargs", ")", "def", "argspec", "(", "func", ")", ":", "if", "hasattr", "(", "inspect", ",", "'getfullargspec'", ")", ":", "return", "inspect", ".", "getfullargspec", "(", "func", ")", "else", ":", "return", "inspect", ".", "getargspec", "(", "func", ")", "def", "label_value", "(", "f", ")", ":", "if", "not", "callable", "(", "f", ")", ":", "return", "lambda", "x", ":", "f", "if", "argspec", "(", "f", ")", ".", "args", ":", "return", "lambda", "x", ":", "f", "(", "x", ")", "else", ":", "return", "lambda", "x", ":", "f", "(", ")", "label_generator", "=", "tuple", "(", "(", "key", ",", "label_value", "(", "call", ")", ")", "for", "key", ",", "call", "in", "labels", ".", "items", "(", ")", ")", "if", "labels", "else", "tuple", "(", ")", "def", "get_metric", "(", "response", ")", ":", "if", "label_names", ":", "return", "parent_metric", ".", "labels", "(", "*", "*", "{", "key", ":", "call", "(", "response", ")", "for", "key", ",", "call", "in", "label_generator", "}", ")", "else", ":", "return", "parent_metric", "def", "decorator", "(", "f", ")", ":", "@", "functools", ".", "wraps", "(", "f", ")", "def", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "before", ":", "metric", "=", "get_metric", "(", "None", ")", "before", "(", "metric", ")", "else", ":", "metric", "=", "None", "start_time", "=", "default_timer", "(", ")", "try", ":", "response", "=", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "HTTPException", "as", "ex", ":", "response", "=", "ex", "except", "Exception", "as", "ex", ":", "response", "=", "make_response", "(", "'Exception: %s'", "%", "ex", ",", "500", ")", "total_time", "=", "max", "(", "default_timer", "(", ")", "-", "start_time", ",", "0", ")", "if", "not", "metric", ":", "response_for_metric", "=", "response", "if", "not", "isinstance", "(", "response", ",", "Response", ")", ":", "if", "request", ".", "endpoint", "==", "f", ".", "__name__", ":", "# we are in a request handler method", "response_for_metric", "=", "make_response", "(", "response", ")", "metric", "=", "get_metric", "(", "response_for_metric", ")", "metric_call", "(", "metric", ",", "time", "=", "total_time", ")", "return", "response", "return", "func", "return", "decorator" ]
Internal method decorator logic. :param metric_type: the type of the metric from the `prometheus_client` library :param metric_call: the invocation to execute as a callable with `(metric, time)` :param metric_kwargs: additional keyword arguments for creating the metric :param name: the name of the metric :param description: the description of the metric :param labels: a dictionary of `{labelname: callable_or_value}` for labels :param before: an optional callable to invoke before executing the request handler method accepting the single `metric` argument :param registry: the Prometheus Registry to use
[ "Internal", "method", "decorator", "logic", "." ]
678dbf3097e82a0ddb697268406004cc1f4a26bc
https://github.com/rycus86/prometheus_flask_exporter/blob/678dbf3097e82a0ddb697268406004cc1f4a26bc/prometheus_flask_exporter/__init__.py#L390-L477
train
rycus86/prometheus_flask_exporter
prometheus_flask_exporter/__init__.py
PrometheusMetrics.do_not_track
def do_not_track(): """ Decorator to skip the default metrics collection for the method. *Note*: explicit metrics decorators will still collect the data """ def decorator(f): @functools.wraps(f) def func(*args, **kwargs): request.prom_do_not_track = True return f(*args, **kwargs) return func return decorator
python
def do_not_track(): """ Decorator to skip the default metrics collection for the method. *Note*: explicit metrics decorators will still collect the data """ def decorator(f): @functools.wraps(f) def func(*args, **kwargs): request.prom_do_not_track = True return f(*args, **kwargs) return func return decorator
[ "def", "do_not_track", "(", ")", ":", "def", "decorator", "(", "f", ")", ":", "@", "functools", ".", "wraps", "(", "f", ")", "def", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "request", ".", "prom_do_not_track", "=", "True", "return", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "func", "return", "decorator" ]
Decorator to skip the default metrics collection for the method. *Note*: explicit metrics decorators will still collect the data
[ "Decorator", "to", "skip", "the", "default", "metrics", "collection", "for", "the", "method", "." ]
678dbf3097e82a0ddb697268406004cc1f4a26bc
https://github.com/rycus86/prometheus_flask_exporter/blob/678dbf3097e82a0ddb697268406004cc1f4a26bc/prometheus_flask_exporter/__init__.py#L480-L495
train
rycus86/prometheus_flask_exporter
prometheus_flask_exporter/__init__.py
PrometheusMetrics.info
def info(self, name, description, labelnames=None, labelvalues=None, **labels): """ Report any information as a Prometheus metric. This will create a `Gauge` with the initial value of 1. The easiest way to use it is: metrics = PrometheusMetrics(app) metrics.info( 'app_info', 'Application info', version='1.0', major=1, minor=0 ) If the order of the labels matters: metrics = PrometheusMetrics(app) metrics.info( 'app_info', 'Application info', ('version', 'major', 'minor'), ('1.0', 1, 0) ) :param name: the name of the metric :param description: the description of the metric :param labelnames: the names of the labels :param labelvalues: the values of the labels :param labels: the names and values of the labels :return: the newly created `Gauge` metric """ if labels and labelnames: raise ValueError( 'Cannot have labels defined as `dict` ' 'and collections of names and values' ) if labelnames is None and labels: labelnames = labels.keys() elif labelnames and labelvalues: for idx, label_name in enumerate(labelnames): labels[label_name] = labelvalues[idx] gauge = Gauge( name, description, labelnames or tuple(), registry=self.registry ) if labels: gauge = gauge.labels(**labels) gauge.set(1) return gauge
python
def info(self, name, description, labelnames=None, labelvalues=None, **labels): """ Report any information as a Prometheus metric. This will create a `Gauge` with the initial value of 1. The easiest way to use it is: metrics = PrometheusMetrics(app) metrics.info( 'app_info', 'Application info', version='1.0', major=1, minor=0 ) If the order of the labels matters: metrics = PrometheusMetrics(app) metrics.info( 'app_info', 'Application info', ('version', 'major', 'minor'), ('1.0', 1, 0) ) :param name: the name of the metric :param description: the description of the metric :param labelnames: the names of the labels :param labelvalues: the values of the labels :param labels: the names and values of the labels :return: the newly created `Gauge` metric """ if labels and labelnames: raise ValueError( 'Cannot have labels defined as `dict` ' 'and collections of names and values' ) if labelnames is None and labels: labelnames = labels.keys() elif labelnames and labelvalues: for idx, label_name in enumerate(labelnames): labels[label_name] = labelvalues[idx] gauge = Gauge( name, description, labelnames or tuple(), registry=self.registry ) if labels: gauge = gauge.labels(**labels) gauge.set(1) return gauge
[ "def", "info", "(", "self", ",", "name", ",", "description", ",", "labelnames", "=", "None", ",", "labelvalues", "=", "None", ",", "*", "*", "labels", ")", ":", "if", "labels", "and", "labelnames", ":", "raise", "ValueError", "(", "'Cannot have labels defined as `dict` '", "'and collections of names and values'", ")", "if", "labelnames", "is", "None", "and", "labels", ":", "labelnames", "=", "labels", ".", "keys", "(", ")", "elif", "labelnames", "and", "labelvalues", ":", "for", "idx", ",", "label_name", "in", "enumerate", "(", "labelnames", ")", ":", "labels", "[", "label_name", "]", "=", "labelvalues", "[", "idx", "]", "gauge", "=", "Gauge", "(", "name", ",", "description", ",", "labelnames", "or", "tuple", "(", ")", ",", "registry", "=", "self", ".", "registry", ")", "if", "labels", ":", "gauge", "=", "gauge", ".", "labels", "(", "*", "*", "labels", ")", "gauge", ".", "set", "(", "1", ")", "return", "gauge" ]
Report any information as a Prometheus metric. This will create a `Gauge` with the initial value of 1. The easiest way to use it is: metrics = PrometheusMetrics(app) metrics.info( 'app_info', 'Application info', version='1.0', major=1, minor=0 ) If the order of the labels matters: metrics = PrometheusMetrics(app) metrics.info( 'app_info', 'Application info', ('version', 'major', 'minor'), ('1.0', 1, 0) ) :param name: the name of the metric :param description: the description of the metric :param labelnames: the names of the labels :param labelvalues: the values of the labels :param labels: the names and values of the labels :return: the newly created `Gauge` metric
[ "Report", "any", "information", "as", "a", "Prometheus", "metric", ".", "This", "will", "create", "a", "Gauge", "with", "the", "initial", "value", "of", "1", "." ]
678dbf3097e82a0ddb697268406004cc1f4a26bc
https://github.com/rycus86/prometheus_flask_exporter/blob/678dbf3097e82a0ddb697268406004cc1f4a26bc/prometheus_flask_exporter/__init__.py#L497-L550
train
berdario/pew
pew/pew.py
inve
def inve(env, command, *args, **kwargs): """Run a command in the given virtual environment. Pass additional keyword arguments to ``subprocess.check_call()``.""" # we don't strictly need to restore the environment, since pew runs in # its own process, but it feels like the right thing to do with temp_environ(): os.environ['VIRTUAL_ENV'] = str(workon_home / env) os.environ['PATH'] = compute_path(env) unsetenv('PYTHONHOME') unsetenv('__PYVENV_LAUNCHER__') try: return check_call([command] + list(args), shell=windows, **kwargs) # need to have shell=True on windows, otherwise the PYTHONPATH # won't inherit the PATH except OSError as e: if e.errno == 2: err('Unable to find', command) return 2 else: raise
python
def inve(env, command, *args, **kwargs): """Run a command in the given virtual environment. Pass additional keyword arguments to ``subprocess.check_call()``.""" # we don't strictly need to restore the environment, since pew runs in # its own process, but it feels like the right thing to do with temp_environ(): os.environ['VIRTUAL_ENV'] = str(workon_home / env) os.environ['PATH'] = compute_path(env) unsetenv('PYTHONHOME') unsetenv('__PYVENV_LAUNCHER__') try: return check_call([command] + list(args), shell=windows, **kwargs) # need to have shell=True on windows, otherwise the PYTHONPATH # won't inherit the PATH except OSError as e: if e.errno == 2: err('Unable to find', command) return 2 else: raise
[ "def", "inve", "(", "env", ",", "command", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# we don't strictly need to restore the environment, since pew runs in", "# its own process, but it feels like the right thing to do", "with", "temp_environ", "(", ")", ":", "os", ".", "environ", "[", "'VIRTUAL_ENV'", "]", "=", "str", "(", "workon_home", "/", "env", ")", "os", ".", "environ", "[", "'PATH'", "]", "=", "compute_path", "(", "env", ")", "unsetenv", "(", "'PYTHONHOME'", ")", "unsetenv", "(", "'__PYVENV_LAUNCHER__'", ")", "try", ":", "return", "check_call", "(", "[", "command", "]", "+", "list", "(", "args", ")", ",", "shell", "=", "windows", ",", "*", "*", "kwargs", ")", "# need to have shell=True on windows, otherwise the PYTHONPATH", "# won't inherit the PATH", "except", "OSError", "as", "e", ":", "if", "e", ".", "errno", "==", "2", ":", "err", "(", "'Unable to find'", ",", "command", ")", "return", "2", "else", ":", "raise" ]
Run a command in the given virtual environment. Pass additional keyword arguments to ``subprocess.check_call()``.
[ "Run", "a", "command", "in", "the", "given", "virtual", "environment", "." ]
37d9ff79342336b8ef6437d9a551008be07afe9b
https://github.com/berdario/pew/blob/37d9ff79342336b8ef6437d9a551008be07afe9b/pew/pew.py#L130-L152
train
berdario/pew
pew/pew.py
ls_cmd
def ls_cmd(argv): """List available environments.""" parser = argparse.ArgumentParser() p_group = parser.add_mutually_exclusive_group() p_group.add_argument('-b', '--brief', action='store_false') p_group.add_argument('-l', '--long', action='store_true') args = parser.parse_args(argv) lsvirtualenv(args.long)
python
def ls_cmd(argv): """List available environments.""" parser = argparse.ArgumentParser() p_group = parser.add_mutually_exclusive_group() p_group.add_argument('-b', '--brief', action='store_false') p_group.add_argument('-l', '--long', action='store_true') args = parser.parse_args(argv) lsvirtualenv(args.long)
[ "def", "ls_cmd", "(", "argv", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "p_group", "=", "parser", ".", "add_mutually_exclusive_group", "(", ")", "p_group", ".", "add_argument", "(", "'-b'", ",", "'--brief'", ",", "action", "=", "'store_false'", ")", "p_group", ".", "add_argument", "(", "'-l'", ",", "'--long'", ",", "action", "=", "'store_true'", ")", "args", "=", "parser", ".", "parse_args", "(", "argv", ")", "lsvirtualenv", "(", "args", ".", "long", ")" ]
List available environments.
[ "List", "available", "environments", "." ]
37d9ff79342336b8ef6437d9a551008be07afe9b
https://github.com/berdario/pew/blob/37d9ff79342336b8ef6437d9a551008be07afe9b/pew/pew.py#L345-L352
train
berdario/pew
pew/pew.py
workon_cmd
def workon_cmd(argv): """List or change working virtual environments.""" parser = argparse.ArgumentParser(prog='pew workon') parser.add_argument('envname', nargs='?') parser.add_argument( '-n', '--no-cd', action='store_true', help=('Do not change working directory to project directory after ' 'activating virtualenv.') ) args = parser.parse_args(argv) def list_and_exit(): lsvirtualenv(False) sys.exit(0) env = parse_envname([args.envname], list_and_exit) # Check if the virtualenv has an associated project directory and in # this case, use it as the current working directory. project_dir = get_project_dir(env) if project_dir is None or args.no_cd: project_dir = os.getcwd() return shell(env, cwd=project_dir)
python
def workon_cmd(argv): """List or change working virtual environments.""" parser = argparse.ArgumentParser(prog='pew workon') parser.add_argument('envname', nargs='?') parser.add_argument( '-n', '--no-cd', action='store_true', help=('Do not change working directory to project directory after ' 'activating virtualenv.') ) args = parser.parse_args(argv) def list_and_exit(): lsvirtualenv(False) sys.exit(0) env = parse_envname([args.envname], list_and_exit) # Check if the virtualenv has an associated project directory and in # this case, use it as the current working directory. project_dir = get_project_dir(env) if project_dir is None or args.no_cd: project_dir = os.getcwd() return shell(env, cwd=project_dir)
[ "def", "workon_cmd", "(", "argv", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "prog", "=", "'pew workon'", ")", "parser", ".", "add_argument", "(", "'envname'", ",", "nargs", "=", "'?'", ")", "parser", ".", "add_argument", "(", "'-n'", ",", "'--no-cd'", ",", "action", "=", "'store_true'", ",", "help", "=", "(", "'Do not change working directory to project directory after '", "'activating virtualenv.'", ")", ")", "args", "=", "parser", ".", "parse_args", "(", "argv", ")", "def", "list_and_exit", "(", ")", ":", "lsvirtualenv", "(", "False", ")", "sys", ".", "exit", "(", "0", ")", "env", "=", "parse_envname", "(", "[", "args", ".", "envname", "]", ",", "list_and_exit", ")", "# Check if the virtualenv has an associated project directory and in", "# this case, use it as the current working directory.", "project_dir", "=", "get_project_dir", "(", "env", ")", "if", "project_dir", "is", "None", "or", "args", ".", "no_cd", ":", "project_dir", "=", "os", ".", "getcwd", "(", ")", "return", "shell", "(", "env", ",", "cwd", "=", "project_dir", ")" ]
List or change working virtual environments.
[ "List", "or", "change", "working", "virtual", "environments", "." ]
37d9ff79342336b8ef6437d9a551008be07afe9b
https://github.com/berdario/pew/blob/37d9ff79342336b8ef6437d9a551008be07afe9b/pew/pew.py#L367-L390
train
berdario/pew
pew/pew.py
add_cmd
def add_cmd(argv): """Add the specified directories to the Python path for the currently active virtualenv. This will be done by placing the directory names in a path file named "virtualenv_path_extensions.pth" inside the virtualenv's site-packages directory; if this file does not exists, it will be created first. """ parser = argparse.ArgumentParser() parser.add_argument('-d', dest='remove', action='store_true') parser.add_argument('dirs', nargs='+') args = parser.parse_args(argv) extra_paths = sitepackages_dir() / '_virtualenv_path_extensions.pth' new_paths = [os.path.abspath(d) + "\n" for d in args.dirs] if not extra_paths.exists(): with extra_paths.open('w') as extra: extra.write('''import sys; sys.__plen = len(sys.path) import sys; new=sys.path[sys.__plen:]; del sys.path[sys.__plen:]; p=getattr(sys,'__egginsert',0); sys.path[p:p]=new; sys.__egginsert = p+len(new) ''') def rewrite(f): with extra_paths.open('r+') as extra: to_write = f(extra.readlines()) extra.seek(0) extra.truncate() extra.writelines(to_write) if args.remove: rewrite(lambda ls: [line for line in ls if line not in new_paths]) else: rewrite(lambda lines: lines[0:1] + new_paths + lines[1:])
python
def add_cmd(argv): """Add the specified directories to the Python path for the currently active virtualenv. This will be done by placing the directory names in a path file named "virtualenv_path_extensions.pth" inside the virtualenv's site-packages directory; if this file does not exists, it will be created first. """ parser = argparse.ArgumentParser() parser.add_argument('-d', dest='remove', action='store_true') parser.add_argument('dirs', nargs='+') args = parser.parse_args(argv) extra_paths = sitepackages_dir() / '_virtualenv_path_extensions.pth' new_paths = [os.path.abspath(d) + "\n" for d in args.dirs] if not extra_paths.exists(): with extra_paths.open('w') as extra: extra.write('''import sys; sys.__plen = len(sys.path) import sys; new=sys.path[sys.__plen:]; del sys.path[sys.__plen:]; p=getattr(sys,'__egginsert',0); sys.path[p:p]=new; sys.__egginsert = p+len(new) ''') def rewrite(f): with extra_paths.open('r+') as extra: to_write = f(extra.readlines()) extra.seek(0) extra.truncate() extra.writelines(to_write) if args.remove: rewrite(lambda ls: [line for line in ls if line not in new_paths]) else: rewrite(lambda lines: lines[0:1] + new_paths + lines[1:])
[ "def", "add_cmd", "(", "argv", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "'-d'", ",", "dest", "=", "'remove'", ",", "action", "=", "'store_true'", ")", "parser", ".", "add_argument", "(", "'dirs'", ",", "nargs", "=", "'+'", ")", "args", "=", "parser", ".", "parse_args", "(", "argv", ")", "extra_paths", "=", "sitepackages_dir", "(", ")", "/", "'_virtualenv_path_extensions.pth'", "new_paths", "=", "[", "os", ".", "path", ".", "abspath", "(", "d", ")", "+", "\"\\n\"", "for", "d", "in", "args", ".", "dirs", "]", "if", "not", "extra_paths", ".", "exists", "(", ")", ":", "with", "extra_paths", ".", "open", "(", "'w'", ")", "as", "extra", ":", "extra", ".", "write", "(", "'''import sys; sys.__plen = len(sys.path)\nimport sys; new=sys.path[sys.__plen:]; del sys.path[sys.__plen:]; p=getattr(sys,'__egginsert',0); sys.path[p:p]=new; sys.__egginsert = p+len(new)\n '''", ")", "def", "rewrite", "(", "f", ")", ":", "with", "extra_paths", ".", "open", "(", "'r+'", ")", "as", "extra", ":", "to_write", "=", "f", "(", "extra", ".", "readlines", "(", ")", ")", "extra", ".", "seek", "(", "0", ")", "extra", ".", "truncate", "(", ")", "extra", ".", "writelines", "(", "to_write", ")", "if", "args", ".", "remove", ":", "rewrite", "(", "lambda", "ls", ":", "[", "line", "for", "line", "in", "ls", "if", "line", "not", "in", "new_paths", "]", ")", "else", ":", "rewrite", "(", "lambda", "lines", ":", "lines", "[", "0", ":", "1", "]", "+", "new_paths", "+", "lines", "[", "1", ":", "]", ")" ]
Add the specified directories to the Python path for the currently active virtualenv. This will be done by placing the directory names in a path file named "virtualenv_path_extensions.pth" inside the virtualenv's site-packages directory; if this file does not exists, it will be created first.
[ "Add", "the", "specified", "directories", "to", "the", "Python", "path", "for", "the", "currently", "active", "virtualenv", "." ]
37d9ff79342336b8ef6437d9a551008be07afe9b
https://github.com/berdario/pew/blob/37d9ff79342336b8ef6437d9a551008be07afe9b/pew/pew.py#L402-L433
train
berdario/pew
pew/pew.py
lssitepackages_cmd
def lssitepackages_cmd(argv): """Show the content of the site-packages directory of the current virtualenv.""" site = sitepackages_dir() print(*sorted(site.iterdir()), sep=os.linesep) extra_paths = site / '_virtualenv_path_extensions.pth' if extra_paths.exists(): print('from _virtualenv_path_extensions.pth:') with extra_paths.open() as extra: print(''.join(extra.readlines()))
python
def lssitepackages_cmd(argv): """Show the content of the site-packages directory of the current virtualenv.""" site = sitepackages_dir() print(*sorted(site.iterdir()), sep=os.linesep) extra_paths = site / '_virtualenv_path_extensions.pth' if extra_paths.exists(): print('from _virtualenv_path_extensions.pth:') with extra_paths.open() as extra: print(''.join(extra.readlines()))
[ "def", "lssitepackages_cmd", "(", "argv", ")", ":", "site", "=", "sitepackages_dir", "(", ")", "print", "(", "*", "sorted", "(", "site", ".", "iterdir", "(", ")", ")", ",", "sep", "=", "os", ".", "linesep", ")", "extra_paths", "=", "site", "/", "'_virtualenv_path_extensions.pth'", "if", "extra_paths", ".", "exists", "(", ")", ":", "print", "(", "'from _virtualenv_path_extensions.pth:'", ")", "with", "extra_paths", ".", "open", "(", ")", "as", "extra", ":", "print", "(", "''", ".", "join", "(", "extra", ".", "readlines", "(", ")", ")", ")" ]
Show the content of the site-packages directory of the current virtualenv.
[ "Show", "the", "content", "of", "the", "site", "-", "packages", "directory", "of", "the", "current", "virtualenv", "." ]
37d9ff79342336b8ef6437d9a551008be07afe9b
https://github.com/berdario/pew/blob/37d9ff79342336b8ef6437d9a551008be07afe9b/pew/pew.py#L440-L448
train
berdario/pew
pew/pew.py
toggleglobalsitepackages_cmd
def toggleglobalsitepackages_cmd(argv): """Toggle the current virtualenv between having and not having access to the global site-packages.""" quiet = argv == ['-q'] site = sitepackages_dir() ngsp_file = site.parent / 'no-global-site-packages.txt' if ngsp_file.exists(): ngsp_file.unlink() if not quiet: print('Enabled global site-packages') else: with ngsp_file.open('w'): if not quiet: print('Disabled global site-packages')
python
def toggleglobalsitepackages_cmd(argv): """Toggle the current virtualenv between having and not having access to the global site-packages.""" quiet = argv == ['-q'] site = sitepackages_dir() ngsp_file = site.parent / 'no-global-site-packages.txt' if ngsp_file.exists(): ngsp_file.unlink() if not quiet: print('Enabled global site-packages') else: with ngsp_file.open('w'): if not quiet: print('Disabled global site-packages')
[ "def", "toggleglobalsitepackages_cmd", "(", "argv", ")", ":", "quiet", "=", "argv", "==", "[", "'-q'", "]", "site", "=", "sitepackages_dir", "(", ")", "ngsp_file", "=", "site", ".", "parent", "/", "'no-global-site-packages.txt'", "if", "ngsp_file", ".", "exists", "(", ")", ":", "ngsp_file", ".", "unlink", "(", ")", "if", "not", "quiet", ":", "print", "(", "'Enabled global site-packages'", ")", "else", ":", "with", "ngsp_file", ".", "open", "(", "'w'", ")", ":", "if", "not", "quiet", ":", "print", "(", "'Disabled global site-packages'", ")" ]
Toggle the current virtualenv between having and not having access to the global site-packages.
[ "Toggle", "the", "current", "virtualenv", "between", "having", "and", "not", "having", "access", "to", "the", "global", "site", "-", "packages", "." ]
37d9ff79342336b8ef6437d9a551008be07afe9b
https://github.com/berdario/pew/blob/37d9ff79342336b8ef6437d9a551008be07afe9b/pew/pew.py#L451-L463
train
berdario/pew
pew/pew.py
cp_cmd
def cp_cmd(argv): """Duplicate the named virtualenv to make a new one.""" parser = argparse.ArgumentParser() parser.add_argument('source') parser.add_argument('target', nargs='?') parser.add_argument('-d', '--dont-activate', action='store_false', default=True, dest='activate', help="After \ creation, continue with the existing shell (don't \ activate the new environment).") args = parser.parse_args(argv) target_name = copy_virtualenv_project(args.source, args.target) if args.activate: shell(target_name)
python
def cp_cmd(argv): """Duplicate the named virtualenv to make a new one.""" parser = argparse.ArgumentParser() parser.add_argument('source') parser.add_argument('target', nargs='?') parser.add_argument('-d', '--dont-activate', action='store_false', default=True, dest='activate', help="After \ creation, continue with the existing shell (don't \ activate the new environment).") args = parser.parse_args(argv) target_name = copy_virtualenv_project(args.source, args.target) if args.activate: shell(target_name)
[ "def", "cp_cmd", "(", "argv", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "'source'", ")", "parser", ".", "add_argument", "(", "'target'", ",", "nargs", "=", "'?'", ")", "parser", ".", "add_argument", "(", "'-d'", ",", "'--dont-activate'", ",", "action", "=", "'store_false'", ",", "default", "=", "True", ",", "dest", "=", "'activate'", ",", "help", "=", "\"After \\\n creation, continue with the existing shell (don't \\\n activate the new environment).\"", ")", "args", "=", "parser", ".", "parse_args", "(", "argv", ")", "target_name", "=", "copy_virtualenv_project", "(", "args", ".", "source", ",", "args", ".", "target", ")", "if", "args", ".", "activate", ":", "shell", "(", "target_name", ")" ]
Duplicate the named virtualenv to make a new one.
[ "Duplicate", "the", "named", "virtualenv", "to", "make", "a", "new", "one", "." ]
37d9ff79342336b8ef6437d9a551008be07afe9b
https://github.com/berdario/pew/blob/37d9ff79342336b8ef6437d9a551008be07afe9b/pew/pew.py#L466-L479
train
berdario/pew
pew/pew.py
rename_cmd
def rename_cmd(argv): """Rename a virtualenv""" parser = argparse.ArgumentParser() parser.add_argument('source') parser.add_argument('target') pargs = parser.parse_args(argv) copy_virtualenv_project(pargs.source, pargs.target) return rmvirtualenvs([pargs.source])
python
def rename_cmd(argv): """Rename a virtualenv""" parser = argparse.ArgumentParser() parser.add_argument('source') parser.add_argument('target') pargs = parser.parse_args(argv) copy_virtualenv_project(pargs.source, pargs.target) return rmvirtualenvs([pargs.source])
[ "def", "rename_cmd", "(", "argv", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "'source'", ")", "parser", ".", "add_argument", "(", "'target'", ")", "pargs", "=", "parser", ".", "parse_args", "(", "argv", ")", "copy_virtualenv_project", "(", "pargs", ".", "source", ",", "pargs", ".", "target", ")", "return", "rmvirtualenvs", "(", "[", "pargs", ".", "source", "]", ")" ]
Rename a virtualenv
[ "Rename", "a", "virtualenv" ]
37d9ff79342336b8ef6437d9a551008be07afe9b
https://github.com/berdario/pew/blob/37d9ff79342336b8ef6437d9a551008be07afe9b/pew/pew.py#L503-L510
train
berdario/pew
pew/pew.py
setproject_cmd
def setproject_cmd(argv): """Given a virtualenv directory and a project directory, set the \ virtualenv up to be associated with the project.""" args = dict(enumerate(argv)) project = os.path.abspath(args.get(1, '.')) env = args.get(0, os.environ.get('VIRTUAL_ENV')) if not env: sys.exit('pew setproject [virtualenv] [project_path]') if not (workon_home / env).exists(): sys.exit("Environment '%s' doesn't exist." % env) if not os.path.isdir(project): sys.exit('pew setproject: %s does not exist' % project) setvirtualenvproject(env, project)
python
def setproject_cmd(argv): """Given a virtualenv directory and a project directory, set the \ virtualenv up to be associated with the project.""" args = dict(enumerate(argv)) project = os.path.abspath(args.get(1, '.')) env = args.get(0, os.environ.get('VIRTUAL_ENV')) if not env: sys.exit('pew setproject [virtualenv] [project_path]') if not (workon_home / env).exists(): sys.exit("Environment '%s' doesn't exist." % env) if not os.path.isdir(project): sys.exit('pew setproject: %s does not exist' % project) setvirtualenvproject(env, project)
[ "def", "setproject_cmd", "(", "argv", ")", ":", "args", "=", "dict", "(", "enumerate", "(", "argv", ")", ")", "project", "=", "os", ".", "path", ".", "abspath", "(", "args", ".", "get", "(", "1", ",", "'.'", ")", ")", "env", "=", "args", ".", "get", "(", "0", ",", "os", ".", "environ", ".", "get", "(", "'VIRTUAL_ENV'", ")", ")", "if", "not", "env", ":", "sys", ".", "exit", "(", "'pew setproject [virtualenv] [project_path]'", ")", "if", "not", "(", "workon_home", "/", "env", ")", ".", "exists", "(", ")", ":", "sys", ".", "exit", "(", "\"Environment '%s' doesn't exist.\"", "%", "env", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "project", ")", ":", "sys", ".", "exit", "(", "'pew setproject: %s does not exist'", "%", "project", ")", "setvirtualenvproject", "(", "env", ",", "project", ")" ]
Given a virtualenv directory and a project directory, set the \ virtualenv up to be associated with the project.
[ "Given", "a", "virtualenv", "directory", "and", "a", "project", "directory", "set", "the", "\\", "virtualenv", "up", "to", "be", "associated", "with", "the", "project", "." ]
37d9ff79342336b8ef6437d9a551008be07afe9b
https://github.com/berdario/pew/blob/37d9ff79342336b8ef6437d9a551008be07afe9b/pew/pew.py#L519-L531
train
berdario/pew
pew/pew.py
getproject_cmd
def getproject_cmd(argv): """Print a virtualenv's project directory, if set. If called without providing a virtualenv name as argument, print the current virtualenv's project directory. """ # Parse command line arguments parser = argparse.ArgumentParser( description="Print an environment's project directory.", ) parser.add_argument( 'envname', nargs='?', default=os.environ.get('VIRTUAL_ENV'), help=( 'The name of the environment to return the project directory ' 'for. If omitted, will use the currently active environment.' ), ) args = parser.parse_args(argv) # Now, do the actual work if not args.envname: sys.exit('ERROR: no virtualenv active') if not (workon_home / args.envname).exists(): sys.exit("ERROR: Environment '{0}' does not exist." .format(args.envname)) project_dir = get_project_dir(args.envname) if project_dir is None: sys.exit("ERROR: no project directory set for Environment '{0}'" .format(args.envname)) print(project_dir)
python
def getproject_cmd(argv): """Print a virtualenv's project directory, if set. If called without providing a virtualenv name as argument, print the current virtualenv's project directory. """ # Parse command line arguments parser = argparse.ArgumentParser( description="Print an environment's project directory.", ) parser.add_argument( 'envname', nargs='?', default=os.environ.get('VIRTUAL_ENV'), help=( 'The name of the environment to return the project directory ' 'for. If omitted, will use the currently active environment.' ), ) args = parser.parse_args(argv) # Now, do the actual work if not args.envname: sys.exit('ERROR: no virtualenv active') if not (workon_home / args.envname).exists(): sys.exit("ERROR: Environment '{0}' does not exist." .format(args.envname)) project_dir = get_project_dir(args.envname) if project_dir is None: sys.exit("ERROR: no project directory set for Environment '{0}'" .format(args.envname)) print(project_dir)
[ "def", "getproject_cmd", "(", "argv", ")", ":", "# Parse command line arguments", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"Print an environment's project directory.\"", ",", ")", "parser", ".", "add_argument", "(", "'envname'", ",", "nargs", "=", "'?'", ",", "default", "=", "os", ".", "environ", ".", "get", "(", "'VIRTUAL_ENV'", ")", ",", "help", "=", "(", "'The name of the environment to return the project directory '", "'for. If omitted, will use the currently active environment.'", ")", ",", ")", "args", "=", "parser", ".", "parse_args", "(", "argv", ")", "# Now, do the actual work", "if", "not", "args", ".", "envname", ":", "sys", ".", "exit", "(", "'ERROR: no virtualenv active'", ")", "if", "not", "(", "workon_home", "/", "args", ".", "envname", ")", ".", "exists", "(", ")", ":", "sys", ".", "exit", "(", "\"ERROR: Environment '{0}' does not exist.\"", ".", "format", "(", "args", ".", "envname", ")", ")", "project_dir", "=", "get_project_dir", "(", "args", ".", "envname", ")", "if", "project_dir", "is", "None", ":", "sys", ".", "exit", "(", "\"ERROR: no project directory set for Environment '{0}'\"", ".", "format", "(", "args", ".", "envname", ")", ")", "print", "(", "project_dir", ")" ]
Print a virtualenv's project directory, if set. If called without providing a virtualenv name as argument, print the current virtualenv's project directory.
[ "Print", "a", "virtualenv", "s", "project", "directory", "if", "set", "." ]
37d9ff79342336b8ef6437d9a551008be07afe9b
https://github.com/berdario/pew/blob/37d9ff79342336b8ef6437d9a551008be07afe9b/pew/pew.py#L534-L564
train
berdario/pew
pew/pew.py
mkproject_cmd
def mkproject_cmd(argv): """Create a new project directory and its associated virtualenv.""" if '-l' in argv or '--list' in argv: templates = [t.name[9:] for t in workon_home.glob("template_*")] print("Available project templates:", *templates, sep='\n') return parser = mkvirtualenv_argparser() parser.add_argument('envname') parser.add_argument( '-t', action='append', default=[], dest='templates', help='Multiple \ templates may be selected. They are applied in the order specified on the \ command line.') parser.add_argument( '-l', '--list', action='store_true', help='List available templates.') args, rest = parser.parse_known_args(argv) projects_home = Path(os.environ.get('PROJECT_HOME', '.')) if not projects_home.exists(): sys.exit('ERROR: Projects directory %s does not exist. \ Create it or set PROJECT_HOME to an existing directory.' % projects_home) project = (projects_home / args.envname).absolute() if project.exists(): sys.exit('Project %s already exists.' % args.envname) mkvirtualenv(args.envname, args.python, args.packages, project.absolute(), args.requirements, rest) project.mkdir() for template_name in args.templates: template = workon_home / ("template_" + template_name) inve(args.envname, str(template), args.envname, str(project)) if args.activate: shell(args.envname, cwd=str(project))
python
def mkproject_cmd(argv): """Create a new project directory and its associated virtualenv.""" if '-l' in argv or '--list' in argv: templates = [t.name[9:] for t in workon_home.glob("template_*")] print("Available project templates:", *templates, sep='\n') return parser = mkvirtualenv_argparser() parser.add_argument('envname') parser.add_argument( '-t', action='append', default=[], dest='templates', help='Multiple \ templates may be selected. They are applied in the order specified on the \ command line.') parser.add_argument( '-l', '--list', action='store_true', help='List available templates.') args, rest = parser.parse_known_args(argv) projects_home = Path(os.environ.get('PROJECT_HOME', '.')) if not projects_home.exists(): sys.exit('ERROR: Projects directory %s does not exist. \ Create it or set PROJECT_HOME to an existing directory.' % projects_home) project = (projects_home / args.envname).absolute() if project.exists(): sys.exit('Project %s already exists.' % args.envname) mkvirtualenv(args.envname, args.python, args.packages, project.absolute(), args.requirements, rest) project.mkdir() for template_name in args.templates: template = workon_home / ("template_" + template_name) inve(args.envname, str(template), args.envname, str(project)) if args.activate: shell(args.envname, cwd=str(project))
[ "def", "mkproject_cmd", "(", "argv", ")", ":", "if", "'-l'", "in", "argv", "or", "'--list'", "in", "argv", ":", "templates", "=", "[", "t", ".", "name", "[", "9", ":", "]", "for", "t", "in", "workon_home", ".", "glob", "(", "\"template_*\"", ")", "]", "print", "(", "\"Available project templates:\"", ",", "*", "templates", ",", "sep", "=", "'\\n'", ")", "return", "parser", "=", "mkvirtualenv_argparser", "(", ")", "parser", ".", "add_argument", "(", "'envname'", ")", "parser", ".", "add_argument", "(", "'-t'", ",", "action", "=", "'append'", ",", "default", "=", "[", "]", ",", "dest", "=", "'templates'", ",", "help", "=", "'Multiple \\\ntemplates may be selected. They are applied in the order specified on the \\\ncommand line.'", ")", "parser", ".", "add_argument", "(", "'-l'", ",", "'--list'", ",", "action", "=", "'store_true'", ",", "help", "=", "'List available templates.'", ")", "args", ",", "rest", "=", "parser", ".", "parse_known_args", "(", "argv", ")", "projects_home", "=", "Path", "(", "os", ".", "environ", ".", "get", "(", "'PROJECT_HOME'", ",", "'.'", ")", ")", "if", "not", "projects_home", ".", "exists", "(", ")", ":", "sys", ".", "exit", "(", "'ERROR: Projects directory %s does not exist. \\\nCreate it or set PROJECT_HOME to an existing directory.'", "%", "projects_home", ")", "project", "=", "(", "projects_home", "/", "args", ".", "envname", ")", ".", "absolute", "(", ")", "if", "project", ".", "exists", "(", ")", ":", "sys", ".", "exit", "(", "'Project %s already exists.'", "%", "args", ".", "envname", ")", "mkvirtualenv", "(", "args", ".", "envname", ",", "args", ".", "python", ",", "args", ".", "packages", ",", "project", ".", "absolute", "(", ")", ",", "args", ".", "requirements", ",", "rest", ")", "project", ".", "mkdir", "(", ")", "for", "template_name", "in", "args", ".", "templates", ":", "template", "=", "workon_home", "/", "(", "\"template_\"", "+", "template_name", ")", "inve", "(", "args", ".", "envname", ",", "str", "(", "template", ")", ",", "args", ".", "envname", ",", "str", "(", "project", ")", ")", "if", "args", ".", "activate", ":", "shell", "(", "args", ".", "envname", ",", "cwd", "=", "str", "(", "project", ")", ")" ]
Create a new project directory and its associated virtualenv.
[ "Create", "a", "new", "project", "directory", "and", "its", "associated", "virtualenv", "." ]
37d9ff79342336b8ef6437d9a551008be07afe9b
https://github.com/berdario/pew/blob/37d9ff79342336b8ef6437d9a551008be07afe9b/pew/pew.py#L567-L603
train
berdario/pew
pew/pew.py
mktmpenv_cmd
def mktmpenv_cmd(argv): """Create a temporary virtualenv.""" parser = mkvirtualenv_argparser() env = '.' while (workon_home / env).exists(): env = hex(random.getrandbits(64))[2:-1] args, rest = parser.parse_known_args(argv) mkvirtualenv(env, args.python, args.packages, requirements=args.requirements, rest=rest) print('This is a temporary environment. It will be deleted when you exit') try: if args.activate: # only used for testing on windows shell(env) finally: return rmvirtualenvs([env])
python
def mktmpenv_cmd(argv): """Create a temporary virtualenv.""" parser = mkvirtualenv_argparser() env = '.' while (workon_home / env).exists(): env = hex(random.getrandbits(64))[2:-1] args, rest = parser.parse_known_args(argv) mkvirtualenv(env, args.python, args.packages, requirements=args.requirements, rest=rest) print('This is a temporary environment. It will be deleted when you exit') try: if args.activate: # only used for testing on windows shell(env) finally: return rmvirtualenvs([env])
[ "def", "mktmpenv_cmd", "(", "argv", ")", ":", "parser", "=", "mkvirtualenv_argparser", "(", ")", "env", "=", "'.'", "while", "(", "workon_home", "/", "env", ")", ".", "exists", "(", ")", ":", "env", "=", "hex", "(", "random", ".", "getrandbits", "(", "64", ")", ")", "[", "2", ":", "-", "1", "]", "args", ",", "rest", "=", "parser", ".", "parse_known_args", "(", "argv", ")", "mkvirtualenv", "(", "env", ",", "args", ".", "python", ",", "args", ".", "packages", ",", "requirements", "=", "args", ".", "requirements", ",", "rest", "=", "rest", ")", "print", "(", "'This is a temporary environment. It will be deleted when you exit'", ")", "try", ":", "if", "args", ".", "activate", ":", "# only used for testing on windows", "shell", "(", "env", ")", "finally", ":", "return", "rmvirtualenvs", "(", "[", "env", "]", ")" ]
Create a temporary virtualenv.
[ "Create", "a", "temporary", "virtualenv", "." ]
37d9ff79342336b8ef6437d9a551008be07afe9b
https://github.com/berdario/pew/blob/37d9ff79342336b8ef6437d9a551008be07afe9b/pew/pew.py#L606-L623
train
berdario/pew
pew/pew.py
inall_cmd
def inall_cmd(argv): """Run a command in each virtualenv.""" envs = lsenvs() errors = False for env in envs: print("\n%s:" % env) try: inve(env, *argv) except CalledProcessError as e: errors = True err(e) sys.exit(errors)
python
def inall_cmd(argv): """Run a command in each virtualenv.""" envs = lsenvs() errors = False for env in envs: print("\n%s:" % env) try: inve(env, *argv) except CalledProcessError as e: errors = True err(e) sys.exit(errors)
[ "def", "inall_cmd", "(", "argv", ")", ":", "envs", "=", "lsenvs", "(", ")", "errors", "=", "False", "for", "env", "in", "envs", ":", "print", "(", "\"\\n%s:\"", "%", "env", ")", "try", ":", "inve", "(", "env", ",", "*", "argv", ")", "except", "CalledProcessError", "as", "e", ":", "errors", "=", "True", "err", "(", "e", ")", "sys", ".", "exit", "(", "errors", ")" ]
Run a command in each virtualenv.
[ "Run", "a", "command", "in", "each", "virtualenv", "." ]
37d9ff79342336b8ef6437d9a551008be07afe9b
https://github.com/berdario/pew/blob/37d9ff79342336b8ef6437d9a551008be07afe9b/pew/pew.py#L649-L660
train
berdario/pew
pew/pew.py
in_cmd
def in_cmd(argv): """Run a command in the given virtualenv.""" if len(argv) == 1: return workon_cmd(argv) parse_envname(argv, lambda : sys.exit('You must provide a valid virtualenv to target')) return inve(*argv)
python
def in_cmd(argv): """Run a command in the given virtualenv.""" if len(argv) == 1: return workon_cmd(argv) parse_envname(argv, lambda : sys.exit('You must provide a valid virtualenv to target')) return inve(*argv)
[ "def", "in_cmd", "(", "argv", ")", ":", "if", "len", "(", "argv", ")", "==", "1", ":", "return", "workon_cmd", "(", "argv", ")", "parse_envname", "(", "argv", ",", "lambda", ":", "sys", ".", "exit", "(", "'You must provide a valid virtualenv to target'", ")", ")", "return", "inve", "(", "*", "argv", ")" ]
Run a command in the given virtualenv.
[ "Run", "a", "command", "in", "the", "given", "virtualenv", "." ]
37d9ff79342336b8ef6437d9a551008be07afe9b
https://github.com/berdario/pew/blob/37d9ff79342336b8ef6437d9a551008be07afe9b/pew/pew.py#L663-L671
train
berdario/pew
pew/pew.py
restore_cmd
def restore_cmd(argv): """Try to restore a broken virtualenv by reinstalling the same python version on top of it""" if len(argv) < 1: sys.exit('You must provide a valid virtualenv to target') env = argv[0] path = workon_home / env py = path / env_bin_dir / ('python.exe' if windows else 'python') exact_py = py.resolve().name return check_call([sys.executable, "-m", "virtualenv", str(path.absolute()), "--python=%s" % exact_py])
python
def restore_cmd(argv): """Try to restore a broken virtualenv by reinstalling the same python version on top of it""" if len(argv) < 1: sys.exit('You must provide a valid virtualenv to target') env = argv[0] path = workon_home / env py = path / env_bin_dir / ('python.exe' if windows else 'python') exact_py = py.resolve().name return check_call([sys.executable, "-m", "virtualenv", str(path.absolute()), "--python=%s" % exact_py])
[ "def", "restore_cmd", "(", "argv", ")", ":", "if", "len", "(", "argv", ")", "<", "1", ":", "sys", ".", "exit", "(", "'You must provide a valid virtualenv to target'", ")", "env", "=", "argv", "[", "0", "]", "path", "=", "workon_home", "/", "env", "py", "=", "path", "/", "env_bin_dir", "/", "(", "'python.exe'", "if", "windows", "else", "'python'", ")", "exact_py", "=", "py", ".", "resolve", "(", ")", ".", "name", "return", "check_call", "(", "[", "sys", ".", "executable", ",", "\"-m\"", ",", "\"virtualenv\"", ",", "str", "(", "path", ".", "absolute", "(", ")", ")", ",", "\"--python=%s\"", "%", "exact_py", "]", ")" ]
Try to restore a broken virtualenv by reinstalling the same python version on top of it
[ "Try", "to", "restore", "a", "broken", "virtualenv", "by", "reinstalling", "the", "same", "python", "version", "on", "top", "of", "it" ]
37d9ff79342336b8ef6437d9a551008be07afe9b
https://github.com/berdario/pew/blob/37d9ff79342336b8ef6437d9a551008be07afe9b/pew/pew.py#L674-L685
train
berdario/pew
pew/pew.py
dir_cmd
def dir_cmd(argv): """Print the path for the virtualenv directory""" env = parse_envname(argv, lambda : sys.exit('You must provide a valid virtualenv to target')) print(workon_home / env)
python
def dir_cmd(argv): """Print the path for the virtualenv directory""" env = parse_envname(argv, lambda : sys.exit('You must provide a valid virtualenv to target')) print(workon_home / env)
[ "def", "dir_cmd", "(", "argv", ")", ":", "env", "=", "parse_envname", "(", "argv", ",", "lambda", ":", "sys", ".", "exit", "(", "'You must provide a valid virtualenv to target'", ")", ")", "print", "(", "workon_home", "/", "env", ")" ]
Print the path for the virtualenv directory
[ "Print", "the", "path", "for", "the", "virtualenv", "directory" ]
37d9ff79342336b8ef6437d9a551008be07afe9b
https://github.com/berdario/pew/blob/37d9ff79342336b8ef6437d9a551008be07afe9b/pew/pew.py#L688-L691
train
berdario/pew
pew/pew.py
install_cmd
def install_cmd(argv): '''Use Pythonz to download and build the specified Python version''' installer = InstallCommand() options, versions = installer.parser.parse_args(argv) if len(versions) != 1: installer.parser.print_help() sys.exit(1) else: try: actual_installer = PythonInstaller.get_installer(versions[0], options) return actual_installer.install() except AlreadyInstalledError as e: print(e)
python
def install_cmd(argv): '''Use Pythonz to download and build the specified Python version''' installer = InstallCommand() options, versions = installer.parser.parse_args(argv) if len(versions) != 1: installer.parser.print_help() sys.exit(1) else: try: actual_installer = PythonInstaller.get_installer(versions[0], options) return actual_installer.install() except AlreadyInstalledError as e: print(e)
[ "def", "install_cmd", "(", "argv", ")", ":", "installer", "=", "InstallCommand", "(", ")", "options", ",", "versions", "=", "installer", ".", "parser", ".", "parse_args", "(", "argv", ")", "if", "len", "(", "versions", ")", "!=", "1", ":", "installer", ".", "parser", ".", "print_help", "(", ")", "sys", ".", "exit", "(", "1", ")", "else", ":", "try", ":", "actual_installer", "=", "PythonInstaller", ".", "get_installer", "(", "versions", "[", "0", "]", ",", "options", ")", "return", "actual_installer", ".", "install", "(", ")", "except", "AlreadyInstalledError", "as", "e", ":", "print", "(", "e", ")" ]
Use Pythonz to download and build the specified Python version
[ "Use", "Pythonz", "to", "download", "and", "build", "the", "specified", "Python", "version" ]
37d9ff79342336b8ef6437d9a551008be07afe9b
https://github.com/berdario/pew/blob/37d9ff79342336b8ef6437d9a551008be07afe9b/pew/pew.py#L694-L706
train
berdario/pew
pew/pew.py
version_cmd
def version_cmd(argv): """Prints current pew version""" import pkg_resources try: __version__ = pkg_resources.get_distribution('pew').version except pkg_resources.DistributionNotFound: __version__ = 'unknown' print('Setuptools has some issues here, failed to get our own package.', file=sys.stderr) print(__version__)
python
def version_cmd(argv): """Prints current pew version""" import pkg_resources try: __version__ = pkg_resources.get_distribution('pew').version except pkg_resources.DistributionNotFound: __version__ = 'unknown' print('Setuptools has some issues here, failed to get our own package.', file=sys.stderr) print(__version__)
[ "def", "version_cmd", "(", "argv", ")", ":", "import", "pkg_resources", "try", ":", "__version__", "=", "pkg_resources", ".", "get_distribution", "(", "'pew'", ")", ".", "version", "except", "pkg_resources", ".", "DistributionNotFound", ":", "__version__", "=", "'unknown'", "print", "(", "'Setuptools has some issues here, failed to get our own package.'", ",", "file", "=", "sys", ".", "stderr", ")", "print", "(", "__version__", ")" ]
Prints current pew version
[ "Prints", "current", "pew", "version" ]
37d9ff79342336b8ef6437d9a551008be07afe9b
https://github.com/berdario/pew/blob/37d9ff79342336b8ef6437d9a551008be07afe9b/pew/pew.py#L724-L734
train
peterbe/premailer
premailer/merge_style.py
csstext_to_pairs
def csstext_to_pairs(csstext): """ csstext_to_pairs takes css text and make it to list of tuple of key,value. """ # The lock is required to avoid ``cssutils`` concurrency # issues documented in issue #65 with csstext_to_pairs._lock: return sorted( [ (prop.name.strip(), format_value(prop)) for prop in cssutils.parseStyle(csstext) ], key=itemgetter(0), )
python
def csstext_to_pairs(csstext): """ csstext_to_pairs takes css text and make it to list of tuple of key,value. """ # The lock is required to avoid ``cssutils`` concurrency # issues documented in issue #65 with csstext_to_pairs._lock: return sorted( [ (prop.name.strip(), format_value(prop)) for prop in cssutils.parseStyle(csstext) ], key=itemgetter(0), )
[ "def", "csstext_to_pairs", "(", "csstext", ")", ":", "# The lock is required to avoid ``cssutils`` concurrency", "# issues documented in issue #65", "with", "csstext_to_pairs", ".", "_lock", ":", "return", "sorted", "(", "[", "(", "prop", ".", "name", ".", "strip", "(", ")", ",", "format_value", "(", "prop", ")", ")", "for", "prop", "in", "cssutils", ".", "parseStyle", "(", "csstext", ")", "]", ",", "key", "=", "itemgetter", "(", "0", ")", ",", ")" ]
csstext_to_pairs takes css text and make it to list of tuple of key,value.
[ "csstext_to_pairs", "takes", "css", "text", "and", "make", "it", "to", "list", "of", "tuple", "of", "key", "value", "." ]
4d74656fb12e8e44683fa787ae71c0735282376b
https://github.com/peterbe/premailer/blob/4d74656fb12e8e44683fa787ae71c0735282376b/premailer/merge_style.py#L23-L37
train
peterbe/premailer
premailer/merge_style.py
merge_styles
def merge_styles(inline_style, new_styles, classes, remove_unset_properties=False): """ This will merge all new styles where the order is important The last one will override the first When that is done it will apply old inline style again The old inline style is always important and override all new ones. The inline style must be valid. Args: inline_style(str): the old inline style of the element if there is one new_styles: a list of new styles, each element should be a list of tuple classes: a list of classes which maps new_styles, important! remove_unset_properties(bool): Allow us to remove certain CSS properties with rules that set their value to 'unset' Returns: str: the final style """ # building classes styles = OrderedDict([("", OrderedDict())]) for pc in set(classes): styles[pc] = OrderedDict() for i, style in enumerate(new_styles): for k, v in style: styles[classes[i]][k] = v # keep always the old inline style if inline_style: # inline should be a declaration list as I understand # ie property-name:property-value;... for k, v in csstext_to_pairs(inline_style): styles[""][k] = v normal_styles = [] pseudo_styles = [] for pseudoclass, kv in styles.items(): if remove_unset_properties: # Remove rules that we were going to have value 'unset' because # they effectively are the same as not saying anything about the # property when inlined kv = OrderedDict( (k, v) for (k, v) in kv.items() if not v.lower() == "unset" ) if not kv: continue if pseudoclass: pseudo_styles.append( "%s{%s}" % (pseudoclass, "; ".join("%s:%s" % (k, v) for k, v in kv.items())) ) else: normal_styles.append("; ".join("%s:%s" % (k, v) for k, v in kv.items())) if pseudo_styles: # if we do or code thing correct this should not happen # inline style definition: declarations without braces all_styles = ( (["{%s}" % "".join(normal_styles)] + pseudo_styles) if normal_styles else pseudo_styles ) else: all_styles = normal_styles return " ".join(all_styles).strip()
python
def merge_styles(inline_style, new_styles, classes, remove_unset_properties=False): """ This will merge all new styles where the order is important The last one will override the first When that is done it will apply old inline style again The old inline style is always important and override all new ones. The inline style must be valid. Args: inline_style(str): the old inline style of the element if there is one new_styles: a list of new styles, each element should be a list of tuple classes: a list of classes which maps new_styles, important! remove_unset_properties(bool): Allow us to remove certain CSS properties with rules that set their value to 'unset' Returns: str: the final style """ # building classes styles = OrderedDict([("", OrderedDict())]) for pc in set(classes): styles[pc] = OrderedDict() for i, style in enumerate(new_styles): for k, v in style: styles[classes[i]][k] = v # keep always the old inline style if inline_style: # inline should be a declaration list as I understand # ie property-name:property-value;... for k, v in csstext_to_pairs(inline_style): styles[""][k] = v normal_styles = [] pseudo_styles = [] for pseudoclass, kv in styles.items(): if remove_unset_properties: # Remove rules that we were going to have value 'unset' because # they effectively are the same as not saying anything about the # property when inlined kv = OrderedDict( (k, v) for (k, v) in kv.items() if not v.lower() == "unset" ) if not kv: continue if pseudoclass: pseudo_styles.append( "%s{%s}" % (pseudoclass, "; ".join("%s:%s" % (k, v) for k, v in kv.items())) ) else: normal_styles.append("; ".join("%s:%s" % (k, v) for k, v in kv.items())) if pseudo_styles: # if we do or code thing correct this should not happen # inline style definition: declarations without braces all_styles = ( (["{%s}" % "".join(normal_styles)] + pseudo_styles) if normal_styles else pseudo_styles ) else: all_styles = normal_styles return " ".join(all_styles).strip()
[ "def", "merge_styles", "(", "inline_style", ",", "new_styles", ",", "classes", ",", "remove_unset_properties", "=", "False", ")", ":", "# building classes", "styles", "=", "OrderedDict", "(", "[", "(", "\"\"", ",", "OrderedDict", "(", ")", ")", "]", ")", "for", "pc", "in", "set", "(", "classes", ")", ":", "styles", "[", "pc", "]", "=", "OrderedDict", "(", ")", "for", "i", ",", "style", "in", "enumerate", "(", "new_styles", ")", ":", "for", "k", ",", "v", "in", "style", ":", "styles", "[", "classes", "[", "i", "]", "]", "[", "k", "]", "=", "v", "# keep always the old inline style", "if", "inline_style", ":", "# inline should be a declaration list as I understand", "# ie property-name:property-value;...", "for", "k", ",", "v", "in", "csstext_to_pairs", "(", "inline_style", ")", ":", "styles", "[", "\"\"", "]", "[", "k", "]", "=", "v", "normal_styles", "=", "[", "]", "pseudo_styles", "=", "[", "]", "for", "pseudoclass", ",", "kv", "in", "styles", ".", "items", "(", ")", ":", "if", "remove_unset_properties", ":", "# Remove rules that we were going to have value 'unset' because", "# they effectively are the same as not saying anything about the", "# property when inlined", "kv", "=", "OrderedDict", "(", "(", "k", ",", "v", ")", "for", "(", "k", ",", "v", ")", "in", "kv", ".", "items", "(", ")", "if", "not", "v", ".", "lower", "(", ")", "==", "\"unset\"", ")", "if", "not", "kv", ":", "continue", "if", "pseudoclass", ":", "pseudo_styles", ".", "append", "(", "\"%s{%s}\"", "%", "(", "pseudoclass", ",", "\"; \"", ".", "join", "(", "\"%s:%s\"", "%", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "kv", ".", "items", "(", ")", ")", ")", ")", "else", ":", "normal_styles", ".", "append", "(", "\"; \"", ".", "join", "(", "\"%s:%s\"", "%", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "kv", ".", "items", "(", ")", ")", ")", "if", "pseudo_styles", ":", "# if we do or code thing correct this should not happen", "# inline style definition: declarations without braces", "all_styles", "=", "(", "(", "[", "\"{%s}\"", "%", "\"\"", ".", "join", "(", "normal_styles", ")", "]", "+", "pseudo_styles", ")", "if", "normal_styles", "else", "pseudo_styles", ")", "else", ":", "all_styles", "=", "normal_styles", "return", "\" \"", ".", "join", "(", "all_styles", ")", ".", "strip", "(", ")" ]
This will merge all new styles where the order is important The last one will override the first When that is done it will apply old inline style again The old inline style is always important and override all new ones. The inline style must be valid. Args: inline_style(str): the old inline style of the element if there is one new_styles: a list of new styles, each element should be a list of tuple classes: a list of classes which maps new_styles, important! remove_unset_properties(bool): Allow us to remove certain CSS properties with rules that set their value to 'unset' Returns: str: the final style
[ "This", "will", "merge", "all", "new", "styles", "where", "the", "order", "is", "important", "The", "last", "one", "will", "override", "the", "first", "When", "that", "is", "done", "it", "will", "apply", "old", "inline", "style", "again", "The", "old", "inline", "style", "is", "always", "important", "and", "override", "all", "new", "ones", ".", "The", "inline", "style", "must", "be", "valid", "." ]
4d74656fb12e8e44683fa787ae71c0735282376b
https://github.com/peterbe/premailer/blob/4d74656fb12e8e44683fa787ae71c0735282376b/premailer/merge_style.py#L43-L110
train
peterbe/premailer
premailer/premailer.py
make_important
def make_important(bulk): """makes every property in a string !important. """ return ";".join( "%s !important" % p if not p.endswith("!important") else p for p in bulk.split(";") )
python
def make_important(bulk): """makes every property in a string !important. """ return ";".join( "%s !important" % p if not p.endswith("!important") else p for p in bulk.split(";") )
[ "def", "make_important", "(", "bulk", ")", ":", "return", "\";\"", ".", "join", "(", "\"%s !important\"", "%", "p", "if", "not", "p", ".", "endswith", "(", "\"!important\"", ")", "else", "p", "for", "p", "in", "bulk", ".", "split", "(", "\";\"", ")", ")" ]
makes every property in a string !important.
[ "makes", "every", "property", "in", "a", "string", "!important", "." ]
4d74656fb12e8e44683fa787ae71c0735282376b
https://github.com/peterbe/premailer/blob/4d74656fb12e8e44683fa787ae71c0735282376b/premailer/premailer.py#L53-L59
train
peterbe/premailer
premailer/premailer.py
capitalize_float_margin
def capitalize_float_margin(css_body): """Capitalize float and margin CSS property names """ def _capitalize_property(match): return "{0}:{1}{2}".format( match.group("property").capitalize(), match.group("value"), match.group("terminator"), ) return _lowercase_margin_float_rule.sub(_capitalize_property, css_body)
python
def capitalize_float_margin(css_body): """Capitalize float and margin CSS property names """ def _capitalize_property(match): return "{0}:{1}{2}".format( match.group("property").capitalize(), match.group("value"), match.group("terminator"), ) return _lowercase_margin_float_rule.sub(_capitalize_property, css_body)
[ "def", "capitalize_float_margin", "(", "css_body", ")", ":", "def", "_capitalize_property", "(", "match", ")", ":", "return", "\"{0}:{1}{2}\"", ".", "format", "(", "match", ".", "group", "(", "\"property\"", ")", ".", "capitalize", "(", ")", ",", "match", ".", "group", "(", "\"value\"", ")", ",", "match", ".", "group", "(", "\"terminator\"", ")", ",", ")", "return", "_lowercase_margin_float_rule", ".", "sub", "(", "_capitalize_property", ",", "css_body", ")" ]
Capitalize float and margin CSS property names
[ "Capitalize", "float", "and", "margin", "CSS", "property", "names" ]
4d74656fb12e8e44683fa787ae71c0735282376b
https://github.com/peterbe/premailer/blob/4d74656fb12e8e44683fa787ae71c0735282376b/premailer/premailer.py#L100-L111
train
peterbe/premailer
premailer/premailer.py
Premailer._load_external
def _load_external(self, url): """loads an external stylesheet from a remote url or local path """ if url.startswith("//"): # then we have to rely on the base_url if self.base_url and "https://" in self.base_url: url = "https:" + url else: url = "http:" + url if url.startswith("http://") or url.startswith("https://"): css_body = self._load_external_url(url) else: stylefile = url if not os.path.isabs(stylefile): stylefile = os.path.abspath( os.path.join(self.base_path or "", stylefile) ) if os.path.exists(stylefile): with codecs.open(stylefile, encoding="utf-8") as f: css_body = f.read() elif self.base_url: url = urljoin(self.base_url, url) return self._load_external(url) else: raise ExternalNotFoundError(stylefile) return css_body
python
def _load_external(self, url): """loads an external stylesheet from a remote url or local path """ if url.startswith("//"): # then we have to rely on the base_url if self.base_url and "https://" in self.base_url: url = "https:" + url else: url = "http:" + url if url.startswith("http://") or url.startswith("https://"): css_body = self._load_external_url(url) else: stylefile = url if not os.path.isabs(stylefile): stylefile = os.path.abspath( os.path.join(self.base_path or "", stylefile) ) if os.path.exists(stylefile): with codecs.open(stylefile, encoding="utf-8") as f: css_body = f.read() elif self.base_url: url = urljoin(self.base_url, url) return self._load_external(url) else: raise ExternalNotFoundError(stylefile) return css_body
[ "def", "_load_external", "(", "self", ",", "url", ")", ":", "if", "url", ".", "startswith", "(", "\"//\"", ")", ":", "# then we have to rely on the base_url", "if", "self", ".", "base_url", "and", "\"https://\"", "in", "self", ".", "base_url", ":", "url", "=", "\"https:\"", "+", "url", "else", ":", "url", "=", "\"http:\"", "+", "url", "if", "url", ".", "startswith", "(", "\"http://\"", ")", "or", "url", ".", "startswith", "(", "\"https://\"", ")", ":", "css_body", "=", "self", ".", "_load_external_url", "(", "url", ")", "else", ":", "stylefile", "=", "url", "if", "not", "os", ".", "path", ".", "isabs", "(", "stylefile", ")", ":", "stylefile", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "self", ".", "base_path", "or", "\"\"", ",", "stylefile", ")", ")", "if", "os", ".", "path", ".", "exists", "(", "stylefile", ")", ":", "with", "codecs", ".", "open", "(", "stylefile", ",", "encoding", "=", "\"utf-8\"", ")", "as", "f", ":", "css_body", "=", "f", ".", "read", "(", ")", "elif", "self", ".", "base_url", ":", "url", "=", "urljoin", "(", "self", ".", "base_url", ",", "url", ")", "return", "self", ".", "_load_external", "(", "url", ")", "else", ":", "raise", "ExternalNotFoundError", "(", "stylefile", ")", "return", "css_body" ]
loads an external stylesheet from a remote url or local path
[ "loads", "an", "external", "stylesheet", "from", "a", "remote", "url", "or", "local", "path" ]
4d74656fb12e8e44683fa787ae71c0735282376b
https://github.com/peterbe/premailer/blob/4d74656fb12e8e44683fa787ae71c0735282376b/premailer/premailer.py#L546-L573
train
peterbe/premailer
premailer/premailer.py
Premailer._css_rules_to_string
def _css_rules_to_string(self, rules): """given a list of css rules returns a css string """ lines = [] for item in rules: if isinstance(item, tuple): k, v = item lines.append("%s {%s}" % (k, make_important(v))) # media rule else: for rule in item.cssRules: if isinstance( rule, ( cssutils.css.csscomment.CSSComment, cssutils.css.cssunknownrule.CSSUnknownRule, ), ): continue for key in rule.style.keys(): rule.style[key] = ( rule.style.getPropertyValue(key, False), "!important", ) lines.append(item.cssText) return "\n".join(lines)
python
def _css_rules_to_string(self, rules): """given a list of css rules returns a css string """ lines = [] for item in rules: if isinstance(item, tuple): k, v = item lines.append("%s {%s}" % (k, make_important(v))) # media rule else: for rule in item.cssRules: if isinstance( rule, ( cssutils.css.csscomment.CSSComment, cssutils.css.cssunknownrule.CSSUnknownRule, ), ): continue for key in rule.style.keys(): rule.style[key] = ( rule.style.getPropertyValue(key, False), "!important", ) lines.append(item.cssText) return "\n".join(lines)
[ "def", "_css_rules_to_string", "(", "self", ",", "rules", ")", ":", "lines", "=", "[", "]", "for", "item", "in", "rules", ":", "if", "isinstance", "(", "item", ",", "tuple", ")", ":", "k", ",", "v", "=", "item", "lines", ".", "append", "(", "\"%s {%s}\"", "%", "(", "k", ",", "make_important", "(", "v", ")", ")", ")", "# media rule", "else", ":", "for", "rule", "in", "item", ".", "cssRules", ":", "if", "isinstance", "(", "rule", ",", "(", "cssutils", ".", "css", ".", "csscomment", ".", "CSSComment", ",", "cssutils", ".", "css", ".", "cssunknownrule", ".", "CSSUnknownRule", ",", ")", ",", ")", ":", "continue", "for", "key", "in", "rule", ".", "style", ".", "keys", "(", ")", ":", "rule", ".", "style", "[", "key", "]", "=", "(", "rule", ".", "style", ".", "getPropertyValue", "(", "key", ",", "False", ")", ",", "\"!important\"", ",", ")", "lines", ".", "append", "(", "item", ".", "cssText", ")", "return", "\"\\n\"", ".", "join", "(", "lines", ")" ]
given a list of css rules returns a css string
[ "given", "a", "list", "of", "css", "rules", "returns", "a", "css", "string" ]
4d74656fb12e8e44683fa787ae71c0735282376b
https://github.com/peterbe/premailer/blob/4d74656fb12e8e44683fa787ae71c0735282376b/premailer/premailer.py#L631-L656
train
vatlab/SoS
src/sos/workers.py
WorkerManager.check_workers
def check_workers(self): '''Kill workers that have been pending for a while and check if all workers are alive. ''' if time.time() - self._worker_alive_time > 5: self._worker_alive_time = time.time() # join processes if they are now gone, it should not do anything bad # if the process is still running [worker.join() for worker in self._workers if not worker.is_alive()] self._workers = [ worker for worker in self._workers if worker.is_alive() ] if len(self._workers) < self._num_workers: raise ProcessKilled('One of the workers has been killed.')
python
def check_workers(self): '''Kill workers that have been pending for a while and check if all workers are alive. ''' if time.time() - self._worker_alive_time > 5: self._worker_alive_time = time.time() # join processes if they are now gone, it should not do anything bad # if the process is still running [worker.join() for worker in self._workers if not worker.is_alive()] self._workers = [ worker for worker in self._workers if worker.is_alive() ] if len(self._workers) < self._num_workers: raise ProcessKilled('One of the workers has been killed.')
[ "def", "check_workers", "(", "self", ")", ":", "if", "time", ".", "time", "(", ")", "-", "self", ".", "_worker_alive_time", ">", "5", ":", "self", ".", "_worker_alive_time", "=", "time", ".", "time", "(", ")", "# join processes if they are now gone, it should not do anything bad", "# if the process is still running", "[", "worker", ".", "join", "(", ")", "for", "worker", "in", "self", ".", "_workers", "if", "not", "worker", ".", "is_alive", "(", ")", "]", "self", ".", "_workers", "=", "[", "worker", "for", "worker", "in", "self", ".", "_workers", "if", "worker", ".", "is_alive", "(", ")", "]", "if", "len", "(", "self", ".", "_workers", ")", "<", "self", ".", "_num_workers", ":", "raise", "ProcessKilled", "(", "'One of the workers has been killed.'", ")" ]
Kill workers that have been pending for a while and check if all workers are alive.
[ "Kill", "workers", "that", "have", "been", "pending", "for", "a", "while", "and", "check", "if", "all", "workers", "are", "alive", "." ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/workers.py#L515-L527
train
vatlab/SoS
src/sos/workers.py
WorkerManager.kill_all
def kill_all(self): '''Kill all workers''' while self._num_workers > 0 and self._worker_backend_socket.poll(1000): msg = self._worker_backend_socket.recv_pyobj() self._worker_backend_socket.send_pyobj(None) self._num_workers -= 1 self.report(f'Kill {msg[1:]}') # join all processes [worker.join() for worker in self._workers]
python
def kill_all(self): '''Kill all workers''' while self._num_workers > 0 and self._worker_backend_socket.poll(1000): msg = self._worker_backend_socket.recv_pyobj() self._worker_backend_socket.send_pyobj(None) self._num_workers -= 1 self.report(f'Kill {msg[1:]}') # join all processes [worker.join() for worker in self._workers]
[ "def", "kill_all", "(", "self", ")", ":", "while", "self", ".", "_num_workers", ">", "0", "and", "self", ".", "_worker_backend_socket", ".", "poll", "(", "1000", ")", ":", "msg", "=", "self", ".", "_worker_backend_socket", ".", "recv_pyobj", "(", ")", "self", ".", "_worker_backend_socket", ".", "send_pyobj", "(", "None", ")", "self", ".", "_num_workers", "-=", "1", "self", ".", "report", "(", "f'Kill {msg[1:]}'", ")", "# join all processes", "[", "worker", ".", "join", "(", ")", "for", "worker", "in", "self", ".", "_workers", "]" ]
Kill all workers
[ "Kill", "all", "workers" ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/workers.py#L529-L537
train
vatlab/SoS
src/sos/targets_python.py
Py_Module._install
def _install(self, name, autoinstall): '''Check existence of Python module and install it using command pip install if necessary.''' import importlib import pkg_resources spam_spec = importlib.util.find_spec(name) reinstall = False if spam_spec is not None: if self._version: mod = importlib.__import__(name) if hasattr(mod, '__version__'): ver = mod.__version__ else: try: ver = pkg_resources.get_distribution(name).version except Exception as e: env.logger.debug( f'Failed to get version of {name}: {e}') env.logger.debug( f'Comparing exiting version {ver} against requested version {self._version}' ) if self._version.startswith( '==') and pkg_resources.parse_version( ver) == pkg_resources.parse_version( self._version[2:]): pass elif self._version.startswith( '<=') and pkg_resources.parse_version( ver) <= pkg_resources.parse_version( self._version[2:]): pass elif self._version.startswith( '<') and not self._version.startswith( '<=') and pkg_resources.parse_version( ver) < pkg_resources.parse_version( self._version[1:]): pass elif self._version.startswith( '>=') and pkg_resources.parse_version( ver) >= pkg_resources.parse_version( self._version[2:]): pass # the case of > elif self._version.startswith( '>') and not self._version.startswith( '>=') and pkg_resources.parse_version( ver) > pkg_resources.parse_version( self._version[1:]): pass elif self._version.startswith( '!=') and pkg_resources.parse_version( ver) != pkg_resources.parse_version( self._version[2:]): pass elif self._version[0] not in ( '=', '>', '<', '!') and pkg_resources.parse_version( ver) == pkg_resources.parse_version(self._version): pass else: env.logger.warning( f'Version {ver} of installed {name} does not match specified version {self._version}.' ) reinstall = True if spam_spec and not reinstall: return True if not autoinstall: return False # try to install it? import subprocess cmd = ['pip', 'install'] + ([] if self._version else ['-U']) + [ self._module + (self._version if self._version else '') if self._autoinstall is True else self._autoinstall ] env.logger.info( f'Installing python module {name} with command {" ".join(cmd)}') ret = subprocess.call(cmd) if reinstall: import sys importlib.reload(sys.modules[name]) # try to check version return ret == 0 and self._install(name, False)
python
def _install(self, name, autoinstall): '''Check existence of Python module and install it using command pip install if necessary.''' import importlib import pkg_resources spam_spec = importlib.util.find_spec(name) reinstall = False if spam_spec is not None: if self._version: mod = importlib.__import__(name) if hasattr(mod, '__version__'): ver = mod.__version__ else: try: ver = pkg_resources.get_distribution(name).version except Exception as e: env.logger.debug( f'Failed to get version of {name}: {e}') env.logger.debug( f'Comparing exiting version {ver} against requested version {self._version}' ) if self._version.startswith( '==') and pkg_resources.parse_version( ver) == pkg_resources.parse_version( self._version[2:]): pass elif self._version.startswith( '<=') and pkg_resources.parse_version( ver) <= pkg_resources.parse_version( self._version[2:]): pass elif self._version.startswith( '<') and not self._version.startswith( '<=') and pkg_resources.parse_version( ver) < pkg_resources.parse_version( self._version[1:]): pass elif self._version.startswith( '>=') and pkg_resources.parse_version( ver) >= pkg_resources.parse_version( self._version[2:]): pass # the case of > elif self._version.startswith( '>') and not self._version.startswith( '>=') and pkg_resources.parse_version( ver) > pkg_resources.parse_version( self._version[1:]): pass elif self._version.startswith( '!=') and pkg_resources.parse_version( ver) != pkg_resources.parse_version( self._version[2:]): pass elif self._version[0] not in ( '=', '>', '<', '!') and pkg_resources.parse_version( ver) == pkg_resources.parse_version(self._version): pass else: env.logger.warning( f'Version {ver} of installed {name} does not match specified version {self._version}.' ) reinstall = True if spam_spec and not reinstall: return True if not autoinstall: return False # try to install it? import subprocess cmd = ['pip', 'install'] + ([] if self._version else ['-U']) + [ self._module + (self._version if self._version else '') if self._autoinstall is True else self._autoinstall ] env.logger.info( f'Installing python module {name} with command {" ".join(cmd)}') ret = subprocess.call(cmd) if reinstall: import sys importlib.reload(sys.modules[name]) # try to check version return ret == 0 and self._install(name, False)
[ "def", "_install", "(", "self", ",", "name", ",", "autoinstall", ")", ":", "import", "importlib", "import", "pkg_resources", "spam_spec", "=", "importlib", ".", "util", ".", "find_spec", "(", "name", ")", "reinstall", "=", "False", "if", "spam_spec", "is", "not", "None", ":", "if", "self", ".", "_version", ":", "mod", "=", "importlib", ".", "__import__", "(", "name", ")", "if", "hasattr", "(", "mod", ",", "'__version__'", ")", ":", "ver", "=", "mod", ".", "__version__", "else", ":", "try", ":", "ver", "=", "pkg_resources", ".", "get_distribution", "(", "name", ")", ".", "version", "except", "Exception", "as", "e", ":", "env", ".", "logger", ".", "debug", "(", "f'Failed to get version of {name}: {e}'", ")", "env", ".", "logger", ".", "debug", "(", "f'Comparing exiting version {ver} against requested version {self._version}'", ")", "if", "self", ".", "_version", ".", "startswith", "(", "'=='", ")", "and", "pkg_resources", ".", "parse_version", "(", "ver", ")", "==", "pkg_resources", ".", "parse_version", "(", "self", ".", "_version", "[", "2", ":", "]", ")", ":", "pass", "elif", "self", ".", "_version", ".", "startswith", "(", "'<='", ")", "and", "pkg_resources", ".", "parse_version", "(", "ver", ")", "<=", "pkg_resources", ".", "parse_version", "(", "self", ".", "_version", "[", "2", ":", "]", ")", ":", "pass", "elif", "self", ".", "_version", ".", "startswith", "(", "'<'", ")", "and", "not", "self", ".", "_version", ".", "startswith", "(", "'<='", ")", "and", "pkg_resources", ".", "parse_version", "(", "ver", ")", "<", "pkg_resources", ".", "parse_version", "(", "self", ".", "_version", "[", "1", ":", "]", ")", ":", "pass", "elif", "self", ".", "_version", ".", "startswith", "(", "'>='", ")", "and", "pkg_resources", ".", "parse_version", "(", "ver", ")", ">=", "pkg_resources", ".", "parse_version", "(", "self", ".", "_version", "[", "2", ":", "]", ")", ":", "pass", "# the case of >", "elif", "self", ".", "_version", ".", "startswith", "(", "'>'", ")", "and", "not", "self", ".", "_version", ".", "startswith", "(", "'>='", ")", "and", "pkg_resources", ".", "parse_version", "(", "ver", ")", ">", "pkg_resources", ".", "parse_version", "(", "self", ".", "_version", "[", "1", ":", "]", ")", ":", "pass", "elif", "self", ".", "_version", ".", "startswith", "(", "'!='", ")", "and", "pkg_resources", ".", "parse_version", "(", "ver", ")", "!=", "pkg_resources", ".", "parse_version", "(", "self", ".", "_version", "[", "2", ":", "]", ")", ":", "pass", "elif", "self", ".", "_version", "[", "0", "]", "not", "in", "(", "'='", ",", "'>'", ",", "'<'", ",", "'!'", ")", "and", "pkg_resources", ".", "parse_version", "(", "ver", ")", "==", "pkg_resources", ".", "parse_version", "(", "self", ".", "_version", ")", ":", "pass", "else", ":", "env", ".", "logger", ".", "warning", "(", "f'Version {ver} of installed {name} does not match specified version {self._version}.'", ")", "reinstall", "=", "True", "if", "spam_spec", "and", "not", "reinstall", ":", "return", "True", "if", "not", "autoinstall", ":", "return", "False", "# try to install it?", "import", "subprocess", "cmd", "=", "[", "'pip'", ",", "'install'", "]", "+", "(", "[", "]", "if", "self", ".", "_version", "else", "[", "'-U'", "]", ")", "+", "[", "self", ".", "_module", "+", "(", "self", ".", "_version", "if", "self", ".", "_version", "else", "''", ")", "if", "self", ".", "_autoinstall", "is", "True", "else", "self", ".", "_autoinstall", "]", "env", ".", "logger", ".", "info", "(", "f'Installing python module {name} with command {\" \".join(cmd)}'", ")", "ret", "=", "subprocess", ".", "call", "(", "cmd", ")", "if", "reinstall", ":", "import", "sys", "importlib", ".", "reload", "(", "sys", ".", "modules", "[", "name", "]", ")", "# try to check version", "return", "ret", "==", "0", "and", "self", ".", "_install", "(", "name", ",", "False", ")" ]
Check existence of Python module and install it using command pip install if necessary.
[ "Check", "existence", "of", "Python", "module", "and", "install", "it", "using", "command", "pip", "install", "if", "necessary", "." ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/targets_python.py#L38-L118
train
vatlab/SoS
src/sos/task_executor.py
execute_task
def execute_task(task_id, verbosity=None, runmode='run', sigmode=None, monitor_interval=5, resource_monitor_interval=60): '''Execute single or master task, return a dictionary''' tf = TaskFile(task_id) # this will automatically create a pulse file tf.status = 'running' # write result file try: signal.signal(signal.SIGTERM, signal_handler) res = _execute_task(task_id, verbosity, runmode, sigmode, monitor_interval, resource_monitor_interval) except KeyboardInterrupt: tf.status = 'aborted' raise except ProcessKilled: tf.status = 'aborted' raise ProcessKilled('task interrupted') finally: signal.signal(signal.SIGTERM, signal.SIG_DFL) if res['ret_code'] != 0 and 'exception' in res: with open( os.path.join( os.path.expanduser('~'), '.sos', 'tasks', task_id + '.err'), 'a') as err: err.write(f'Task {task_id} exits with code {res["ret_code"]}') if res.get('skipped', False): # a special mode for skipped to set running time to zero tf.status = 'skipped' else: tf.add_outputs() sig = res.get('signature', {}) res.pop('signature', None) tf.add_result(res) if sig: tf.add_signature(sig) # **after** result file is created, remove other files # # NOTE: if the pulse is not removed. When another sos process checkes # the task is started very quickly so the task has satus 'pending', # the task might be considered already running. tf.status = 'completed' if res['ret_code'] == 0 else 'failed' return res['ret_code']
python
def execute_task(task_id, verbosity=None, runmode='run', sigmode=None, monitor_interval=5, resource_monitor_interval=60): '''Execute single or master task, return a dictionary''' tf = TaskFile(task_id) # this will automatically create a pulse file tf.status = 'running' # write result file try: signal.signal(signal.SIGTERM, signal_handler) res = _execute_task(task_id, verbosity, runmode, sigmode, monitor_interval, resource_monitor_interval) except KeyboardInterrupt: tf.status = 'aborted' raise except ProcessKilled: tf.status = 'aborted' raise ProcessKilled('task interrupted') finally: signal.signal(signal.SIGTERM, signal.SIG_DFL) if res['ret_code'] != 0 and 'exception' in res: with open( os.path.join( os.path.expanduser('~'), '.sos', 'tasks', task_id + '.err'), 'a') as err: err.write(f'Task {task_id} exits with code {res["ret_code"]}') if res.get('skipped', False): # a special mode for skipped to set running time to zero tf.status = 'skipped' else: tf.add_outputs() sig = res.get('signature', {}) res.pop('signature', None) tf.add_result(res) if sig: tf.add_signature(sig) # **after** result file is created, remove other files # # NOTE: if the pulse is not removed. When another sos process checkes # the task is started very quickly so the task has satus 'pending', # the task might be considered already running. tf.status = 'completed' if res['ret_code'] == 0 else 'failed' return res['ret_code']
[ "def", "execute_task", "(", "task_id", ",", "verbosity", "=", "None", ",", "runmode", "=", "'run'", ",", "sigmode", "=", "None", ",", "monitor_interval", "=", "5", ",", "resource_monitor_interval", "=", "60", ")", ":", "tf", "=", "TaskFile", "(", "task_id", ")", "# this will automatically create a pulse file", "tf", ".", "status", "=", "'running'", "# write result file", "try", ":", "signal", ".", "signal", "(", "signal", ".", "SIGTERM", ",", "signal_handler", ")", "res", "=", "_execute_task", "(", "task_id", ",", "verbosity", ",", "runmode", ",", "sigmode", ",", "monitor_interval", ",", "resource_monitor_interval", ")", "except", "KeyboardInterrupt", ":", "tf", ".", "status", "=", "'aborted'", "raise", "except", "ProcessKilled", ":", "tf", ".", "status", "=", "'aborted'", "raise", "ProcessKilled", "(", "'task interrupted'", ")", "finally", ":", "signal", ".", "signal", "(", "signal", ".", "SIGTERM", ",", "signal", ".", "SIG_DFL", ")", "if", "res", "[", "'ret_code'", "]", "!=", "0", "and", "'exception'", "in", "res", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "expanduser", "(", "'~'", ")", ",", "'.sos'", ",", "'tasks'", ",", "task_id", "+", "'.err'", ")", ",", "'a'", ")", "as", "err", ":", "err", ".", "write", "(", "f'Task {task_id} exits with code {res[\"ret_code\"]}'", ")", "if", "res", ".", "get", "(", "'skipped'", ",", "False", ")", ":", "# a special mode for skipped to set running time to zero", "tf", ".", "status", "=", "'skipped'", "else", ":", "tf", ".", "add_outputs", "(", ")", "sig", "=", "res", ".", "get", "(", "'signature'", ",", "{", "}", ")", "res", ".", "pop", "(", "'signature'", ",", "None", ")", "tf", ".", "add_result", "(", "res", ")", "if", "sig", ":", "tf", ".", "add_signature", "(", "sig", ")", "# **after** result file is created, remove other files", "#", "# NOTE: if the pulse is not removed. When another sos process checkes", "# the task is started very quickly so the task has satus 'pending',", "# the task might be considered already running.", "tf", ".", "status", "=", "'completed'", "if", "res", "[", "'ret_code'", "]", "==", "0", "else", "'failed'", "return", "res", "[", "'ret_code'", "]" ]
Execute single or master task, return a dictionary
[ "Execute", "single", "or", "master", "task", "return", "a", "dictionary" ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/task_executor.py#L129-L178
train
vatlab/SoS
src/sos/targets.py
textMD5
def textMD5(text): '''Get md5 of a piece of text''' m = hash_md5() if isinstance(text, str): m.update(text.encode()) else: m.update(text) return m.hexdigest()
python
def textMD5(text): '''Get md5 of a piece of text''' m = hash_md5() if isinstance(text, str): m.update(text.encode()) else: m.update(text) return m.hexdigest()
[ "def", "textMD5", "(", "text", ")", ":", "m", "=", "hash_md5", "(", ")", "if", "isinstance", "(", "text", ",", "str", ")", ":", "m", ".", "update", "(", "text", ".", "encode", "(", ")", ")", "else", ":", "m", ".", "update", "(", "text", ")", "return", "m", ".", "hexdigest", "(", ")" ]
Get md5 of a piece of text
[ "Get", "md5", "of", "a", "piece", "of", "text" ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/targets.py#L89-L96
train
vatlab/SoS
src/sos/targets.py
objectMD5
def objectMD5(obj): '''Get md5 of an object''' if hasattr(obj, 'target_name'): return obj.target_name() try: return textMD5(pickle.dumps(obj)) except: return ''
python
def objectMD5(obj): '''Get md5 of an object''' if hasattr(obj, 'target_name'): return obj.target_name() try: return textMD5(pickle.dumps(obj)) except: return ''
[ "def", "objectMD5", "(", "obj", ")", ":", "if", "hasattr", "(", "obj", ",", "'target_name'", ")", ":", "return", "obj", ".", "target_name", "(", ")", "try", ":", "return", "textMD5", "(", "pickle", ".", "dumps", "(", "obj", ")", ")", "except", ":", "return", "''" ]
Get md5 of an object
[ "Get", "md5", "of", "an", "object" ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/targets.py#L99-L106
train
vatlab/SoS
src/sos/targets.py
fileMD5
def fileMD5(filename, partial=True): '''Calculate partial MD5, basically the first and last 8M of the file for large files. This should signicicantly reduce the time spent on the creation and comparison of file signature when dealing with large bioinformat ics datasets. ''' filesize = os.path.getsize(filename) # calculate md5 for specified file md5 = hash_md5() block_size = 2**20 # buffer of 1M try: # 2**24 = 16M if (not partial) or filesize < 2**24: with open(filename, 'rb') as f: while True: data = f.read(block_size) if not data: break md5.update(data) else: count = 16 # otherwise, use the first and last 8M with open(filename, 'rb') as f: while True: data = f.read(block_size) count -= 1 if count == 8: # 2**23 = 8M f.seek(-2**23, 2) if not data or count == 0: break md5.update(data) except IOError as e: sys.exit(f'Failed to read {filename}: {e}') return md5.hexdigest()
python
def fileMD5(filename, partial=True): '''Calculate partial MD5, basically the first and last 8M of the file for large files. This should signicicantly reduce the time spent on the creation and comparison of file signature when dealing with large bioinformat ics datasets. ''' filesize = os.path.getsize(filename) # calculate md5 for specified file md5 = hash_md5() block_size = 2**20 # buffer of 1M try: # 2**24 = 16M if (not partial) or filesize < 2**24: with open(filename, 'rb') as f: while True: data = f.read(block_size) if not data: break md5.update(data) else: count = 16 # otherwise, use the first and last 8M with open(filename, 'rb') as f: while True: data = f.read(block_size) count -= 1 if count == 8: # 2**23 = 8M f.seek(-2**23, 2) if not data or count == 0: break md5.update(data) except IOError as e: sys.exit(f'Failed to read {filename}: {e}') return md5.hexdigest()
[ "def", "fileMD5", "(", "filename", ",", "partial", "=", "True", ")", ":", "filesize", "=", "os", ".", "path", ".", "getsize", "(", "filename", ")", "# calculate md5 for specified file", "md5", "=", "hash_md5", "(", ")", "block_size", "=", "2", "**", "20", "# buffer of 1M", "try", ":", "# 2**24 = 16M", "if", "(", "not", "partial", ")", "or", "filesize", "<", "2", "**", "24", ":", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "f", ":", "while", "True", ":", "data", "=", "f", ".", "read", "(", "block_size", ")", "if", "not", "data", ":", "break", "md5", ".", "update", "(", "data", ")", "else", ":", "count", "=", "16", "# otherwise, use the first and last 8M", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "f", ":", "while", "True", ":", "data", "=", "f", ".", "read", "(", "block_size", ")", "count", "-=", "1", "if", "count", "==", "8", ":", "# 2**23 = 8M", "f", ".", "seek", "(", "-", "2", "**", "23", ",", "2", ")", "if", "not", "data", "or", "count", "==", "0", ":", "break", "md5", ".", "update", "(", "data", ")", "except", "IOError", "as", "e", ":", "sys", ".", "exit", "(", "f'Failed to read {filename}: {e}'", ")", "return", "md5", ".", "hexdigest", "(", ")" ]
Calculate partial MD5, basically the first and last 8M of the file for large files. This should signicicantly reduce the time spent on the creation and comparison of file signature when dealing with large bioinformat ics datasets.
[ "Calculate", "partial", "MD5", "basically", "the", "first", "and", "last", "8M", "of", "the", "file", "for", "large", "files", ".", "This", "should", "signicicantly", "reduce", "the", "time", "spent", "on", "the", "creation", "and", "comparison", "of", "file", "signature", "when", "dealing", "with", "large", "bioinformat", "ics", "datasets", "." ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/targets.py#L109-L142
train
vatlab/SoS
src/sos/targets.py
file_target.target_signature
def target_signature(self): '''Return file signature''' if self.exists(): if not self._md5: self._md5 = fileMD5(self) return (os.path.getmtime(self), os.path.getsize(self), self._md5) elif (self + '.zapped').is_file(): with open(self + '.zapped') as sig: line = sig.readline() _, mtime, size, md5 = line.strip().rsplit('\t', 3) self._md5 = md5 return (float(mtime), int(size), md5) else: raise ValueError(f'{self} does not exist.')
python
def target_signature(self): '''Return file signature''' if self.exists(): if not self._md5: self._md5 = fileMD5(self) return (os.path.getmtime(self), os.path.getsize(self), self._md5) elif (self + '.zapped').is_file(): with open(self + '.zapped') as sig: line = sig.readline() _, mtime, size, md5 = line.strip().rsplit('\t', 3) self._md5 = md5 return (float(mtime), int(size), md5) else: raise ValueError(f'{self} does not exist.')
[ "def", "target_signature", "(", "self", ")", ":", "if", "self", ".", "exists", "(", ")", ":", "if", "not", "self", ".", "_md5", ":", "self", ".", "_md5", "=", "fileMD5", "(", "self", ")", "return", "(", "os", ".", "path", ".", "getmtime", "(", "self", ")", ",", "os", ".", "path", ".", "getsize", "(", "self", ")", ",", "self", ".", "_md5", ")", "elif", "(", "self", "+", "'.zapped'", ")", ".", "is_file", "(", ")", ":", "with", "open", "(", "self", "+", "'.zapped'", ")", "as", "sig", ":", "line", "=", "sig", ".", "readline", "(", ")", "_", ",", "mtime", ",", "size", ",", "md5", "=", "line", ".", "strip", "(", ")", ".", "rsplit", "(", "'\\t'", ",", "3", ")", "self", ".", "_md5", "=", "md5", "return", "(", "float", "(", "mtime", ")", ",", "int", "(", "size", ")", ",", "md5", ")", "else", ":", "raise", "ValueError", "(", "f'{self} does not exist.'", ")" ]
Return file signature
[ "Return", "file", "signature" ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/targets.py#L747-L760
train
vatlab/SoS
src/sos/targets.py
file_target.validate
def validate(self, sig=None): '''Check if file matches its signature''' if sig is not None: sig_mtime, sig_size, sig_md5 = sig else: try: with open(self.sig_file()) as sig: sig_mtime, sig_size, sig_md5 = sig.read().strip().split() except: return False if not self.exists(): if (self + '.zapped').is_file(): with open(self + '.zapped') as sig: line = sig.readline() return sig_md5 == line.strip().rsplit('\t', 3)[-1] else: return False if sig_mtime == os.path.getmtime(self) and sig_size == os.path.getsize( self): return True return fileMD5(self) == sig_md5
python
def validate(self, sig=None): '''Check if file matches its signature''' if sig is not None: sig_mtime, sig_size, sig_md5 = sig else: try: with open(self.sig_file()) as sig: sig_mtime, sig_size, sig_md5 = sig.read().strip().split() except: return False if not self.exists(): if (self + '.zapped').is_file(): with open(self + '.zapped') as sig: line = sig.readline() return sig_md5 == line.strip().rsplit('\t', 3)[-1] else: return False if sig_mtime == os.path.getmtime(self) and sig_size == os.path.getsize( self): return True return fileMD5(self) == sig_md5
[ "def", "validate", "(", "self", ",", "sig", "=", "None", ")", ":", "if", "sig", "is", "not", "None", ":", "sig_mtime", ",", "sig_size", ",", "sig_md5", "=", "sig", "else", ":", "try", ":", "with", "open", "(", "self", ".", "sig_file", "(", ")", ")", "as", "sig", ":", "sig_mtime", ",", "sig_size", ",", "sig_md5", "=", "sig", ".", "read", "(", ")", ".", "strip", "(", ")", ".", "split", "(", ")", "except", ":", "return", "False", "if", "not", "self", ".", "exists", "(", ")", ":", "if", "(", "self", "+", "'.zapped'", ")", ".", "is_file", "(", ")", ":", "with", "open", "(", "self", "+", "'.zapped'", ")", "as", "sig", ":", "line", "=", "sig", ".", "readline", "(", ")", "return", "sig_md5", "==", "line", ".", "strip", "(", ")", ".", "rsplit", "(", "'\\t'", ",", "3", ")", "[", "-", "1", "]", "else", ":", "return", "False", "if", "sig_mtime", "==", "os", ".", "path", ".", "getmtime", "(", "self", ")", "and", "sig_size", "==", "os", ".", "path", ".", "getsize", "(", "self", ")", ":", "return", "True", "return", "fileMD5", "(", "self", ")", "==", "sig_md5" ]
Check if file matches its signature
[ "Check", "if", "file", "matches", "its", "signature" ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/targets.py#L766-L786
train
vatlab/SoS
src/sos/targets.py
file_target.write_sig
def write_sig(self): '''Write signature to sig store''' if not self._md5: self._md5 = fileMD5(self) with open(self.sig_file(), 'w') as sig: sig.write( f'{os.path.getmtime(self)}\t{os.path.getsize(self)}\t{self._md5}' )
python
def write_sig(self): '''Write signature to sig store''' if not self._md5: self._md5 = fileMD5(self) with open(self.sig_file(), 'w') as sig: sig.write( f'{os.path.getmtime(self)}\t{os.path.getsize(self)}\t{self._md5}' )
[ "def", "write_sig", "(", "self", ")", ":", "if", "not", "self", ".", "_md5", ":", "self", ".", "_md5", "=", "fileMD5", "(", "self", ")", "with", "open", "(", "self", ".", "sig_file", "(", ")", ",", "'w'", ")", "as", "sig", ":", "sig", ".", "write", "(", "f'{os.path.getmtime(self)}\\t{os.path.getsize(self)}\\t{self._md5}'", ")" ]
Write signature to sig store
[ "Write", "signature", "to", "sig", "store" ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/targets.py#L788-L795
train
vatlab/SoS
src/sos/targets.py
sos_targets.remove_targets
def remove_targets(self, type, kept=None): '''Remove targets of certain type''' if kept is None: kept = [ i for i, x in enumerate(self._targets) if not isinstance(x, type) ] if len(kept) == len(self._targets): return self self._targets = [self._targets[x] for x in kept] self._labels = [self._labels[x] for x in kept] if not self._groups: return self index_map = { o_idx: n_idx for n_idx, o_idx in zip(range(len(self._targets)), kept) } kept = set(kept) for idx, grp in enumerate(self._groups): self._groups[idx] = _sos_group( [index_map[x] for x in grp._indexes if x in kept], [y for x, y in zip(grp._indexes, grp._labels) if x in kept ]).set(**grp._dict) return self
python
def remove_targets(self, type, kept=None): '''Remove targets of certain type''' if kept is None: kept = [ i for i, x in enumerate(self._targets) if not isinstance(x, type) ] if len(kept) == len(self._targets): return self self._targets = [self._targets[x] for x in kept] self._labels = [self._labels[x] for x in kept] if not self._groups: return self index_map = { o_idx: n_idx for n_idx, o_idx in zip(range(len(self._targets)), kept) } kept = set(kept) for idx, grp in enumerate(self._groups): self._groups[idx] = _sos_group( [index_map[x] for x in grp._indexes if x in kept], [y for x, y in zip(grp._indexes, grp._labels) if x in kept ]).set(**grp._dict) return self
[ "def", "remove_targets", "(", "self", ",", "type", ",", "kept", "=", "None", ")", ":", "if", "kept", "is", "None", ":", "kept", "=", "[", "i", "for", "i", ",", "x", "in", "enumerate", "(", "self", ".", "_targets", ")", "if", "not", "isinstance", "(", "x", ",", "type", ")", "]", "if", "len", "(", "kept", ")", "==", "len", "(", "self", ".", "_targets", ")", ":", "return", "self", "self", ".", "_targets", "=", "[", "self", ".", "_targets", "[", "x", "]", "for", "x", "in", "kept", "]", "self", ".", "_labels", "=", "[", "self", ".", "_labels", "[", "x", "]", "for", "x", "in", "kept", "]", "if", "not", "self", ".", "_groups", ":", "return", "self", "index_map", "=", "{", "o_idx", ":", "n_idx", "for", "n_idx", ",", "o_idx", "in", "zip", "(", "range", "(", "len", "(", "self", ".", "_targets", ")", ")", ",", "kept", ")", "}", "kept", "=", "set", "(", "kept", ")", "for", "idx", ",", "grp", "in", "enumerate", "(", "self", ".", "_groups", ")", ":", "self", ".", "_groups", "[", "idx", "]", "=", "_sos_group", "(", "[", "index_map", "[", "x", "]", "for", "x", "in", "grp", ".", "_indexes", "if", "x", "in", "kept", "]", ",", "[", "y", "for", "x", ",", "y", "in", "zip", "(", "grp", ".", "_indexes", ",", "grp", ".", "_labels", ")", "if", "x", "in", "kept", "]", ")", ".", "set", "(", "*", "*", "grp", ".", "_dict", ")", "return", "self" ]
Remove targets of certain type
[ "Remove", "targets", "of", "certain", "type" ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/targets.py#L1406-L1429
train
vatlab/SoS
src/sos/targets.py
sos_targets.resolve_remote
def resolve_remote(self): '''If target is of remote type, resolve it''' for idx, target in enumerate(self._targets): if isinstance(target, remote): resolved = target.resolve() if isinstance(resolved, str): resolved = interpolate(resolved, env.sos_dict.dict()) self._targets[idx] = file_target(resolved).set(**target._dict) return self
python
def resolve_remote(self): '''If target is of remote type, resolve it''' for idx, target in enumerate(self._targets): if isinstance(target, remote): resolved = target.resolve() if isinstance(resolved, str): resolved = interpolate(resolved, env.sos_dict.dict()) self._targets[idx] = file_target(resolved).set(**target._dict) return self
[ "def", "resolve_remote", "(", "self", ")", ":", "for", "idx", ",", "target", "in", "enumerate", "(", "self", ".", "_targets", ")", ":", "if", "isinstance", "(", "target", ",", "remote", ")", ":", "resolved", "=", "target", ".", "resolve", "(", ")", "if", "isinstance", "(", "resolved", ",", "str", ")", ":", "resolved", "=", "interpolate", "(", "resolved", ",", "env", ".", "sos_dict", ".", "dict", "(", ")", ")", "self", ".", "_targets", "[", "idx", "]", "=", "file_target", "(", "resolved", ")", ".", "set", "(", "*", "*", "target", ".", "_dict", ")", "return", "self" ]
If target is of remote type, resolve it
[ "If", "target", "is", "of", "remote", "type", "resolve", "it" ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/targets.py#L1431-L1439
train
vatlab/SoS
src/sos/targets.py
sos_targets._handle_paired_with
def _handle_paired_with(self, paired_with): '''Handle input option paired_with''' if paired_with is None or not paired_with: var_name = [] var_value = [] elif isinstance(paired_with, str): var_name = ['_' + paired_with] if paired_with not in env.sos_dict: raise ValueError(f'Variable {paired_with} does not exist.') var_value = [env.sos_dict[paired_with]] elif isinstance(paired_with, dict): var_name = [] var_value = [] for k, v in paired_with.items(): var_name.append(k) var_value.append(v) elif isinstance(paired_with, Iterable): try: var_name = ['_' + x for x in paired_with] except Exception: raise ValueError( f'Invalud value for option paired_with {paired_with}') var_value = [] for vn in var_name: if vn[1:] not in env.sos_dict: raise ValueError(f'Variable {vn[1:]} does not exist.') var_value.append(env.sos_dict[vn[1:]]) else: raise ValueError( f'Unacceptable value for parameter paired_with: {paired_with}') # for vn, vv in zip(var_name, var_value): # set paired with values to step_input self.paired_with(vn, vv)
python
def _handle_paired_with(self, paired_with): '''Handle input option paired_with''' if paired_with is None or not paired_with: var_name = [] var_value = [] elif isinstance(paired_with, str): var_name = ['_' + paired_with] if paired_with not in env.sos_dict: raise ValueError(f'Variable {paired_with} does not exist.') var_value = [env.sos_dict[paired_with]] elif isinstance(paired_with, dict): var_name = [] var_value = [] for k, v in paired_with.items(): var_name.append(k) var_value.append(v) elif isinstance(paired_with, Iterable): try: var_name = ['_' + x for x in paired_with] except Exception: raise ValueError( f'Invalud value for option paired_with {paired_with}') var_value = [] for vn in var_name: if vn[1:] not in env.sos_dict: raise ValueError(f'Variable {vn[1:]} does not exist.') var_value.append(env.sos_dict[vn[1:]]) else: raise ValueError( f'Unacceptable value for parameter paired_with: {paired_with}') # for vn, vv in zip(var_name, var_value): # set paired with values to step_input self.paired_with(vn, vv)
[ "def", "_handle_paired_with", "(", "self", ",", "paired_with", ")", ":", "if", "paired_with", "is", "None", "or", "not", "paired_with", ":", "var_name", "=", "[", "]", "var_value", "=", "[", "]", "elif", "isinstance", "(", "paired_with", ",", "str", ")", ":", "var_name", "=", "[", "'_'", "+", "paired_with", "]", "if", "paired_with", "not", "in", "env", ".", "sos_dict", ":", "raise", "ValueError", "(", "f'Variable {paired_with} does not exist.'", ")", "var_value", "=", "[", "env", ".", "sos_dict", "[", "paired_with", "]", "]", "elif", "isinstance", "(", "paired_with", ",", "dict", ")", ":", "var_name", "=", "[", "]", "var_value", "=", "[", "]", "for", "k", ",", "v", "in", "paired_with", ".", "items", "(", ")", ":", "var_name", ".", "append", "(", "k", ")", "var_value", ".", "append", "(", "v", ")", "elif", "isinstance", "(", "paired_with", ",", "Iterable", ")", ":", "try", ":", "var_name", "=", "[", "'_'", "+", "x", "for", "x", "in", "paired_with", "]", "except", "Exception", ":", "raise", "ValueError", "(", "f'Invalud value for option paired_with {paired_with}'", ")", "var_value", "=", "[", "]", "for", "vn", "in", "var_name", ":", "if", "vn", "[", "1", ":", "]", "not", "in", "env", ".", "sos_dict", ":", "raise", "ValueError", "(", "f'Variable {vn[1:]} does not exist.'", ")", "var_value", ".", "append", "(", "env", ".", "sos_dict", "[", "vn", "[", "1", ":", "]", "]", ")", "else", ":", "raise", "ValueError", "(", "f'Unacceptable value for parameter paired_with: {paired_with}'", ")", "#", "for", "vn", ",", "vv", "in", "zip", "(", "var_name", ",", "var_value", ")", ":", "# set paired with values to step_input", "self", ".", "paired_with", "(", "vn", ",", "vv", ")" ]
Handle input option paired_with
[ "Handle", "input", "option", "paired_with" ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/targets.py#L1685-L1718
train
vatlab/SoS
src/sos/targets.py
sos_targets._handle_group_with
def _handle_group_with(self, group_with): '''Handle input option group_with''' if group_with is None or not group_with: var_name = [] var_value = [] elif isinstance(group_with, str): var_name = ['_' + group_with] if group_with not in env.sos_dict: raise ValueError(f'Variable {group_with} does not exist.') var_value = [env.sos_dict[group_with]] elif isinstance(group_with, dict): var_name = [] var_value = [] for k, v in group_with.items(): var_name.append(k) var_value.append(v) elif isinstance(group_with, Iterable): try: var_name = ['_' + x for x in group_with] except Exception: raise ValueError( f'Invalud value for option group_with {group_with}') var_value = [] for vn in var_name: if vn[1:] not in env.sos_dict: raise ValueError(f'Variable {vn[1:]} does not exist.') var_value.append(env.sos_dict[vn[1:]]) else: raise ValueError( f'Unacceptable value for parameter group_with: {group_with}') # for vn, vv in zip(var_name, var_value): self.group_with(vn, vv)
python
def _handle_group_with(self, group_with): '''Handle input option group_with''' if group_with is None or not group_with: var_name = [] var_value = [] elif isinstance(group_with, str): var_name = ['_' + group_with] if group_with not in env.sos_dict: raise ValueError(f'Variable {group_with} does not exist.') var_value = [env.sos_dict[group_with]] elif isinstance(group_with, dict): var_name = [] var_value = [] for k, v in group_with.items(): var_name.append(k) var_value.append(v) elif isinstance(group_with, Iterable): try: var_name = ['_' + x for x in group_with] except Exception: raise ValueError( f'Invalud value for option group_with {group_with}') var_value = [] for vn in var_name: if vn[1:] not in env.sos_dict: raise ValueError(f'Variable {vn[1:]} does not exist.') var_value.append(env.sos_dict[vn[1:]]) else: raise ValueError( f'Unacceptable value for parameter group_with: {group_with}') # for vn, vv in zip(var_name, var_value): self.group_with(vn, vv)
[ "def", "_handle_group_with", "(", "self", ",", "group_with", ")", ":", "if", "group_with", "is", "None", "or", "not", "group_with", ":", "var_name", "=", "[", "]", "var_value", "=", "[", "]", "elif", "isinstance", "(", "group_with", ",", "str", ")", ":", "var_name", "=", "[", "'_'", "+", "group_with", "]", "if", "group_with", "not", "in", "env", ".", "sos_dict", ":", "raise", "ValueError", "(", "f'Variable {group_with} does not exist.'", ")", "var_value", "=", "[", "env", ".", "sos_dict", "[", "group_with", "]", "]", "elif", "isinstance", "(", "group_with", ",", "dict", ")", ":", "var_name", "=", "[", "]", "var_value", "=", "[", "]", "for", "k", ",", "v", "in", "group_with", ".", "items", "(", ")", ":", "var_name", ".", "append", "(", "k", ")", "var_value", ".", "append", "(", "v", ")", "elif", "isinstance", "(", "group_with", ",", "Iterable", ")", ":", "try", ":", "var_name", "=", "[", "'_'", "+", "x", "for", "x", "in", "group_with", "]", "except", "Exception", ":", "raise", "ValueError", "(", "f'Invalud value for option group_with {group_with}'", ")", "var_value", "=", "[", "]", "for", "vn", "in", "var_name", ":", "if", "vn", "[", "1", ":", "]", "not", "in", "env", ".", "sos_dict", ":", "raise", "ValueError", "(", "f'Variable {vn[1:]} does not exist.'", ")", "var_value", ".", "append", "(", "env", ".", "sos_dict", "[", "vn", "[", "1", ":", "]", "]", ")", "else", ":", "raise", "ValueError", "(", "f'Unacceptable value for parameter group_with: {group_with}'", ")", "#", "for", "vn", ",", "vv", "in", "zip", "(", "var_name", ",", "var_value", ")", ":", "self", ".", "group_with", "(", "vn", ",", "vv", ")" ]
Handle input option group_with
[ "Handle", "input", "option", "group_with" ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/targets.py#L1720-L1752
train
vatlab/SoS
src/sos/targets.py
sos_targets._handle_extract_pattern
def _handle_extract_pattern(self, pattern): '''Handle input option pattern''' if pattern is None or not pattern: patterns = [] elif isinstance(pattern, str): patterns = [pattern] elif isinstance(pattern, Iterable): patterns = pattern else: raise ValueError( f'Unacceptable value for parameter pattern: {pattern}') # for pattern in patterns: res = extract_pattern(pattern, self._targets) self.set(**res) # also make k, v pair with _input self._handle_paired_with({'_' + x: y for x, y in res.items()})
python
def _handle_extract_pattern(self, pattern): '''Handle input option pattern''' if pattern is None or not pattern: patterns = [] elif isinstance(pattern, str): patterns = [pattern] elif isinstance(pattern, Iterable): patterns = pattern else: raise ValueError( f'Unacceptable value for parameter pattern: {pattern}') # for pattern in patterns: res = extract_pattern(pattern, self._targets) self.set(**res) # also make k, v pair with _input self._handle_paired_with({'_' + x: y for x, y in res.items()})
[ "def", "_handle_extract_pattern", "(", "self", ",", "pattern", ")", ":", "if", "pattern", "is", "None", "or", "not", "pattern", ":", "patterns", "=", "[", "]", "elif", "isinstance", "(", "pattern", ",", "str", ")", ":", "patterns", "=", "[", "pattern", "]", "elif", "isinstance", "(", "pattern", ",", "Iterable", ")", ":", "patterns", "=", "pattern", "else", ":", "raise", "ValueError", "(", "f'Unacceptable value for parameter pattern: {pattern}'", ")", "#", "for", "pattern", "in", "patterns", ":", "res", "=", "extract_pattern", "(", "pattern", ",", "self", ".", "_targets", ")", "self", ".", "set", "(", "*", "*", "res", ")", "# also make k, v pair with _input", "self", ".", "_handle_paired_with", "(", "{", "'_'", "+", "x", ":", "y", "for", "x", ",", "y", "in", "res", ".", "items", "(", ")", "}", ")" ]
Handle input option pattern
[ "Handle", "input", "option", "pattern" ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/targets.py#L1754-L1770
train
vatlab/SoS
src/sos/targets.py
RuntimeInfo.write
def write(self): '''Write signature file with signature of script, input, output and dependent files. Because local input and output files can only be determined after the execution of workflow. They are not part of the construction. ''' if not self.output_files.valid(): raise ValueError( f'Cannot write signature with undetermined output {self.output_files}' ) else: if 'TARGET' in env.config['SOS_DEBUG'] or 'ALL' in env.config['SOS_DEBUG']: env.log_to_file( 'TARGET', f'write signature {self.sig_id} with output {self.output_files}' ) ret = super(RuntimeInfo, self).write() if ret is False: env.logger.debug(f'Failed to write signature {self.sig_id}') return ret send_message_to_controller(['step_sig', self.sig_id, ret]) send_message_to_controller([ 'workflow_sig', 'tracked_files', self.sig_id, repr({ 'input_files': [ str(f.resolve()) for f in self.input_files if isinstance(f, file_target) ], 'dependent_files': [ str(f.resolve()) for f in self.dependent_files if isinstance(f, file_target) ], 'output_files': [ str(f.resolve()) for f in self.output_files if isinstance(f, file_target) ] }) ]) return True
python
def write(self): '''Write signature file with signature of script, input, output and dependent files. Because local input and output files can only be determined after the execution of workflow. They are not part of the construction. ''' if not self.output_files.valid(): raise ValueError( f'Cannot write signature with undetermined output {self.output_files}' ) else: if 'TARGET' in env.config['SOS_DEBUG'] or 'ALL' in env.config['SOS_DEBUG']: env.log_to_file( 'TARGET', f'write signature {self.sig_id} with output {self.output_files}' ) ret = super(RuntimeInfo, self).write() if ret is False: env.logger.debug(f'Failed to write signature {self.sig_id}') return ret send_message_to_controller(['step_sig', self.sig_id, ret]) send_message_to_controller([ 'workflow_sig', 'tracked_files', self.sig_id, repr({ 'input_files': [ str(f.resolve()) for f in self.input_files if isinstance(f, file_target) ], 'dependent_files': [ str(f.resolve()) for f in self.dependent_files if isinstance(f, file_target) ], 'output_files': [ str(f.resolve()) for f in self.output_files if isinstance(f, file_target) ] }) ]) return True
[ "def", "write", "(", "self", ")", ":", "if", "not", "self", ".", "output_files", ".", "valid", "(", ")", ":", "raise", "ValueError", "(", "f'Cannot write signature with undetermined output {self.output_files}'", ")", "else", ":", "if", "'TARGET'", "in", "env", ".", "config", "[", "'SOS_DEBUG'", "]", "or", "'ALL'", "in", "env", ".", "config", "[", "'SOS_DEBUG'", "]", ":", "env", ".", "log_to_file", "(", "'TARGET'", ",", "f'write signature {self.sig_id} with output {self.output_files}'", ")", "ret", "=", "super", "(", "RuntimeInfo", ",", "self", ")", ".", "write", "(", ")", "if", "ret", "is", "False", ":", "env", ".", "logger", ".", "debug", "(", "f'Failed to write signature {self.sig_id}'", ")", "return", "ret", "send_message_to_controller", "(", "[", "'step_sig'", ",", "self", ".", "sig_id", ",", "ret", "]", ")", "send_message_to_controller", "(", "[", "'workflow_sig'", ",", "'tracked_files'", ",", "self", ".", "sig_id", ",", "repr", "(", "{", "'input_files'", ":", "[", "str", "(", "f", ".", "resolve", "(", ")", ")", "for", "f", "in", "self", ".", "input_files", "if", "isinstance", "(", "f", ",", "file_target", ")", "]", ",", "'dependent_files'", ":", "[", "str", "(", "f", ".", "resolve", "(", ")", ")", "for", "f", "in", "self", ".", "dependent_files", "if", "isinstance", "(", "f", ",", "file_target", ")", "]", ",", "'output_files'", ":", "[", "str", "(", "f", ".", "resolve", "(", ")", ")", "for", "f", "in", "self", ".", "output_files", "if", "isinstance", "(", "f", ",", "file_target", ")", "]", "}", ")", "]", ")", "return", "True" ]
Write signature file with signature of script, input, output and dependent files. Because local input and output files can only be determined after the execution of workflow. They are not part of the construction.
[ "Write", "signature", "file", "with", "signature", "of", "script", "input", "output", "and", "dependent", "files", ".", "Because", "local", "input", "and", "output", "files", "can", "only", "be", "determined", "after", "the", "execution", "of", "workflow", ".", "They", "are", "not", "part", "of", "the", "construction", "." ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/targets.py#L2219-L2259
train
vatlab/SoS
src/sos/executor_utils.py
clear_output
def clear_output(output=None): ''' Remove file targets in `_output` when a step fails to complete ''' for target in env.sos_dict['_output'] if output is None else output: if isinstance(target, file_target) and target.exists(): try: target.unlink() except Exception as e: env.logger.warning(f'Failed to remove {target}: {e}')
python
def clear_output(output=None): ''' Remove file targets in `_output` when a step fails to complete ''' for target in env.sos_dict['_output'] if output is None else output: if isinstance(target, file_target) and target.exists(): try: target.unlink() except Exception as e: env.logger.warning(f'Failed to remove {target}: {e}')
[ "def", "clear_output", "(", "output", "=", "None", ")", ":", "for", "target", "in", "env", ".", "sos_dict", "[", "'_output'", "]", "if", "output", "is", "None", "else", "output", ":", "if", "isinstance", "(", "target", ",", "file_target", ")", "and", "target", ".", "exists", "(", ")", ":", "try", ":", "target", ".", "unlink", "(", ")", "except", "Exception", "as", "e", ":", "env", ".", "logger", ".", "warning", "(", "f'Failed to remove {target}: {e}'", ")" ]
Remove file targets in `_output` when a step fails to complete
[ "Remove", "file", "targets", "in", "_output", "when", "a", "step", "fails", "to", "complete" ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/executor_utils.py#L121-L130
train
vatlab/SoS
src/sos/workflow_executor.py
Base_Executor.add_forward_workflow
def add_forward_workflow(self, dag, sections, satisfies=None): '''Add a forward-workflow, return number of nodes added ''' dag.new_forward_workflow() if 'DAG' in env.config['SOS_DEBUG'] or 'ALL' in env.config['SOS_DEBUG']: env.log_to_file( 'DAG', f'Adding mini-workflow with {len(sections)} sections') default_input: sos_targets = sos_targets([]) for idx, section in enumerate(sections): # res = analyze_section(section, default_input=default_input) environ_vars = res['environ_vars'] signature_vars = res['signature_vars'] changed_vars = res['changed_vars'] # parameters, if used in the step, should be considered environmental environ_vars |= env.parameter_vars & signature_vars # add shared to targets if res['changed_vars']: if 'provides' in section.options: if isinstance(section.options['provides'], str): section.options.set('provides', [section.options['provides']]) else: section.options.set('provides', []) # section.options.set( 'provides', section.options['provides'] + [sos_variable(var) for var in changed_vars]) context = { '__signature_vars__': signature_vars, '__environ_vars__': environ_vars, '__changed_vars__': changed_vars, '__dynamic_depends__': res['dynamic_depends'], '__dynamic_input__': res['dynamic_input'] } # for nested workflow, the input is specified by sos_run, not None. if idx == 0: context['__step_output__'] = env.sos_dict['__step_output__'] # can be the only step if idx == len(sections) - 1 and satisfies is not None: res['step_output'].extend(satisfies) dag.add_step( section.uuid, section.step_name(), idx, res['step_input'], res['step_depends'], res['step_output'], context=context) default_input = res['step_output'] return len(sections)
python
def add_forward_workflow(self, dag, sections, satisfies=None): '''Add a forward-workflow, return number of nodes added ''' dag.new_forward_workflow() if 'DAG' in env.config['SOS_DEBUG'] or 'ALL' in env.config['SOS_DEBUG']: env.log_to_file( 'DAG', f'Adding mini-workflow with {len(sections)} sections') default_input: sos_targets = sos_targets([]) for idx, section in enumerate(sections): # res = analyze_section(section, default_input=default_input) environ_vars = res['environ_vars'] signature_vars = res['signature_vars'] changed_vars = res['changed_vars'] # parameters, if used in the step, should be considered environmental environ_vars |= env.parameter_vars & signature_vars # add shared to targets if res['changed_vars']: if 'provides' in section.options: if isinstance(section.options['provides'], str): section.options.set('provides', [section.options['provides']]) else: section.options.set('provides', []) # section.options.set( 'provides', section.options['provides'] + [sos_variable(var) for var in changed_vars]) context = { '__signature_vars__': signature_vars, '__environ_vars__': environ_vars, '__changed_vars__': changed_vars, '__dynamic_depends__': res['dynamic_depends'], '__dynamic_input__': res['dynamic_input'] } # for nested workflow, the input is specified by sos_run, not None. if idx == 0: context['__step_output__'] = env.sos_dict['__step_output__'] # can be the only step if idx == len(sections) - 1 and satisfies is not None: res['step_output'].extend(satisfies) dag.add_step( section.uuid, section.step_name(), idx, res['step_input'], res['step_depends'], res['step_output'], context=context) default_input = res['step_output'] return len(sections)
[ "def", "add_forward_workflow", "(", "self", ",", "dag", ",", "sections", ",", "satisfies", "=", "None", ")", ":", "dag", ".", "new_forward_workflow", "(", ")", "if", "'DAG'", "in", "env", ".", "config", "[", "'SOS_DEBUG'", "]", "or", "'ALL'", "in", "env", ".", "config", "[", "'SOS_DEBUG'", "]", ":", "env", ".", "log_to_file", "(", "'DAG'", ",", "f'Adding mini-workflow with {len(sections)} sections'", ")", "default_input", ":", "sos_targets", "=", "sos_targets", "(", "[", "]", ")", "for", "idx", ",", "section", "in", "enumerate", "(", "sections", ")", ":", "#", "res", "=", "analyze_section", "(", "section", ",", "default_input", "=", "default_input", ")", "environ_vars", "=", "res", "[", "'environ_vars'", "]", "signature_vars", "=", "res", "[", "'signature_vars'", "]", "changed_vars", "=", "res", "[", "'changed_vars'", "]", "# parameters, if used in the step, should be considered environmental", "environ_vars", "|=", "env", ".", "parameter_vars", "&", "signature_vars", "# add shared to targets", "if", "res", "[", "'changed_vars'", "]", ":", "if", "'provides'", "in", "section", ".", "options", ":", "if", "isinstance", "(", "section", ".", "options", "[", "'provides'", "]", ",", "str", ")", ":", "section", ".", "options", ".", "set", "(", "'provides'", ",", "[", "section", ".", "options", "[", "'provides'", "]", "]", ")", "else", ":", "section", ".", "options", ".", "set", "(", "'provides'", ",", "[", "]", ")", "#", "section", ".", "options", ".", "set", "(", "'provides'", ",", "section", ".", "options", "[", "'provides'", "]", "+", "[", "sos_variable", "(", "var", ")", "for", "var", "in", "changed_vars", "]", ")", "context", "=", "{", "'__signature_vars__'", ":", "signature_vars", ",", "'__environ_vars__'", ":", "environ_vars", ",", "'__changed_vars__'", ":", "changed_vars", ",", "'__dynamic_depends__'", ":", "res", "[", "'dynamic_depends'", "]", ",", "'__dynamic_input__'", ":", "res", "[", "'dynamic_input'", "]", "}", "# for nested workflow, the input is specified by sos_run, not None.", "if", "idx", "==", "0", ":", "context", "[", "'__step_output__'", "]", "=", "env", ".", "sos_dict", "[", "'__step_output__'", "]", "# can be the only step", "if", "idx", "==", "len", "(", "sections", ")", "-", "1", "and", "satisfies", "is", "not", "None", ":", "res", "[", "'step_output'", "]", ".", "extend", "(", "satisfies", ")", "dag", ".", "add_step", "(", "section", ".", "uuid", ",", "section", ".", "step_name", "(", ")", ",", "idx", ",", "res", "[", "'step_input'", "]", ",", "res", "[", "'step_depends'", "]", ",", "res", "[", "'step_output'", "]", ",", "context", "=", "context", ")", "default_input", "=", "res", "[", "'step_output'", "]", "return", "len", "(", "sections", ")" ]
Add a forward-workflow, return number of nodes added
[ "Add", "a", "forward", "-", "workflow", "return", "number", "of", "nodes", "added" ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/workflow_executor.py#L702-L758
train
vatlab/SoS
src/sos/workflow_executor.py
Base_Executor.initialize_dag
def initialize_dag(self, targets: Optional[List[str]] = [], nested: bool = False) -> SoS_DAG: '''Create a DAG by analyzing sections statically.''' self.reset_dict() dag = SoS_DAG(name=self.md5) targets = sos_targets(targets) self.add_forward_workflow(dag, self.workflow.sections) # if self.resolve_dangling_targets(dag, targets) == 0: if targets: raise UnknownTarget(f'No step to generate target {targets}.') # now, there should be no dangling targets, let us connect nodes dag.build() # dag.show_nodes() # trim the DAG if targets are specified if targets: dag = dag.subgraph_from(targets) # check error cycle = dag.circular_dependencies() if cycle: raise RuntimeError( f'Circular dependency detected {cycle}. It is likely a later step produces input of a previous step.' ) dag.save(env.config['output_dag']) return dag
python
def initialize_dag(self, targets: Optional[List[str]] = [], nested: bool = False) -> SoS_DAG: '''Create a DAG by analyzing sections statically.''' self.reset_dict() dag = SoS_DAG(name=self.md5) targets = sos_targets(targets) self.add_forward_workflow(dag, self.workflow.sections) # if self.resolve_dangling_targets(dag, targets) == 0: if targets: raise UnknownTarget(f'No step to generate target {targets}.') # now, there should be no dangling targets, let us connect nodes dag.build() # dag.show_nodes() # trim the DAG if targets are specified if targets: dag = dag.subgraph_from(targets) # check error cycle = dag.circular_dependencies() if cycle: raise RuntimeError( f'Circular dependency detected {cycle}. It is likely a later step produces input of a previous step.' ) dag.save(env.config['output_dag']) return dag
[ "def", "initialize_dag", "(", "self", ",", "targets", ":", "Optional", "[", "List", "[", "str", "]", "]", "=", "[", "]", ",", "nested", ":", "bool", "=", "False", ")", "->", "SoS_DAG", ":", "self", ".", "reset_dict", "(", ")", "dag", "=", "SoS_DAG", "(", "name", "=", "self", ".", "md5", ")", "targets", "=", "sos_targets", "(", "targets", ")", "self", ".", "add_forward_workflow", "(", "dag", ",", "self", ".", "workflow", ".", "sections", ")", "#", "if", "self", ".", "resolve_dangling_targets", "(", "dag", ",", "targets", ")", "==", "0", ":", "if", "targets", ":", "raise", "UnknownTarget", "(", "f'No step to generate target {targets}.'", ")", "# now, there should be no dangling targets, let us connect nodes", "dag", ".", "build", "(", ")", "# dag.show_nodes()", "# trim the DAG if targets are specified", "if", "targets", ":", "dag", "=", "dag", ".", "subgraph_from", "(", "targets", ")", "# check error", "cycle", "=", "dag", ".", "circular_dependencies", "(", ")", "if", "cycle", ":", "raise", "RuntimeError", "(", "f'Circular dependency detected {cycle}. It is likely a later step produces input of a previous step.'", ")", "dag", ".", "save", "(", "env", ".", "config", "[", "'output_dag'", "]", ")", "return", "dag" ]
Create a DAG by analyzing sections statically.
[ "Create", "a", "DAG", "by", "analyzing", "sections", "statically", "." ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/workflow_executor.py#L831-L859
train
vatlab/SoS
src/sos/utils.py
short_repr
def short_repr(obj, noneAsNA=False): '''Return a short representation of obj for clarity.''' if obj is None: return 'unspecified' if noneAsNA else 'None' elif isinstance(obj, str) and len(obj) > 80: return '{}...{}'.format(obj[:60].replace('\n', '\\n'), obj[-20:].replace('\n', '\\n')) elif isinstance(obj, (str, int, float, bool)): return repr(obj) elif hasattr(obj, '__short_repr__'): return obj.__short_repr__() elif isinstance(obj, Sequence): # should be a list or tuple if len(obj) == 0: return '[]' elif len(obj) == 1: return f'{short_repr(obj[0])}' elif len(obj) == 2: return f'{short_repr(obj[0])}, {short_repr(obj[1])}' else: return f'{short_repr(obj[0])}, {short_repr(obj[1])}, ... ({len(obj)} items)' elif isinstance(obj, dict): if not obj: return '' elif len(obj) == 1: first_key = list(obj.keys())[0] return f'{short_repr(first_key)!r}:{short_repr(obj[first_key])!r}' else: first_key = list(obj.keys())[0] return f'{short_repr(first_key)}:{short_repr(obj[first_key])}, ... ({len(obj)} items)' elif isinstance(obj, KeysView): if not obj: return '' elif len(obj) == 1: return short_repr(next(iter(obj))) else: return f'{short_repr(next(iter(obj)))}, ... ({len(obj)} items)' #elif hasattr(obj, 'target_name'): # return obj.target_name() else: ret = str(obj) if len(ret) > 40: return f'{repr(obj)[:35]}...' else: return ret
python
def short_repr(obj, noneAsNA=False): '''Return a short representation of obj for clarity.''' if obj is None: return 'unspecified' if noneAsNA else 'None' elif isinstance(obj, str) and len(obj) > 80: return '{}...{}'.format(obj[:60].replace('\n', '\\n'), obj[-20:].replace('\n', '\\n')) elif isinstance(obj, (str, int, float, bool)): return repr(obj) elif hasattr(obj, '__short_repr__'): return obj.__short_repr__() elif isinstance(obj, Sequence): # should be a list or tuple if len(obj) == 0: return '[]' elif len(obj) == 1: return f'{short_repr(obj[0])}' elif len(obj) == 2: return f'{short_repr(obj[0])}, {short_repr(obj[1])}' else: return f'{short_repr(obj[0])}, {short_repr(obj[1])}, ... ({len(obj)} items)' elif isinstance(obj, dict): if not obj: return '' elif len(obj) == 1: first_key = list(obj.keys())[0] return f'{short_repr(first_key)!r}:{short_repr(obj[first_key])!r}' else: first_key = list(obj.keys())[0] return f'{short_repr(first_key)}:{short_repr(obj[first_key])}, ... ({len(obj)} items)' elif isinstance(obj, KeysView): if not obj: return '' elif len(obj) == 1: return short_repr(next(iter(obj))) else: return f'{short_repr(next(iter(obj)))}, ... ({len(obj)} items)' #elif hasattr(obj, 'target_name'): # return obj.target_name() else: ret = str(obj) if len(ret) > 40: return f'{repr(obj)[:35]}...' else: return ret
[ "def", "short_repr", "(", "obj", ",", "noneAsNA", "=", "False", ")", ":", "if", "obj", "is", "None", ":", "return", "'unspecified'", "if", "noneAsNA", "else", "'None'", "elif", "isinstance", "(", "obj", ",", "str", ")", "and", "len", "(", "obj", ")", ">", "80", ":", "return", "'{}...{}'", ".", "format", "(", "obj", "[", ":", "60", "]", ".", "replace", "(", "'\\n'", ",", "'\\\\n'", ")", ",", "obj", "[", "-", "20", ":", "]", ".", "replace", "(", "'\\n'", ",", "'\\\\n'", ")", ")", "elif", "isinstance", "(", "obj", ",", "(", "str", ",", "int", ",", "float", ",", "bool", ")", ")", ":", "return", "repr", "(", "obj", ")", "elif", "hasattr", "(", "obj", ",", "'__short_repr__'", ")", ":", "return", "obj", ".", "__short_repr__", "(", ")", "elif", "isinstance", "(", "obj", ",", "Sequence", ")", ":", "# should be a list or tuple", "if", "len", "(", "obj", ")", "==", "0", ":", "return", "'[]'", "elif", "len", "(", "obj", ")", "==", "1", ":", "return", "f'{short_repr(obj[0])}'", "elif", "len", "(", "obj", ")", "==", "2", ":", "return", "f'{short_repr(obj[0])}, {short_repr(obj[1])}'", "else", ":", "return", "f'{short_repr(obj[0])}, {short_repr(obj[1])}, ... ({len(obj)} items)'", "elif", "isinstance", "(", "obj", ",", "dict", ")", ":", "if", "not", "obj", ":", "return", "''", "elif", "len", "(", "obj", ")", "==", "1", ":", "first_key", "=", "list", "(", "obj", ".", "keys", "(", ")", ")", "[", "0", "]", "return", "f'{short_repr(first_key)!r}:{short_repr(obj[first_key])!r}'", "else", ":", "first_key", "=", "list", "(", "obj", ".", "keys", "(", ")", ")", "[", "0", "]", "return", "f'{short_repr(first_key)}:{short_repr(obj[first_key])}, ... ({len(obj)} items)'", "elif", "isinstance", "(", "obj", ",", "KeysView", ")", ":", "if", "not", "obj", ":", "return", "''", "elif", "len", "(", "obj", ")", "==", "1", ":", "return", "short_repr", "(", "next", "(", "iter", "(", "obj", ")", ")", ")", "else", ":", "return", "f'{short_repr(next(iter(obj)))}, ... ({len(obj)} items)'", "#elif hasattr(obj, 'target_name'):", "# return obj.target_name()", "else", ":", "ret", "=", "str", "(", "obj", ")", "if", "len", "(", "ret", ")", ">", "40", ":", "return", "f'{repr(obj)[:35]}...'", "else", ":", "return", "ret" ]
Return a short representation of obj for clarity.
[ "Return", "a", "short", "representation", "of", "obj", "for", "clarity", "." ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/utils.py#L138-L181
train
vatlab/SoS
src/sos/utils.py
tail_of_file
def tail_of_file(filename, n, ansi2html=False): """Reads a n lines from f with an offset of offset lines. """ avg_line_length = 74 to_read = n with open(filename) as f: while 1: try: f.seek(-(avg_line_length * to_read), 2) except IOError: # woops. apparently file is smaller than what we want # to step back, go to the beginning instead f.seek(0) pos = f.tell() lines = f.read().splitlines() if len(lines) >= to_read or pos == 0: if ansi2html: return convertAnsi2html('\n'.join(lines[-to_read:])) return '\n'.join(lines[-to_read:]) + '\n' avg_line_length *= 1.3
python
def tail_of_file(filename, n, ansi2html=False): """Reads a n lines from f with an offset of offset lines. """ avg_line_length = 74 to_read = n with open(filename) as f: while 1: try: f.seek(-(avg_line_length * to_read), 2) except IOError: # woops. apparently file is smaller than what we want # to step back, go to the beginning instead f.seek(0) pos = f.tell() lines = f.read().splitlines() if len(lines) >= to_read or pos == 0: if ansi2html: return convertAnsi2html('\n'.join(lines[-to_read:])) return '\n'.join(lines[-to_read:]) + '\n' avg_line_length *= 1.3
[ "def", "tail_of_file", "(", "filename", ",", "n", ",", "ansi2html", "=", "False", ")", ":", "avg_line_length", "=", "74", "to_read", "=", "n", "with", "open", "(", "filename", ")", "as", "f", ":", "while", "1", ":", "try", ":", "f", ".", "seek", "(", "-", "(", "avg_line_length", "*", "to_read", ")", ",", "2", ")", "except", "IOError", ":", "# woops. apparently file is smaller than what we want", "# to step back, go to the beginning instead", "f", ".", "seek", "(", "0", ")", "pos", "=", "f", ".", "tell", "(", ")", "lines", "=", "f", ".", "read", "(", ")", ".", "splitlines", "(", ")", "if", "len", "(", "lines", ")", ">=", "to_read", "or", "pos", "==", "0", ":", "if", "ansi2html", ":", "return", "convertAnsi2html", "(", "'\\n'", ".", "join", "(", "lines", "[", "-", "to_read", ":", "]", ")", ")", "return", "'\\n'", ".", "join", "(", "lines", "[", "-", "to_read", ":", "]", ")", "+", "'\\n'", "avg_line_length", "*=", "1.3" ]
Reads a n lines from f with an offset of offset lines.
[ "Reads", "a", "n", "lines", "from", "f", "with", "an", "offset", "of", "offset", "lines", "." ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/utils.py#L1476-L1495
train
vatlab/SoS
src/sos/utils.py
sample_lines
def sample_lines(lines, n): '''Draw a sample of n lines from filename, largely evenly.''' if len(lines) <= n: return ''.join(lines) else: m = len(lines) return ''.join([lines[x * m // n + m // (2 * n)] for x in range(n)])
python
def sample_lines(lines, n): '''Draw a sample of n lines from filename, largely evenly.''' if len(lines) <= n: return ''.join(lines) else: m = len(lines) return ''.join([lines[x * m // n + m // (2 * n)] for x in range(n)])
[ "def", "sample_lines", "(", "lines", ",", "n", ")", ":", "if", "len", "(", "lines", ")", "<=", "n", ":", "return", "''", ".", "join", "(", "lines", ")", "else", ":", "m", "=", "len", "(", "lines", ")", "return", "''", ".", "join", "(", "[", "lines", "[", "x", "*", "m", "//", "n", "+", "m", "//", "(", "2", "*", "n", ")", "]", "for", "x", "in", "range", "(", "n", ")", "]", ")" ]
Draw a sample of n lines from filename, largely evenly.
[ "Draw", "a", "sample", "of", "n", "lines", "from", "filename", "largely", "evenly", "." ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/utils.py#L1498-L1504
train
vatlab/SoS
src/sos/utils.py
WorkflowDict.set
def set(self, key, value): '''A short cut to set value to key without triggering any logging or warning message.''' if hasattr(value, 'labels'): if 'VARIABLE' in env.config['SOS_DEBUG'] or 'ALL' in env.config[ 'SOS_DEBUG']: env.log_to_file( 'VARIABLE', f"Set {key} to {short_repr(value)} with labels {short_repr(value.labels)}" ) else: if 'VARIABLE' in env.config['SOS_DEBUG'] or 'ALL' in env.config[ 'SOS_DEBUG']: env.log_to_file( 'VARIABLE', f"Set {key} to {short_repr(value)} of type {value.__class__.__name__}" ) self._dict[key] = value
python
def set(self, key, value): '''A short cut to set value to key without triggering any logging or warning message.''' if hasattr(value, 'labels'): if 'VARIABLE' in env.config['SOS_DEBUG'] or 'ALL' in env.config[ 'SOS_DEBUG']: env.log_to_file( 'VARIABLE', f"Set {key} to {short_repr(value)} with labels {short_repr(value.labels)}" ) else: if 'VARIABLE' in env.config['SOS_DEBUG'] or 'ALL' in env.config[ 'SOS_DEBUG']: env.log_to_file( 'VARIABLE', f"Set {key} to {short_repr(value)} of type {value.__class__.__name__}" ) self._dict[key] = value
[ "def", "set", "(", "self", ",", "key", ",", "value", ")", ":", "if", "hasattr", "(", "value", ",", "'labels'", ")", ":", "if", "'VARIABLE'", "in", "env", ".", "config", "[", "'SOS_DEBUG'", "]", "or", "'ALL'", "in", "env", ".", "config", "[", "'SOS_DEBUG'", "]", ":", "env", ".", "log_to_file", "(", "'VARIABLE'", ",", "f\"Set {key} to {short_repr(value)} with labels {short_repr(value.labels)}\"", ")", "else", ":", "if", "'VARIABLE'", "in", "env", ".", "config", "[", "'SOS_DEBUG'", "]", "or", "'ALL'", "in", "env", ".", "config", "[", "'SOS_DEBUG'", "]", ":", "env", ".", "log_to_file", "(", "'VARIABLE'", ",", "f\"Set {key} to {short_repr(value)} of type {value.__class__.__name__}\"", ")", "self", ".", "_dict", "[", "key", "]", "=", "value" ]
A short cut to set value to key without triggering any logging or warning message.
[ "A", "short", "cut", "to", "set", "value", "to", "key", "without", "triggering", "any", "logging", "or", "warning", "message", "." ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/utils.py#L209-L226
train
vatlab/SoS
src/sos/utils.py
WorkflowDict.update
def update(self, obj): '''Redefine update to trigger logging message''' self._dict.update(obj) for k, v in obj.items(): # if k.isupper(): # self._check_readonly(k, v) if env.verbosity > 2: self._log(k, v)
python
def update(self, obj): '''Redefine update to trigger logging message''' self._dict.update(obj) for k, v in obj.items(): # if k.isupper(): # self._check_readonly(k, v) if env.verbosity > 2: self._log(k, v)
[ "def", "update", "(", "self", ",", "obj", ")", ":", "self", ".", "_dict", ".", "update", "(", "obj", ")", "for", "k", ",", "v", "in", "obj", ".", "items", "(", ")", ":", "# if k.isupper():", "# self._check_readonly(k, v)", "if", "env", ".", "verbosity", ">", "2", ":", "self", ".", "_log", "(", "k", ",", "v", ")" ]
Redefine update to trigger logging message
[ "Redefine", "update", "to", "trigger", "logging", "message" ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/utils.py#L234-L241
train
vatlab/SoS
src/sos/substep_executor.py
execute_substep
def execute_substep(stmt, global_def, global_vars, task='', task_params='', proc_vars={}, shared_vars=[], config={}): '''Execute a substep with specific input etc Substep executed by this function should be self-contained. It can contain tasks (which will be sent to the master process) but not nested workflows. The executor checks step signatures and might skip the substep if it has been executed and the signature matches. The executor accepts connections to the controller, and a socket using which the results will be returned. However, the calling process should take care of the connection and disconnection of controller sockets and this function only takes care of the connection and disconnection of result socket. stmt: Main statement of the substep global_def: Global definitions, might define functions useful to the substep task: External task proc_vars: Environmental variables, signature variables etc shared_vars: Variables that should be returned after the execution config: Runmode, signature mode, verbosity, etc. The return value should be a dictionary with the following keys: index: index of the substep within the step ret_code: (all) return code, 0 for successful sig_skipped: (optional) return if the step is skipped due to signature shared: (optional) shared variable as specified by 'shared_vars' stdout: (optional) if in interactive mode stderr: (optional) if in interactive mode exception: (optional) if an exception occures ''' assert not env.zmq_context.closed assert 'workflow_id' in proc_vars assert 'step_id' in proc_vars assert '_input' in proc_vars assert '_output' in proc_vars assert '_depends' in proc_vars assert 'step_output' in proc_vars assert '_index' in proc_vars assert 'result_push_socket' in config["sockets"] # this should not happen but check nevertheless if env.result_socket_port is not None and env.result_socket_port != config[ "sockets"]["result_push_socket"]: close_socket(env.result_socket) env.result_socket = None if env.result_socket is None: env.result_socket = create_socket(env.zmq_context, zmq.PUSH) env.result_socket_port = config["sockets"]["result_push_socket"] env.result_socket.connect(f'tcp://127.0.0.1:{env.result_socket_port}') res = _execute_substep( stmt=stmt, global_def=global_def, global_vars=global_vars, task=task, task_params=task_params, proc_vars=proc_vars, shared_vars=shared_vars, config=config) env.result_socket.send_pyobj(res)
python
def execute_substep(stmt, global_def, global_vars, task='', task_params='', proc_vars={}, shared_vars=[], config={}): '''Execute a substep with specific input etc Substep executed by this function should be self-contained. It can contain tasks (which will be sent to the master process) but not nested workflows. The executor checks step signatures and might skip the substep if it has been executed and the signature matches. The executor accepts connections to the controller, and a socket using which the results will be returned. However, the calling process should take care of the connection and disconnection of controller sockets and this function only takes care of the connection and disconnection of result socket. stmt: Main statement of the substep global_def: Global definitions, might define functions useful to the substep task: External task proc_vars: Environmental variables, signature variables etc shared_vars: Variables that should be returned after the execution config: Runmode, signature mode, verbosity, etc. The return value should be a dictionary with the following keys: index: index of the substep within the step ret_code: (all) return code, 0 for successful sig_skipped: (optional) return if the step is skipped due to signature shared: (optional) shared variable as specified by 'shared_vars' stdout: (optional) if in interactive mode stderr: (optional) if in interactive mode exception: (optional) if an exception occures ''' assert not env.zmq_context.closed assert 'workflow_id' in proc_vars assert 'step_id' in proc_vars assert '_input' in proc_vars assert '_output' in proc_vars assert '_depends' in proc_vars assert 'step_output' in proc_vars assert '_index' in proc_vars assert 'result_push_socket' in config["sockets"] # this should not happen but check nevertheless if env.result_socket_port is not None and env.result_socket_port != config[ "sockets"]["result_push_socket"]: close_socket(env.result_socket) env.result_socket = None if env.result_socket is None: env.result_socket = create_socket(env.zmq_context, zmq.PUSH) env.result_socket_port = config["sockets"]["result_push_socket"] env.result_socket.connect(f'tcp://127.0.0.1:{env.result_socket_port}') res = _execute_substep( stmt=stmt, global_def=global_def, global_vars=global_vars, task=task, task_params=task_params, proc_vars=proc_vars, shared_vars=shared_vars, config=config) env.result_socket.send_pyobj(res)
[ "def", "execute_substep", "(", "stmt", ",", "global_def", ",", "global_vars", ",", "task", "=", "''", ",", "task_params", "=", "''", ",", "proc_vars", "=", "{", "}", ",", "shared_vars", "=", "[", "]", ",", "config", "=", "{", "}", ")", ":", "assert", "not", "env", ".", "zmq_context", ".", "closed", "assert", "'workflow_id'", "in", "proc_vars", "assert", "'step_id'", "in", "proc_vars", "assert", "'_input'", "in", "proc_vars", "assert", "'_output'", "in", "proc_vars", "assert", "'_depends'", "in", "proc_vars", "assert", "'step_output'", "in", "proc_vars", "assert", "'_index'", "in", "proc_vars", "assert", "'result_push_socket'", "in", "config", "[", "\"sockets\"", "]", "# this should not happen but check nevertheless", "if", "env", ".", "result_socket_port", "is", "not", "None", "and", "env", ".", "result_socket_port", "!=", "config", "[", "\"sockets\"", "]", "[", "\"result_push_socket\"", "]", ":", "close_socket", "(", "env", ".", "result_socket", ")", "env", ".", "result_socket", "=", "None", "if", "env", ".", "result_socket", "is", "None", ":", "env", ".", "result_socket", "=", "create_socket", "(", "env", ".", "zmq_context", ",", "zmq", ".", "PUSH", ")", "env", ".", "result_socket_port", "=", "config", "[", "\"sockets\"", "]", "[", "\"result_push_socket\"", "]", "env", ".", "result_socket", ".", "connect", "(", "f'tcp://127.0.0.1:{env.result_socket_port}'", ")", "res", "=", "_execute_substep", "(", "stmt", "=", "stmt", ",", "global_def", "=", "global_def", ",", "global_vars", "=", "global_vars", ",", "task", "=", "task", ",", "task_params", "=", "task_params", ",", "proc_vars", "=", "proc_vars", ",", "shared_vars", "=", "shared_vars", ",", "config", "=", "config", ")", "env", ".", "result_socket", ".", "send_pyobj", "(", "res", ")" ]
Execute a substep with specific input etc Substep executed by this function should be self-contained. It can contain tasks (which will be sent to the master process) but not nested workflows. The executor checks step signatures and might skip the substep if it has been executed and the signature matches. The executor accepts connections to the controller, and a socket using which the results will be returned. However, the calling process should take care of the connection and disconnection of controller sockets and this function only takes care of the connection and disconnection of result socket. stmt: Main statement of the substep global_def: Global definitions, might define functions useful to the substep task: External task proc_vars: Environmental variables, signature variables etc shared_vars: Variables that should be returned after the execution config: Runmode, signature mode, verbosity, etc. The return value should be a dictionary with the following keys: index: index of the substep within the step ret_code: (all) return code, 0 for successful sig_skipped: (optional) return if the step is skipped due to signature shared: (optional) shared variable as specified by 'shared_vars' stdout: (optional) if in interactive mode stderr: (optional) if in interactive mode exception: (optional) if an exception occures
[ "Execute", "a", "substep", "with", "specific", "input", "etc" ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/substep_executor.py#L36-L116
train
vatlab/SoS
src/sos/signatures.py
WorkflowSignatures.files
def files(self): '''Listing files related to workflows related to current directory''' try: cur = self.conn.cursor() cur.execute( 'SELECT id, item FROM workflows WHERE entry_type = "tracked_files"' ) return [(x[0], eval(x[1])) for x in cur.fetchall()] except sqlite3.DatabaseError as e: env.logger.warning( f'Failed to get files from signature database: {e}') return []
python
def files(self): '''Listing files related to workflows related to current directory''' try: cur = self.conn.cursor() cur.execute( 'SELECT id, item FROM workflows WHERE entry_type = "tracked_files"' ) return [(x[0], eval(x[1])) for x in cur.fetchall()] except sqlite3.DatabaseError as e: env.logger.warning( f'Failed to get files from signature database: {e}') return []
[ "def", "files", "(", "self", ")", ":", "try", ":", "cur", "=", "self", ".", "conn", ".", "cursor", "(", ")", "cur", ".", "execute", "(", "'SELECT id, item FROM workflows WHERE entry_type = \"tracked_files\"'", ")", "return", "[", "(", "x", "[", "0", "]", ",", "eval", "(", "x", "[", "1", "]", ")", ")", "for", "x", "in", "cur", ".", "fetchall", "(", ")", "]", "except", "sqlite3", ".", "DatabaseError", "as", "e", ":", "env", ".", "logger", ".", "warning", "(", "f'Failed to get files from signature database: {e}'", ")", "return", "[", "]" ]
Listing files related to workflows related to current directory
[ "Listing", "files", "related", "to", "workflows", "related", "to", "current", "directory" ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/signatures.py#L176-L187
train
vatlab/SoS
src/sos/dag.py
SoS_DAG.find_executable
def find_executable(self): '''Find an executable node, which means nodes that has not been completed and has no input dependency.''' if 'DAG' in env.config['SOS_DEBUG'] or 'ALL' in env.config['SOS_DEBUG']: env.log_to_file('DAG', 'find_executable') for node in self.nodes(): # if it has not been executed if node._status is None: with_dependency = False for edge in self.in_edges(node): if edge[0]._status != 'completed': with_dependency = True break if not with_dependency: return node # if no node could be found, let use try pending ones pending_jobs = [ x for x in self.nodes() if x._status == 'signature_pending' ] if pending_jobs: try: notifier = ActivityNotifier( f'Waiting for {len(pending_jobs)} pending job{"s: e.g." if len(pending_jobs) > 1 else ":"} output {short_repr(pending_jobs[0]._signature[0])} with signature file {pending_jobs[0]._signature[1] + "_"}. You can manually remove this lock file if you are certain that no other process is working on the output.' ) while True: for node in pending_jobs: # if it has not been executed lock = fasteners.InterProcessLock(node._signature[1] + '_') if lock.acquire(blocking=False): lock.release() node._status = None return node time.sleep(0.1) except Exception as e: env.logger.error(e) finally: notifier.stop() return None
python
def find_executable(self): '''Find an executable node, which means nodes that has not been completed and has no input dependency.''' if 'DAG' in env.config['SOS_DEBUG'] or 'ALL' in env.config['SOS_DEBUG']: env.log_to_file('DAG', 'find_executable') for node in self.nodes(): # if it has not been executed if node._status is None: with_dependency = False for edge in self.in_edges(node): if edge[0]._status != 'completed': with_dependency = True break if not with_dependency: return node # if no node could be found, let use try pending ones pending_jobs = [ x for x in self.nodes() if x._status == 'signature_pending' ] if pending_jobs: try: notifier = ActivityNotifier( f'Waiting for {len(pending_jobs)} pending job{"s: e.g." if len(pending_jobs) > 1 else ":"} output {short_repr(pending_jobs[0]._signature[0])} with signature file {pending_jobs[0]._signature[1] + "_"}. You can manually remove this lock file if you are certain that no other process is working on the output.' ) while True: for node in pending_jobs: # if it has not been executed lock = fasteners.InterProcessLock(node._signature[1] + '_') if lock.acquire(blocking=False): lock.release() node._status = None return node time.sleep(0.1) except Exception as e: env.logger.error(e) finally: notifier.stop() return None
[ "def", "find_executable", "(", "self", ")", ":", "if", "'DAG'", "in", "env", ".", "config", "[", "'SOS_DEBUG'", "]", "or", "'ALL'", "in", "env", ".", "config", "[", "'SOS_DEBUG'", "]", ":", "env", ".", "log_to_file", "(", "'DAG'", ",", "'find_executable'", ")", "for", "node", "in", "self", ".", "nodes", "(", ")", ":", "# if it has not been executed", "if", "node", ".", "_status", "is", "None", ":", "with_dependency", "=", "False", "for", "edge", "in", "self", ".", "in_edges", "(", "node", ")", ":", "if", "edge", "[", "0", "]", ".", "_status", "!=", "'completed'", ":", "with_dependency", "=", "True", "break", "if", "not", "with_dependency", ":", "return", "node", "# if no node could be found, let use try pending ones", "pending_jobs", "=", "[", "x", "for", "x", "in", "self", ".", "nodes", "(", ")", "if", "x", ".", "_status", "==", "'signature_pending'", "]", "if", "pending_jobs", ":", "try", ":", "notifier", "=", "ActivityNotifier", "(", "f'Waiting for {len(pending_jobs)} pending job{\"s: e.g.\" if len(pending_jobs) > 1 else \":\"} output {short_repr(pending_jobs[0]._signature[0])} with signature file {pending_jobs[0]._signature[1] + \"_\"}. You can manually remove this lock file if you are certain that no other process is working on the output.'", ")", "while", "True", ":", "for", "node", "in", "pending_jobs", ":", "# if it has not been executed", "lock", "=", "fasteners", ".", "InterProcessLock", "(", "node", ".", "_signature", "[", "1", "]", "+", "'_'", ")", "if", "lock", ".", "acquire", "(", "blocking", "=", "False", ")", ":", "lock", ".", "release", "(", ")", "node", ".", "_status", "=", "None", "return", "node", "time", ".", "sleep", "(", "0.1", ")", "except", "Exception", "as", "e", ":", "env", ".", "logger", ".", "error", "(", "e", ")", "finally", ":", "notifier", ".", "stop", "(", ")", "return", "None" ]
Find an executable node, which means nodes that has not been completed and has no input dependency.
[ "Find", "an", "executable", "node", "which", "means", "nodes", "that", "has", "not", "been", "completed", "and", "has", "no", "input", "dependency", "." ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/dag.py#L184-L222
train
vatlab/SoS
src/sos/dag.py
SoS_DAG.dangling
def dangling(self, targets: sos_targets): '''returns 1. missing targets, which are missing from the DAG or from the provided targets 2. existing targets of provided target list, not in DAG ''' existing = [] missing = [] if env.config['trace_existing']: for x in self._all_depends_files.keys(): if x not in self._all_output_files: if x.target_exists(): existing.append(x) else: missing.append(x) else: missing = [ x for x in self._all_depends_files.keys() if x not in self._all_output_files and not x.target_exists() ] for x in targets: if x not in self._all_output_files: if x.target_exists('target'): existing.append(x) else: missing.append(x) return missing, existing
python
def dangling(self, targets: sos_targets): '''returns 1. missing targets, which are missing from the DAG or from the provided targets 2. existing targets of provided target list, not in DAG ''' existing = [] missing = [] if env.config['trace_existing']: for x in self._all_depends_files.keys(): if x not in self._all_output_files: if x.target_exists(): existing.append(x) else: missing.append(x) else: missing = [ x for x in self._all_depends_files.keys() if x not in self._all_output_files and not x.target_exists() ] for x in targets: if x not in self._all_output_files: if x.target_exists('target'): existing.append(x) else: missing.append(x) return missing, existing
[ "def", "dangling", "(", "self", ",", "targets", ":", "sos_targets", ")", ":", "existing", "=", "[", "]", "missing", "=", "[", "]", "if", "env", ".", "config", "[", "'trace_existing'", "]", ":", "for", "x", "in", "self", ".", "_all_depends_files", ".", "keys", "(", ")", ":", "if", "x", "not", "in", "self", ".", "_all_output_files", ":", "if", "x", ".", "target_exists", "(", ")", ":", "existing", ".", "append", "(", "x", ")", "else", ":", "missing", ".", "append", "(", "x", ")", "else", ":", "missing", "=", "[", "x", "for", "x", "in", "self", ".", "_all_depends_files", ".", "keys", "(", ")", "if", "x", "not", "in", "self", ".", "_all_output_files", "and", "not", "x", ".", "target_exists", "(", ")", "]", "for", "x", "in", "targets", ":", "if", "x", "not", "in", "self", ".", "_all_output_files", ":", "if", "x", ".", "target_exists", "(", "'target'", ")", ":", "existing", ".", "append", "(", "x", ")", "else", ":", "missing", ".", "append", "(", "x", ")", "return", "missing", ",", "existing" ]
returns 1. missing targets, which are missing from the DAG or from the provided targets 2. existing targets of provided target list, not in DAG
[ "returns", "1", ".", "missing", "targets", "which", "are", "missing", "from", "the", "DAG", "or", "from", "the", "provided", "targets", "2", ".", "existing", "targets", "of", "provided", "target", "list", "not", "in", "DAG" ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/dag.py#L258-L283
train
vatlab/SoS
src/sos/dag.py
SoS_DAG.subgraph_from
def subgraph_from(self, targets: sos_targets): '''Trim DAG to keep only nodes that produce targets''' if 'DAG' in env.config['SOS_DEBUG'] or 'ALL' in env.config['SOS_DEBUG']: env.log_to_file('DAG', 'create subgraph') # first, find all nodes with targets subnodes = [] for node in self.nodes(): if node._output_targets.valid() and any( x in node._output_targets for x in targets): subnodes.append(node) # ancestors = set() for node in subnodes: ancestors |= nx.ancestors(self, node) return SoS_DAG(nx.subgraph(self, subnodes + list(ancestors)))
python
def subgraph_from(self, targets: sos_targets): '''Trim DAG to keep only nodes that produce targets''' if 'DAG' in env.config['SOS_DEBUG'] or 'ALL' in env.config['SOS_DEBUG']: env.log_to_file('DAG', 'create subgraph') # first, find all nodes with targets subnodes = [] for node in self.nodes(): if node._output_targets.valid() and any( x in node._output_targets for x in targets): subnodes.append(node) # ancestors = set() for node in subnodes: ancestors |= nx.ancestors(self, node) return SoS_DAG(nx.subgraph(self, subnodes + list(ancestors)))
[ "def", "subgraph_from", "(", "self", ",", "targets", ":", "sos_targets", ")", ":", "if", "'DAG'", "in", "env", ".", "config", "[", "'SOS_DEBUG'", "]", "or", "'ALL'", "in", "env", ".", "config", "[", "'SOS_DEBUG'", "]", ":", "env", ".", "log_to_file", "(", "'DAG'", ",", "'create subgraph'", ")", "# first, find all nodes with targets", "subnodes", "=", "[", "]", "for", "node", "in", "self", ".", "nodes", "(", ")", ":", "if", "node", ".", "_output_targets", ".", "valid", "(", ")", "and", "any", "(", "x", "in", "node", ".", "_output_targets", "for", "x", "in", "targets", ")", ":", "subnodes", ".", "append", "(", "node", ")", "#", "ancestors", "=", "set", "(", ")", "for", "node", "in", "subnodes", ":", "ancestors", "|=", "nx", ".", "ancestors", "(", "self", ",", "node", ")", "return", "SoS_DAG", "(", "nx", ".", "subgraph", "(", "self", ",", "subnodes", "+", "list", "(", "ancestors", ")", ")", ")" ]
Trim DAG to keep only nodes that produce targets
[ "Trim", "DAG", "to", "keep", "only", "nodes", "that", "produce", "targets" ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/dag.py#L301-L315
train
vatlab/SoS
src/sos/dag.py
SoS_DAG.build
def build(self): '''Connect nodes according to status of targets''' # right now we do not worry about status of nodes # connecting the output to the input of other nodes # # NOTE: This is implemented in the least efficient way just for # testing. It has to be re-implemented. # # refer to http://stackoverflow.com/questions/33494376/networkx-add-edges-to-graph-from-node-attributes # # several cases triggers dependency. if 'DAG' in env.config['SOS_DEBUG'] or 'ALL' in env.config['SOS_DEBUG']: env.log_to_file('DAG', 'build DAG') for wf in range(self._forward_workflow_id + 1): indexed = [x for x in self.nodes() if x._wf_index == wf] indexed.sort(key=lambda x: x._node_index) for idx, node in enumerate(indexed): # 1. if a node changes context (using option alias), all later steps # has to rely on it. if node._context['__changed_vars__']: for later_node in indexed[idx + 1:]: if node._context['__changed_vars__'] & ( later_node._context['__signature_vars__'] | later_node._context['__environ_vars__']): self.add_edge(node, later_node) # 2. if the input of a step is undetermined, it has to be executed # after all its previous steps. if not node._input_targets.valid() and idx > 0: # if there is some input specified, it does not use default # input, so the relationship can be further looked before if node._input_targets.undetermined(): # if the input is dynamic, has to rely on previous step... if 'dynamic' in node._context['__environ_vars__']: self.add_edge(indexed[idx - 1], node) else: # otherwise let us look back. for prev_node in indexed[idx - 1::-1]: if node._context[ '__environ_vars__'] & prev_node._context[ '__changed_vars__']: self.add_edge(prev_node, node) else: self.add_edge(indexed[idx - 1], node) # # 3. if the input of a step depends on the output of another step for target, in_node in self._all_depends_files.items(): if target not in self._all_output_files: continue # it is possible that multiple nodes satisfy the same target out_node = self._all_output_files[target] for i in in_node: for j in out_node: if j != i: self.add_edge(j, i) self.mark_dirty()
python
def build(self): '''Connect nodes according to status of targets''' # right now we do not worry about status of nodes # connecting the output to the input of other nodes # # NOTE: This is implemented in the least efficient way just for # testing. It has to be re-implemented. # # refer to http://stackoverflow.com/questions/33494376/networkx-add-edges-to-graph-from-node-attributes # # several cases triggers dependency. if 'DAG' in env.config['SOS_DEBUG'] or 'ALL' in env.config['SOS_DEBUG']: env.log_to_file('DAG', 'build DAG') for wf in range(self._forward_workflow_id + 1): indexed = [x for x in self.nodes() if x._wf_index == wf] indexed.sort(key=lambda x: x._node_index) for idx, node in enumerate(indexed): # 1. if a node changes context (using option alias), all later steps # has to rely on it. if node._context['__changed_vars__']: for later_node in indexed[idx + 1:]: if node._context['__changed_vars__'] & ( later_node._context['__signature_vars__'] | later_node._context['__environ_vars__']): self.add_edge(node, later_node) # 2. if the input of a step is undetermined, it has to be executed # after all its previous steps. if not node._input_targets.valid() and idx > 0: # if there is some input specified, it does not use default # input, so the relationship can be further looked before if node._input_targets.undetermined(): # if the input is dynamic, has to rely on previous step... if 'dynamic' in node._context['__environ_vars__']: self.add_edge(indexed[idx - 1], node) else: # otherwise let us look back. for prev_node in indexed[idx - 1::-1]: if node._context[ '__environ_vars__'] & prev_node._context[ '__changed_vars__']: self.add_edge(prev_node, node) else: self.add_edge(indexed[idx - 1], node) # # 3. if the input of a step depends on the output of another step for target, in_node in self._all_depends_files.items(): if target not in self._all_output_files: continue # it is possible that multiple nodes satisfy the same target out_node = self._all_output_files[target] for i in in_node: for j in out_node: if j != i: self.add_edge(j, i) self.mark_dirty()
[ "def", "build", "(", "self", ")", ":", "# right now we do not worry about status of nodes", "# connecting the output to the input of other nodes", "#", "# NOTE: This is implemented in the least efficient way just for", "# testing. It has to be re-implemented.", "#", "# refer to http://stackoverflow.com/questions/33494376/networkx-add-edges-to-graph-from-node-attributes", "#", "# several cases triggers dependency.", "if", "'DAG'", "in", "env", ".", "config", "[", "'SOS_DEBUG'", "]", "or", "'ALL'", "in", "env", ".", "config", "[", "'SOS_DEBUG'", "]", ":", "env", ".", "log_to_file", "(", "'DAG'", ",", "'build DAG'", ")", "for", "wf", "in", "range", "(", "self", ".", "_forward_workflow_id", "+", "1", ")", ":", "indexed", "=", "[", "x", "for", "x", "in", "self", ".", "nodes", "(", ")", "if", "x", ".", "_wf_index", "==", "wf", "]", "indexed", ".", "sort", "(", "key", "=", "lambda", "x", ":", "x", ".", "_node_index", ")", "for", "idx", ",", "node", "in", "enumerate", "(", "indexed", ")", ":", "# 1. if a node changes context (using option alias), all later steps", "# has to rely on it.", "if", "node", ".", "_context", "[", "'__changed_vars__'", "]", ":", "for", "later_node", "in", "indexed", "[", "idx", "+", "1", ":", "]", ":", "if", "node", ".", "_context", "[", "'__changed_vars__'", "]", "&", "(", "later_node", ".", "_context", "[", "'__signature_vars__'", "]", "|", "later_node", ".", "_context", "[", "'__environ_vars__'", "]", ")", ":", "self", ".", "add_edge", "(", "node", ",", "later_node", ")", "# 2. if the input of a step is undetermined, it has to be executed", "# after all its previous steps.", "if", "not", "node", ".", "_input_targets", ".", "valid", "(", ")", "and", "idx", ">", "0", ":", "# if there is some input specified, it does not use default", "# input, so the relationship can be further looked before", "if", "node", ".", "_input_targets", ".", "undetermined", "(", ")", ":", "# if the input is dynamic, has to rely on previous step...", "if", "'dynamic'", "in", "node", ".", "_context", "[", "'__environ_vars__'", "]", ":", "self", ".", "add_edge", "(", "indexed", "[", "idx", "-", "1", "]", ",", "node", ")", "else", ":", "# otherwise let us look back.", "for", "prev_node", "in", "indexed", "[", "idx", "-", "1", ":", ":", "-", "1", "]", ":", "if", "node", ".", "_context", "[", "'__environ_vars__'", "]", "&", "prev_node", ".", "_context", "[", "'__changed_vars__'", "]", ":", "self", ".", "add_edge", "(", "prev_node", ",", "node", ")", "else", ":", "self", ".", "add_edge", "(", "indexed", "[", "idx", "-", "1", "]", ",", "node", ")", "#", "# 3. if the input of a step depends on the output of another step", "for", "target", ",", "in_node", "in", "self", ".", "_all_depends_files", ".", "items", "(", ")", ":", "if", "target", "not", "in", "self", ".", "_all_output_files", ":", "continue", "# it is possible that multiple nodes satisfy the same target", "out_node", "=", "self", ".", "_all_output_files", "[", "target", "]", "for", "i", "in", "in_node", ":", "for", "j", "in", "out_node", ":", "if", "j", "!=", "i", ":", "self", ".", "add_edge", "(", "j", ",", "i", ")", "self", ".", "mark_dirty", "(", ")" ]
Connect nodes according to status of targets
[ "Connect", "nodes", "according", "to", "status", "of", "targets" ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/dag.py#L317-L373
train
vatlab/SoS
src/sos/task_engines.py
TaskEngine.monitor_tasks
def monitor_tasks(self, tasks=None, status=None, age=None): '''Start monitoring specified or all tasks''' self.engine_ready.wait() if not tasks: tasks = self.task_status.keys() else: tasks = [x for x in tasks if x in self.task_status] # we only monitor running tasks with threading.Lock(): for task in tasks: if self.task_status[task] in ( 'submitted', 'running') and task not in self.running_tasks: # these tasks will be actively monitored self.running_tasks.append(task) # if age is not None: age = expand_time(age, default_unit='d') return sorted([ (x, self.task_status[x], self.task_info[x].get( 'data', (time.time(), None, None))) for x in tasks if (status is None or self.task_status[x] in status) and (age is None or ( (age > 0 and time.time() - self.task_info[x].get('date', (time.time(), None, None))[0] > age) or (age < 0 and time.time() - self.task_info[x].get('date', (time.time(), None, None))[0] < -age))) ], key=lambda x: -x[2][0])
python
def monitor_tasks(self, tasks=None, status=None, age=None): '''Start monitoring specified or all tasks''' self.engine_ready.wait() if not tasks: tasks = self.task_status.keys() else: tasks = [x for x in tasks if x in self.task_status] # we only monitor running tasks with threading.Lock(): for task in tasks: if self.task_status[task] in ( 'submitted', 'running') and task not in self.running_tasks: # these tasks will be actively monitored self.running_tasks.append(task) # if age is not None: age = expand_time(age, default_unit='d') return sorted([ (x, self.task_status[x], self.task_info[x].get( 'data', (time.time(), None, None))) for x in tasks if (status is None or self.task_status[x] in status) and (age is None or ( (age > 0 and time.time() - self.task_info[x].get('date', (time.time(), None, None))[0] > age) or (age < 0 and time.time() - self.task_info[x].get('date', (time.time(), None, None))[0] < -age))) ], key=lambda x: -x[2][0])
[ "def", "monitor_tasks", "(", "self", ",", "tasks", "=", "None", ",", "status", "=", "None", ",", "age", "=", "None", ")", ":", "self", ".", "engine_ready", ".", "wait", "(", ")", "if", "not", "tasks", ":", "tasks", "=", "self", ".", "task_status", ".", "keys", "(", ")", "else", ":", "tasks", "=", "[", "x", "for", "x", "in", "tasks", "if", "x", "in", "self", ".", "task_status", "]", "# we only monitor running tasks", "with", "threading", ".", "Lock", "(", ")", ":", "for", "task", "in", "tasks", ":", "if", "self", ".", "task_status", "[", "task", "]", "in", "(", "'submitted'", ",", "'running'", ")", "and", "task", "not", "in", "self", ".", "running_tasks", ":", "# these tasks will be actively monitored", "self", ".", "running_tasks", ".", "append", "(", "task", ")", "#", "if", "age", "is", "not", "None", ":", "age", "=", "expand_time", "(", "age", ",", "default_unit", "=", "'d'", ")", "return", "sorted", "(", "[", "(", "x", ",", "self", ".", "task_status", "[", "x", "]", ",", "self", ".", "task_info", "[", "x", "]", ".", "get", "(", "'data'", ",", "(", "time", ".", "time", "(", ")", ",", "None", ",", "None", ")", ")", ")", "for", "x", "in", "tasks", "if", "(", "status", "is", "None", "or", "self", ".", "task_status", "[", "x", "]", "in", "status", ")", "and", "(", "age", "is", "None", "or", "(", "(", "age", ">", "0", "and", "time", ".", "time", "(", ")", "-", "self", ".", "task_info", "[", "x", "]", ".", "get", "(", "'date'", ",", "(", "time", ".", "time", "(", ")", ",", "None", ",", "None", ")", ")", "[", "0", "]", ">", "age", ")", "or", "(", "age", "<", "0", "and", "time", ".", "time", "(", ")", "-", "self", ".", "task_info", "[", "x", "]", ".", "get", "(", "'date'", ",", "(", "time", ".", "time", "(", ")", ",", "None", ",", "None", ")", ")", "[", "0", "]", "<", "-", "age", ")", ")", ")", "]", ",", "key", "=", "lambda", "x", ":", "-", "x", "[", "2", "]", "[", "0", "]", ")" ]
Start monitoring specified or all tasks
[ "Start", "monitoring", "specified", "or", "all", "tasks" ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/task_engines.py#L97-L129
train
vatlab/SoS
src/sos/task_engines.py
BackgroundProcess_TaskEngine._submit_task_with_template
def _submit_task_with_template(self, task_ids): '''Submit tasks by interpolating a shell script defined in job_template''' runtime = self.config runtime.update({ 'workdir': os.getcwd(), 'cur_dir': os.getcwd(), # for backward compatibility 'verbosity': env.verbosity, 'sig_mode': env.config.get('sig_mode', 'default'), 'run_mode': env.config.get('run_mode', 'run'), 'home_dir': os.path.expanduser('~') }) if '_runtime' in env.sos_dict: runtime.update({ x: env.sos_dict['_runtime'][x] for x in ('nodes', 'cores', 'workdir', 'mem', 'walltime') if x in env.sos_dict['_runtime'] }) if 'nodes' not in runtime: runtime['nodes'] = 1 if 'cores' not in runtime: runtime['cores'] = 1 # let us first prepare a task file job_text = '' for task_id in task_ids: runtime['task'] = task_id try: job_text += cfg_interpolate(self.job_template, runtime) job_text += '\n' except Exception as e: raise ValueError( f'Failed to generate job file for task {task_id}: {e}') filename = task_ids[0] + ('.sh' if len(task_ids) == 1 else f'-{task_ids[-1]}.sh') # now we need to write a job file job_file = os.path.join( os.path.expanduser('~'), '.sos', 'tasks', filename) # do not translate newline under windows because the script will be executed # under linux/mac with open(job_file, 'w', newline='') as job: job.write(job_text) # then copy the job file to remote host if necessary self.agent.send_task_file(job_file) try: cmd = f'bash ~/.sos/tasks/{filename}' self.agent.run_command(cmd, wait_for_task=self.wait_for_task) except Exception as e: raise RuntimeError(f'Failed to submit task {task_ids}: {e}') return True
python
def _submit_task_with_template(self, task_ids): '''Submit tasks by interpolating a shell script defined in job_template''' runtime = self.config runtime.update({ 'workdir': os.getcwd(), 'cur_dir': os.getcwd(), # for backward compatibility 'verbosity': env.verbosity, 'sig_mode': env.config.get('sig_mode', 'default'), 'run_mode': env.config.get('run_mode', 'run'), 'home_dir': os.path.expanduser('~') }) if '_runtime' in env.sos_dict: runtime.update({ x: env.sos_dict['_runtime'][x] for x in ('nodes', 'cores', 'workdir', 'mem', 'walltime') if x in env.sos_dict['_runtime'] }) if 'nodes' not in runtime: runtime['nodes'] = 1 if 'cores' not in runtime: runtime['cores'] = 1 # let us first prepare a task file job_text = '' for task_id in task_ids: runtime['task'] = task_id try: job_text += cfg_interpolate(self.job_template, runtime) job_text += '\n' except Exception as e: raise ValueError( f'Failed to generate job file for task {task_id}: {e}') filename = task_ids[0] + ('.sh' if len(task_ids) == 1 else f'-{task_ids[-1]}.sh') # now we need to write a job file job_file = os.path.join( os.path.expanduser('~'), '.sos', 'tasks', filename) # do not translate newline under windows because the script will be executed # under linux/mac with open(job_file, 'w', newline='') as job: job.write(job_text) # then copy the job file to remote host if necessary self.agent.send_task_file(job_file) try: cmd = f'bash ~/.sos/tasks/{filename}' self.agent.run_command(cmd, wait_for_task=self.wait_for_task) except Exception as e: raise RuntimeError(f'Failed to submit task {task_ids}: {e}') return True
[ "def", "_submit_task_with_template", "(", "self", ",", "task_ids", ")", ":", "runtime", "=", "self", ".", "config", "runtime", ".", "update", "(", "{", "'workdir'", ":", "os", ".", "getcwd", "(", ")", ",", "'cur_dir'", ":", "os", ".", "getcwd", "(", ")", ",", "# for backward compatibility", "'verbosity'", ":", "env", ".", "verbosity", ",", "'sig_mode'", ":", "env", ".", "config", ".", "get", "(", "'sig_mode'", ",", "'default'", ")", ",", "'run_mode'", ":", "env", ".", "config", ".", "get", "(", "'run_mode'", ",", "'run'", ")", ",", "'home_dir'", ":", "os", ".", "path", ".", "expanduser", "(", "'~'", ")", "}", ")", "if", "'_runtime'", "in", "env", ".", "sos_dict", ":", "runtime", ".", "update", "(", "{", "x", ":", "env", ".", "sos_dict", "[", "'_runtime'", "]", "[", "x", "]", "for", "x", "in", "(", "'nodes'", ",", "'cores'", ",", "'workdir'", ",", "'mem'", ",", "'walltime'", ")", "if", "x", "in", "env", ".", "sos_dict", "[", "'_runtime'", "]", "}", ")", "if", "'nodes'", "not", "in", "runtime", ":", "runtime", "[", "'nodes'", "]", "=", "1", "if", "'cores'", "not", "in", "runtime", ":", "runtime", "[", "'cores'", "]", "=", "1", "# let us first prepare a task file", "job_text", "=", "''", "for", "task_id", "in", "task_ids", ":", "runtime", "[", "'task'", "]", "=", "task_id", "try", ":", "job_text", "+=", "cfg_interpolate", "(", "self", ".", "job_template", ",", "runtime", ")", "job_text", "+=", "'\\n'", "except", "Exception", "as", "e", ":", "raise", "ValueError", "(", "f'Failed to generate job file for task {task_id}: {e}'", ")", "filename", "=", "task_ids", "[", "0", "]", "+", "(", "'.sh'", "if", "len", "(", "task_ids", ")", "==", "1", "else", "f'-{task_ids[-1]}.sh'", ")", "# now we need to write a job file", "job_file", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "expanduser", "(", "'~'", ")", ",", "'.sos'", ",", "'tasks'", ",", "filename", ")", "# do not translate newline under windows because the script will be executed", "# under linux/mac", "with", "open", "(", "job_file", ",", "'w'", ",", "newline", "=", "''", ")", "as", "job", ":", "job", ".", "write", "(", "job_text", ")", "# then copy the job file to remote host if necessary", "self", ".", "agent", ".", "send_task_file", "(", "job_file", ")", "try", ":", "cmd", "=", "f'bash ~/.sos/tasks/{filename}'", "self", ".", "agent", ".", "run_command", "(", "cmd", ",", "wait_for_task", "=", "self", ".", "wait_for_task", ")", "except", "Exception", "as", "e", ":", "raise", "RuntimeError", "(", "f'Failed to submit task {task_ids}: {e}'", ")", "return", "True" ]
Submit tasks by interpolating a shell script defined in job_template
[ "Submit", "tasks", "by", "interpolating", "a", "shell", "script", "defined", "in", "job_template" ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/task_engines.py#L651-L702
train
vatlab/SoS
src/sos/parser.py
is_type_hint
def is_type_hint(stmt: str) -> bool: '''Try to differentiate var: type = value with action: input = whatever ''' if stmt.count('=') > 1: return False if ':' not in stmt: return False # # action: if not stmt.split(':')[1].strip(): return False # # action: int # # or # # input: variable # if '=' not in stmt: action, par = [x.strip() for x in stmt.split(':', 1)] else: # one parameter? # # action: input={'a': b} # action, par = [x.strip() for x in stmt.split('=', 1)[0].split(':', 1)] if action in SOS_DIRECTIVES: return False if par in SOS_ACTION_OPTIONS: return False # if par is something like List[Any], or 'classname' if not par.isidentifier(): return True # if action is a builtin function, such as sort, it cannot be # a variable assignment. if action in dir(builtins): return False # if action is registered global _action_list if _action_list is None: import pkg_resources _action_list = [ x.name for x in pkg_resources.iter_entry_points(group='sos_actions') ] if action in _action_list: return False # if par is something like List, Tuple, str if par in dir(typing) or par in dir(builtins): return True # if not quite sure??? env.logger.debug( f"Failed to tell if '{stmt}' is an assignment with type hint or function in script format. Assuming type hint." ) # regular function written in this format? return True
python
def is_type_hint(stmt: str) -> bool: '''Try to differentiate var: type = value with action: input = whatever ''' if stmt.count('=') > 1: return False if ':' not in stmt: return False # # action: if not stmt.split(':')[1].strip(): return False # # action: int # # or # # input: variable # if '=' not in stmt: action, par = [x.strip() for x in stmt.split(':', 1)] else: # one parameter? # # action: input={'a': b} # action, par = [x.strip() for x in stmt.split('=', 1)[0].split(':', 1)] if action in SOS_DIRECTIVES: return False if par in SOS_ACTION_OPTIONS: return False # if par is something like List[Any], or 'classname' if not par.isidentifier(): return True # if action is a builtin function, such as sort, it cannot be # a variable assignment. if action in dir(builtins): return False # if action is registered global _action_list if _action_list is None: import pkg_resources _action_list = [ x.name for x in pkg_resources.iter_entry_points(group='sos_actions') ] if action in _action_list: return False # if par is something like List, Tuple, str if par in dir(typing) or par in dir(builtins): return True # if not quite sure??? env.logger.debug( f"Failed to tell if '{stmt}' is an assignment with type hint or function in script format. Assuming type hint." ) # regular function written in this format? return True
[ "def", "is_type_hint", "(", "stmt", ":", "str", ")", "->", "bool", ":", "if", "stmt", ".", "count", "(", "'='", ")", ">", "1", ":", "return", "False", "if", "':'", "not", "in", "stmt", ":", "return", "False", "#", "# action:", "if", "not", "stmt", ".", "split", "(", "':'", ")", "[", "1", "]", ".", "strip", "(", ")", ":", "return", "False", "#", "# action: int", "#", "# or", "#", "# input: variable", "#", "if", "'='", "not", "in", "stmt", ":", "action", ",", "par", "=", "[", "x", ".", "strip", "(", ")", "for", "x", "in", "stmt", ".", "split", "(", "':'", ",", "1", ")", "]", "else", ":", "# one parameter?", "#", "# action: input={'a': b}", "#", "action", ",", "par", "=", "[", "x", ".", "strip", "(", ")", "for", "x", "in", "stmt", ".", "split", "(", "'='", ",", "1", ")", "[", "0", "]", ".", "split", "(", "':'", ",", "1", ")", "]", "if", "action", "in", "SOS_DIRECTIVES", ":", "return", "False", "if", "par", "in", "SOS_ACTION_OPTIONS", ":", "return", "False", "# if par is something like List[Any], or 'classname'", "if", "not", "par", ".", "isidentifier", "(", ")", ":", "return", "True", "# if action is a builtin function, such as sort, it cannot be", "# a variable assignment.", "if", "action", "in", "dir", "(", "builtins", ")", ":", "return", "False", "# if action is registered", "global", "_action_list", "if", "_action_list", "is", "None", ":", "import", "pkg_resources", "_action_list", "=", "[", "x", ".", "name", "for", "x", "in", "pkg_resources", ".", "iter_entry_points", "(", "group", "=", "'sos_actions'", ")", "]", "if", "action", "in", "_action_list", ":", "return", "False", "# if par is something like List, Tuple, str", "if", "par", "in", "dir", "(", "typing", ")", "or", "par", "in", "dir", "(", "builtins", ")", ":", "return", "True", "# if not quite sure???", "env", ".", "logger", ".", "debug", "(", "f\"Failed to tell if '{stmt}' is an assignment with type hint or function in script format. Assuming type hint.\"", ")", "# regular function written in this format?", "return", "True" ]
Try to differentiate var: type = value with action: input = whatever
[ "Try", "to", "differentiate" ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/parser.py#L60-L130
train
vatlab/SoS
src/sos/parser.py
SoS_Step.indented_script
def indented_script(self) -> bool: ''' check self._script and see if it is indented ''' # get all leading space, tab and newline leading = INDENTED.match(self._script) return 0 if leading is None else len(leading.group(2))
python
def indented_script(self) -> bool: ''' check self._script and see if it is indented ''' # get all leading space, tab and newline leading = INDENTED.match(self._script) return 0 if leading is None else len(leading.group(2))
[ "def", "indented_script", "(", "self", ")", "->", "bool", ":", "# get all leading space, tab and newline", "leading", "=", "INDENTED", ".", "match", "(", "self", ".", "_script", ")", "return", "0", "if", "leading", "is", "None", "else", "len", "(", "leading", ".", "group", "(", "2", ")", ")" ]
check self._script and see if it is indented
[ "check", "self", ".", "_script", "and", "see", "if", "it", "is", "indented" ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/parser.py#L299-L303
train
vatlab/SoS
src/sos/parser.py
SoS_Step.category
def category(self) -> Optional[str]: '''Determine the category of existing statement''' if self.statements: if self.statements[-1][0] == ':': # a hack. ... to avoid calling isValid recursively def validDirective(): if not self.values: return True if self.values[-1].strip().endswith(','): return False try: compile( 'func(' + ''.join(self.values) + ')', filename='<string>', mode='eval') except Exception: return False return True if validDirective() and self._action is not None: return 'script' return 'directive' return 'statements' return None
python
def category(self) -> Optional[str]: '''Determine the category of existing statement''' if self.statements: if self.statements[-1][0] == ':': # a hack. ... to avoid calling isValid recursively def validDirective(): if not self.values: return True if self.values[-1].strip().endswith(','): return False try: compile( 'func(' + ''.join(self.values) + ')', filename='<string>', mode='eval') except Exception: return False return True if validDirective() and self._action is not None: return 'script' return 'directive' return 'statements' return None
[ "def", "category", "(", "self", ")", "->", "Optional", "[", "str", "]", ":", "if", "self", ".", "statements", ":", "if", "self", ".", "statements", "[", "-", "1", "]", "[", "0", "]", "==", "':'", ":", "# a hack. ... to avoid calling isValid recursively", "def", "validDirective", "(", ")", ":", "if", "not", "self", ".", "values", ":", "return", "True", "if", "self", ".", "values", "[", "-", "1", "]", ".", "strip", "(", ")", ".", "endswith", "(", "','", ")", ":", "return", "False", "try", ":", "compile", "(", "'func('", "+", "''", ".", "join", "(", "self", ".", "values", ")", "+", "')'", ",", "filename", "=", "'<string>'", ",", "mode", "=", "'eval'", ")", "except", "Exception", ":", "return", "False", "return", "True", "if", "validDirective", "(", ")", "and", "self", ".", "_action", "is", "not", "None", ":", "return", "'script'", "return", "'directive'", "return", "'statements'", "return", "None" ]
Determine the category of existing statement
[ "Determine", "the", "category", "of", "existing", "statement" ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/parser.py#L305-L328
train
vatlab/SoS
src/sos/parser.py
SoS_Step.isValid
def isValid(self) -> bool: '''Determine if the statement, expression or directive is valid. Otherwise the parser will continue until a valid multi-line expression or statement can be found.''' if not self.values: return True try: if self.category() == 'directive': # we add func() because the expression can be multi-line and # can have keyword-argument like options # # However, python considers # # func('value', ) # # a valid syntax but we do want , to continue to the next line if self.values[-1].strip().endswith(','): self.error_msg = 'Trailing ,' return False # to allow type trait, we will have to test the expression as if in a function # definition, with something like "def func(a : str, b : list=[])" try: compile( 'func(' + ''.join(self.values) + ')', filename='<string>', mode='eval') except: compile( 'def func(' + ''.join(self.values) + '):\n pass', filename='<string>', mode='exec') elif self.category() == 'statements': compile((''.join(self.values)), filename='<string>', mode='exec') elif self.category() == 'script': # # A valid script has an identation defined at the first line. That is to say # # line 1 # line 2 # # is allowed # # line 1 # line 2 # # line 3 # # is not so the addition of line 3 would fail. However, the last line # will be tested before inserted so this function will always return True return True else: raise RuntimeError( f'Unrecognized expression type {self.category()}') return True except Exception as e: self.error_msg = repr(e) return False
python
def isValid(self) -> bool: '''Determine if the statement, expression or directive is valid. Otherwise the parser will continue until a valid multi-line expression or statement can be found.''' if not self.values: return True try: if self.category() == 'directive': # we add func() because the expression can be multi-line and # can have keyword-argument like options # # However, python considers # # func('value', ) # # a valid syntax but we do want , to continue to the next line if self.values[-1].strip().endswith(','): self.error_msg = 'Trailing ,' return False # to allow type trait, we will have to test the expression as if in a function # definition, with something like "def func(a : str, b : list=[])" try: compile( 'func(' + ''.join(self.values) + ')', filename='<string>', mode='eval') except: compile( 'def func(' + ''.join(self.values) + '):\n pass', filename='<string>', mode='exec') elif self.category() == 'statements': compile((''.join(self.values)), filename='<string>', mode='exec') elif self.category() == 'script': # # A valid script has an identation defined at the first line. That is to say # # line 1 # line 2 # # is allowed # # line 1 # line 2 # # line 3 # # is not so the addition of line 3 would fail. However, the last line # will be tested before inserted so this function will always return True return True else: raise RuntimeError( f'Unrecognized expression type {self.category()}') return True except Exception as e: self.error_msg = repr(e) return False
[ "def", "isValid", "(", "self", ")", "->", "bool", ":", "if", "not", "self", ".", "values", ":", "return", "True", "try", ":", "if", "self", ".", "category", "(", ")", "==", "'directive'", ":", "# we add func() because the expression can be multi-line and", "# can have keyword-argument like options", "#", "# However, python considers", "#", "# func('value', )", "#", "# a valid syntax but we do want , to continue to the next line", "if", "self", ".", "values", "[", "-", "1", "]", ".", "strip", "(", ")", ".", "endswith", "(", "','", ")", ":", "self", ".", "error_msg", "=", "'Trailing ,'", "return", "False", "# to allow type trait, we will have to test the expression as if in a function", "# definition, with something like \"def func(a : str, b : list=[])\"", "try", ":", "compile", "(", "'func('", "+", "''", ".", "join", "(", "self", ".", "values", ")", "+", "')'", ",", "filename", "=", "'<string>'", ",", "mode", "=", "'eval'", ")", "except", ":", "compile", "(", "'def func('", "+", "''", ".", "join", "(", "self", ".", "values", ")", "+", "'):\\n pass'", ",", "filename", "=", "'<string>'", ",", "mode", "=", "'exec'", ")", "elif", "self", ".", "category", "(", ")", "==", "'statements'", ":", "compile", "(", "(", "''", ".", "join", "(", "self", ".", "values", ")", ")", ",", "filename", "=", "'<string>'", ",", "mode", "=", "'exec'", ")", "elif", "self", ".", "category", "(", ")", "==", "'script'", ":", "#", "# A valid script has an identation defined at the first line. That is to say", "#", "# line 1", "# line 2", "#", "# is allowed", "#", "# line 1", "# line 2", "#", "# line 3", "#", "# is not so the addition of line 3 would fail. However, the last line", "# will be tested before inserted so this function will always return True", "return", "True", "else", ":", "raise", "RuntimeError", "(", "f'Unrecognized expression type {self.category()}'", ")", "return", "True", "except", "Exception", "as", "e", ":", "self", ".", "error_msg", "=", "repr", "(", "e", ")", "return", "False" ]
Determine if the statement, expression or directive is valid. Otherwise the parser will continue until a valid multi-line expression or statement can be found.
[ "Determine", "if", "the", "statement", "expression", "or", "directive", "is", "valid", ".", "Otherwise", "the", "parser", "will", "continue", "until", "a", "valid", "multi", "-", "line", "expression", "or", "statement", "can", "be", "found", "." ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/parser.py#L330-L388
train
vatlab/SoS
src/sos/parser.py
SoS_Step.extend
def extend(self, line: str) -> None: '''Extend the current directive, expression or script''' if self.category() == 'directive': self.add_directive(None, line) elif self.category() == 'script': self._script += line else: self.add_statement(line)
python
def extend(self, line: str) -> None: '''Extend the current directive, expression or script''' if self.category() == 'directive': self.add_directive(None, line) elif self.category() == 'script': self._script += line else: self.add_statement(line)
[ "def", "extend", "(", "self", ",", "line", ":", "str", ")", "->", "None", ":", "if", "self", ".", "category", "(", ")", "==", "'directive'", ":", "self", ".", "add_directive", "(", "None", ",", "line", ")", "elif", "self", ".", "category", "(", ")", "==", "'script'", ":", "self", ".", "_script", "+=", "line", "else", ":", "self", ".", "add_statement", "(", "line", ")" ]
Extend the current directive, expression or script
[ "Extend", "the", "current", "directive", "expression", "or", "script" ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/parser.py#L394-L401
train
vatlab/SoS
src/sos/parser.py
SoS_Step.add_statement
def add_statement(self, line: str, lineno: Optional[int] = None) -> None: '''statements are regular python statements''' # there can be only one statement block if self.category() != 'statements': self.values = [line] else: self.values.append(line) if self.statements and self.statements[-1][0] == '!': self.statements[-1][-1] += line else: self.statements.append(['!', line]) if lineno: self.lineno = lineno
python
def add_statement(self, line: str, lineno: Optional[int] = None) -> None: '''statements are regular python statements''' # there can be only one statement block if self.category() != 'statements': self.values = [line] else: self.values.append(line) if self.statements and self.statements[-1][0] == '!': self.statements[-1][-1] += line else: self.statements.append(['!', line]) if lineno: self.lineno = lineno
[ "def", "add_statement", "(", "self", ",", "line", ":", "str", ",", "lineno", ":", "Optional", "[", "int", "]", "=", "None", ")", "->", "None", ":", "# there can be only one statement block", "if", "self", ".", "category", "(", ")", "!=", "'statements'", ":", "self", ".", "values", "=", "[", "line", "]", "else", ":", "self", ".", "values", ".", "append", "(", "line", ")", "if", "self", ".", "statements", "and", "self", ".", "statements", "[", "-", "1", "]", "[", "0", "]", "==", "'!'", ":", "self", ".", "statements", "[", "-", "1", "]", "[", "-", "1", "]", "+=", "line", "else", ":", "self", ".", "statements", ".", "append", "(", "[", "'!'", ",", "line", "]", ")", "if", "lineno", ":", "self", ".", "lineno", "=", "lineno" ]
statements are regular python statements
[ "statements", "are", "regular", "python", "statements" ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/parser.py#L434-L446
train
vatlab/SoS
src/sos/parser.py
SoS_Step.get_tokens
def get_tokens(self) -> str: '''Get tokens after input statement''' def _get_tokens(statement): return [ x[1] for x in generate_tokens(StringIO(statement).readline) if x[1] not in ('', '\n') ] tokens: List = [] for statement in self.statements: tokens.extend( _get_tokens(statement[2] if statement[0] == ':' else statement[1])) if self.task: tokens.extend(_get_tokens(self.task)) return ' '.join(tokens)
python
def get_tokens(self) -> str: '''Get tokens after input statement''' def _get_tokens(statement): return [ x[1] for x in generate_tokens(StringIO(statement).readline) if x[1] not in ('', '\n') ] tokens: List = [] for statement in self.statements: tokens.extend( _get_tokens(statement[2] if statement[0] == ':' else statement[1])) if self.task: tokens.extend(_get_tokens(self.task)) return ' '.join(tokens)
[ "def", "get_tokens", "(", "self", ")", "->", "str", ":", "def", "_get_tokens", "(", "statement", ")", ":", "return", "[", "x", "[", "1", "]", "for", "x", "in", "generate_tokens", "(", "StringIO", "(", "statement", ")", ".", "readline", ")", "if", "x", "[", "1", "]", "not", "in", "(", "''", ",", "'\\n'", ")", "]", "tokens", ":", "List", "=", "[", "]", "for", "statement", "in", "self", ".", "statements", ":", "tokens", ".", "extend", "(", "_get_tokens", "(", "statement", "[", "2", "]", "if", "statement", "[", "0", "]", "==", "':'", "else", "statement", "[", "1", "]", ")", ")", "if", "self", ".", "task", ":", "tokens", ".", "extend", "(", "_get_tokens", "(", "self", ".", "task", ")", ")", "return", "' '", ".", "join", "(", "tokens", ")" ]
Get tokens after input statement
[ "Get", "tokens", "after", "input", "statement" ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/parser.py#L484-L503
train
vatlab/SoS
src/sos/parser.py
SoS_Step.show
def show(self): '''Output for command sos show''' textWidth = max(60, shutil.get_terminal_size((80, 20)).columns) text = f' {self.step_name() + ":":<21} ' + self.comment print('\n'.join( textwrap.wrap( text, width=textWidth, initial_indent='', subsequent_indent=' ' * 24))) local_parameters = { x: y for x, y in self.parameters.items() if x not in self.global_parameters } if local_parameters: print(' Workflow Options:') for name, (value, comment) in local_parameters.items(): par_str = f' {format_par(name, value)}' print(par_str) if comment: print('\n'.join( textwrap.wrap( comment, width=textWidth, initial_indent=' ' * 24, subsequent_indent=' ' * 24)))
python
def show(self): '''Output for command sos show''' textWidth = max(60, shutil.get_terminal_size((80, 20)).columns) text = f' {self.step_name() + ":":<21} ' + self.comment print('\n'.join( textwrap.wrap( text, width=textWidth, initial_indent='', subsequent_indent=' ' * 24))) local_parameters = { x: y for x, y in self.parameters.items() if x not in self.global_parameters } if local_parameters: print(' Workflow Options:') for name, (value, comment) in local_parameters.items(): par_str = f' {format_par(name, value)}' print(par_str) if comment: print('\n'.join( textwrap.wrap( comment, width=textWidth, initial_indent=' ' * 24, subsequent_indent=' ' * 24)))
[ "def", "show", "(", "self", ")", ":", "textWidth", "=", "max", "(", "60", ",", "shutil", ".", "get_terminal_size", "(", "(", "80", ",", "20", ")", ")", ".", "columns", ")", "text", "=", "f' {self.step_name() + \":\":<21} '", "+", "self", ".", "comment", "print", "(", "'\\n'", ".", "join", "(", "textwrap", ".", "wrap", "(", "text", ",", "width", "=", "textWidth", ",", "initial_indent", "=", "''", ",", "subsequent_indent", "=", "' '", "*", "24", ")", ")", ")", "local_parameters", "=", "{", "x", ":", "y", "for", "x", ",", "y", "in", "self", ".", "parameters", ".", "items", "(", ")", "if", "x", "not", "in", "self", ".", "global_parameters", "}", "if", "local_parameters", ":", "print", "(", "' Workflow Options:'", ")", "for", "name", ",", "(", "value", ",", "comment", ")", "in", "local_parameters", ".", "items", "(", ")", ":", "par_str", "=", "f' {format_par(name, value)}'", "print", "(", "par_str", ")", "if", "comment", ":", "print", "(", "'\\n'", ".", "join", "(", "textwrap", ".", "wrap", "(", "comment", ",", "width", "=", "textWidth", ",", "initial_indent", "=", "' '", "*", "24", ",", "subsequent_indent", "=", "' '", "*", "24", ")", ")", ")" ]
Output for command sos show
[ "Output", "for", "command", "sos", "show" ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/parser.py#L610-L636
train
vatlab/SoS
src/sos/parser.py
SoS_Workflow.extend
def extend(self, workflow: 'SoS_Workflow') -> None: '''Append another workflow to existing one to created a combined workflow''' # all sections are simply appended ... # but we will need to make sure that the new workflow is # executed after the previous one. if not workflow.sections: return if not self.sections: self.sections = workflow.sections return section = workflow.sections[0] depends_idx = [ idx for idx, stmt in enumerate(section.statements) if stmt[0] == ':' and stmt[1] == 'depends' ] if not depends_idx: section.statements.insert(0, [ ':', 'depends', f"sos_step('{self.sections[-1].step_name()}')" ]) else: section.statements[depends_idx[0]][2] = section.statements[depends_idx[0]][2].strip() + \ (", " if section.statements[depends_idx[0]][2].strip() else "") + \ f"sos_step('{self.sections[-1].step_name()}')\n" self.sections.extend(workflow.sections)
python
def extend(self, workflow: 'SoS_Workflow') -> None: '''Append another workflow to existing one to created a combined workflow''' # all sections are simply appended ... # but we will need to make sure that the new workflow is # executed after the previous one. if not workflow.sections: return if not self.sections: self.sections = workflow.sections return section = workflow.sections[0] depends_idx = [ idx for idx, stmt in enumerate(section.statements) if stmt[0] == ':' and stmt[1] == 'depends' ] if not depends_idx: section.statements.insert(0, [ ':', 'depends', f"sos_step('{self.sections[-1].step_name()}')" ]) else: section.statements[depends_idx[0]][2] = section.statements[depends_idx[0]][2].strip() + \ (", " if section.statements[depends_idx[0]][2].strip() else "") + \ f"sos_step('{self.sections[-1].step_name()}')\n" self.sections.extend(workflow.sections)
[ "def", "extend", "(", "self", ",", "workflow", ":", "'SoS_Workflow'", ")", "->", "None", ":", "# all sections are simply appended ...", "# but we will need to make sure that the new workflow is", "# executed after the previous one.", "if", "not", "workflow", ".", "sections", ":", "return", "if", "not", "self", ".", "sections", ":", "self", ".", "sections", "=", "workflow", ".", "sections", "return", "section", "=", "workflow", ".", "sections", "[", "0", "]", "depends_idx", "=", "[", "idx", "for", "idx", ",", "stmt", "in", "enumerate", "(", "section", ".", "statements", ")", "if", "stmt", "[", "0", "]", "==", "':'", "and", "stmt", "[", "1", "]", "==", "'depends'", "]", "if", "not", "depends_idx", ":", "section", ".", "statements", ".", "insert", "(", "0", ",", "[", "':'", ",", "'depends'", ",", "f\"sos_step('{self.sections[-1].step_name()}')\"", "]", ")", "else", ":", "section", ".", "statements", "[", "depends_idx", "[", "0", "]", "]", "[", "2", "]", "=", "section", ".", "statements", "[", "depends_idx", "[", "0", "]", "]", "[", "2", "]", ".", "strip", "(", ")", "+", "(", "\", \"", "if", "section", ".", "statements", "[", "depends_idx", "[", "0", "]", "]", "[", "2", "]", ".", "strip", "(", ")", "else", "\"\"", ")", "+", "f\"sos_step('{self.sections[-1].step_name()}')\\n\"", "self", ".", "sections", ".", "extend", "(", "workflow", ".", "sections", ")" ]
Append another workflow to existing one to created a combined workflow
[ "Append", "another", "workflow", "to", "existing", "one", "to", "created", "a", "combined", "workflow" ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/parser.py#L732-L755
train
vatlab/SoS
src/sos/parser.py
SoS_Script.add_comment
def add_comment(self, line: str) -> None: '''Keeping track of "last comment" for section and parameter ''' # the rule is like # # # comment line --> add to last comment # blank line --> clears last comment # [ ] --> use last comment # parameter: --> use last comment # All others: clear last comment self._last_comment += (' ' if self._last_comment else '') + \ line.lstrip('#').strip()
python
def add_comment(self, line: str) -> None: '''Keeping track of "last comment" for section and parameter ''' # the rule is like # # # comment line --> add to last comment # blank line --> clears last comment # [ ] --> use last comment # parameter: --> use last comment # All others: clear last comment self._last_comment += (' ' if self._last_comment else '') + \ line.lstrip('#').strip()
[ "def", "add_comment", "(", "self", ",", "line", ":", "str", ")", "->", "None", ":", "# the rule is like", "#", "# # comment line --> add to last comment", "# blank line --> clears last comment", "# [ ] --> use last comment", "# parameter: --> use last comment", "# All others: clear last comment", "self", ".", "_last_comment", "+=", "(", "' '", "if", "self", ".", "_last_comment", "else", "''", ")", "+", "line", ".", "lstrip", "(", "'#'", ")", ".", "strip", "(", ")" ]
Keeping track of "last comment" for section and parameter
[ "Keeping", "track", "of", "last", "comment", "for", "section", "and", "parameter" ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/parser.py#L924-L934
train
vatlab/SoS
src/sos/parser.py
SoS_Script.workflow
def workflow(self, workflow_name: Optional[str] = None, use_default: bool = True) -> SoS_Workflow: '''Return a workflow with name_step+name_step specified in wf_name This function might be called recursively because of nested workflow.''' if workflow_name is None and not use_default: return SoS_Workflow(self.content, '', '', self.sections, self.global_stmts) allowed_steps = None if not workflow_name: wf_name = '' else: # if consists of multiple workflows if '+' in workflow_name: wfs = [] for wf in workflow_name.split('+'): if not SOS_SUBWORKFLOW.match(wf): raise ValueError( f'Incorrect workflow name {workflow_name}') # if this is a combined workflow, extra_section might be specied. wfs.append(self.workflow(wf)) combined_wf = wfs[0] for wf in wfs[1:]: combined_wf.extend(wf) combined_wf.name = workflow_name return combined_wf # if a single workflow # workflow_10:15 etc mo = SOS_SUBWORKFLOW.match(workflow_name) if not mo: raise ValueError(f'Incorrect workflow name {workflow_name}') wf_name, allowed_steps = mo.group('name', 'steps') # check source if not wf_name: if len(self.workflows) == 1: wf_name = list(self.workflows)[0] elif self.default_workflow: wf_name = self.default_workflow elif 'default' in self.workflows or '' in self.workflows: wf_name = 'default' else: raise ValueError( 'Name of workflow should be specified because ' 'the script defines more than one pipelines without a default one. ' 'Available pipelines are: {}.'.format(', '.join( self.workflows))) elif wf_name not in self.workflows and wf_name != 'default': raise ValueError( f'Workflow {wf_name} is undefined. Available workflows are: {", ".join(self.workflows)}' ) return SoS_Workflow(self.content, wf_name, allowed_steps, self.sections, self.global_stmts)
python
def workflow(self, workflow_name: Optional[str] = None, use_default: bool = True) -> SoS_Workflow: '''Return a workflow with name_step+name_step specified in wf_name This function might be called recursively because of nested workflow.''' if workflow_name is None and not use_default: return SoS_Workflow(self.content, '', '', self.sections, self.global_stmts) allowed_steps = None if not workflow_name: wf_name = '' else: # if consists of multiple workflows if '+' in workflow_name: wfs = [] for wf in workflow_name.split('+'): if not SOS_SUBWORKFLOW.match(wf): raise ValueError( f'Incorrect workflow name {workflow_name}') # if this is a combined workflow, extra_section might be specied. wfs.append(self.workflow(wf)) combined_wf = wfs[0] for wf in wfs[1:]: combined_wf.extend(wf) combined_wf.name = workflow_name return combined_wf # if a single workflow # workflow_10:15 etc mo = SOS_SUBWORKFLOW.match(workflow_name) if not mo: raise ValueError(f'Incorrect workflow name {workflow_name}') wf_name, allowed_steps = mo.group('name', 'steps') # check source if not wf_name: if len(self.workflows) == 1: wf_name = list(self.workflows)[0] elif self.default_workflow: wf_name = self.default_workflow elif 'default' in self.workflows or '' in self.workflows: wf_name = 'default' else: raise ValueError( 'Name of workflow should be specified because ' 'the script defines more than one pipelines without a default one. ' 'Available pipelines are: {}.'.format(', '.join( self.workflows))) elif wf_name not in self.workflows and wf_name != 'default': raise ValueError( f'Workflow {wf_name} is undefined. Available workflows are: {", ".join(self.workflows)}' ) return SoS_Workflow(self.content, wf_name, allowed_steps, self.sections, self.global_stmts)
[ "def", "workflow", "(", "self", ",", "workflow_name", ":", "Optional", "[", "str", "]", "=", "None", ",", "use_default", ":", "bool", "=", "True", ")", "->", "SoS_Workflow", ":", "if", "workflow_name", "is", "None", "and", "not", "use_default", ":", "return", "SoS_Workflow", "(", "self", ".", "content", ",", "''", ",", "''", ",", "self", ".", "sections", ",", "self", ".", "global_stmts", ")", "allowed_steps", "=", "None", "if", "not", "workflow_name", ":", "wf_name", "=", "''", "else", ":", "# if consists of multiple workflows", "if", "'+'", "in", "workflow_name", ":", "wfs", "=", "[", "]", "for", "wf", "in", "workflow_name", ".", "split", "(", "'+'", ")", ":", "if", "not", "SOS_SUBWORKFLOW", ".", "match", "(", "wf", ")", ":", "raise", "ValueError", "(", "f'Incorrect workflow name {workflow_name}'", ")", "# if this is a combined workflow, extra_section might be specied.", "wfs", ".", "append", "(", "self", ".", "workflow", "(", "wf", ")", ")", "combined_wf", "=", "wfs", "[", "0", "]", "for", "wf", "in", "wfs", "[", "1", ":", "]", ":", "combined_wf", ".", "extend", "(", "wf", ")", "combined_wf", ".", "name", "=", "workflow_name", "return", "combined_wf", "# if a single workflow", "# workflow_10:15 etc", "mo", "=", "SOS_SUBWORKFLOW", ".", "match", "(", "workflow_name", ")", "if", "not", "mo", ":", "raise", "ValueError", "(", "f'Incorrect workflow name {workflow_name}'", ")", "wf_name", ",", "allowed_steps", "=", "mo", ".", "group", "(", "'name'", ",", "'steps'", ")", "# check source", "if", "not", "wf_name", ":", "if", "len", "(", "self", ".", "workflows", ")", "==", "1", ":", "wf_name", "=", "list", "(", "self", ".", "workflows", ")", "[", "0", "]", "elif", "self", ".", "default_workflow", ":", "wf_name", "=", "self", ".", "default_workflow", "elif", "'default'", "in", "self", ".", "workflows", "or", "''", "in", "self", ".", "workflows", ":", "wf_name", "=", "'default'", "else", ":", "raise", "ValueError", "(", "'Name of workflow should be specified because '", "'the script defines more than one pipelines without a default one. '", "'Available pipelines are: {}.'", ".", "format", "(", "', '", ".", "join", "(", "self", ".", "workflows", ")", ")", ")", "elif", "wf_name", "not", "in", "self", ".", "workflows", "and", "wf_name", "!=", "'default'", ":", "raise", "ValueError", "(", "f'Workflow {wf_name} is undefined. Available workflows are: {\", \".join(self.workflows)}'", ")", "return", "SoS_Workflow", "(", "self", ".", "content", ",", "wf_name", ",", "allowed_steps", ",", "self", ".", "sections", ",", "self", ".", "global_stmts", ")" ]
Return a workflow with name_step+name_step specified in wf_name This function might be called recursively because of nested workflow.
[ "Return", "a", "workflow", "with", "name_step", "+", "name_step", "specified", "in", "wf_name", "This", "function", "might", "be", "called", "recursively", "because", "of", "nested", "workflow", "." ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/parser.py#L1368-L1421
train
vatlab/SoS
src/sos/parser.py
SoS_Script.print_help
def print_help(self, script_name: str): '''print a help message from the script''' textWidth = max(60, shutil.get_terminal_size((80, 20)).columns) if len(script_name) > 20: print(f'usage: sos run {script_name}') print( ' [workflow_name | -t targets] [options] [workflow_options]' ) else: print( f'usage: sos run {script_name} [workflow_name | -t targets] [options] [workflow_options]' ) print( ' workflow_name: Single or combined workflows defined in this script' ) print(' targets: One or more targets to generate') print( ' options: Single-hyphen sos parameters (see "sos run -h" for details)' ) print( ' workflow_options: Double-hyphen workflow-specific parameters' ) description = [x.lstrip('# ').strip() for x in self.description] description = textwrap.dedent('\n'.join(description)).strip() if description: print('\n' + description) # print('\nWorkflows:') print(' ' + '\n '.join(self.workflows)) # global_parameters = {} for section in self.sections: global_parameters.update(section.global_parameters) if global_parameters: print('\nGlobal Workflow Options:') for name, (value, comment) in global_parameters.items(): par_str = f' {format_par(name, value)}' print(par_str) if comment: print('\n'.join( textwrap.wrap( comment, width=textWidth, initial_indent=' ' * 24, subsequent_indent=' ' * 24))) # print('\nSections') for section in self.sections: section.show()
python
def print_help(self, script_name: str): '''print a help message from the script''' textWidth = max(60, shutil.get_terminal_size((80, 20)).columns) if len(script_name) > 20: print(f'usage: sos run {script_name}') print( ' [workflow_name | -t targets] [options] [workflow_options]' ) else: print( f'usage: sos run {script_name} [workflow_name | -t targets] [options] [workflow_options]' ) print( ' workflow_name: Single or combined workflows defined in this script' ) print(' targets: One or more targets to generate') print( ' options: Single-hyphen sos parameters (see "sos run -h" for details)' ) print( ' workflow_options: Double-hyphen workflow-specific parameters' ) description = [x.lstrip('# ').strip() for x in self.description] description = textwrap.dedent('\n'.join(description)).strip() if description: print('\n' + description) # print('\nWorkflows:') print(' ' + '\n '.join(self.workflows)) # global_parameters = {} for section in self.sections: global_parameters.update(section.global_parameters) if global_parameters: print('\nGlobal Workflow Options:') for name, (value, comment) in global_parameters.items(): par_str = f' {format_par(name, value)}' print(par_str) if comment: print('\n'.join( textwrap.wrap( comment, width=textWidth, initial_indent=' ' * 24, subsequent_indent=' ' * 24))) # print('\nSections') for section in self.sections: section.show()
[ "def", "print_help", "(", "self", ",", "script_name", ":", "str", ")", ":", "textWidth", "=", "max", "(", "60", ",", "shutil", ".", "get_terminal_size", "(", "(", "80", ",", "20", ")", ")", ".", "columns", ")", "if", "len", "(", "script_name", ")", ">", "20", ":", "print", "(", "f'usage: sos run {script_name}'", ")", "print", "(", "' [workflow_name | -t targets] [options] [workflow_options]'", ")", "else", ":", "print", "(", "f'usage: sos run {script_name} [workflow_name | -t targets] [options] [workflow_options]'", ")", "print", "(", "' workflow_name: Single or combined workflows defined in this script'", ")", "print", "(", "' targets: One or more targets to generate'", ")", "print", "(", "' options: Single-hyphen sos parameters (see \"sos run -h\" for details)'", ")", "print", "(", "' workflow_options: Double-hyphen workflow-specific parameters'", ")", "description", "=", "[", "x", ".", "lstrip", "(", "'# '", ")", ".", "strip", "(", ")", "for", "x", "in", "self", ".", "description", "]", "description", "=", "textwrap", ".", "dedent", "(", "'\\n'", ".", "join", "(", "description", ")", ")", ".", "strip", "(", ")", "if", "description", ":", "print", "(", "'\\n'", "+", "description", ")", "#", "print", "(", "'\\nWorkflows:'", ")", "print", "(", "' '", "+", "'\\n '", ".", "join", "(", "self", ".", "workflows", ")", ")", "#", "global_parameters", "=", "{", "}", "for", "section", "in", "self", ".", "sections", ":", "global_parameters", ".", "update", "(", "section", ".", "global_parameters", ")", "if", "global_parameters", ":", "print", "(", "'\\nGlobal Workflow Options:'", ")", "for", "name", ",", "(", "value", ",", "comment", ")", "in", "global_parameters", ".", "items", "(", ")", ":", "par_str", "=", "f' {format_par(name, value)}'", "print", "(", "par_str", ")", "if", "comment", ":", "print", "(", "'\\n'", ".", "join", "(", "textwrap", ".", "wrap", "(", "comment", ",", "width", "=", "textWidth", ",", "initial_indent", "=", "' '", "*", "24", ",", "subsequent_indent", "=", "' '", "*", "24", ")", ")", ")", "#", "print", "(", "'\\nSections'", ")", "for", "section", "in", "self", ".", "sections", ":", "section", ".", "show", "(", ")" ]
print a help message from the script
[ "print", "a", "help", "message", "from", "the", "script" ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/parser.py#L1423-L1472
train
vatlab/SoS
src/sos/pattern.py
glob_wildcards
def glob_wildcards(pattern: str, files: Optional[List[str]] = None ) -> Dict[str, Union[List[Any], List[str]]]: """ Glob the values of the wildcards by matching the given pattern to the filesystem. Returns a named tuple with a list of values for each wildcard. """ pattern = os.path.normpath(pattern) if sys.platform == 'win32': # we perform path matching with / slash only pattern = pattern.replace('\\', '/') first_wildcard = re.search("{[^{]", pattern) dirname = os.path.dirname(pattern[:first_wildcard.start()] ) if first_wildcard else os.path.dirname(pattern) if not dirname: dirname = "." names = [match.group('name') for match in SOS_WILDCARD.finditer(pattern)] res = {x: [] for x in names} pattern = re.compile(regex(pattern)) if files is None: files = ((os.path.join(dirpath, f) if dirpath != "." else f) for dirpath, dirnames, filenames in os.walk(dirname) for f in chain(filenames, dirnames)) for f in files: # we perform path matching with only / slash match = re.match(pattern, str(f).replace('\\', '/')) if match: for name, value in match.groupdict().items(): res[name].append(value) return res
python
def glob_wildcards(pattern: str, files: Optional[List[str]] = None ) -> Dict[str, Union[List[Any], List[str]]]: """ Glob the values of the wildcards by matching the given pattern to the filesystem. Returns a named tuple with a list of values for each wildcard. """ pattern = os.path.normpath(pattern) if sys.platform == 'win32': # we perform path matching with / slash only pattern = pattern.replace('\\', '/') first_wildcard = re.search("{[^{]", pattern) dirname = os.path.dirname(pattern[:first_wildcard.start()] ) if first_wildcard else os.path.dirname(pattern) if not dirname: dirname = "." names = [match.group('name') for match in SOS_WILDCARD.finditer(pattern)] res = {x: [] for x in names} pattern = re.compile(regex(pattern)) if files is None: files = ((os.path.join(dirpath, f) if dirpath != "." else f) for dirpath, dirnames, filenames in os.walk(dirname) for f in chain(filenames, dirnames)) for f in files: # we perform path matching with only / slash match = re.match(pattern, str(f).replace('\\', '/')) if match: for name, value in match.groupdict().items(): res[name].append(value) return res
[ "def", "glob_wildcards", "(", "pattern", ":", "str", ",", "files", ":", "Optional", "[", "List", "[", "str", "]", "]", "=", "None", ")", "->", "Dict", "[", "str", ",", "Union", "[", "List", "[", "Any", "]", ",", "List", "[", "str", "]", "]", "]", ":", "pattern", "=", "os", ".", "path", ".", "normpath", "(", "pattern", ")", "if", "sys", ".", "platform", "==", "'win32'", ":", "# we perform path matching with / slash only", "pattern", "=", "pattern", ".", "replace", "(", "'\\\\'", ",", "'/'", ")", "first_wildcard", "=", "re", ".", "search", "(", "\"{[^{]\"", ",", "pattern", ")", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "pattern", "[", ":", "first_wildcard", ".", "start", "(", ")", "]", ")", "if", "first_wildcard", "else", "os", ".", "path", ".", "dirname", "(", "pattern", ")", "if", "not", "dirname", ":", "dirname", "=", "\".\"", "names", "=", "[", "match", ".", "group", "(", "'name'", ")", "for", "match", "in", "SOS_WILDCARD", ".", "finditer", "(", "pattern", ")", "]", "res", "=", "{", "x", ":", "[", "]", "for", "x", "in", "names", "}", "pattern", "=", "re", ".", "compile", "(", "regex", "(", "pattern", ")", ")", "if", "files", "is", "None", ":", "files", "=", "(", "(", "os", ".", "path", ".", "join", "(", "dirpath", ",", "f", ")", "if", "dirpath", "!=", "\".\"", "else", "f", ")", "for", "dirpath", ",", "dirnames", ",", "filenames", "in", "os", ".", "walk", "(", "dirname", ")", "for", "f", "in", "chain", "(", "filenames", ",", "dirnames", ")", ")", "for", "f", "in", "files", ":", "# we perform path matching with only / slash", "match", "=", "re", ".", "match", "(", "pattern", ",", "str", "(", "f", ")", ".", "replace", "(", "'\\\\'", ",", "'/'", ")", ")", "if", "match", ":", "for", "name", ",", "value", "in", "match", ".", "groupdict", "(", ")", ".", "items", "(", ")", ":", "res", "[", "name", "]", ".", "append", "(", "value", ")", "return", "res" ]
Glob the values of the wildcards by matching the given pattern to the filesystem. Returns a named tuple with a list of values for each wildcard.
[ "Glob", "the", "values", "of", "the", "wildcards", "by", "matching", "the", "given", "pattern", "to", "the", "filesystem", ".", "Returns", "a", "named", "tuple", "with", "a", "list", "of", "values", "for", "each", "wildcard", "." ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/pattern.py#L56-L87
train
vatlab/SoS
src/sos/pattern.py
extract_pattern
def extract_pattern(pattern: str, ifiles: List[str]) -> Dict[str, any]: '''This function match pattern to a list of input files, extract and return pieces of filenames as a list of variables with keys defined by pattern.''' res = glob_wildcards(pattern, []) for ifile in ifiles: matched = glob_wildcards(pattern, [ifile]) for key in matched.keys(): if not matched[key]: #env.logger.warning('Filename {} does not match pattern {}. None returned.'.format(ifile, pattern)) res[key].append(None) else: res[key].extend(matched[key]) return res
python
def extract_pattern(pattern: str, ifiles: List[str]) -> Dict[str, any]: '''This function match pattern to a list of input files, extract and return pieces of filenames as a list of variables with keys defined by pattern.''' res = glob_wildcards(pattern, []) for ifile in ifiles: matched = glob_wildcards(pattern, [ifile]) for key in matched.keys(): if not matched[key]: #env.logger.warning('Filename {} does not match pattern {}. None returned.'.format(ifile, pattern)) res[key].append(None) else: res[key].extend(matched[key]) return res
[ "def", "extract_pattern", "(", "pattern", ":", "str", ",", "ifiles", ":", "List", "[", "str", "]", ")", "->", "Dict", "[", "str", ",", "any", "]", ":", "res", "=", "glob_wildcards", "(", "pattern", ",", "[", "]", ")", "for", "ifile", "in", "ifiles", ":", "matched", "=", "glob_wildcards", "(", "pattern", ",", "[", "ifile", "]", ")", "for", "key", "in", "matched", ".", "keys", "(", ")", ":", "if", "not", "matched", "[", "key", "]", ":", "#env.logger.warning('Filename {} does not match pattern {}. None returned.'.format(ifile, pattern))", "res", "[", "key", "]", ".", "append", "(", "None", ")", "else", ":", "res", "[", "key", "]", ".", "extend", "(", "matched", "[", "key", "]", ")", "return", "res" ]
This function match pattern to a list of input files, extract and return pieces of filenames as a list of variables with keys defined by pattern.
[ "This", "function", "match", "pattern", "to", "a", "list", "of", "input", "files", "extract", "and", "return", "pieces", "of", "filenames", "as", "a", "list", "of", "variables", "with", "keys", "defined", "by", "pattern", "." ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/pattern.py#L115-L127
train
vatlab/SoS
src/sos/pattern.py
expand_pattern
def expand_pattern(pattern: str) -> List[str]: '''This function expand patterns against the current namespace and return a list of filenames''' ofiles = [] sz = None res = glob_wildcards(pattern, []) sz = None wildcard = [{}] for key in res.keys(): if key not in env.sos_dict: raise ValueError(f'Undefined variable {key} in pattern {pattern}') if not isinstance(env.sos_dict[key], str) and isinstance( env.sos_dict[key], collections.Sequence): if sz is None: sz = len(env.sos_dict[key]) wildcard = [copy.deepcopy(wildcard[0]) for x in range(sz)] elif sz != len(env.sos_dict[key]): raise ValueError( f'Variables in output pattern should have the same length (other={sz}, len({key})={len(env.sos_dict[key])})' ) for idx, value in enumerate(env.sos_dict[key]): wildcard[idx][key] = value else: for v in wildcard: v[key] = env.sos_dict[key] # for card in wildcard: ofiles.append( apply_wildcards( pattern, card, fill_missing=False, fail_dynamic=False, dynamic_fill=None, keep_dynamic=False)) return ofiles
python
def expand_pattern(pattern: str) -> List[str]: '''This function expand patterns against the current namespace and return a list of filenames''' ofiles = [] sz = None res = glob_wildcards(pattern, []) sz = None wildcard = [{}] for key in res.keys(): if key not in env.sos_dict: raise ValueError(f'Undefined variable {key} in pattern {pattern}') if not isinstance(env.sos_dict[key], str) and isinstance( env.sos_dict[key], collections.Sequence): if sz is None: sz = len(env.sos_dict[key]) wildcard = [copy.deepcopy(wildcard[0]) for x in range(sz)] elif sz != len(env.sos_dict[key]): raise ValueError( f'Variables in output pattern should have the same length (other={sz}, len({key})={len(env.sos_dict[key])})' ) for idx, value in enumerate(env.sos_dict[key]): wildcard[idx][key] = value else: for v in wildcard: v[key] = env.sos_dict[key] # for card in wildcard: ofiles.append( apply_wildcards( pattern, card, fill_missing=False, fail_dynamic=False, dynamic_fill=None, keep_dynamic=False)) return ofiles
[ "def", "expand_pattern", "(", "pattern", ":", "str", ")", "->", "List", "[", "str", "]", ":", "ofiles", "=", "[", "]", "sz", "=", "None", "res", "=", "glob_wildcards", "(", "pattern", ",", "[", "]", ")", "sz", "=", "None", "wildcard", "=", "[", "{", "}", "]", "for", "key", "in", "res", ".", "keys", "(", ")", ":", "if", "key", "not", "in", "env", ".", "sos_dict", ":", "raise", "ValueError", "(", "f'Undefined variable {key} in pattern {pattern}'", ")", "if", "not", "isinstance", "(", "env", ".", "sos_dict", "[", "key", "]", ",", "str", ")", "and", "isinstance", "(", "env", ".", "sos_dict", "[", "key", "]", ",", "collections", ".", "Sequence", ")", ":", "if", "sz", "is", "None", ":", "sz", "=", "len", "(", "env", ".", "sos_dict", "[", "key", "]", ")", "wildcard", "=", "[", "copy", ".", "deepcopy", "(", "wildcard", "[", "0", "]", ")", "for", "x", "in", "range", "(", "sz", ")", "]", "elif", "sz", "!=", "len", "(", "env", ".", "sos_dict", "[", "key", "]", ")", ":", "raise", "ValueError", "(", "f'Variables in output pattern should have the same length (other={sz}, len({key})={len(env.sos_dict[key])})'", ")", "for", "idx", ",", "value", "in", "enumerate", "(", "env", ".", "sos_dict", "[", "key", "]", ")", ":", "wildcard", "[", "idx", "]", "[", "key", "]", "=", "value", "else", ":", "for", "v", "in", "wildcard", ":", "v", "[", "key", "]", "=", "env", ".", "sos_dict", "[", "key", "]", "#", "for", "card", "in", "wildcard", ":", "ofiles", ".", "append", "(", "apply_wildcards", "(", "pattern", ",", "card", ",", "fill_missing", "=", "False", ",", "fail_dynamic", "=", "False", ",", "dynamic_fill", "=", "None", ",", "keep_dynamic", "=", "False", ")", ")", "return", "ofiles" ]
This function expand patterns against the current namespace and return a list of filenames
[ "This", "function", "expand", "patterns", "against", "the", "current", "namespace", "and", "return", "a", "list", "of", "filenames" ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/pattern.py#L130-L165
train
vatlab/SoS
src/sos/eval.py
interpolate
def interpolate(text, global_dict=None, local_dict=None): '''Evaluate expressions in `text` ''' # step 1, make it a f-string (add quotation marks and f # step 2, evaluate as a string try: return eval(as_fstring(text), global_dict, local_dict) except Exception as e: raise ValueError(f'Failed to interpolate {text}: {e}')
python
def interpolate(text, global_dict=None, local_dict=None): '''Evaluate expressions in `text` ''' # step 1, make it a f-string (add quotation marks and f # step 2, evaluate as a string try: return eval(as_fstring(text), global_dict, local_dict) except Exception as e: raise ValueError(f'Failed to interpolate {text}: {e}')
[ "def", "interpolate", "(", "text", ",", "global_dict", "=", "None", ",", "local_dict", "=", "None", ")", ":", "# step 1, make it a f-string (add quotation marks and f", "# step 2, evaluate as a string", "try", ":", "return", "eval", "(", "as_fstring", "(", "text", ")", ",", "global_dict", ",", "local_dict", ")", "except", "Exception", "as", "e", ":", "raise", "ValueError", "(", "f'Failed to interpolate {text}: {e}'", ")" ]
Evaluate expressions in `text`
[ "Evaluate", "expressions", "in", "text" ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/eval.py#L15-L22
train
vatlab/SoS
src/sos/eval.py
SoS_eval
def SoS_eval(expr: str, extra_dict: dict = {}) -> Any: '''Evaluate an expression with sos dict.''' return eval(expr, env.sos_dict.dict(), extra_dict)
python
def SoS_eval(expr: str, extra_dict: dict = {}) -> Any: '''Evaluate an expression with sos dict.''' return eval(expr, env.sos_dict.dict(), extra_dict)
[ "def", "SoS_eval", "(", "expr", ":", "str", ",", "extra_dict", ":", "dict", "=", "{", "}", ")", "->", "Any", ":", "return", "eval", "(", "expr", ",", "env", ".", "sos_dict", ".", "dict", "(", ")", ",", "extra_dict", ")" ]
Evaluate an expression with sos dict.
[ "Evaluate", "an", "expression", "with", "sos", "dict", "." ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/eval.py#L96-L98
train
vatlab/SoS
src/sos/eval.py
SoS_exec
def SoS_exec(script: str, _dict: dict = None, return_result: bool = True) -> None: '''Execute a statement.''' if _dict is None: _dict = env.sos_dict.dict() if not return_result: exec( compile(script, filename=stmtHash.hash(script), mode='exec'), _dict) return None try: stmts = list(ast.iter_child_nodes(ast.parse(script))) if not stmts: return if isinstance(stmts[-1], ast.Expr): # the last one is an expression and we will try to return the results # so we first execute the previous statements if len(stmts) > 1: exec( compile( ast.Module(body=stmts[:-1]), filename=stmtHash.hash(script), mode="exec"), _dict) # then we eval the last one res = eval( compile( ast.Expression(body=stmts[-1].value), filename=stmtHash.hash(script), mode="eval"), _dict) else: # otherwise we just execute the entire code exec( compile(script, filename=stmtHash.hash(script), mode='exec'), _dict) res = None except SyntaxError as e: raise SyntaxError(f"Invalid code {script}: {e}") # if check_readonly: # env.sos_dict.check_readonly_vars() return res
python
def SoS_exec(script: str, _dict: dict = None, return_result: bool = True) -> None: '''Execute a statement.''' if _dict is None: _dict = env.sos_dict.dict() if not return_result: exec( compile(script, filename=stmtHash.hash(script), mode='exec'), _dict) return None try: stmts = list(ast.iter_child_nodes(ast.parse(script))) if not stmts: return if isinstance(stmts[-1], ast.Expr): # the last one is an expression and we will try to return the results # so we first execute the previous statements if len(stmts) > 1: exec( compile( ast.Module(body=stmts[:-1]), filename=stmtHash.hash(script), mode="exec"), _dict) # then we eval the last one res = eval( compile( ast.Expression(body=stmts[-1].value), filename=stmtHash.hash(script), mode="eval"), _dict) else: # otherwise we just execute the entire code exec( compile(script, filename=stmtHash.hash(script), mode='exec'), _dict) res = None except SyntaxError as e: raise SyntaxError(f"Invalid code {script}: {e}") # if check_readonly: # env.sos_dict.check_readonly_vars() return res
[ "def", "SoS_exec", "(", "script", ":", "str", ",", "_dict", ":", "dict", "=", "None", ",", "return_result", ":", "bool", "=", "True", ")", "->", "None", ":", "if", "_dict", "is", "None", ":", "_dict", "=", "env", ".", "sos_dict", ".", "dict", "(", ")", "if", "not", "return_result", ":", "exec", "(", "compile", "(", "script", ",", "filename", "=", "stmtHash", ".", "hash", "(", "script", ")", ",", "mode", "=", "'exec'", ")", ",", "_dict", ")", "return", "None", "try", ":", "stmts", "=", "list", "(", "ast", ".", "iter_child_nodes", "(", "ast", ".", "parse", "(", "script", ")", ")", ")", "if", "not", "stmts", ":", "return", "if", "isinstance", "(", "stmts", "[", "-", "1", "]", ",", "ast", ".", "Expr", ")", ":", "# the last one is an expression and we will try to return the results", "# so we first execute the previous statements", "if", "len", "(", "stmts", ")", ">", "1", ":", "exec", "(", "compile", "(", "ast", ".", "Module", "(", "body", "=", "stmts", "[", ":", "-", "1", "]", ")", ",", "filename", "=", "stmtHash", ".", "hash", "(", "script", ")", ",", "mode", "=", "\"exec\"", ")", ",", "_dict", ")", "# then we eval the last one", "res", "=", "eval", "(", "compile", "(", "ast", ".", "Expression", "(", "body", "=", "stmts", "[", "-", "1", "]", ".", "value", ")", ",", "filename", "=", "stmtHash", ".", "hash", "(", "script", ")", ",", "mode", "=", "\"eval\"", ")", ",", "_dict", ")", "else", ":", "# otherwise we just execute the entire code", "exec", "(", "compile", "(", "script", ",", "filename", "=", "stmtHash", ".", "hash", "(", "script", ")", ",", "mode", "=", "'exec'", ")", ",", "_dict", ")", "res", "=", "None", "except", "SyntaxError", "as", "e", ":", "raise", "SyntaxError", "(", "f\"Invalid code {script}: {e}\"", ")", "# if check_readonly:", "# env.sos_dict.check_readonly_vars()", "return", "res" ]
Execute a statement.
[ "Execute", "a", "statement", "." ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/eval.py#L127-L168
train
vatlab/SoS
src/sos/step_executor.py
expand_depends_files
def expand_depends_files(*args, **kwargs): '''handle directive depends''' args = [x.resolve() if isinstance(x, dynamic) else x for x in args] kwargs = { x: (y.resolve() if isinstance(y, dynamic) else y) for x, y in kwargs.items() } return sos_targets( *args, **kwargs, _verify_existence=True, _undetermined=False, _source=env.sos_dict['step_name'])
python
def expand_depends_files(*args, **kwargs): '''handle directive depends''' args = [x.resolve() if isinstance(x, dynamic) else x for x in args] kwargs = { x: (y.resolve() if isinstance(y, dynamic) else y) for x, y in kwargs.items() } return sos_targets( *args, **kwargs, _verify_existence=True, _undetermined=False, _source=env.sos_dict['step_name'])
[ "def", "expand_depends_files", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "args", "=", "[", "x", ".", "resolve", "(", ")", "if", "isinstance", "(", "x", ",", "dynamic", ")", "else", "x", "for", "x", "in", "args", "]", "kwargs", "=", "{", "x", ":", "(", "y", ".", "resolve", "(", ")", "if", "isinstance", "(", "y", ",", "dynamic", ")", "else", "y", ")", "for", "x", ",", "y", "in", "kwargs", ".", "items", "(", ")", "}", "return", "sos_targets", "(", "*", "args", ",", "*", "*", "kwargs", ",", "_verify_existence", "=", "True", ",", "_undetermined", "=", "False", ",", "_source", "=", "env", ".", "sos_dict", "[", "'step_name'", "]", ")" ]
handle directive depends
[ "handle", "directive", "depends" ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/step_executor.py#L209-L221
train
vatlab/SoS
src/sos/step_executor.py
Step_Executor.wait_for_subworkflows
def wait_for_subworkflows(self, workflow_results): '''Wait for results from subworkflows''' wf_ids = sum([x['pending_workflows'] for x in workflow_results], []) for wf_id in wf_ids: # here we did not check if workflow ids match yield self.socket res = self.socket.recv_pyobj() if res is None: sys.exit(0) elif isinstance(res, Exception): raise res
python
def wait_for_subworkflows(self, workflow_results): '''Wait for results from subworkflows''' wf_ids = sum([x['pending_workflows'] for x in workflow_results], []) for wf_id in wf_ids: # here we did not check if workflow ids match yield self.socket res = self.socket.recv_pyobj() if res is None: sys.exit(0) elif isinstance(res, Exception): raise res
[ "def", "wait_for_subworkflows", "(", "self", ",", "workflow_results", ")", ":", "wf_ids", "=", "sum", "(", "[", "x", "[", "'pending_workflows'", "]", "for", "x", "in", "workflow_results", "]", ",", "[", "]", ")", "for", "wf_id", "in", "wf_ids", ":", "# here we did not check if workflow ids match", "yield", "self", ".", "socket", "res", "=", "self", ".", "socket", ".", "recv_pyobj", "(", ")", "if", "res", "is", "None", ":", "sys", ".", "exit", "(", "0", ")", "elif", "isinstance", "(", "res", ",", "Exception", ")", ":", "raise", "res" ]
Wait for results from subworkflows
[ "Wait", "for", "results", "from", "subworkflows" ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/step_executor.py#L1852-L1862
train
vatlab/SoS
src/sos/actions_r.py
Rmarkdown
def Rmarkdown(script=None, input=None, output=None, args='{input:r}, output_file={output:ar}', **kwargs): '''Convert input file to output using Rmarkdown The input can be specified in three ways: 1. instant script, which is assumed to be in md format Rmarkdown: output='report.html' script 2. one or more input files. The format is determined by extension of input file Rmarkdown(input, output='report.html') 3. input file specified by command line option `-r` . Rmarkdown(output='report.html') If no output is specified, it is assumed to be in html format and is written to standard output. You can specify more options using the args parameter of the action. The default value of args is `${input!r} --output ${output!ar}' ''' if not R_library('rmarkdown').target_exists(): raise RuntimeError('Library rmarkdown does not exist') input = sos_targets(collect_input(script, input)) output = sos_targets(output) if len(output) == 0: write_to_stdout = True output = sos_targets( tempfile.NamedTemporaryFile( mode='w+t', suffix='.html', delete=False).name) else: write_to_stdout = False # ret = 1 try: # render(input, output_format = NULL, output_file = NULL, output_dir = NULL, # output_options = NULL, intermediates_dir = NULL, # runtime = c("auto", "static", "shiny"), # clean = TRUE, params = NULL, knit_meta = NULL, envir = parent.frame(), # run_Rmarkdown = TRUE, quiet = FALSE, encoding = getOption("encoding")) cmd = interpolate(f'Rscript -e "rmarkdown::render({args})"', { 'input': input, 'output': output }) if 'ACTION' in env.config['SOS_DEBUG'] or 'ALL' in env.config['SOS_DEBUG']: env.log_to_file('ACTION', f'Running command "{cmd}"') if env.config['run_mode'] == 'interactive': # need to catch output and send to python output, which will in trun be hijacked by SoS notebook p = subprocess.Popen( cmd, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE) #pid = p.pid out, err = p.communicate() sys.stdout.write(out.decode()) sys.stderr.write(err.decode()) ret = p.returncode else: p = subprocess.Popen(cmd, shell=True) #pid = p.pid ret = p.wait() except Exception as e: env.logger.error(e) if ret != 0: temp_file = os.path.join('.sos', f'{"Rmarkdown"}_{os.getpid()}.md') shutil.copyfile(str(input), temp_file) cmd = interpolate(f'Rscript -e "rmarkdown::render({args})"', { 'input': input, 'output': sos_targets(temp_file) }) raise RuntimeError( f'Failed to execute script. Please use command \n"{cmd}"\nunder {os.getcwd()} to test it.' ) if write_to_stdout: with open(str(output[0])) as out: sys.stdout.write(out.read()) else: env.logger.info(f'Report saved to {output}')
python
def Rmarkdown(script=None, input=None, output=None, args='{input:r}, output_file={output:ar}', **kwargs): '''Convert input file to output using Rmarkdown The input can be specified in three ways: 1. instant script, which is assumed to be in md format Rmarkdown: output='report.html' script 2. one or more input files. The format is determined by extension of input file Rmarkdown(input, output='report.html') 3. input file specified by command line option `-r` . Rmarkdown(output='report.html') If no output is specified, it is assumed to be in html format and is written to standard output. You can specify more options using the args parameter of the action. The default value of args is `${input!r} --output ${output!ar}' ''' if not R_library('rmarkdown').target_exists(): raise RuntimeError('Library rmarkdown does not exist') input = sos_targets(collect_input(script, input)) output = sos_targets(output) if len(output) == 0: write_to_stdout = True output = sos_targets( tempfile.NamedTemporaryFile( mode='w+t', suffix='.html', delete=False).name) else: write_to_stdout = False # ret = 1 try: # render(input, output_format = NULL, output_file = NULL, output_dir = NULL, # output_options = NULL, intermediates_dir = NULL, # runtime = c("auto", "static", "shiny"), # clean = TRUE, params = NULL, knit_meta = NULL, envir = parent.frame(), # run_Rmarkdown = TRUE, quiet = FALSE, encoding = getOption("encoding")) cmd = interpolate(f'Rscript -e "rmarkdown::render({args})"', { 'input': input, 'output': output }) if 'ACTION' in env.config['SOS_DEBUG'] or 'ALL' in env.config['SOS_DEBUG']: env.log_to_file('ACTION', f'Running command "{cmd}"') if env.config['run_mode'] == 'interactive': # need to catch output and send to python output, which will in trun be hijacked by SoS notebook p = subprocess.Popen( cmd, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE) #pid = p.pid out, err = p.communicate() sys.stdout.write(out.decode()) sys.stderr.write(err.decode()) ret = p.returncode else: p = subprocess.Popen(cmd, shell=True) #pid = p.pid ret = p.wait() except Exception as e: env.logger.error(e) if ret != 0: temp_file = os.path.join('.sos', f'{"Rmarkdown"}_{os.getpid()}.md') shutil.copyfile(str(input), temp_file) cmd = interpolate(f'Rscript -e "rmarkdown::render({args})"', { 'input': input, 'output': sos_targets(temp_file) }) raise RuntimeError( f'Failed to execute script. Please use command \n"{cmd}"\nunder {os.getcwd()} to test it.' ) if write_to_stdout: with open(str(output[0])) as out: sys.stdout.write(out.read()) else: env.logger.info(f'Report saved to {output}')
[ "def", "Rmarkdown", "(", "script", "=", "None", ",", "input", "=", "None", ",", "output", "=", "None", ",", "args", "=", "'{input:r}, output_file={output:ar}'", ",", "*", "*", "kwargs", ")", ":", "if", "not", "R_library", "(", "'rmarkdown'", ")", ".", "target_exists", "(", ")", ":", "raise", "RuntimeError", "(", "'Library rmarkdown does not exist'", ")", "input", "=", "sos_targets", "(", "collect_input", "(", "script", ",", "input", ")", ")", "output", "=", "sos_targets", "(", "output", ")", "if", "len", "(", "output", ")", "==", "0", ":", "write_to_stdout", "=", "True", "output", "=", "sos_targets", "(", "tempfile", ".", "NamedTemporaryFile", "(", "mode", "=", "'w+t'", ",", "suffix", "=", "'.html'", ",", "delete", "=", "False", ")", ".", "name", ")", "else", ":", "write_to_stdout", "=", "False", "#", "ret", "=", "1", "try", ":", "# render(input, output_format = NULL, output_file = NULL, output_dir = NULL,", "# output_options = NULL, intermediates_dir = NULL,", "# runtime = c(\"auto\", \"static\", \"shiny\"),", "# clean = TRUE, params = NULL, knit_meta = NULL, envir = parent.frame(),", "# run_Rmarkdown = TRUE, quiet = FALSE, encoding = getOption(\"encoding\"))", "cmd", "=", "interpolate", "(", "f'Rscript -e \"rmarkdown::render({args})\"'", ",", "{", "'input'", ":", "input", ",", "'output'", ":", "output", "}", ")", "if", "'ACTION'", "in", "env", ".", "config", "[", "'SOS_DEBUG'", "]", "or", "'ALL'", "in", "env", ".", "config", "[", "'SOS_DEBUG'", "]", ":", "env", ".", "log_to_file", "(", "'ACTION'", ",", "f'Running command \"{cmd}\"'", ")", "if", "env", ".", "config", "[", "'run_mode'", "]", "==", "'interactive'", ":", "# need to catch output and send to python output, which will in trun be hijacked by SoS notebook", "p", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "shell", "=", "True", ",", "stderr", "=", "subprocess", ".", "PIPE", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "#pid = p.pid", "out", ",", "err", "=", "p", ".", "communicate", "(", ")", "sys", ".", "stdout", ".", "write", "(", "out", ".", "decode", "(", ")", ")", "sys", ".", "stderr", ".", "write", "(", "err", ".", "decode", "(", ")", ")", "ret", "=", "p", ".", "returncode", "else", ":", "p", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "shell", "=", "True", ")", "#pid = p.pid", "ret", "=", "p", ".", "wait", "(", ")", "except", "Exception", "as", "e", ":", "env", ".", "logger", ".", "error", "(", "e", ")", "if", "ret", "!=", "0", ":", "temp_file", "=", "os", ".", "path", ".", "join", "(", "'.sos'", ",", "f'{\"Rmarkdown\"}_{os.getpid()}.md'", ")", "shutil", ".", "copyfile", "(", "str", "(", "input", ")", ",", "temp_file", ")", "cmd", "=", "interpolate", "(", "f'Rscript -e \"rmarkdown::render({args})\"'", ",", "{", "'input'", ":", "input", ",", "'output'", ":", "sos_targets", "(", "temp_file", ")", "}", ")", "raise", "RuntimeError", "(", "f'Failed to execute script. Please use command \\n\"{cmd}\"\\nunder {os.getcwd()} to test it.'", ")", "if", "write_to_stdout", ":", "with", "open", "(", "str", "(", "output", "[", "0", "]", ")", ")", "as", "out", ":", "sys", ".", "stdout", ".", "write", "(", "out", ".", "read", "(", ")", ")", "else", ":", "env", ".", "logger", ".", "info", "(", "f'Report saved to {output}'", ")" ]
Convert input file to output using Rmarkdown The input can be specified in three ways: 1. instant script, which is assumed to be in md format Rmarkdown: output='report.html' script 2. one or more input files. The format is determined by extension of input file Rmarkdown(input, output='report.html') 3. input file specified by command line option `-r` . Rmarkdown(output='report.html') If no output is specified, it is assumed to be in html format and is written to standard output. You can specify more options using the args parameter of the action. The default value of args is `${input!r} --output ${output!ar}'
[ "Convert", "input", "file", "to", "output", "using", "Rmarkdown" ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/actions_r.py#L41-L124
train
vatlab/SoS
src/sos/docker/client.py
SoS_DockerClient.total_memory
def total_memory(self, image='ubuntu'): '''Get the available ram fo the docker machine in Kb''' try: ret = subprocess.check_output( f'''docker run -t {image} cat /proc/meminfo | grep MemTotal''', shell=True, stdin=subprocess.DEVNULL) # ret: MemTotal: 30208916 kB self.tot_mem = int(ret.split()[1]) except Exception: # some system does not have cat or grep self.tot_mem = None return self.tot_mem
python
def total_memory(self, image='ubuntu'): '''Get the available ram fo the docker machine in Kb''' try: ret = subprocess.check_output( f'''docker run -t {image} cat /proc/meminfo | grep MemTotal''', shell=True, stdin=subprocess.DEVNULL) # ret: MemTotal: 30208916 kB self.tot_mem = int(ret.split()[1]) except Exception: # some system does not have cat or grep self.tot_mem = None return self.tot_mem
[ "def", "total_memory", "(", "self", ",", "image", "=", "'ubuntu'", ")", ":", "try", ":", "ret", "=", "subprocess", ".", "check_output", "(", "f'''docker run -t {image} cat /proc/meminfo | grep MemTotal'''", ",", "shell", "=", "True", ",", "stdin", "=", "subprocess", ".", "DEVNULL", ")", "# ret: MemTotal: 30208916 kB", "self", ".", "tot_mem", "=", "int", "(", "ret", ".", "split", "(", ")", "[", "1", "]", ")", "except", "Exception", ":", "# some system does not have cat or grep", "self", ".", "tot_mem", "=", "None", "return", "self", ".", "tot_mem" ]
Get the available ram fo the docker machine in Kb
[ "Get", "the", "available", "ram", "fo", "the", "docker", "machine", "in", "Kb" ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/docker/client.py#L34-L46
train
vatlab/SoS
src/sos/actions.py
script
def script(script, interpreter='', suffix='', args='', **kwargs): '''Execute specified script using specified interpreter. This action accepts common action arguments such as input, active, workdir, docker_image and args. In particular, content of one or more files specified by option input would be prepended before the specified script.''' return SoS_ExecuteScript(script, interpreter, suffix, args).run(**kwargs)
python
def script(script, interpreter='', suffix='', args='', **kwargs): '''Execute specified script using specified interpreter. This action accepts common action arguments such as input, active, workdir, docker_image and args. In particular, content of one or more files specified by option input would be prepended before the specified script.''' return SoS_ExecuteScript(script, interpreter, suffix, args).run(**kwargs)
[ "def", "script", "(", "script", ",", "interpreter", "=", "''", ",", "suffix", "=", "''", ",", "args", "=", "''", ",", "*", "*", "kwargs", ")", ":", "return", "SoS_ExecuteScript", "(", "script", ",", "interpreter", ",", "suffix", ",", "args", ")", ".", "run", "(", "*", "*", "kwargs", ")" ]
Execute specified script using specified interpreter. This action accepts common action arguments such as input, active, workdir, docker_image and args. In particular, content of one or more files specified by option input would be prepended before the specified script.
[ "Execute", "specified", "script", "using", "specified", "interpreter", ".", "This", "action", "accepts", "common", "action", "arguments", "such", "as", "input", "active", "workdir", "docker_image", "and", "args", ".", "In", "particular", "content", "of", "one", "or", "more", "files", "specified", "by", "option", "input", "would", "be", "prepended", "before", "the", "specified", "script", "." ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/actions.py#L656-L661
train
vatlab/SoS
src/sos/actions.py
stop_if
def stop_if(expr, msg='', no_output=False): '''Abort the execution of the current step or loop and yield an warning message `msg` if `expr` is False ''' if expr: raise StopInputGroup(msg=msg, keep_output=not no_output) return 0
python
def stop_if(expr, msg='', no_output=False): '''Abort the execution of the current step or loop and yield an warning message `msg` if `expr` is False ''' if expr: raise StopInputGroup(msg=msg, keep_output=not no_output) return 0
[ "def", "stop_if", "(", "expr", ",", "msg", "=", "''", ",", "no_output", "=", "False", ")", ":", "if", "expr", ":", "raise", "StopInputGroup", "(", "msg", "=", "msg", ",", "keep_output", "=", "not", "no_output", ")", "return", "0" ]
Abort the execution of the current step or loop and yield an warning message `msg` if `expr` is False
[ "Abort", "the", "execution", "of", "the", "current", "step", "or", "loop", "and", "yield", "an", "warning", "message", "msg", "if", "expr", "is", "False" ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/actions.py#L682-L687
train
vatlab/SoS
src/sos/actions.py
download
def download(URLs, dest_dir='.', dest_file=None, decompress=False, max_jobs=5): '''Download files from specified URL, which should be space, tab or newline separated URLs. The files will be downloaded to specified destination. If `filename.md5` files are downloaded, they are used to validate downloaded `filename`. Unless otherwise specified, compressed files are decompressed. If `max_jobs` is given, a maximum of `max_jobs` concurrent download jobs will be used for each domain. This restriction applies to domain names and will be applied to multiple download instances. ''' if env.config['run_mode'] == 'dryrun': print(f'HINT: download\n{URLs}\n') return None if isinstance(URLs, str): urls = [x.strip() for x in URLs.split() if x.strip()] else: urls = list(URLs) if not urls: env.logger.debug(f'No download URL specified: {URLs}') return # if dest_file is not None and len(urls) != 1: raise RuntimeError( 'Only one URL is allowed if a destination file is specified.') # if dest_file is None: filenames = [] for idx, url in enumerate(urls): token = urllib.parse.urlparse(url) # if no scheme or netloc, the URL is not acceptable if not all([ getattr(token, qualifying_attr) for qualifying_attr in ('scheme', 'netloc') ]): raise ValueError(f'Invalid URL {url}') filename = os.path.split(token.path)[-1] if not filename: raise ValueError(f'Cannot determine destination file for {url}') filenames.append(os.path.join(dest_dir, filename)) else: token = urllib.parse.urlparse(urls[0]) if not all([ getattr(token, qualifying_attr) for qualifying_attr in ('scheme', 'netloc') ]): raise ValueError(f'Invalid URL {url}') filenames = [dest_file] # succ = [(False, None) for x in urls] with ProcessPoolExecutor(max_workers=max_jobs) as executor: for idx, (url, filename) in enumerate(zip(urls, filenames)): # if there is alot, start download succ[idx] = executor.submit(downloadURL, url, filename, decompress, idx) succ = [x.result() for x in succ] # for su, url in zip(succ, urls): # if not su: # env.logger.warning('Failed to download {}'.format(url)) failed = [y for x, y in zip(succ, urls) if not x] if failed: if len(urls) == 1: raise RuntimeError('Failed to download {urls[0]}') else: raise RuntimeError( f'Failed to download {failed[0]} ({len(failed)} out of {len(urls)})' ) return 0
python
def download(URLs, dest_dir='.', dest_file=None, decompress=False, max_jobs=5): '''Download files from specified URL, which should be space, tab or newline separated URLs. The files will be downloaded to specified destination. If `filename.md5` files are downloaded, they are used to validate downloaded `filename`. Unless otherwise specified, compressed files are decompressed. If `max_jobs` is given, a maximum of `max_jobs` concurrent download jobs will be used for each domain. This restriction applies to domain names and will be applied to multiple download instances. ''' if env.config['run_mode'] == 'dryrun': print(f'HINT: download\n{URLs}\n') return None if isinstance(URLs, str): urls = [x.strip() for x in URLs.split() if x.strip()] else: urls = list(URLs) if not urls: env.logger.debug(f'No download URL specified: {URLs}') return # if dest_file is not None and len(urls) != 1: raise RuntimeError( 'Only one URL is allowed if a destination file is specified.') # if dest_file is None: filenames = [] for idx, url in enumerate(urls): token = urllib.parse.urlparse(url) # if no scheme or netloc, the URL is not acceptable if not all([ getattr(token, qualifying_attr) for qualifying_attr in ('scheme', 'netloc') ]): raise ValueError(f'Invalid URL {url}') filename = os.path.split(token.path)[-1] if not filename: raise ValueError(f'Cannot determine destination file for {url}') filenames.append(os.path.join(dest_dir, filename)) else: token = urllib.parse.urlparse(urls[0]) if not all([ getattr(token, qualifying_attr) for qualifying_attr in ('scheme', 'netloc') ]): raise ValueError(f'Invalid URL {url}') filenames = [dest_file] # succ = [(False, None) for x in urls] with ProcessPoolExecutor(max_workers=max_jobs) as executor: for idx, (url, filename) in enumerate(zip(urls, filenames)): # if there is alot, start download succ[idx] = executor.submit(downloadURL, url, filename, decompress, idx) succ = [x.result() for x in succ] # for su, url in zip(succ, urls): # if not su: # env.logger.warning('Failed to download {}'.format(url)) failed = [y for x, y in zip(succ, urls) if not x] if failed: if len(urls) == 1: raise RuntimeError('Failed to download {urls[0]}') else: raise RuntimeError( f'Failed to download {failed[0]} ({len(failed)} out of {len(urls)})' ) return 0
[ "def", "download", "(", "URLs", ",", "dest_dir", "=", "'.'", ",", "dest_file", "=", "None", ",", "decompress", "=", "False", ",", "max_jobs", "=", "5", ")", ":", "if", "env", ".", "config", "[", "'run_mode'", "]", "==", "'dryrun'", ":", "print", "(", "f'HINT: download\\n{URLs}\\n'", ")", "return", "None", "if", "isinstance", "(", "URLs", ",", "str", ")", ":", "urls", "=", "[", "x", ".", "strip", "(", ")", "for", "x", "in", "URLs", ".", "split", "(", ")", "if", "x", ".", "strip", "(", ")", "]", "else", ":", "urls", "=", "list", "(", "URLs", ")", "if", "not", "urls", ":", "env", ".", "logger", ".", "debug", "(", "f'No download URL specified: {URLs}'", ")", "return", "#", "if", "dest_file", "is", "not", "None", "and", "len", "(", "urls", ")", "!=", "1", ":", "raise", "RuntimeError", "(", "'Only one URL is allowed if a destination file is specified.'", ")", "#", "if", "dest_file", "is", "None", ":", "filenames", "=", "[", "]", "for", "idx", ",", "url", "in", "enumerate", "(", "urls", ")", ":", "token", "=", "urllib", ".", "parse", ".", "urlparse", "(", "url", ")", "# if no scheme or netloc, the URL is not acceptable", "if", "not", "all", "(", "[", "getattr", "(", "token", ",", "qualifying_attr", ")", "for", "qualifying_attr", "in", "(", "'scheme'", ",", "'netloc'", ")", "]", ")", ":", "raise", "ValueError", "(", "f'Invalid URL {url}'", ")", "filename", "=", "os", ".", "path", ".", "split", "(", "token", ".", "path", ")", "[", "-", "1", "]", "if", "not", "filename", ":", "raise", "ValueError", "(", "f'Cannot determine destination file for {url}'", ")", "filenames", ".", "append", "(", "os", ".", "path", ".", "join", "(", "dest_dir", ",", "filename", ")", ")", "else", ":", "token", "=", "urllib", ".", "parse", ".", "urlparse", "(", "urls", "[", "0", "]", ")", "if", "not", "all", "(", "[", "getattr", "(", "token", ",", "qualifying_attr", ")", "for", "qualifying_attr", "in", "(", "'scheme'", ",", "'netloc'", ")", "]", ")", ":", "raise", "ValueError", "(", "f'Invalid URL {url}'", ")", "filenames", "=", "[", "dest_file", "]", "#", "succ", "=", "[", "(", "False", ",", "None", ")", "for", "x", "in", "urls", "]", "with", "ProcessPoolExecutor", "(", "max_workers", "=", "max_jobs", ")", "as", "executor", ":", "for", "idx", ",", "(", "url", ",", "filename", ")", "in", "enumerate", "(", "zip", "(", "urls", ",", "filenames", ")", ")", ":", "# if there is alot, start download", "succ", "[", "idx", "]", "=", "executor", ".", "submit", "(", "downloadURL", ",", "url", ",", "filename", ",", "decompress", ",", "idx", ")", "succ", "=", "[", "x", ".", "result", "(", ")", "for", "x", "in", "succ", "]", "# for su, url in zip(succ, urls):", "# if not su:", "# env.logger.warning('Failed to download {}'.format(url))", "failed", "=", "[", "y", "for", "x", ",", "y", "in", "zip", "(", "succ", ",", "urls", ")", "if", "not", "x", "]", "if", "failed", ":", "if", "len", "(", "urls", ")", "==", "1", ":", "raise", "RuntimeError", "(", "'Failed to download {urls[0]}'", ")", "else", ":", "raise", "RuntimeError", "(", "f'Failed to download {failed[0]} ({len(failed)} out of {len(urls)})'", ")", "return", "0" ]
Download files from specified URL, which should be space, tab or newline separated URLs. The files will be downloaded to specified destination. If `filename.md5` files are downloaded, they are used to validate downloaded `filename`. Unless otherwise specified, compressed files are decompressed. If `max_jobs` is given, a maximum of `max_jobs` concurrent download jobs will be used for each domain. This restriction applies to domain names and will be applied to multiple download instances.
[ "Download", "files", "from", "specified", "URL", "which", "should", "be", "space", "tab", "or", "newline", "separated", "URLs", ".", "The", "files", "will", "be", "downloaded", "to", "specified", "destination", ".", "If", "filename", ".", "md5", "files", "are", "downloaded", "they", "are", "used", "to", "validate", "downloaded", "filename", ".", "Unless", "otherwise", "specified", "compressed", "files", "are", "decompressed", ".", "If", "max_jobs", "is", "given", "a", "maximum", "of", "max_jobs", "concurrent", "download", "jobs", "will", "be", "used", "for", "each", "domain", ".", "This", "restriction", "applies", "to", "domain", "names", "and", "will", "be", "applied", "to", "multiple", "download", "instances", "." ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/actions.py#L923-L991
train
vatlab/SoS
src/sos/actions.py
run
def run(script, args='', **kwargs): '''Execute specified script using bash. This action accepts common action arguments such as input, active, workdir, docker_image and args. In particular, content of one or more files specified by option input would be prepended before the specified script.''' if sys.platform == 'win32': # in the case there is no interpreter, we put the script # at first (this is the case for windows) # and we donot add default args. interpreter = '' else: # if there is a shebang line, we ... if not script.startswith('#!'): interpreter = '/bin/bash' if not args: args = '-ev {filename:q}' else: # execute script directly interpreter = '' return SoS_ExecuteScript(script, interpreter, '', args).run(**kwargs)
python
def run(script, args='', **kwargs): '''Execute specified script using bash. This action accepts common action arguments such as input, active, workdir, docker_image and args. In particular, content of one or more files specified by option input would be prepended before the specified script.''' if sys.platform == 'win32': # in the case there is no interpreter, we put the script # at first (this is the case for windows) # and we donot add default args. interpreter = '' else: # if there is a shebang line, we ... if not script.startswith('#!'): interpreter = '/bin/bash' if not args: args = '-ev {filename:q}' else: # execute script directly interpreter = '' return SoS_ExecuteScript(script, interpreter, '', args).run(**kwargs)
[ "def", "run", "(", "script", ",", "args", "=", "''", ",", "*", "*", "kwargs", ")", ":", "if", "sys", ".", "platform", "==", "'win32'", ":", "# in the case there is no interpreter, we put the script", "# at first (this is the case for windows)", "# and we donot add default args.", "interpreter", "=", "''", "else", ":", "# if there is a shebang line, we ...", "if", "not", "script", ".", "startswith", "(", "'#!'", ")", ":", "interpreter", "=", "'/bin/bash'", "if", "not", "args", ":", "args", "=", "'-ev {filename:q}'", "else", ":", "# execute script directly", "interpreter", "=", "''", "return", "SoS_ExecuteScript", "(", "script", ",", "interpreter", ",", "''", ",", "args", ")", ".", "run", "(", "*", "*", "kwargs", ")" ]
Execute specified script using bash. This action accepts common action arguments such as input, active, workdir, docker_image and args. In particular, content of one or more files specified by option input would be prepended before the specified script.
[ "Execute", "specified", "script", "using", "bash", ".", "This", "action", "accepts", "common", "action", "arguments", "such", "as", "input", "active", "workdir", "docker_image", "and", "args", ".", "In", "particular", "content", "of", "one", "or", "more", "files", "specified", "by", "option", "input", "would", "be", "prepended", "before", "the", "specified", "script", "." ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/actions.py#L995-L1013
train
vatlab/SoS
src/sos/actions.py
pandoc
def pandoc(script=None, input=None, output=None, args='{input:q} --output {output:q}', **kwargs): '''Convert input file to output using pandoc The input can be specified in three ways: 1. instant script, which is assumed to be in md format pandoc: output='report.html' script 2. one or more input files. The format is determined by extension of input file pandoc(input, output='report.html') 3. input file specified by command line option `-r` . pandoc(output='report.html') If no output is specified, it is assumed to be in html format and is written to standard output. You can specify more options such as "from" and "to" by customizing the args parameter of the action. The default value of args is `{input:q} --output {output:q}' ''' # # # this is output format # pandoc [OPTIONS] [FILES] # Input formats: commonmark, docbook, docx, epub, haddock, html, json*, latex, # markdown, markdown_github, markdown_mmd, markdown_phpextra, # markdown_strict, mediawiki, native, odt, opml, org, rst, t2t, # textile, twiki # [ *only Pandoc's JSON version of native AST] # Output formats: asciidoc, beamer, commonmark, context, docbook, docx, dokuwiki, # dzslides, epub, epub3, fb2, haddock, html, html5, icml, json*, # latex, man, markdown, markdown_github, markdown_mmd, # markdown_phpextra, markdown_strict, mediawiki, native, odt, # opendocument, opml, org, pdf**, plain, revealjs, rst, rtf, s5, # slideous, slidy, tei, texinfo, textile # [**for pdf output, use latex or beamer and -o FILENAME.pdf] # Options: # -f FORMAT, -r FORMAT --from=FORMAT, --read=FORMAT # -t FORMAT, -w FORMAT --to=FORMAT, --write=FORMAT # -o FILENAME --output=FILENAME # --data-dir=DIRECTORY # -R --parse-raw # -S --smart # # IGNORED # if not executable('pandoc').target_exists(): raise RuntimeError('pandoc not found') input = sos_targets(collect_input(script, input)) output = sos_targets(output) if len(output) == 0: write_to_stdout = True output = sos_targets( tempfile.NamedTemporaryFile( mode='w+t', suffix='.html', delete=False).name) else: write_to_stdout = False # ret = 1 try: p = None cmd = interpolate(f'pandoc {args}', {'input': input, 'output': output}) if 'ACTION' in env.config['SOS_DEBUG'] or 'ALL' in env.config['SOS_DEBUG']: env.log_to_file('ACTION', f'Running command "{cmd}"') if env.config['run_mode'] == 'interactive': # need to catch output and send to python output, which will in trun be hijacked by SoS notebook from .utils import pexpect_run ret = pexpect_run(cmd) else: p = subprocess.Popen(cmd, shell=True) ret = p.wait() except Exception as e: env.logger.error(e) if ret != 0: temp_file = os.path.join('.sos', f'pandoc_{os.getpid()}.md') shutil.copyfile(input, temp_file) cmd = interpolate(f'pandoc {args}', { 'input': sos_targets(temp_file), 'output': sos_targets(output) }) raise RuntimeError( f'Failed to execute script. Please use command \n{cmd}\nunder {os.getcwd()} to test it.' ) if write_to_stdout: with open(output[0].fullname()) as out: sys.stdout.write(out.read()) else: env.logger.info(f'Report saved to {output}') try: os.remove(input) except Exception: pass
python
def pandoc(script=None, input=None, output=None, args='{input:q} --output {output:q}', **kwargs): '''Convert input file to output using pandoc The input can be specified in three ways: 1. instant script, which is assumed to be in md format pandoc: output='report.html' script 2. one or more input files. The format is determined by extension of input file pandoc(input, output='report.html') 3. input file specified by command line option `-r` . pandoc(output='report.html') If no output is specified, it is assumed to be in html format and is written to standard output. You can specify more options such as "from" and "to" by customizing the args parameter of the action. The default value of args is `{input:q} --output {output:q}' ''' # # # this is output format # pandoc [OPTIONS] [FILES] # Input formats: commonmark, docbook, docx, epub, haddock, html, json*, latex, # markdown, markdown_github, markdown_mmd, markdown_phpextra, # markdown_strict, mediawiki, native, odt, opml, org, rst, t2t, # textile, twiki # [ *only Pandoc's JSON version of native AST] # Output formats: asciidoc, beamer, commonmark, context, docbook, docx, dokuwiki, # dzslides, epub, epub3, fb2, haddock, html, html5, icml, json*, # latex, man, markdown, markdown_github, markdown_mmd, # markdown_phpextra, markdown_strict, mediawiki, native, odt, # opendocument, opml, org, pdf**, plain, revealjs, rst, rtf, s5, # slideous, slidy, tei, texinfo, textile # [**for pdf output, use latex or beamer and -o FILENAME.pdf] # Options: # -f FORMAT, -r FORMAT --from=FORMAT, --read=FORMAT # -t FORMAT, -w FORMAT --to=FORMAT, --write=FORMAT # -o FILENAME --output=FILENAME # --data-dir=DIRECTORY # -R --parse-raw # -S --smart # # IGNORED # if not executable('pandoc').target_exists(): raise RuntimeError('pandoc not found') input = sos_targets(collect_input(script, input)) output = sos_targets(output) if len(output) == 0: write_to_stdout = True output = sos_targets( tempfile.NamedTemporaryFile( mode='w+t', suffix='.html', delete=False).name) else: write_to_stdout = False # ret = 1 try: p = None cmd = interpolate(f'pandoc {args}', {'input': input, 'output': output}) if 'ACTION' in env.config['SOS_DEBUG'] or 'ALL' in env.config['SOS_DEBUG']: env.log_to_file('ACTION', f'Running command "{cmd}"') if env.config['run_mode'] == 'interactive': # need to catch output and send to python output, which will in trun be hijacked by SoS notebook from .utils import pexpect_run ret = pexpect_run(cmd) else: p = subprocess.Popen(cmd, shell=True) ret = p.wait() except Exception as e: env.logger.error(e) if ret != 0: temp_file = os.path.join('.sos', f'pandoc_{os.getpid()}.md') shutil.copyfile(input, temp_file) cmd = interpolate(f'pandoc {args}', { 'input': sos_targets(temp_file), 'output': sos_targets(output) }) raise RuntimeError( f'Failed to execute script. Please use command \n{cmd}\nunder {os.getcwd()} to test it.' ) if write_to_stdout: with open(output[0].fullname()) as out: sys.stdout.write(out.read()) else: env.logger.info(f'Report saved to {output}') try: os.remove(input) except Exception: pass
[ "def", "pandoc", "(", "script", "=", "None", ",", "input", "=", "None", ",", "output", "=", "None", ",", "args", "=", "'{input:q} --output {output:q}'", ",", "*", "*", "kwargs", ")", ":", "#", "# # this is output format", "# pandoc [OPTIONS] [FILES]", "# Input formats: commonmark, docbook, docx, epub, haddock, html, json*, latex,", "# markdown, markdown_github, markdown_mmd, markdown_phpextra,", "# markdown_strict, mediawiki, native, odt, opml, org, rst, t2t,", "# textile, twiki", "# [ *only Pandoc's JSON version of native AST]", "# Output formats: asciidoc, beamer, commonmark, context, docbook, docx, dokuwiki,", "# dzslides, epub, epub3, fb2, haddock, html, html5, icml, json*,", "# latex, man, markdown, markdown_github, markdown_mmd,", "# markdown_phpextra, markdown_strict, mediawiki, native, odt,", "# opendocument, opml, org, pdf**, plain, revealjs, rst, rtf, s5,", "# slideous, slidy, tei, texinfo, textile", "# [**for pdf output, use latex or beamer and -o FILENAME.pdf]", "# Options:", "# -f FORMAT, -r FORMAT --from=FORMAT, --read=FORMAT", "# -t FORMAT, -w FORMAT --to=FORMAT, --write=FORMAT", "# -o FILENAME --output=FILENAME", "# --data-dir=DIRECTORY", "# -R --parse-raw", "# -S --smart", "#", "# IGNORED", "#", "if", "not", "executable", "(", "'pandoc'", ")", ".", "target_exists", "(", ")", ":", "raise", "RuntimeError", "(", "'pandoc not found'", ")", "input", "=", "sos_targets", "(", "collect_input", "(", "script", ",", "input", ")", ")", "output", "=", "sos_targets", "(", "output", ")", "if", "len", "(", "output", ")", "==", "0", ":", "write_to_stdout", "=", "True", "output", "=", "sos_targets", "(", "tempfile", ".", "NamedTemporaryFile", "(", "mode", "=", "'w+t'", ",", "suffix", "=", "'.html'", ",", "delete", "=", "False", ")", ".", "name", ")", "else", ":", "write_to_stdout", "=", "False", "#", "ret", "=", "1", "try", ":", "p", "=", "None", "cmd", "=", "interpolate", "(", "f'pandoc {args}'", ",", "{", "'input'", ":", "input", ",", "'output'", ":", "output", "}", ")", "if", "'ACTION'", "in", "env", ".", "config", "[", "'SOS_DEBUG'", "]", "or", "'ALL'", "in", "env", ".", "config", "[", "'SOS_DEBUG'", "]", ":", "env", ".", "log_to_file", "(", "'ACTION'", ",", "f'Running command \"{cmd}\"'", ")", "if", "env", ".", "config", "[", "'run_mode'", "]", "==", "'interactive'", ":", "# need to catch output and send to python output, which will in trun be hijacked by SoS notebook", "from", ".", "utils", "import", "pexpect_run", "ret", "=", "pexpect_run", "(", "cmd", ")", "else", ":", "p", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "shell", "=", "True", ")", "ret", "=", "p", ".", "wait", "(", ")", "except", "Exception", "as", "e", ":", "env", ".", "logger", ".", "error", "(", "e", ")", "if", "ret", "!=", "0", ":", "temp_file", "=", "os", ".", "path", ".", "join", "(", "'.sos'", ",", "f'pandoc_{os.getpid()}.md'", ")", "shutil", ".", "copyfile", "(", "input", ",", "temp_file", ")", "cmd", "=", "interpolate", "(", "f'pandoc {args}'", ",", "{", "'input'", ":", "sos_targets", "(", "temp_file", ")", ",", "'output'", ":", "sos_targets", "(", "output", ")", "}", ")", "raise", "RuntimeError", "(", "f'Failed to execute script. Please use command \\n{cmd}\\nunder {os.getcwd()} to test it.'", ")", "if", "write_to_stdout", ":", "with", "open", "(", "output", "[", "0", "]", ".", "fullname", "(", ")", ")", "as", "out", ":", "sys", ".", "stdout", ".", "write", "(", "out", ".", "read", "(", ")", ")", "else", ":", "env", ".", "logger", ".", "info", "(", "f'Report saved to {output}'", ")", "try", ":", "os", ".", "remove", "(", "input", ")", "except", "Exception", ":", "pass" ]
Convert input file to output using pandoc The input can be specified in three ways: 1. instant script, which is assumed to be in md format pandoc: output='report.html' script 2. one or more input files. The format is determined by extension of input file pandoc(input, output='report.html') 3. input file specified by command line option `-r` . pandoc(output='report.html') If no output is specified, it is assumed to be in html format and is written to standard output. You can specify more options such as "from" and "to" by customizing the args parameter of the action. The default value of args is `{input:q} --output {output:q}'
[ "Convert", "input", "file", "to", "output", "using", "pandoc" ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/actions.py#L1134-L1234
train
vatlab/SoS
src/sos/section_analyzer.py
get_changed_vars
def get_changed_vars(section: SoS_Step): '''changed vars are variables that are "shared" and therefore "provides" to others ''' if 'shared' not in section.options: return set() changed_vars = set() svars = section.options['shared'] if isinstance(svars, str): changed_vars.add(svars) svars = {svars: svars} elif isinstance(svars, Sequence): for item in svars: if isinstance(item, str): changed_vars.add(item) elif isinstance(item, Mapping): changed_vars |= set(item.keys()) else: raise ValueError( f'Option shared should be a string, a mapping of expression, or list of string or mappings. {svars} provided' ) elif isinstance(svars, Mapping): changed_vars |= set(svars.keys()) else: raise ValueError( f'Option shared should be a string, a mapping of expression, or list of string or mappings. {svars} provided' ) return changed_vars
python
def get_changed_vars(section: SoS_Step): '''changed vars are variables that are "shared" and therefore "provides" to others ''' if 'shared' not in section.options: return set() changed_vars = set() svars = section.options['shared'] if isinstance(svars, str): changed_vars.add(svars) svars = {svars: svars} elif isinstance(svars, Sequence): for item in svars: if isinstance(item, str): changed_vars.add(item) elif isinstance(item, Mapping): changed_vars |= set(item.keys()) else: raise ValueError( f'Option shared should be a string, a mapping of expression, or list of string or mappings. {svars} provided' ) elif isinstance(svars, Mapping): changed_vars |= set(svars.keys()) else: raise ValueError( f'Option shared should be a string, a mapping of expression, or list of string or mappings. {svars} provided' ) return changed_vars
[ "def", "get_changed_vars", "(", "section", ":", "SoS_Step", ")", ":", "if", "'shared'", "not", "in", "section", ".", "options", ":", "return", "set", "(", ")", "changed_vars", "=", "set", "(", ")", "svars", "=", "section", ".", "options", "[", "'shared'", "]", "if", "isinstance", "(", "svars", ",", "str", ")", ":", "changed_vars", ".", "add", "(", "svars", ")", "svars", "=", "{", "svars", ":", "svars", "}", "elif", "isinstance", "(", "svars", ",", "Sequence", ")", ":", "for", "item", "in", "svars", ":", "if", "isinstance", "(", "item", ",", "str", ")", ":", "changed_vars", ".", "add", "(", "item", ")", "elif", "isinstance", "(", "item", ",", "Mapping", ")", ":", "changed_vars", "|=", "set", "(", "item", ".", "keys", "(", ")", ")", "else", ":", "raise", "ValueError", "(", "f'Option shared should be a string, a mapping of expression, or list of string or mappings. {svars} provided'", ")", "elif", "isinstance", "(", "svars", ",", "Mapping", ")", ":", "changed_vars", "|=", "set", "(", "svars", ".", "keys", "(", ")", ")", "else", ":", "raise", "ValueError", "(", "f'Option shared should be a string, a mapping of expression, or list of string or mappings. {svars} provided'", ")", "return", "changed_vars" ]
changed vars are variables that are "shared" and therefore "provides" to others
[ "changed", "vars", "are", "variables", "that", "are", "shared", "and", "therefore", "provides", "to", "others" ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/section_analyzer.py#L138-L165
train
vatlab/SoS
src/sos/section_analyzer.py
get_all_used_vars
def get_all_used_vars(section): '''Get variables which are variables used by input statement and statements before it''' all_used_vars = set() for statement in section.statements: if statement[0] == '=': all_used_vars |= accessed_vars('='.join(statement[1:3])) elif statement[0] == '!': all_used_vars |= accessed_vars(statement[1]) elif statement[0] == ':': all_used_vars |= accessed_vars(statement[2], mode='eval') if statement[1] != 'input': continue if 'paired_with' in statement[2]: try: pws = get_names_of_param( 'paired_with', statement[2], extra_dict=env.sos_dict.dict()) all_used_vars |= set(pws) except Exception as e: raise ValueError( f'Failed to parse parameter paired_with: {e}') if 'group_with' in statement[2]: try: pws = get_names_of_param( 'group_with', statement[2], extra_dict=env.sos_dict.dict()) all_used_vars |= set(pws) except Exception as e: raise ValueError( f'Failed to parse parameter group_with: {e}') if 'for_each' in statement[2]: try: pws = get_names_of_param( 'for_each', statement[2], extra_dict=env.sos_dict.dict()) for pw in pws: all_used_vars |= set(pw.split(',')) except Exception as e: raise ValueError(f'Failed to parse parameter for_each: {e}') if section.task: all_used_vars |= accessed_vars(section.task) # now we have a list of global variables that are actually used in the functions # this is specifically designed to handle the last case in #1225 func_with_vars = [ y for x, y in used_in_func(section.global_stmts).items() if x in all_used_vars ] return set.union(all_used_vars, *func_with_vars)
python
def get_all_used_vars(section): '''Get variables which are variables used by input statement and statements before it''' all_used_vars = set() for statement in section.statements: if statement[0] == '=': all_used_vars |= accessed_vars('='.join(statement[1:3])) elif statement[0] == '!': all_used_vars |= accessed_vars(statement[1]) elif statement[0] == ':': all_used_vars |= accessed_vars(statement[2], mode='eval') if statement[1] != 'input': continue if 'paired_with' in statement[2]: try: pws = get_names_of_param( 'paired_with', statement[2], extra_dict=env.sos_dict.dict()) all_used_vars |= set(pws) except Exception as e: raise ValueError( f'Failed to parse parameter paired_with: {e}') if 'group_with' in statement[2]: try: pws = get_names_of_param( 'group_with', statement[2], extra_dict=env.sos_dict.dict()) all_used_vars |= set(pws) except Exception as e: raise ValueError( f'Failed to parse parameter group_with: {e}') if 'for_each' in statement[2]: try: pws = get_names_of_param( 'for_each', statement[2], extra_dict=env.sos_dict.dict()) for pw in pws: all_used_vars |= set(pw.split(',')) except Exception as e: raise ValueError(f'Failed to parse parameter for_each: {e}') if section.task: all_used_vars |= accessed_vars(section.task) # now we have a list of global variables that are actually used in the functions # this is specifically designed to handle the last case in #1225 func_with_vars = [ y for x, y in used_in_func(section.global_stmts).items() if x in all_used_vars ] return set.union(all_used_vars, *func_with_vars)
[ "def", "get_all_used_vars", "(", "section", ")", ":", "all_used_vars", "=", "set", "(", ")", "for", "statement", "in", "section", ".", "statements", ":", "if", "statement", "[", "0", "]", "==", "'='", ":", "all_used_vars", "|=", "accessed_vars", "(", "'='", ".", "join", "(", "statement", "[", "1", ":", "3", "]", ")", ")", "elif", "statement", "[", "0", "]", "==", "'!'", ":", "all_used_vars", "|=", "accessed_vars", "(", "statement", "[", "1", "]", ")", "elif", "statement", "[", "0", "]", "==", "':'", ":", "all_used_vars", "|=", "accessed_vars", "(", "statement", "[", "2", "]", ",", "mode", "=", "'eval'", ")", "if", "statement", "[", "1", "]", "!=", "'input'", ":", "continue", "if", "'paired_with'", "in", "statement", "[", "2", "]", ":", "try", ":", "pws", "=", "get_names_of_param", "(", "'paired_with'", ",", "statement", "[", "2", "]", ",", "extra_dict", "=", "env", ".", "sos_dict", ".", "dict", "(", ")", ")", "all_used_vars", "|=", "set", "(", "pws", ")", "except", "Exception", "as", "e", ":", "raise", "ValueError", "(", "f'Failed to parse parameter paired_with: {e}'", ")", "if", "'group_with'", "in", "statement", "[", "2", "]", ":", "try", ":", "pws", "=", "get_names_of_param", "(", "'group_with'", ",", "statement", "[", "2", "]", ",", "extra_dict", "=", "env", ".", "sos_dict", ".", "dict", "(", ")", ")", "all_used_vars", "|=", "set", "(", "pws", ")", "except", "Exception", "as", "e", ":", "raise", "ValueError", "(", "f'Failed to parse parameter group_with: {e}'", ")", "if", "'for_each'", "in", "statement", "[", "2", "]", ":", "try", ":", "pws", "=", "get_names_of_param", "(", "'for_each'", ",", "statement", "[", "2", "]", ",", "extra_dict", "=", "env", ".", "sos_dict", ".", "dict", "(", ")", ")", "for", "pw", "in", "pws", ":", "all_used_vars", "|=", "set", "(", "pw", ".", "split", "(", "','", ")", ")", "except", "Exception", "as", "e", ":", "raise", "ValueError", "(", "f'Failed to parse parameter for_each: {e}'", ")", "if", "section", ".", "task", ":", "all_used_vars", "|=", "accessed_vars", "(", "section", ".", "task", ")", "# now we have a list of global variables that are actually used in the functions", "# this is specifically designed to handle the last case in #1225", "func_with_vars", "=", "[", "y", "for", "x", ",", "y", "in", "used_in_func", "(", "section", ".", "global_stmts", ")", ".", "items", "(", ")", "if", "x", "in", "all_used_vars", "]", "return", "set", ".", "union", "(", "all_used_vars", ",", "*", "func_with_vars", ")" ]
Get variables which are variables used by input statement and statements before it
[ "Get", "variables", "which", "are", "variables", "used", "by", "input", "statement", "and", "statements", "before", "it" ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/section_analyzer.py#L185-L236
train
vatlab/SoS
src/sos/section_analyzer.py
get_signature_vars
def get_signature_vars(section): '''Get signature variables which are variables that will be saved with step signatures''' # signature vars should contain parameters defined in global section # #1155 signature_vars = set( section.parameters.keys() & accessed_vars(strip_param_defs(section.global_stmts))) input_idx = find_statement(section, 'input') after_input_idx = 0 if input_idx is None else input_idx + 1 for statement in section.statements[after_input_idx:]: if statement[0] == '=': signature_vars |= accessed_vars('='.join(statement[1:3])) elif statement[0] == '!': signature_vars |= accessed_vars(statement[1]) # finally, tasks.. if section.task: signature_vars |= accessed_vars(section.task) return {x for x in signature_vars if not x.startswith('__')}
python
def get_signature_vars(section): '''Get signature variables which are variables that will be saved with step signatures''' # signature vars should contain parameters defined in global section # #1155 signature_vars = set( section.parameters.keys() & accessed_vars(strip_param_defs(section.global_stmts))) input_idx = find_statement(section, 'input') after_input_idx = 0 if input_idx is None else input_idx + 1 for statement in section.statements[after_input_idx:]: if statement[0] == '=': signature_vars |= accessed_vars('='.join(statement[1:3])) elif statement[0] == '!': signature_vars |= accessed_vars(statement[1]) # finally, tasks.. if section.task: signature_vars |= accessed_vars(section.task) return {x for x in signature_vars if not x.startswith('__')}
[ "def", "get_signature_vars", "(", "section", ")", ":", "# signature vars should contain parameters defined in global section", "# #1155", "signature_vars", "=", "set", "(", "section", ".", "parameters", ".", "keys", "(", ")", "&", "accessed_vars", "(", "strip_param_defs", "(", "section", ".", "global_stmts", ")", ")", ")", "input_idx", "=", "find_statement", "(", "section", ",", "'input'", ")", "after_input_idx", "=", "0", "if", "input_idx", "is", "None", "else", "input_idx", "+", "1", "for", "statement", "in", "section", ".", "statements", "[", "after_input_idx", ":", "]", ":", "if", "statement", "[", "0", "]", "==", "'='", ":", "signature_vars", "|=", "accessed_vars", "(", "'='", ".", "join", "(", "statement", "[", "1", ":", "3", "]", ")", ")", "elif", "statement", "[", "0", "]", "==", "'!'", ":", "signature_vars", "|=", "accessed_vars", "(", "statement", "[", "1", "]", ")", "# finally, tasks..", "if", "section", ".", "task", ":", "signature_vars", "|=", "accessed_vars", "(", "section", ".", "task", ")", "return", "{", "x", "for", "x", "in", "signature_vars", "if", "not", "x", ".", "startswith", "(", "'__'", ")", "}" ]
Get signature variables which are variables that will be saved with step signatures
[ "Get", "signature", "variables", "which", "are", "variables", "that", "will", "be", "saved", "with", "step", "signatures" ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/section_analyzer.py#L239-L261
train
vatlab/SoS
src/sos/section_analyzer.py
get_step_input
def get_step_input(section, default_input): '''Find step input ''' step_input: sos_targets = sos_targets() dynamic_input = True # look for input statement. input_idx = find_statement(section, 'input') if input_idx is None: return step_input, dynamic_input # input statement stmt = section.statements[input_idx][2] try: svars = ['output_from', 'named_output', 'sos_step', 'sos_variable'] old_values = { x: env.sos_dict.dict()[x] for x in svars if x in env.sos_dict.dict() } env.sos_dict.quick_update({ 'output_from': lambda *args, **kwargs: None, 'named_output': lambda *args, **kwargs: None, 'traced': lambda *args, **kwargs: sos_targets(*args, **kwargs), 'sos_step': no_sos_step, 'sos_variable': no_sos_variable, }) args, kwargs = SoS_eval( f'__null_func__({stmt})', extra_dict=env.sos_dict.dict()) if not args: if default_input is None: step_input = sos_targets() else: step_input = default_input elif not any(isinstance(x, (dynamic, remote)) for x in args): step_input = sos_targets(*args) except SyntaxError: raise except Exception as e: # if anything is not evalutable, keep Undetermined env.logger.debug( f'Input of step {section.name if section.index is None else f"{section.name}_{section.index}"} is set to Undertermined: {e}' ) # expression ... step_input = sos_targets(_undetermined=stmt) finally: [env.sos_dict.dict().pop(x) for x in svars] env.sos_dict.quick_update(old_values) return step_input, dynamic_input
python
def get_step_input(section, default_input): '''Find step input ''' step_input: sos_targets = sos_targets() dynamic_input = True # look for input statement. input_idx = find_statement(section, 'input') if input_idx is None: return step_input, dynamic_input # input statement stmt = section.statements[input_idx][2] try: svars = ['output_from', 'named_output', 'sos_step', 'sos_variable'] old_values = { x: env.sos_dict.dict()[x] for x in svars if x in env.sos_dict.dict() } env.sos_dict.quick_update({ 'output_from': lambda *args, **kwargs: None, 'named_output': lambda *args, **kwargs: None, 'traced': lambda *args, **kwargs: sos_targets(*args, **kwargs), 'sos_step': no_sos_step, 'sos_variable': no_sos_variable, }) args, kwargs = SoS_eval( f'__null_func__({stmt})', extra_dict=env.sos_dict.dict()) if not args: if default_input is None: step_input = sos_targets() else: step_input = default_input elif not any(isinstance(x, (dynamic, remote)) for x in args): step_input = sos_targets(*args) except SyntaxError: raise except Exception as e: # if anything is not evalutable, keep Undetermined env.logger.debug( f'Input of step {section.name if section.index is None else f"{section.name}_{section.index}"} is set to Undertermined: {e}' ) # expression ... step_input = sos_targets(_undetermined=stmt) finally: [env.sos_dict.dict().pop(x) for x in svars] env.sos_dict.quick_update(old_values) return step_input, dynamic_input
[ "def", "get_step_input", "(", "section", ",", "default_input", ")", ":", "step_input", ":", "sos_targets", "=", "sos_targets", "(", ")", "dynamic_input", "=", "True", "# look for input statement.", "input_idx", "=", "find_statement", "(", "section", ",", "'input'", ")", "if", "input_idx", "is", "None", ":", "return", "step_input", ",", "dynamic_input", "# input statement", "stmt", "=", "section", ".", "statements", "[", "input_idx", "]", "[", "2", "]", "try", ":", "svars", "=", "[", "'output_from'", ",", "'named_output'", ",", "'sos_step'", ",", "'sos_variable'", "]", "old_values", "=", "{", "x", ":", "env", ".", "sos_dict", ".", "dict", "(", ")", "[", "x", "]", "for", "x", "in", "svars", "if", "x", "in", "env", ".", "sos_dict", ".", "dict", "(", ")", "}", "env", ".", "sos_dict", ".", "quick_update", "(", "{", "'output_from'", ":", "lambda", "*", "args", ",", "*", "*", "kwargs", ":", "None", ",", "'named_output'", ":", "lambda", "*", "args", ",", "*", "*", "kwargs", ":", "None", ",", "'traced'", ":", "lambda", "*", "args", ",", "*", "*", "kwargs", ":", "sos_targets", "(", "*", "args", ",", "*", "*", "kwargs", ")", ",", "'sos_step'", ":", "no_sos_step", ",", "'sos_variable'", ":", "no_sos_variable", ",", "}", ")", "args", ",", "kwargs", "=", "SoS_eval", "(", "f'__null_func__({stmt})'", ",", "extra_dict", "=", "env", ".", "sos_dict", ".", "dict", "(", ")", ")", "if", "not", "args", ":", "if", "default_input", "is", "None", ":", "step_input", "=", "sos_targets", "(", ")", "else", ":", "step_input", "=", "default_input", "elif", "not", "any", "(", "isinstance", "(", "x", ",", "(", "dynamic", ",", "remote", ")", ")", "for", "x", "in", "args", ")", ":", "step_input", "=", "sos_targets", "(", "*", "args", ")", "except", "SyntaxError", ":", "raise", "except", "Exception", "as", "e", ":", "# if anything is not evalutable, keep Undetermined", "env", ".", "logger", ".", "debug", "(", "f'Input of step {section.name if section.index is None else f\"{section.name}_{section.index}\"} is set to Undertermined: {e}'", ")", "# expression ...", "step_input", "=", "sos_targets", "(", "_undetermined", "=", "stmt", ")", "finally", ":", "[", "env", ".", "sos_dict", ".", "dict", "(", ")", ".", "pop", "(", "x", ")", "for", "x", "in", "svars", "]", "env", ".", "sos_dict", ".", "quick_update", "(", "old_values", ")", "return", "step_input", ",", "dynamic_input" ]
Find step input
[ "Find", "step", "input" ]
6b60ed0770916d135e17322e469520d778e9d4e7
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/section_analyzer.py#L343-L391
train