output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Checks whether a document with the specified workflow id already exists in the data store.
Explain what the following Python 3 code does def exists(self, workflow_id): try: db = self._client[self.database] col = db[WORKFLOW_DATA_COLLECTION_NAME] return col.find_one({"_id": ObjectId(workflow_id)}) is not None except ConnectionFailure: raise Data...
As a python code expert, you are capable of creating scripts from specifications.
def add(self, payload=None): """ Adds a new document to the data store and returns its id. Args: payload (dict): Dictionary of initial data that should be stored in the new document in the meta section. Raises: DataStoreNotConnected: If the data store is...
Write a Python 3 script to add a new document to the data store and returns its id.
You are a Python code analyst, evaluating scripts for potential improvements.
def remove(self, workflow_id): """ Removes a document specified by its id from the data store. All associated GridFs documents are deleted as well. Args: workflow_id (str): The id of the document that represents a workflow run. Raises: DataStoreNotConnected: If...
Write a Python 3 script to remove a document specified by its id from the data store.
You are a Python code architect, reviewing and designing scalable and efficient code
Returns the document for the given workflow id.
Here you have a function in Python 3, explain what it does def get(self, workflow_id): try: db = self._client[self.database] fs = GridFSProxy(GridFS(db.unproxied_object)) return DataStoreDocument(db[WORKFLOW_DATA_COLLECTION_NAME], fs, workflow_id) except ConnectionFa...
As a Python code translator, you convert algorithms and pseudocode into Python.
def get(self, key, default=None, *, section=DataStoreDocumentSection.Data): """ Return the field specified by its key from the specified section. This method access the specified section of the workflow document and returns the value for the given key. Args: key (str): The ...
Write a Python 3 function that can return the field specified by its key from the specified section. This method access the specified section of the workflow document and returns the value for the given key. Args: key (str): The key pointing to the value that should be retrieved. It supports MongoDB's dot notation for ...
As a python code expert, you are capable of creating scripts from specifications.
def set(self, key, value, *, section=DataStoreDocumentSection.Data): """ Store a value under the specified key in the given section of the document. This method stores a value into the specified section of the workflow data store document. Any existing value is overridden. Before storing a valu...
How would you implement a function in Python 3 that stores a value under the specified key in the given section of the document. This method stores a value into the specified section of the workflow data store document. Any existing value is overridden. Before storing a value, any linked GridFS document under the speci...
You are a Python code generator, capable of creating scripts from specifications.
def push(self, key, value, *, section=DataStoreDocumentSection.Data): """ Appends a value to a list in the specified section of the document. Args: key (str): The key pointing to the value that should be stored/updated. It supports MongoDB's dot notation for nested fields. ...
How would you implement a function in Python 3 that adds a value to a list in the specified section of the document.
You are a Python code generator, capable of creating scripts from specifications.
Extends a list in the data store with the elements of values.
Can you generate a brief explanation for the following Python 3 code def extend(self, key, values, *, section=DataStoreDocumentSection.Data): key_notation = '.'.join([section, key]) if not isinstance(values, list): return False result = self._collection.update_one( {"_id...
As a Python code analyst, you investigate and solve complex coding mysteries
def _data_from_dotnotation(self, key, default=None): """ Returns the MongoDB data from a key using dot notation. Args: key (str): The key to the field in the workflow document. Supports MongoDB's dot notation for embedded fields. default (object): The default val...
Implement a function in Python 3 to return the MongoDB data for the specified key using dot notation.
As a Python code composer, you craft elegant and concise scripts.
def _encode_value(self, value): """ Encodes the value such that it can be stored into MongoDB. Any primitive types are stored directly into MongoDB, while non-primitive types are pickled and stored as GridFS objects. The id pointing to a GridFS object replaces the original value. ...
Write a Python 3 function for encoding the value into a GridFS object.
You are a Python code analyst, evaluating scripts for potential improvements.
def _decode_value(self, value): """ Decodes the value by turning any binary data back into Python objects. The method searches for ObjectId values, loads the associated binary data from GridFS and returns the decoded Python object. Args: value (object): The value that shoul...
How would you code a function in Python 3 to decode the value into a Python object.
As a Python code analyst, you investigate and solve complex coding mysteries
def _delete_gridfs_data(self, data): """ Delete all GridFS data that is linked by fields in the specified data. Args: data: The data that is parsed for MongoDB ObjectIDs. The linked GridFs object for any ObjectID is deleted. """ if isinstance(data, ObjectId):...
Can you implement a function in Python 3 that deletes all GridFS data that is linked by fields in the specified data.
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_homecall(callsign): """Strips off country prefixes (HC2/DH1TW) and activity suffixes (DH1TW/P). Args: callsign (str): Amateur Radio callsign Returns: str: callsign without country/activity pre/suffixes Raises: ValueError: No callsign found i...
Write a Python 3 script to return the Homecall call for a given callsign.
You are a Python code analyst, evaluating scripts for potential improvements.
iterate over the prefix in the database
Can you tell what is the following Python 3 function doing def _iterate_prefix(self, callsign, timestamp=timestamp_now): prefix = callsign if re.search('(VK|AX|VI)9[A-Z]{3}', callsign): #special rule for VK9 calls if timestamp > datetime(2006,1,1, tzinfo=UTC): prefix = calls...
You are a Python code architect, reviewing and designing scalable and efficient code
def _dismantle_callsign(self, callsign, timestamp=timestamp_now): """ try to identify the callsign's identity by analyzing it in the following order: Args: callsign (str): Amateur Radio callsign timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC) Raises: ...
Can you implement a function in Python 3 that dismantles a callsign by analyzing the callsign s identity and returns a dictionary of the information that can be used to identify the callsign.
You are a Python code architect, reviewing and designing scalable and efficient code
Lookup a callsign and return all available data for the specified date.
Explain what the following Python 3 code does def get_all(self, callsign, timestamp=timestamp_now): callsign_data = self._lookup_callsign(callsign, timestamp) try: cqz = self._lookuplib.lookup_zone_exception(callsign, timestamp) callsign_data[const.CQZ] = cqz except KeyE...
As a Python code composer, you craft elegant and concise scripts.
def is_valid_callsign(self, callsign, timestamp=timestamp_now): """ Checks if a callsign is valid Args: callsign (str): Amateur Radio callsign timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC) Returns: bool: True / False Example: ...
Implement a Python 3 function for checking if a callsign is valid for a given date.
As a python code expert, you are capable of creating scripts from specifications.
def get_lat_long(self, callsign, timestamp=timestamp_now): """ Returns Latitude and Longitude for a callsign Args: callsign (str): Amateur Radio callsign timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC) Returns: dict: Containing Latitude and...
Can you create a Python 3 function that returns Latitude and Longitude for a callsign.
You are a Python code analyst, evaluating scripts for potential improvements.
def get_cqz(self, callsign, timestamp=timestamp_now): """ Returns CQ Zone of a callsign Args: callsign (str): Amateur Radio callsign timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC) Returns: int: containing the callsign's CQ Zone Ra...
Write a Python 3 function for returning the CQ Zone of a callsign
As a python code expert, you are capable of creating scripts from specifications.
def get_ituz(self, callsign, timestamp=timestamp_now): """ Returns ITU Zone of a callsign Args: callsign (str): Amateur Radio callsign timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC) Returns: int: containing the callsign's CQ Zone ...
Create a Python 3 function for returning the ITU Zone of a callsign
You are a Python code architect, reviewing and designing scalable and efficient code
Returns the name of the country that the callsign is located in
Given the following Python 3 function, write the documentation def get_country_name(self, callsign, timestamp=timestamp_now): return self.get_all(callsign, timestamp)[const.COUNTRY]
As a Python code composer, you craft elegant and concise scripts.
Returns the ADIF id of a callsign s country.
Here you have a function in Python 3, explain what it does def get_adif_id(self, callsign, timestamp=timestamp_now): return self.get_all(callsign, timestamp)[const.ADIF]
As a Python code analyst, you investigate and solve complex coding mysteries
def get_continent(self, callsign, timestamp=timestamp_now): """ Returns the continent Identifier of a callsign Args: callsign (str): Amateur Radio callsign timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC) Returns: str: continent identified ...
Write a Python 3 script to return the continent Identifier of a callsign
You are a Python code analyst, evaluating scripts for potential improvements.
Returns the indices for all occurrences of element in lst.
Can you tell what is the following Python 3 function doing def find_indices(lst, element): result = [] offset = -1 while True: try: offset = lst.index(element, offset+1) except ValueError: return result result.append(offset)
You are a Python code architect, reviewing and designing scalable and efficient code
def from_name(cls, name, *, queue=DefaultJobQueueName.Workflow, clear_data_store=True, arguments=None): """ Create a workflow object from a workflow script. Args: name (str): The name of the workflow script. queue (str): Name of the queue the workflow should be...
Implement a function in Python 3 to create a fully initialised workflow object from a workflow script.
You are a Python code generator, capable of creating scripts from specifications.
def load(self, name, *, arguments=None, validate_arguments=True, strict_dag=False): """ Import the workflow script and load all known objects. The workflow script is treated like a module and imported into the Python namespace. After the import, the method looks for instances of known c...
Can you write a function in Python 3 where it imports the workflow script and loads all known objects into the data store.
As a Python code composer, you craft elegant and concise scripts.
def run(self, config, data_store, signal_server, workflow_id): """ Run all autostart dags in the workflow. Only the dags that are flagged as autostart are started. Args: config (Config): Reference to the configuration object from which the settings for ...
Create a Python 3 function to run all autostart dags in the workflow.
As a Python code composer, you craft elegant and concise scripts.
Add a new dag to the queue.
Explain what the following Python 3 code does def _queue_dag(self, name, *, data=None): if self._stop_workflow: return None if name not in self._dags_blueprint: raise DagNameUnknown() new_dag = copy.deepcopy(self._dags_blueprint[name]) new_dag.workflow_name = se...
As a python code expert, you are capable of creating scripts from specifications.
def _handle_request(self, request): """ Handle an incoming request by forwarding it to the appropriate method. Args: request (Request): Reference to a request object containing the incoming request. Raises: RequestActionUnknown: If the act...
Write a Python 3 function for handling an incoming request by forwarding it to the appropriate method.
You are a Python code analyst, evaluating scripts for potential improvements.
The handler for the start_dag request.
Make a summary of the following Python 3 code def _handle_start_dag(self, request): dag_name = self._queue_dag(name=request.payload['name'], data=request.payload['data']) return Response(success=dag_name is not None, uid=request.uid, payload={'d...
You are a Python code generator, capable of creating scripts from specifications.
The handler for the stop_dag request.
How would you explain what the following Python 3 function does def _handle_stop_dag(self, request): if (request.payload['name'] is not None) and \ (request.payload['name'] not in self._stop_dags): self._stop_dags.append(request.payload['name']) return Response(success=True, uid=r...
As a Python code analyst, you investigate and solve complex coding mysteries
The handler for the dag_stopped request.
How would you explain what the following Python 3 function does def _handle_is_dag_stopped(self, request): return Response(success=True, uid=request.uid, payload={ 'is_stopped': request.payload['dag_name'] in self._stop_dags ...
As a Python code composer, you craft elegant and concise scripts.
Starts execution of a dag.
Here you have a function in Python 3, explain what it does def start_dag(self, dag, *, data=None): return self._client.send( Request( action='start_dag', payload={'name': dag.name if isinstance(dag, Dag) else dag, 'data': data if isinstance(da...
As a python code expert, you are capable of creating scripts from specifications.
def join_dags(self, names=None): """ Wait for the specified dags to terminate. This function blocks until the specified dags terminate. If no dags are specified wait for all dags of the workflow, except the dag of the task calling this signal, to terminate. Args: na...
How would you implement a function in Python 3 that waits for the specified dags to terminate.
As a Python code composer, you craft elegant and concise scripts.
def stop_dag(self, name=None): """ Send a stop signal to the specified dag or the dag that hosts this task. Args: name str: The name of the dag that should be stopped. If no name is given the dag that hosts this task is stopped. Upon receiving the stop signal,...
How would you implement a function in Python 3 that sends a stop signal to the specified dag or the dag that hosts this task.
You are a Python code architect, reviewing and designing scalable and efficient code
Check whether the task is stopped.
Make a summary of the following Python 3 code def is_stopped(self): resp = self._client.send( Request( action='is_dag_stopped', payload={'dag_name': self._dag_name} ) ) return resp.payload['is_stopped']
You are a Python code architect, reviewing and designing scalable and efficient code
A generator function that returns celery events.
How would you explain what the following Python 3 function does def event_stream(app, *, filter_by_prefix=None): q = Queue() def handle_event(event): if filter_by_prefix is None or\ (filter_by_prefix is not None and event['type'].startswith(filter_by_prefix)): ...
You are a Python code generator, capable of creating scripts from specifications.
def create_event_model(event): """ Factory function that turns a celery event into an event object. Args: event (dict): A dictionary that represents a celery event. Returns: object: An event object representing the received event. Raises: JobEventTypeUnsupported: If an unsuppo...
Write a Python 3 script to create an event model from a celery event.
As a Python code analyst, you investigate and solve complex coding mysteries
Decorator that checks whether a configuration file is set.
How would you explain what the following Python 3 function does def config_required(f): def new_func(obj, *args, **kwargs): if 'config' not in obj: click.echo(_style(obj.get('show_color', False), 'Could not find a valid configuration file!', ...
You are a Python code architect, reviewing and designing scalable and efficient code
Ingest the configuration object into the click context.
Can you generate the documentation for the following Python 3 function def ingest_config_obj(ctx, *, silent=True): try: ctx.obj['config'] = Config.from_file(ctx.obj['config_path']) except ConfigLoadError as err: click.echo(_style(ctx.obj['show_color'], str(err), fg='red', bold=True)) if ...
You are a Python code analyst, evaluating scripts for potential improvements.
def cli(ctx, config, no_color): """ Command line client for lightflow. A lightweight, high performance pipeline system for synchrotrons. Lightflow is being developed at the Australian Synchrotron. """ ctx.obj = { 'show_color': not no_color if no_color is not None else True, 'config_...
Implement a function in Python 3 to command line client for lightflow.
You are a Python code analyst, evaluating scripts for potential improvements.
def config_default(dest): """ Create a default configuration file. \b DEST: Path or file name for the configuration file. """ conf_path = Path(dest).resolve() if conf_path.is_dir(): conf_path = conf_path / LIGHTFLOW_CONFIG_NAME conf_path.write_text(Config.default()) click.echo(...
Can you write a function in Python 3 where it creates a default configuration file.
You are a Python code analyst, evaluating scripts for potential improvements.
def config_list(ctx): """ List the current configuration. """ ingest_config_obj(ctx, silent=False) click.echo(json.dumps(ctx.obj['config'].to_dict(), indent=4))
Can you implement a function in Python 3 that lists the current configuration.
You are a Python code architect, reviewing and designing scalable and efficient code
Copy the examples to a directory.
Here you have a function in Python 3, explain what it does def config_examples(dest, user_dir): examples_path = Path(lightflow.__file__).parents[1] / 'examples' if examples_path.exists(): dest_path = Path(dest).resolve() if not user_dir: dest_path = dest_path / 'examples' if...
You are a Python code generator, capable of creating scripts from specifications.
List all available workflows.
Can you tell what is the following Python 3 function doing def workflow_list(obj): try: for wf in list_workflows(config=obj['config']): click.echo('{:23} {}'.format( _style(obj['show_color'], wf.name, bold=True), wf.docstring.split('\n')[0] if wf.docstring is not ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def workflow_start(obj, queue, keep_data, name, workflow_args): """ Send a workflow to the queue. \b NAME: The name of the workflow that should be started. WORKFLOW_ARGS: Workflow arguments in the form key1=value1 key2=value2. """ try: start_workflow(name=name, co...
How would you code a function in Python 3 to send a workflow to the queue.
As a Python code composer, you craft elegant and concise scripts.
def workflow_stop(obj, names): """ Stop one or more running workflows. \b NAMES: The names, ids or job ids of the workflows that should be stopped. Leave empty to stop all running workflows. """ if len(names) == 0: msg = 'Would you like to stop all workflows?' else: m...
Create a Python 3 function to stop one or more workflows.
You are a Python code analyst, evaluating scripts for potential improvements.
Show the status of the workflows.
Given the following Python 3 function, write the documentation def workflow_status(obj, details): show_colors = obj['show_color'] config_cli = obj['config'].cli if details: temp_form = '{:>{}} {:20} {:25} {:25} {:38} {}' else: temp_form = '{:>{}} {:20} {:25} {} {} {}' click.echo(...
As a Python code analyst, you investigate and solve complex coding mysteries
Start a worker process.
Can you generate a brief explanation for the following Python 3 code def worker_start(obj, queues, name, celery_args): try: start_worker(queues=queues.split(','), config=obj['config'], name=name, celery_args=celery_args) except DataStoreNotC...
You are a Python code analyst, evaluating scripts for potential improvements.
def worker_stop(obj, worker_ids): """ Stop running workers. \b WORKER_IDS: The IDs of the worker that should be stopped or none to stop them all. """ if len(worker_ids) == 0: msg = 'Would you like to stop all workers?' else: msg = '\n{}\n\n{}'.format('\n'.join(worker_ids), ...
How would you code a function in Python 3 to stop running workers. \b WORKER_IDS: The IDs of the worker that should be stopped or none to stop them all.
As a Python code composer, you craft elegant and concise scripts.
def worker_status(obj, filter_queues, details): """ Show the status of all running workers. """ show_colors = obj['show_color'] f_queues = filter_queues.split(',') if filter_queues is not None else None workers = list_workers(config=obj['config'], filter_by_queues=f_queues) if len(workers) == 0: ...
How would you code a function in Python 3 to show the status of all running workers.
As a Python code composer, you craft elegant and concise scripts.
def monitor(ctx, details): """ Show the worker and workflow event stream. """ ingest_config_obj(ctx, silent=False) show_colors = ctx.obj['show_color'] event_display = { JobEventName.Started: {'color': 'blue', 'label': 'started'}, JobEventName.Succeeded: {'color': 'green', 'label': 'suc...
Create a Python 3 function for printing the worker and workflow event stream.
As a Python code analyst, you investigate and solve complex coding mysteries
def ext(obj, ext_name, ext_args): """ Run an extension by its name. \b EXT_NAME: The name of the extension. EXT_ARGS: Arguments that are passed to the extension. """ try: mod = import_module('lightflow_{}.__main__'.format(ext_name)) mod.main(ext_args) except ImportError as e...
Create a Python 3 function for running an extension by its name.
You are a Python code analyst, evaluating scripts for potential improvements.
Helper function to enable or disable styling of the base item in a node tree.
How would you explain what the following Python 3 function does def _style(enabled, text, **kwargs): if enabled: return click.style(text, **kwargs) else: return text
As a Python code analyst, you investigate and solve complex coding mysteries
converts a Frequency [ kHz ] into the band and mode according to the IARU bandplan
Here you have a function in Python 3, explain what it does def freq_to_band(freq): band = None mode = None if ((freq >= 135) and (freq <= 138)): band = 2190 mode = const.CW elif ((freq >= 1800) and (freq <= 2000)): band = 160 if ((freq >= 1800) and (freq < 1838)): ...
As a Python code analyst, you investigate and solve complex coding mysteries
Create a fully configured Celery application object.
Explain what the following Python 3 code does def create_app(config): # configure the celery logging system with the lightflow settings setup_logging.connect(partial(_initialize_logging, config), weak=False) task_postrun.connect(partial(_cleanup_workflow, config), weak=False) # patch Celery to use clo...
As a Python code composer, you craft elegant and concise scripts.
Cleanup the results of a workflow when it finished.
Given the following Python 3 function, write the documentation def _cleanup_workflow(config, task_id, args, **kwargs): from lightflow.models import Workflow if isinstance(args[0], Workflow): if config.celery['result_expires'] == 0: AsyncResult(task_id).forget()
You are a Python code architect, reviewing and designing scalable and efficient code
def execute_task(self, task, workflow_id, data=None): """ Celery task that runs a single task on a worker. Args: self (Task): Reference to itself, the celery task object. task (BaseTask): Reference to the task object that performs the work in its run() method. w...
Write a Python 3 function for executing a single celery task on a worker.
You are a Python code generator, capable of creating scripts from specifications.
Create a BrokerStats object from a dictionary returned by celery.
Make a summary of the following Python 3 code def from_celery(cls, broker_dict): return BrokerStats( hostname=broker_dict['hostname'], port=broker_dict['port'], transport=broker_dict['transport'], virtual_host=broker_dict['virtual_host'] )
As a Python code analyst, you investigate and solve complex coding mysteries
Return a dictionary of the broker stats.
Explain what the following Python 3 code does def to_dict(self): return { 'hostname': self.hostname, 'port': self.port, 'transport': self.transport, 'virtual_host': self.virtual_host }
You are a Python code architect, reviewing and designing scalable and efficient code
def from_celery(cls, name, worker_dict, queues): """ Create a WorkerStats object from the dictionary returned by celery. Args: name (str): The name of the worker. worker_dict (dict): The dictionary as returned by celery. queues (list): A list of QueueStats objects th...
Create a Python 3 function for creating a WorkerStats object from a dictionary returned by celery.
As a python code expert, you are capable of creating scripts from specifications.
Return a dictionary of the worker stats.
Explain what the following Python 3 code does def to_dict(self): return { 'name': self.name, 'broker': self.broker.to_dict(), 'pid': self.pid, 'process_pids': self.process_pids, 'concurrency': self.concurrency, 'job_count': self.job_count, ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def from_celery(cls, worker_name, job_dict, celery_app): """ Create a JobStats object from the dictionary returned by celery. Args: worker_name (str): The name of the worker this jobs runs on. job_dict (dict): The dictionary as returned by celery. celery_app: Referen...
Write a Python 3 script to create a JobStats object from a dictionary returned by celery.
You are a Python code analyst, evaluating scripts for potential improvements.
def to_dict(self): """ Return a dictionary of the job stats. Returns: dict: Dictionary of the stats. """ return { 'name': self.name, 'id': self.id, 'type': self.type, 'workflow_id': self.workflow_id, 'queue': self.q...
How would you code a function in Python 3 to return a dictionary of the job stats.
As a Python code analyst, you investigate and solve complex coding mysteries
Create a JobEvent object from a dictionary returned by celery.
Make a summary of the following Python 3 code def from_event(cls, event): return cls( uuid=event['uuid'], job_type=event['job_type'], event_type=event['type'], queue=event['queue'], hostname=event['hostname'], pid=event['pid'], ...
You are a Python code architect, reviewing and designing scalable and efficient code
Starts a single workflow by sending it to the workflow queue.
Can you tell what is the following Python 3 function doing def start_workflow(name, config, *, queue=DefaultJobQueueName.Workflow, clear_data_store=True, store_args=None): """ Start a single workflow by sending it to the workflow queue. Args: name (str): The name of the workflow that...
As a Python code composer, you craft elegant and concise scripts.
Stop one or more workflows.
Explain what the following Python 3 code does def stop_workflow(config, *, names=None): jobs = list_jobs(config, filter_by_type=JobType.Workflow) if names is not None: filtered_jobs = [] for job in jobs: if (job.id in names) or (job.name in names) or (job.workflow_id in names): ...
You are a Python code generator, capable of creating scripts from specifications.
List all available workflows.
Explain what the following Python 3 code does def list_workflows(config): workflows = [] for path in config.workflows: filenames = glob.glob(os.path.join(os.path.abspath(path), '*.py')) for filename in filenames: module_name = os.path.splitext(os.path.basename(filename))[0] ...
You are a Python code architect, reviewing and designing scalable and efficient code
def list_jobs(config, *, status=JobStatus.Active, filter_by_type=None, filter_by_worker=None): """ Return a list of Celery jobs. Args: config (Config): Reference to the configuration object from which the settings are retrieved. status (JobStatus): The status of the jo...
Can you implement a function in Python 3 that returns a list of Jobs that are in the given status.
As a Python code composer, you craft elegant and concise scripts.
def events(config): """ Return a generator that yields workflow events. For every workflow event that is sent from celery this generator yields an event object. Args: config (Config): Reference to the configuration object from which the settings are retrieved. Returns: ...
Can you write a function in Python 3 where it returns a generator that yields workflow events.
You are a Python code analyst, evaluating scripts for potential improvements.
Runs the process and returns the current state of the application.
Here you have a function in Python 3, explain what it does def run(self): read_stdout = partial(self._read_output, stream=self._process.stdout, callback=self._callback_stdout, output_file=self._stdout_file) read_stderr = partial(self._read_out...
You are a Python code analyst, evaluating scripts for potential improvements.
Read the output of the process and execute the callback and save the output.
How would you explain what the following Python 3 function does def _read_output(self, stream, callback, output_file): if (callback is None and output_file is None) or stream.closed: return False line = stream.readline() if line: if callback is not None: ...
You are a Python code generator, capable of creating scripts from specifications.
This method is called by the main run method of the Python task. It runs the command and sends the output to the process.
Can you generate the documentation for the following Python 3 function def run(self, data, store, signal, context, **kwargs): params = self.params.eval(data, store, exclude=['command']) capture_stdout = self._callback_stdout is not None or params.capture_stdout capture_stderr = self._callback_s...
As a Python code analyst, you investigate and solve complex coding mysteries
Function wrapper that sets the user and group for the process
How would you explain what the following Python 3 function does def _run_as(user, group): def wrapper(): if user is not None: os.setuid(user) if group is not None: os.setgid(group) return wrapper
As a Python code composer, you craft elegant and concise scripts.
def convert(self, value): """ Convert the specified value to the type of the option. Args: value: The value that should be converted. Returns: The value with the type given by the option. """ if self._type is str: return str(value) el...
Implement a function in Python 3 to convert the specified value to the type given by the option.
You are a Python code generator, capable of creating scripts from specifications.
Checks that all options that are not specified in the passed arguments are present in the current configuration.
How would you explain what the following Python 3 function does def check_missing(self, args): return [opt.name for opt in self if (opt.name not in args) and (opt.default is None)]
As a Python code analyst, you investigate and solve complex coding mysteries
Consolidate the provided arguments.
Given the following Python 3 function, write the documentation def consolidate(self, args): result = dict(args) for opt in self: if opt.name in result: result[opt.name] = opt.convert(result[opt.name]) else: if opt.default is not None: ...
As a Python code composer, you craft elegant and concise scripts.
Define the task graph definition.
Make a summary of the following Python 3 code def define(self, schema, *, validate=True): self._schema = schema if validate: self.validate(self.make_graph(self._schema))
As a Python code analyst, you investigate and solve complex coding mysteries
Runs the dag by calling the tasks in the correct order.
Here you have a function in Python 3, explain what it does def run(self, config, workflow_id, signal, *, data=None): graph = self.make_graph(self._schema) # pre-checks self.validate(graph) if config is None: raise ConfigNotDefinedError() # create the celery app for...
As a Python code translator, you convert algorithms and pseudocode into Python.
Validate the graph by checking whether it is a directed acyclic graph.
How would you explain what the following Python 3 function does def validate(self, graph): if not nx.is_directed_acyclic_graph(graph): raise DirectedAcyclicGraphInvalid(graph_name=self._name)
As a Python code translator, you convert algorithms and pseudocode into Python.
def make_graph(schema): """ Construct the task graph (dag) from a given schema. Parses the graph schema definition and creates the task graph. Tasks are the vertices of the graph and the connections defined in the schema become the edges. A key in the schema dict represents a parent ta...
Write a Python 3 function for constructing a graph object from a given schema.
You are a Python code analyst, evaluating scripts for potential improvements.
Merges the specified dataset on top of the existing data.
Explain what the following Python 3 code does def merge(self, dataset): def merge_data(source, dest): for key, value in source.items(): if isinstance(value, dict): merge_data(value, dest.setdefault(key, {})) else: dest[key] = va...
As a Python code analyst, you investigate and solve complex coding mysteries
def add_dataset(self, task_name, dataset=None, *, aliases=None): """ Add a new dataset to the MultiTaskData. Args: task_name (str): The name of the task from which the dataset was received. dataset (TaskData): The dataset that should be added. aliases (list): A list ...
Can you create a Python 3 function that adds a new dataset to the MultiTaskData.
As a python code expert, you are capable of creating scripts from specifications.
Adds an alias pointing to the given index.
Here you have a function in Python 3, explain what it does def add_alias(self, alias, index): if index >= len(self._datasets): raise DataInvalidIndex('A dataset with index {} does not exist'.format(index)) self._aliases[alias] = index
You are a Python code analyst, evaluating scripts for potential improvements.
Returns a new MultiTaskData object containing all datasets and all aliases.
Can you tell what is the following Python 3 function doing def flatten(self, in_place=True): new_dataset = TaskData() for i, dataset in enumerate(self._datasets): if i != self._default_index: new_dataset.merge(dataset) new_dataset.merge(self.default_dataset) ...
You are a Python code architect, reviewing and designing scalable and efficient code
def set_default_by_alias(self, alias): """ Set the default dataset by its alias. After changing the default dataset, all calls without explicitly specifying the dataset by index or alias will be redirected to this dataset. Args: alias (str): The alias of the dataset that sh...
Can you implement a function in Python 3 that sets the default dataset by its alias.
As a Python code analyst, you investigate and solve complex coding mysteries
def set_default_by_index(self, index): """ Set the default dataset by its index. After changing the default dataset, all calls without explicitly specifying the dataset by index or alias will be redirected to this dataset. Args: index (int): The index of the dataset that sh...
Write a Python 3 function that can set the default dataset by its index.
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_by_alias(self, alias): """ Return a dataset by its alias. Args: alias (str): The alias of the dataset that should be returned. Raises: DataInvalidAlias: If the alias does not represent a valid dataset. """ if alias not in self._aliases: ...
How would you implement a function in Python 3 that returns a dataset by its alias.
As a python code expert, you are capable of creating scripts from specifications.
Return a dataset by its index.
How would you explain what the following Python 3 function does def get_by_index(self, index): if index >= len(self._datasets): raise DataInvalidIndex('A dataset with index {} does not exist'.format(index)) return self._datasets[index]
As a python code expert, you are capable of creating scripts from specifications.
def to_dict(self): """ Return the task context content as a dictionary. """ return { 'task_name': self.task_name, 'dag_name': self.dag_name, 'workflow_name': self.workflow_name, 'workflow_id': self.workflow_id, 'worker_hostname': self.worker_ho...
Write a Python 3 script to return the task context content as a dictionary.
As a Python code analyst, you investigate and solve complex coding mysteries
def start_worker(queues, config, *, name=None, celery_args=None, check_datastore=True): """ Start a worker process. Args: queues (list): List of queue names this worker accepts jobs from. config (Config): Reference to the configuration object from which the settings for the worker a...
Write a Python 3 script for starting a worker process.
You are a Python code architect, reviewing and designing scalable and efficient code
Stop a worker process.
How would you explain what the following Python 3 function does def stop_worker(config, *, worker_ids=None): if worker_ids is not None and not isinstance(worker_ids, list): worker_ids = [worker_ids] celery_app = create_app(config) celery_app.control.shutdown(destination=worker_ids)
You are a Python code analyst, evaluating scripts for potential improvements.
def list_workers(config, *, filter_by_queues=None): """ Return a list of all available workers. Args: config (Config): Reference to the configuration object from which the settings are retrieved. filter_by_queues (list): Restrict the returned workers to workers that listen to ...
Implement a function in Python 3 to return a list of all available workers.
You are a Python code analyst, evaluating scripts for potential improvements.
Evaluate the callable parameters of the current object.
Here you have a function in Python 3, explain what it does def eval(self, data, data_store, *, exclude=None): exclude = [] if exclude is None else exclude result = {} for key, value in self.items(): if key in exclude: continue if value is not None and ca...
You are a Python code architect, reviewing and designing scalable and efficient code
Evaluate the value of a single parameter taking into account callables.
Explain what the following Python 3 code does def eval_single(self, key, data, data_store): if key in self: value = self[key] if value is not None and callable(value): return value(data, data_store) else: return value else: ...
As a python code expert, you are capable of creating scripts from specifications.
Download the latest offical list of the LOTW User Activity of the World and return a dictionary containing the callsign date of the last LOTW upload
Can you generate a brief explanation for the following Python 3 code def get_lotw_users(**kwargs): url = "" lotw = {} try: url = kwargs['url'] except KeyError: # url = "http://wd5eae.org/LoTW_Data.txt" url = "https://lotw.arrl.org/lotw-user-activity.csv" try: resu...
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_clublog_users(**kwargs): """Download the latest offical list of `Clublog`__ users. Args: url (str, optional): Download URL Returns: dict: Dictionary containing (if data available) the fields: firstqso, lastqso, last-lotw, lastupload (datetime), ...
Can you create a Python 3 function that downloads the latest offical list of Clublog __ users.
You are a Python code generator, capable of creating scripts from specifications.
def get_eqsl_users(**kwargs): """Download the latest official list of `EQSL.cc`__ users. The list of users can be found here_. Args: url (str, optional): Download URL Returns: list: List containing the callsigns of EQSL users (unicode) Raises: IOError: ...
Can you implement a function in Python 3 that downloads the latest official list of EQSL. cc __ users. The list of users can be found here_.
You are a Python code architect, reviewing and designing scalable and efficient code
Copy the complete lookup data into Redis.
Make a summary of the following Python 3 code def copy_data_in_redis(self, redis_prefix, redis_instance): if redis_instance is not None: self._redis = redis_instance if self._redis is None: raise AttributeError("redis_instance is missing") if redis_prefix is None: ...
You are a Python code architect, reviewing and designing scalable and efficient code
Returns the lookup data of an ADIF Entity with the specified ID.
Explain what the following Python 3 code does def lookup_entity(self, entity=None): if self._lookuptype == "clublogxml": entity = int(entity) if entity in self._entities: return self._strip_metadata(self._entities[entity]) else: raise KeyError ...
You are a Python code analyst, evaluating scripts for potential improvements.