output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
def update(cls, settings): """Update settings with a dict.""" for key, val in settings.__dict__.items(): if key.startswith('_'): continue setattr(cls, key, val)
Write a Python 3 function that can update the settings with a dict.
You are a Python code architect, reviewing and designing scalable and efficient code
Run the external program tester on the required binaries.
How would you explain what the following Python 3 function does def _set_program_defaults(cls, programs): for program in programs: val = getattr(cls, program.__name__) \ and extern.does_external_program_run(program.__name__, Settin...
As a Python code composer, you craft elegant and concise scripts.
def config_program_reqs(cls, programs): """Run the program tester and determine if we can do anything.""" cls._set_program_defaults(programs) do_png = cls.optipng or cls.pngout or cls.advpng do_jpeg = cls.mozjpeg or cls.jpegrescan or cls.jpegtran do_comics = cls.comics ...
How would you implement a function in Python 3 that runs the program tester and determine if we can do anything.
As a Python code translator, you convert algorithms and pseudocode into Python.
Run the external program optipng on the file.
Can you generate the documentation for the following Python 3 function def optipng(ext_args): args = _OPTIPNG_ARGS + [ext_args.new_filename] extern.run_ext(args) return _PNG_FORMAT
You are a Python code architect, reviewing and designing scalable and efficient code
Run the external program advpng on the file.
How would you explain what the following Python 3 function does def advpng(ext_args): args = _ADVPNG_ARGS + [ext_args.new_filename] extern.run_ext(args) return _PNG_FORMAT
As a Python code translator, you convert algorithms and pseudocode into Python.
def pngout(ext_args): """Run the external program pngout on the file.""" args = _PNGOUT_ARGS + [ext_args.old_filename, ext_args.new_filename] extern.run_ext(args) return _PNG_FORMAT
Can you write a function in Python 3 where it runs the external program pngout on the file.
As a python code expert, you are capable of creating scripts from specifications.
def _from_func(cls, f, *args, _attr_scts=None, **kwargs): """Creates a function chain starting with the specified SCT (f), and its arguments.""" func_chain = cls(attr_scts=_attr_scts) func_chain._stack.append([f, args, kwargs]) return func_chain
Write a Python 3 function that can create a function chain starting with the specified SCT ( f ) and its arguments.
As a Python code analyst, you investigate and solve complex coding mysteries
def check_file( state, fname, missing_msg="Did you create a file named `{}`?", is_dir_msg="Want to check a file named `{}`, but found a directory.", parse=True, use_fs=True, use_solution=False, ): """Test whether file exists, and make its contents the student code. Note: this SCT fa...
How would you implement a function in Python 3 that tests whether a file exists and make its contents the student code.
As a Python code composer, you craft elegant and concise scripts.
def has_dir(state, fname, incorrect_msg="Did you create a directory named `{}`?"): """Test whether a directory exists.""" if not Path(fname).is_dir(): state.report(Feedback(incorrect_msg.format(fname))) return state
Can you write a function in Python 3 where it tests whether a directory exists.
As a Python code composer, you craft elegant and concise scripts.
def exec_task(task_path, data): """Execute task. :param task_path: task path :type task_path: str|Callable :param data: task's data :type data: Any :return: """ if not data: data = {'data': None, 'path': task_path} elif not isinstance(data, (str, bytes)): data = {'d...
Write a Python 3 script for executing task. :param task_path: task path :type task_path: str|Callable :param data: task's data :type data: Any :return:
As a Python code composer, you craft elegant and concise scripts.
def dump(node, config): """ Convert a node tree to a simple nested dict All steps in this conversion are configurable using DumpConfig dump dictionary node: {"type": str, "data": dict} """ if config.is_node(node): fields = OrderedDict() for name in config.fields_iter(node): ...
How would you implement a function in Python 3 that converts a node tree to a simple nested dict
You are a Python code generator, capable of creating scripts from specifications.
def apply_pagination(self, q): """ Filters the query so that a given page is returned. The record count must be set in advance. :param q: Query to be paged. :return: Paged query. """ # type: (Query)->Query assert self.record_count >= 0, "Record count must ...
Write a Python 3 function that can apply the pagination to the query so that a given page is returned.
You are a Python code architect, reviewing and designing scalable and efficient code
Filters the query so that a given page is returned.
Here you have a function in Python 3, explain what it does def paginate(self, q): self.record_count = q.count() return self.apply_pagination(q).all()
As a Python code analyst, you investigate and solve complex coding mysteries
Perform sequence clustering with CD - HIT.
Given the following Python 3 function, write the documentation def cluster(seqs, threshold=0.975, out_file=None, temp_dir=None, make_db=True, quiet=False, threads=0, return_just_seq_ids=False, max_memory=800, debug=False): ''' Perform sequence clustering with CD-HIT. Args: seqs (list):...
As a python code expert, you are capable of creating scripts from specifications.
Run CD - HIT on a list of sequences.
Can you generate a brief explanation for the following Python 3 code def cdhit(seqs, out_file=None, temp_dir=None, threshold=0.975, make_db=True, quiet=False, threads=0, max_memory=800, retries=5, debug=False): ''' Run CD-HIT. Args: seqs (list): An iterable of sequences, in any format that `abutil...
You are a Python code generator, capable of creating scripts from specifications.
def parse_clusters(out_file, clust_file, seq_db=None, db_path=None, seq_dict=None, return_just_seq_ids=False): ''' Parses CD-HIT output. Args: out_file (str): Path to the CD-HIT output file. Required. clust_file (str): Path to the CD-HIT cluster file. Required. seq_db (sqlite.Con...
Write a Python 3 script to parse the CD - HIT output file and returns a list of cluster objects.
As a Python code analyst, you investigate and solve complex coding mysteries
A decorator that logs the output of a function.
Given the following Python 3 function, write the documentation def log_output(f): @wraps(f) def wrapper_fn(*args, **kwargs): res = f(*args, **kwargs) logging.debug("Logging result %s.", res) return res return wrapper_fn
As a Python code translator, you convert algorithms and pseudocode into Python.
Decorator to save the output value to file.
Explain what the following Python 3 code does def save_to_file(destination_filename, append=False): def decorator_fn(f): @wraps(f) def wrapper_fn(*args, **kwargs): res = f(*args, **kwargs) makedirs(os.path.dirname(destination_filename)) mode = "a" if append else...
As a Python code composer, you craft elegant and concise scripts.
def json_input(f): """ Expects task input data in json format and parse this data. """ @wraps(f) def json_input_decorator(*args, **kwargs): # If the data is already transformed, we do not transform it any # further. task_data = _get_data_from_args(args) if task_data...
Create a Python 3 function for expecting task input data in json format and parse this data.
As a Python code composer, you craft elegant and concise scripts.
Decorator to format response to json and in case of web - request set response content type to application / json.
Given the following Python 3 function, write the documentation def json_output(f): @wraps(f) def json_output_decorator(*args, **kwargs): @inject(config=Config) def get_config(config): return config config = get_config() rv = f(*args, **kwargs) indent = None...
As a Python code composer, you craft elegant and concise scripts.
def jsonp_wrap(callback_key='callback'): """ Format response to jsonp and add a callback to JSON data - a jsonp request """ def decorator_fn(f): @wraps(f) def jsonp_output_decorator(*args, **kwargs): task_data = _get_data_from_args(args) data = task_data.get_dat...
Can you create a Python 3 function that formats response to jsonp and add a callback to JSON data - a jsonp request
As a Python code analyst, you investigate and solve complex coding mysteries
def jsend_output(fail_exception_classes=None): """ Format task result to json output in jsend specification format. See: https://github.com/omniti-labs. Task return value must be dict or None. @param fail_exception_classes: exceptions which will produce 'fail' response status. """ fail_exc...
Implement a function in Python 3 to format task result to json output in jsend specification format. See: https://github.com/omniti-labs. Task return value must be dict or None. @param fail_exception_classes: exceptions which will produce 'fail' response status.
You are a Python code architect, reviewing and designing scalable and efficient code
Decorator for web error_and_result
Given the following Python 3 function, write the documentation def web_error_and_result(f): @wraps(f) def web_error_and_result_decorator(*args, **kwargs): return error_and_result_decorator_inner_fn(f, True, *args, **kwargs) return web_error_and_result_decorator
As a Python code analyst, you investigate and solve complex coding mysteries
def error_and_result(f): """ Format task result into json dictionary `{'data': task return value}` if no exception was raised during the task execution. If there was raised an exception during task execution, formats task result into dictionary `{'error': exception message with traceback}`. """ ...
Write a Python 3 script for formatting task result into json dictionary `{'data': task return value}` if no exception was raised during the task execution. If there was raised an exception during task execution, formats task result into dictionary `{'error': exception message with traceback}`.
As a Python code analyst, you investigate and solve complex coding mysteries
def required_data(*data): """ Task decorator which checks if the given variables (indices) are stored inside the task data. """ def decorator_fn(f): @wraps(f) def required_data_decorator(*args, **kwargs): task_data = _get_data_from_args(args).get_data() for ...
Create a Python 3 function for tasking decorator which checks if the given variables (indices) are stored inside the task data.
You are a Python code analyst, evaluating scripts for potential improvements.
Decorator which appends GET parameters to the task data.
Make a summary of the following Python 3 code def append_get_parameters(accept_only_web=True): # type: (bool) -> Callable """ Task decorator which appends the GET data to the task data. :param accept_only_web: Parameter which limits using this task only with web requests. ...
As a python code expert, you are capable of creating scripts from specifications.
Decorator for web tasks.
Make a summary of the following Python 3 code def web_task(f): @wraps(f) def web_task_decorator(*args, **kwargs): jc = JobContext.get_current_context() if not isinstance(jc, WebJobContext): raise Exception( "The WebTask is not called through the web interface.") ...
You are a Python code architect, reviewing and designing scalable and efficient code
A decorator that returns a task that checks that the task data is valid and then passes it to the task decorator.
Given the following Python 3 function, write the documentation def secured_task(f): @wraps(f) def secured_task_decorator(*args, **kwargs): task_data = _get_data_from_args(args) assert isinstance(task_data, TaskData) if not verify_security_data(task_data.get_data()['security']): ...
As a python code expert, you are capable of creating scripts from specifications.
Decorator for handling XML output.
Can you generate the documentation for the following Python 3 function def xml_output(f): @wraps(f) def xml_output_inner_fn(*args, **kwargs): ret_val = f(*args, **kwargs) if isinstance(JobContext.get_current_context(), WebJobContext): JobContext.get_current_context().add_responder(...
You are a Python code architect, reviewing and designing scalable and efficient code
def file_upload(f): """ Return list of `werkzeug.datastructures.FileStorage` objects - files to be uploaded """ @wraps(f) def file_upload_decorator(*args, **kwargs): # If the data is already transformed, we do not transform it any # further. task_data = _get_data_from_ar...
Can you create a Python 3 function that returns list of `werkzeug.datastructures.FileStorage` objects - files to be uploaded
As a Python code analyst, you investigate and solve complex coding mysteries
Decorator for forbid running task using http request.
Can you generate the documentation for the following Python 3 function def forbid_web_access(f): @wraps(f) def wrapper_fn(*args, **kwargs): if isinstance(JobContext.get_current_context(), WebJobContext): raise ForbiddenError('Access forbidden from web.') return f(*args, **kwargs) ...
As a Python code analyst, you investigate and solve complex coding mysteries
def filter_from_url_arg(model_cls, query, arg, query_operator=and_, arg_types=None): """ Parse filter URL argument ``arg`` and apply to ``query`` Example: 'column1<=value,column2==value' -> query.filter(Model.column1 <= value, Model.column2 == value) """ fields = arg.split(...
How would you code a function in Python 3 to parse filter URL argument arg and apply to query.
As a Python code analyst, you investigate and solve complex coding mysteries
def model_tree(name, model_cls, visited=None): """Create a simple tree of model's properties and its related models. It traverse trough relations, but ignore any loops. :param name: name of the model :type name: str :param model_cls: model class :param visited: set of visited models :type ...
Write a Python 3 script to create a simple tree of model s properties and its related models.
As a Python code analyst, you investigate and solve complex coding mysteries
Flatten the tree into a list of properties adding parents as prefixes.
Here you have a function in Python 3, explain what it does def flat_model(tree): names = [] for columns in viewvalues(tree): for col in columns: if isinstance(col, dict): col_name = list(col)[0] names += [col_name + '__' + c for c in flat_model(col)] ...
You are a Python code architect, reviewing and designing scalable and efficient code
Execute a job. :param job: job to execute :type job: Job :param app: service application instance, injected :type app: ServiceApplication :param task_router: task router instance, injected :type task_router: TaskRouter :return: task result :rtype: dict
Make a summary of the following Python 3 code def execute_job(job, app=Injected, task_router=Injected): # type: (Job, Zsl, TaskRouter) -> dict """Execute a job. :param job: job to execute :type job: Job :param app: service application instance, injected :type app: ServiceApplication :param ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Handle exception raised during task execution.
Can you tell what is the following Python 3 function doing def handle_exception(self, e, task_path): # type: (Exception, str) -> dict """Handle exception raised during task execution. :param e: exception :type e: Exception :param task_path: task path :type task_path: str...
As a Python code translator, you convert algorithms and pseudocode into Python.
Execute the job given by the task queue.
Here you have a function in Python 3, explain what it does def execute_job(self, job): # type: (Job) -> dict """Execute job given by the task queue. :param job: job :type job: Job :return: task result :rtype: dict """ try: return execute_job(j...
As a Python code analyst, you investigate and solve complex coding mysteries
A decorator that makes it possible to call a function using old argument names when they are passed as keyword arguments.
Can you tell what is the following Python 3 function doing def legacy_signature(**kwargs_mapping): def signature_decorator(f): @wraps(f) def wrapper(*args, **kwargs): redirected_kwargs = { kwargs_mapping[k] if k in kwargs_mapping else k: v for k, v in kwa...
As a Python code composer, you craft elegant and concise scripts.
Bind a service to application injector.
Can you generate the documentation for the following Python 3 function def _bind_service(package_name, cls_name, binder=Injected): module = importlib.import_module(package_name) cls = getattr(module, cls_name) binder.bind( cls, to=binder.injector.create_object(cls), ...
As a Python code analyst, you investigate and solve complex coding mysteries
Initialize method. :param config: current application config, injected :type config: Config
Make a summary of the following Python 3 code def initialize(config): service_injection_config = config.get('SERVICE_INJECTION', ()) if not isinstance(service_injection_config, (tuple, list)): service_injection_config = (service_injection_config,) for si_conf in service_injection_c...
You are a Python code analyst, evaluating scripts for potential improvements.
def background_task_method(task): """Decorate an object method as a background task (called with help of gearman). You have to create a task which will handle the gearman call. The method arguments will be encoded as JSON. :param task: name of the task :type task: str :return: decorated fu...
Can you write a function in Python 3 where it decorates an object method as a background task (called with help of gearman). You have to create a task which will handle the gearman call. The method arguments will be encoded as JSON. :param task: name of the task :type task: str :return: decorated function
As a Python code translator, you convert algorithms and pseudocode into Python.
Create a dictionary of links to all resources in a resource page.
Can you tell what is the following Python 3 function doing def _get_link_pages(page, per_page, count, page_url): # type: (int, int, int, str) -> Dict[str, str] """Create link header for page metadata. :param page: current page :param per_page: page limit :param count: count of all resources :pa...
As a Python code analyst, you investigate and solve complex coding mysteries
def to_filter(self, query, arg): """Json-server filter using the _or_ operator.""" return filter_from_url_arg(self.model_cls, query, arg, query_operator=or_)
Write a Python 3 script for converting the url arg to a filter.
As a Python code analyst, you investigate and solve complex coding mysteries
def create(self, *args, **kwargs): """Adds created http status response and location link.""" resource = super(JsonServerResource, self).create(*args, **kwargs) return ResourceResult( body=resource, status=get_http_status_code_value(http.client.CREATED), loca...
Create a Python 3 function to add created http status response and location link.
As a python code expert, you are capable of creating scripts from specifications.
Transform the json - server filter arguments to model - resource ones.
Explain what the following Python 3 code does def _create_filter_by(self): filter_by = [] for name, values in request.args.copy().lists(): # copy.lists works in py2 and py3 if name not in _SKIPPED_ARGUMENTS: column = _re_column_name.search(name).group(1) if...
You are a Python code generator, capable of creating scripts from specifications.
Create related field from _embed arguments.
Can you generate the documentation for the following Python 3 function def _create_related(args): # type: (Dict) -> None """Create related field from `_embed` arguments.""" if '_embed' in request.args: embeds = request.args.getlist('_embed') args['related'] = ','.join(em...
As a Python code translator, you convert algorithms and pseudocode into Python.
Support the json - server fulltext search with a broad LIKE filter.
Can you generate the documentation for the following Python 3 function def _create_fulltext_query(self): filter_by = [] if 'q' in request.args: columns = flat_model(model_tree(self.__class__.__name__, self.model_cls)) for q in request.args.getlist('q'): filter_by...
As a Python code analyst, you investigate and solve complex coding mysteries
def _transform_list_args(self, args): # type: (dict) -> None """Transforms all list arguments from json-server to model-resource ones. This modifies the given arguments. """ if '_limit' in args: args['limit'] = int(args['_limit']) del args['_limit'] ...
Can you write a function in Python 3 where it transforms all list arguments from json - server to model - resource ones.
As a Python code composer, you craft elegant and concise scripts.
def read(self, params, args, data): """Modifies the parameters and adds metadata for read results.""" result_count = None result_links = None if params is None: params = [] if args: args = args.copy() else: args = {} ctx = sel...
Write a Python 3 function for modifying the parameters and adds metadata for read results.
You are a Python code analyst, evaluating scripts for potential improvements.
Modifies the parameters and adds metadata for update results.
Explain what the following Python 3 code does def update(self, *args, **kwargs): if request.method == 'PUT': logging.warning("Called not implemented resource method PUT") resource = super(JsonServerResource, self).update(*args, **kwargs) if resource: return resource ...
You are a Python code analyst, evaluating scripts for potential improvements.
Supports only singular delete and adds proper http status.
Make a summary of the following Python 3 code def delete(self, params, args, data): ctx = self._create_context(params, args, data) row_id = ctx.get_row_id() if row_id: deleted = self._delete_one(row_id, ctx) if deleted: return ResourceResult(body={}) ...
You are a Python code analyst, evaluating scripts for potential improvements.
Instantiate and run the perform method od given task data.
Explain what the following Python 3 code does def run_task(task_cls, task_data): task = instantiate(task_cls) task_callable = get_callable(task) return task_callable(TaskData(task_data))
As a Python code analyst, you investigate and solve complex coding mysteries
Instantiate and run the perform method od given task data.
Given the following Python 3 function, write the documentation def run_task_json(task_cls, task_data): # TODO what does set_skipping_json do? task = instantiate(task_cls) task_callable = get_callable(task) td = TaskData(task_data) td.set_skipping_json(True) return task_callable(td)
You are a Python code architect, reviewing and designing scalable and efficient code
def _aggregate(data, norm=True, sort_by='value', keys=None): ''' Counts the number of occurances of each item in 'data'. Inputs data: a list of values. norm: normalize the resulting counts (as percent) sort_by: how to sort the retured data. Options are 'value' and 'count'. Output a non...
How would you code a function in Python 3 to aggregate the data into a single list of counts.
As a python code expert, you are capable of creating scripts from specifications.
Generate apiary documentation. Create a Apiary generator and add application packages to it. :param task_router: task router, injected :type task_router: TaskRouter :return: apiary generator :rtype: ApiaryDoc
Can you generate the documentation for the following Python 3 function def generate_apiary_doc(task_router): generator = ApiaryDoc() for m in task_router.get_task_packages() + get_method_packages(): m = importlib.import_module(m) generator.docmodule(m) return generator
As a python code expert, you are capable of creating scripts from specifications.
Setup logging using the built - in logging package.
How would you explain what the following Python 3 function does def setup_logging(logfile, print_log_location=True, debug=False): ''' Set up logging using the built-in ``logging`` package. A stream handler is added to all logs, so that logs at or above ``logging.INFO`` level are printed to screen as we...
You are a Python code analyst, evaluating scripts for potential improvements.
Get a logging handle.
Given the following Python 3 function, write the documentation def get_logger(name=None): ''' Get a logging handle. As with ``setup_logging``, a stream handler is added to the log handle. Arguments: name (str): Name of the log handle. Default is ``None``. ''' logger = logging.getL...
You are a Python code analyst, evaluating scripts for potential improvements.
def phylogeny(sequences=None, project_dir=None, name=None, aln_file=None, tree_file=None, seq_field=None, name_field=None, aa=False, species='human', unrooted=False, ladderize=True, root=None, root_name=None, show_root_name=False, color_dict=None, color_function=None, order_dict=None, order_func...
Create a Python 3 function to generate a lineage phylogeny figure.
You are a Python code analyst, evaluating scripts for potential improvements.
def igphyml(input_file=None, tree_file=None, root=None, verbose=False): ''' Computes a phylogenetic tree using IgPhyML. .. note:: IgPhyML must be installed. It can be downloaded from https://github.com/kbhoehn/IgPhyML. Args: input_file (str): Path to a Phylip-formatted multip...
How would you implement a function in Python 3 that computes a phylogenetic tree using IgPhyML. .. note:: IgPhyML must be installed. It can be downloaded from https://github.com/kbhoehn/IgPhyML. Args: input_file (str): Path to a Phylip-formatted multiple sequence alignment. Required. tree_file (str): Path to the output...
As a Python code composer, you craft elegant and concise scripts.
def append_headers(f): """ Appends all the web headers: * ZSL version and information, * default CORS if not already set up, * cache. :param f: The decorated function. :return: The function which appends the web headers. """ @wraps(f) def _response_decorator(*args, **kwarg...
Can you implement a function in Python 3 that appends all the web headers: * ZSL version and information, * default CORS if not already set up, * cache. :param f: The decorated function. :return: The function which appends the web headers.
As a Python code analyst, you investigate and solve complex coding mysteries
Integrate content into a file with line marks
Given the following Python 3 function, write the documentation def integrate_to_file(what, filename, start_line, end_line): try: with open(filename) as f: lines = f.readlines() except IOError: lines = [] tmp_file = tempfile.NamedTemporaryFile(delete=False) lines.reverse() ...
As a Python code analyst, you investigate and solve complex coding mysteries
Updates the raw_model according to the values in the app_model.
Can you generate the documentation for the following Python 3 function def update_model(raw_model, app_model, forbidden_keys=None, inverse=False): if forbidden_keys is None: forbidden_keys = [] if type(app_model) != dict: app_model = app_model.__dict__ if inverse: for k in app_mode...
You are a Python code generator, capable of creating scripts from specifications.
Prints a progress bar for the given number of finished jobs and total number of failed jobs.
Can you generate the documentation for the following Python 3 function def progress_bar(finished, total, start_time=None, extra_info=None, autocomplete=True, completion_string='/n'): ''' Prints an ASCII progress bar. Each call to ``progress_bar`` will update the progress bar. An example ...
You are a Python code generator, capable of creating scripts from specifications.
r test -> in1 | in0
Can you generate a brief explanation for the following Python 3 code def _ite(test: str, in1: str, in0: str, output: str = None): r"test -> in1 /\ ~test -> in0" assert len({test, in0, in1}) == 3 true_out = bit_flipper([test]) >> or_gate([test, in1], 'true_out') false_out = or_gate([test, in0], 'false_o...
As a Python code composer, you craft elegant and concise scripts.
Updates the raw model. Consult zsl. utils. model_helper. update_model.
Can you tell what is the following Python 3 function doing def update(self, app_model, forbidden_keys=None, inverse=False): if forbidden_keys is None: forbidden_keys = [] update_model(self, app_model, forbidden_keys, inverse)
You are a Python code analyst, evaluating scripts for potential improvements.
def xml_to_json(element, definition, required=False): # TODO document tuple - it looks little too complex """Convert XML (ElementTree) to dictionary from a definition schema. Definition schema can be a simple string - XPath or @attribute for direct extraction or a complex one described by * dictio...
Write a Python 3 script to convert XML element tree to JSON
You are a Python code architect, reviewing and designing scalable and efficient code
Parse xml element by a definition given in dict format.
How would you explain what the following Python 3 function does def _parse_dict(element, definition): sub_dict = {} for name, subdef in viewitems(definition): (name, required) = _parse_name(name) sub_dict[name] = xml_to_json(element, subdef, required) return sub_dict
As a python code expert, you are capable of creating scripts from specifications.
Parse xml element by a definition given in tuple format.
Explain what the following Python 3 code does def _parse_tuple(element, definition, required): # TODO needs to be documented properly. d_len = len(definition) if d_len == 0: return None if d_len == 1: return xml_to_json(element, definition[0], required) first = definition[0] i...
As a python code expert, you are capable of creating scripts from specifications.
Parse xml element by definition given by list.
Explain what the following Python 3 code does def _parse_list(element, definition): if len(definition) == 0: raise XmlToJsonException('List definition needs some definition') tag = definition[0] tag_def = definition[1] if len(definition) > 1 else None sub_list = [] for el in element.finda...
As a Python code analyst, you investigate and solve complex coding mysteries
def _parse_name(name): """Parse name in complex dict definition. In complex definition required params can be marked with `*`. :param name: :return: name and required flag :rtype: tuple """ required = False if name[-1] == '*': name = name[0:-1] required = True ret...
Write a Python 3 script for parsing name in complex dict definition.
You are a Python code architect, reviewing and designing scalable and efficient code
parse hostname : 22 into a host and port with the port optional
Can you tell what is the following Python 3 function doing def get_host_port(spec, default_port): "parse 'hostname:22' into a host and port, with the port optional" args = (spec.split(':', 1) + [default_port])[:2] args[1] = int(args[1]) return args[0], args[1]
As a python code expert, you are capable of creating scripts from specifications.
Returns the lineage name or None if the name cannot be found.
Can you generate a brief explanation for the following Python 3 code def name(self): ''' Returns the lineage name, or None if the name cannot be found. ''' clonify_ids = [p.heavy['clonify']['id'] for p in self.heavies if 'clonify' in p.heavy] if len(clonify_ids) > 0: ...
As a python code expert, you are capable of creating scripts from specifications.
Returns all lineage Pair objects that contain verified pairings.
Can you tell what is the following Python 3 function doing def verified_pairs(self): ''' Returns all lineage Pair objects that contain verified pairings. ''' if not hasattr(self.just_pairs[0], 'verified'): self.verify_light_chains() return [p for p in self.just_pairs ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Calculate the size of the lineage.
Make a summary of the following Python 3 code def size(self, pairs_only=False): ''' Calculate the size of the lineage. Inputs (optional) ----------------- pairs_only: count only paired sequences Returns ------- Lineage size (int) ''' if p...
As a Python code translator, you convert algorithms and pseudocode into Python.
def verify_light_chains(self, threshold=0.9): ''' Clusters the light chains to identify potentially spurious (non-lineage) pairings. Following clustering, all pairs in the largest light chain cluster are assumed to be correctly paired. For each of those pairs, the <verified> attr...
Implement a function in Python 3 to verify that the light chains are correctly paired.
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a single alignment of all lineage sequences with the UCA as a single line.
Can you generate a brief explanation for the following Python 3 code def dot_alignment(self, seq_field='vdj_nt', name_field='seq_id', uca=None, chain='heavy', uca_name='UCA', as_fasta=False, just_alignment=False): ''' Returns a multiple sequence alignment of all lineage sequence with the UCA...
As a python code expert, you are capable of creating scripts from specifications.
Basic implementation of returning a child state
Can you tell what is the following Python 3 function doing def to_child(self, append_message="", **kwargs): bad_pars = set(kwargs) - set(self._child_params) if bad_pars: raise KeyError("Invalid init params for State: %s" % ", ".join(bad_pars)) child = copy(self) for k, v in...
As a python code expert, you are capable of creating scripts from specifications.
Create element from a dict definition and add it to parent element.
Make a summary of the following Python 3 code def complex_el_from_dict(parent, data, key): el = ET.SubElement(parent, key) value = data[key] if isinstance(value, dict): if '_attr' in value: for a_name, a_value in viewitems(value['_attr']): el.set(a_name, a_value) ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def element_from_dict(parent, data, element): """Create ``element`` to ``parent`` and sets its value to data[element], which will be removed from the ``data``. :param parent: parent element :type parent: Element :param data: dictionary where data[element] is desired value :type data: dict(str, ...
Write a Python 3 function that can create element from dict data.
As a Python code analyst, you investigate and solve complex coding mysteries
def rss_create(channel, articles): """Create RSS xml feed. :param channel: channel info [title, link, description, language] :type channel: dict(str, str) :param articles: list of articles, an article is a dictionary with some \ required fields [title, description, link] and any optional, which wil...
How would you code a function in Python 3 to create RSS xml feed.
You are a Python code analyst, evaluating scripts for potential improvements.
def compute_token(random_token, config): """Compute a hash of the given token with a preconfigured secret. :param random_token: random token :type random_token: str :return: hashed token :rtype: str """ secure_token = config[TOKEN_SERVICE_SECURITY_CONFIG] sha1hash = hashlib.sha1() s...
How would you code a function in Python 3 to compute a hash of the given token with a preconfigured secret.
As a Python code analyst, you investigate and solve complex coding mysteries
def verify_security_data(security): """Verify an untrusted security token. :param security: security token :type security: dict :return: True if valid :rtype: bool """ random_token = security[TOKEN_RANDOM] hashed_token = security[TOKEN_HASHED] return str(hashed_token) == str(compute...
Can you write a function in Python 3 where it verifies an untrusted security token.
You are a Python code analyst, evaluating scripts for potential improvements.
Initializes an AbTools pipeline.
Make a summary of the following Python 3 code def initialize(log_file, project_dir=None, debug=False): ''' Initializes an AbTools pipeline. Initialization includes printing the AbTools splash, setting up logging, creating the project directory, and logging both the project directory and the log loc...
You are a Python code analyst, evaluating scripts for potential improvements.
Lists files in a given directory.
Make a summary of the following Python 3 code def list_files(d, extension=None): ''' Lists files in a given directory. Args: d (str): Path to a directory. extension (str): If supplied, only files that contain the specificied extension will be returned. Default is ``False``, ...
You are a Python code analyst, evaluating scripts for potential improvements.
def _get_version(ctx, _, value): """Click callback for option to show current ZSL version.""" if not value or ctx.resilient_parsing: return message = 'Zsl %(version)s\nPython %(python_version)s' click.echo(message % { 'version': version, 'python_version': sys.version, }, col...
Write a Python 3 function for clicking callback for option to show current ZSL version.
As a Python code composer, you craft elegant and concise scripts.
def create_model_resource(resource_map, name, app=Injected): """Create a model resource from a dict ``resource_map`` {'resource name': ('model package', 'model class')} :param resource_map: dict with resource descriptions :type resource_map: dict(str, tuple(str)) :param name: name of the concrete r...
Write a Python 3 script to create a model resource from a dict with resource descriptions.
As a Python code analyst, you investigate and solve complex coding mysteries
Return a dictionary only with keys found in allowed_keys
Can you generate a brief explanation for the following Python 3 code def dict_pick(dictionary, allowed_keys): return {key: value for key, value in viewitems(dictionary) if key in allowed_keys}
As a python code expert, you are capable of creating scripts from specifications.
def page_to_offset(params): """ Transforms `page`/`per_page` from `params` to `limit`/`offset` suitable for SQL. :param dict params: The dictionary containing `page` and `per_page` values will be added the values `limit` and `offset`. """ if 'page' not in params: re...
Write a Python 3 function that can transform page per_page from params to limit and offset.
You are a Python code analyst, evaluating scripts for potential improvements.
def create(self, params, args, data): # type: (str, dict, dict) -> AppModel """ POST /resource/model_cls/ data Create new resource """ ctx = self._create_context(params, args, data) model = self._create_one(ctx) self._save_one(model, ctx) ...
Write a Python 3 function that can post / resource / model_cls / data Create new resource
You are a Python code analyst, evaluating scripts for potential improvements.
def read(self, params=None, args=None, data=None): # type: (str, dict, dict) -> Union[List[AppModel], AppModel] """ GET /resource/model_cls/[params:id]?[args:{limit,offset,page,per_page,filter_by,order_by,related,fields}] Get resource/s :param params :type params list ...
Write a Python 3 script to get all AppModels for a specific resource.
As a Python code analyst, you investigate and solve complex coding mysteries
Update the resource s related resources.
How would you explain what the following Python 3 function does def update(self, params, args, data): # type: (str, dict, dict) -> Union[List[AppModel], AppModel] """ PUT /resource/model_cls/[params:id] data Update resource/s """ ctx = self._create_context(params...
As a python code expert, you are capable of creating scripts from specifications.
def _create_one(self, ctx): """ Creates an instance to be saved when a model is created. """ assert isinstance(ctx, ResourceQueryContext) fields = dict_pick(ctx.data, self._model_columns) model = self.model_cls(**fields) return model
Implement a Python 3 function for creating an instance of the model class based on the given context.
As a python code expert, you are capable of creating scripts from specifications.
Saves the created instance.
Can you tell what is the following Python 3 function doing def _save_one(self, model, ctx): assert isinstance(ctx, ResourceQueryContext) self._orm.add(model) self._orm.flush()
As a Python code translator, you convert algorithms and pseudocode into Python.
def _update_one(self, ctx): """ Update row """ assert isinstance(ctx, ResourceQueryContext) fields = ctx.data row_id = ctx.get_row_id() return self._update_one_simple(row_id, fields, ctx)
Implement a Python 3 function for updating one entry in the cache
As a Python code composer, you craft elegant and concise scripts.
def _update_collection(self, ctx): """ Bulk update """ assert isinstance(ctx, ResourceQueryContext) models = [] for row in ctx.data: models.append(self._update_one_simple(row.pop('id'), row, ctx)) return models
Write a Python 3 function for bulking update a collection of all the items in the context.
As a python code expert, you are capable of creating scripts from specifications.
Create a delete query for the record with the given id.
Make a summary of the following Python 3 code def _create_delete_one_query(self, row_id, ctx): assert isinstance(ctx, ResourceQueryContext) return self._orm.query(self.model_cls).filter(self._model_pk == row_id)
You are a Python code architect, reviewing and designing scalable and efficient code
Delete a collection from DB optionally filtered by filter_by
Can you tell what is the following Python 3 function doing def _delete_collection(self, ctx): assert isinstance(ctx, ResourceQueryContext) filter_by = ctx.get_filter_by() q = self._orm.query(self.model_cls) if filter_by is not None: q = self.to_filter(q, filter_by) ...
As a python code expert, you are capable of creating scripts from specifications.
def send_email(sender, receivers, subject, text=None, html=None, charset='utf-8', config=Injected): """Sends an email. :param sender: Sender as string or None for default got from config. :param receivers: String or array of recipients. :param subject: Subject. :param text: Plain text message. ...
Write a Python 3 function that can send an email. :param sender: Sender as string or None for default got from config. :param receivers: String or array of recipients. :param subject: Subject. :param text: Plain text message. :param html: Html message. :param charset: Charset. :param config: Current configuration
You are a Python code architect, reviewing and designing scalable and efficient code
Adds an automatic resolution of urls into tasks.
Here you have a function in Python 3, explain what it does def add_packages(self, packages): # type: (List[str])->TaskNamespace assert isinstance(packages, list), "Packages must be list of strings." self._task_packages += packages return self
You are a Python code analyst, evaluating scripts for potential improvements.
Returns the task handling the given request path.
Explain what the following Python 3 code does def route(self, path): # type: (str)->Tuple[Any, Callable] """ Returns the task handling the given request path. """ logging.getLogger(__name__).debug("Routing path '%s'.", path) cls = None for strategy in self._strat...
You are a Python code architect, reviewing and designing scalable and efficient code