output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Sets the number of times an object can be called.
Can you generate the documentation for the following Python 3 function def times_called(self, n): if self._last_declared_call_name: actual_last_call = self._declared_calls[self._last_declared_call_name] if isinstance(actual_last_call, CallStack): raise FakeDeclarationErro...
As a python code expert, you are capable of creating scripts from specifications.
Set the last call to expect specific argument values.
Explain what the following Python 3 code does def with_args(self, *args, **kwargs): exp = self._get_current_call() if args: exp.expected_args = args if kwargs: exp.expected_kwargs = kwargs return self
As a Python code translator, you convert algorithms and pseudocode into Python.
Set the last call to expect specific argument values if those arguments exist.
Can you tell what is the following Python 3 function doing def with_matching_args(self, *args, **kwargs): exp = self._get_current_call() if args: exp.expected_matching_args = args if kwargs: exp.expected_matching_kwargs = kwargs return self
As a Python code translator, you convert algorithms and pseudocode into Python.
This method is used to set the last call to expect that certain arguments will not exist.
Given the following Python 3 function, write the documentation def without_args(self, *args, **kwargs): exp = self._get_current_call() if args: exp.unexpected_args = args if kwargs: exp.unexpected_kwargs = kwargs return self
As a Python code translator, you convert algorithms and pseudocode into Python.
Set the last call to expect an exact argument count.
Make a summary of the following Python 3 code def with_arg_count(self, count): exp = self._get_current_call() exp.expected_arg_count = count return self
You are a Python code analyst, evaluating scripts for potential improvements.
Set the last call to expect an exact count of keyword arguments.
Can you generate the documentation for the following Python 3 function def with_kwarg_count(self, count): exp = self._get_current_call() exp.expected_kwarg_count = count return self
As a Python code translator, you convert algorithms and pseudocode into Python.
setup a ssh tunnel for a single database connection
Given the following Python 3 function, write the documentation def _setup_tunnel( self, tunnelParameters): """ *setup a ssh tunnel for a database connection to port through* **Key Arguments:** - ``tunnelParameters`` -- the tunnel parameters found associated w...
As a python code expert, you are capable of creating scripts from specifications.
Checks that the TCP Port we ve decided to use for tunnelling is available.
Can you generate the documentation for the following Python 3 function def _checkServer(self, address, port): self.log.debug('starting the ``_checkServer`` method') # CREATE A TCP SOCKET import socket s = socket.socket() self.log.debug( """Attempting to connect to `%...
As a Python code translator, you convert algorithms and pseudocode into Python.
def clean_username(self): """ Validate that the username is unique and not listed in ``defaults.ACCOUNTS_FORBIDDEN_USERNAMES`` list. """ try: user = get_user_model().objects.get(username=self.cleaned_data["username"]) except get_user_model().DoesNot...
How would you code a function in Python 3 to validate that the username is unique and not listed in defaults. ACCOUNTS_FORBIDDEN_USERNAMES list.
You are a Python code architect, reviewing and designing scalable and efficient code
def clean_email(self): """ Validate that the email address is unique. """ if get_user_model().objects.filter( Q(email__iexact=self.cleaned_data['email']) | Q(email_unconfirmed__iexact=self.cleaned_data['email'])): raise forms.ValidationError...
Can you write a function in Python 3 where it validates that the email address is unique.
As a python code expert, you are capable of creating scripts from specifications.
Creates a new user and returns the newly created user.
Given the following Python 3 function, write the documentation def save(self): username, email, password = (self.cleaned_data['username'], self.cleaned_data['email'], self.cleaned_data['password1']) user = get_user_model().object...
As a Python code analyst, you investigate and solve complex coding mysteries
Checks for the combination of the identification and password and returns the cleaned_data.
Given the following Python 3 function, write the documentation def clean(self): identification = self.cleaned_data.get('identification') password = self.cleaned_data.get('password') if identification and password: self.user_cache = authenticate(identification=identification, ...
You are a Python code generator, capable of creating scripts from specifications.
Validate that the email is not already registered with another user.
Can you generate a brief explanation for the following Python 3 code def clean_email(self): if self.cleaned_data['email'].lower() == self.user.email: raise forms.ValidationError(_(u"You're already known under " "this email address.")) if get_us...
As a python code expert, you are capable of creating scripts from specifications.
def clean_picture(self): """ Validates format and file size of uploaded profile picture. """ if self.cleaned_data.get('picture'): picture_data = self.cleaned_data['picture'] if 'error' in picture_data: raise forms.ValidationError(_(u'Uploa...
Implement a Python 3 function for validating that the uploaded picture is valid and returns the url of the image.
You are a Python code generator, capable of creating scripts from specifications.
Visit a grouping element.
Explain what the following Python 3 code does def visit_grouping(self, grouping, asfrom=False, **kwargs): return { 'type': 'grouping', 'grouping': grouping.element._compiler_dispatch(self, **kwargs) }
As a Python code translator, you convert algorithms and pseudocode into Python.
def visit_select(self, select, asfrom=False, parens=True, fromhints=None, compound_index=0, nested_join_translation=False, select_wraps_for=None, **kwargs): jsn = {'command': 'advanced/search', 'type': 'sele...
Can you create a Python 3 function that visits a select and return a JSON object that represents the result.
You are a Python code generator, capable of creating scripts from specifications.
def _label_select_column(self, select, column, populate_result_map, asfrom, column_clause_args, name=None, within_columns_clause=True): """produce labeled columns present in a select().""" ...
Implement a function in Python 3 to produce labeled columns present in a select statement.
As a Python code composer, you craft elegant and concise scripts.
def cleanup(): """Stop all started tasks on system exit. Note: This only handles signals caught by the atexit module by default. SIGKILL, for instance, will not be caught, so cleanup is not guaranteed in all cases. """ to_stop = STARTED_TASKS.copy() if to_stop: print "Cleaning up......
How would you implement a function in Python 3 that stops all started tasks on system exit.
As a python code expert, you are capable of creating scripts from specifications.
def start(self, wait=False): """Start a task. This function depends on the underlying implementation of _start, which any subclass of ``Task`` should implement. Args: wait (bool): Whether or not to wait on the task to finish before returning from this functi...
Can you create a Python 3 function that starts a task. This function depends on the underlying implementation of _start, which any subclass of ``Task`` should implement. Args: wait (bool): Whether or not to wait on the task to finish before returning from this function. Default `False`. Raises: RuntimeError: If the tas...
As a Python code analyst, you investigate and solve complex coding mysteries
Wait on a task to finish and stop it when it has finished.
Can you generate a brief explanation for the following Python 3 code def wait(self): if self._status is not TaskStatus.STARTED: raise RuntimeError("Cannot wait on %s in state %s" % (self, self._status)) self._wait() self.stop() return self.retur...
You are a Python code architect, reviewing and designing scalable and efficient code
Stops a task immediately.
Here you have a function in Python 3, explain what it does def stop(self): if self._status is TaskStatus.STOPPED: return if self._status is not TaskStatus.STARTED: raise RuntimeError("Cannot stop %s in state %s" % (self, self._status)) self...
You are a Python code architect, reviewing and designing scalable and efficient code
def reset(self): """Reset a task. Allows a task to be started again, clears the ``return_values``. Raises: RuntimeError: If the task has not been stopped. """ if self._status is not TaskStatus.STOPPED: raise RuntimeError("Cannot reset %s in state %s" % ...
Create a Python 3 function to reset the internal state of the task.
You are a Python code generator, capable of creating scripts from specifications.
Helper method to aggregate RemoteTasks into single ssh session.
Given the following Python 3 function, write the documentation def _aggregate(self): # pylint: disable=W0212 nonremote = [t for t in self._tasks if not isinstance(t, RemoteTask)] remote = [t for t in self._tasks if isinstance(t, RemoteTask)] host_dict = defaultdict(list) for tas...
You are a Python code architect, reviewing and designing scalable and efficient code
def upload_to_picture(instance, filename): """ Uploads a picture for a user to the ``ACCOUNTS_PICTURE_PATH`` and saving it under unique hash for the image. This is for privacy reasons so others can't just browse through the picture directory. """ extension = filename.split('.')[-1].lower() ...
Write a Python 3 script for uploading a picture for a user to the ACCOUNTS_PICTURE_PATH and saves it under unique hash for the image.
You are a Python code generator, capable of creating scripts from specifications.
Checks if activation key is expired.
Can you tell what is the following Python 3 function doing def activation_key_expired(self): expiration_days = datetime.timedelta( days=defaults.ACCOUNTS_ACTIVATION_DAYS) expiration_date = self.date_joined + expiration_days if self.activation_key == defaults.ACCOUNTS_...
You are a Python code analyst, evaluating scripts for potential improvements.
Sends an activation email to the user.
How would you explain what the following Python 3 function does def send_activation_email(self): context= {'user': self, 'protocol': get_protocol(), 'activation_days': defaults.ACCOUNTS_ACTIVATION_DAYS, 'activation_key': self.activation_key, ...
As a Python code composer, you craft elegant and concise scripts.
Changes the email address for a user.
Can you tell what is the following Python 3 function doing def change_email(self, email): self.email_unconfirmed = email salt, hash = generate_sha1(self.username) self.email_confirmation_key = hash self.email_confirmation_key_created = get_datetime_now() self.save() # S...
You are a Python code analyst, evaluating scripts for potential improvements.
This method sends an email to confirm the new email address.
Can you tell what is the following Python 3 function doing def send_confirmation_email(self): context= {'user': self, 'new_email': self.email_unconfirmed, 'protocol': get_protocol(), 'confirmation_key': self.email_confirmation_key, 'site': ...
As a Python code analyst, you investigate and solve complex coding mysteries
def get_picture_url(self): """ Returns the image containing the picture for the user. The picture can be a uploaded image or a Gravatar. Gravatar functionality will only be used when ``ACCOUNTS_GRAVATAR_PICTURE`` is set to ``True``. :return: ``None`` when G...
Can you implement a function in Python 3 that returns the url of the picture for the user.
As a python code expert, you are capable of creating scripts from specifications.
Returns the full name of the user or the username if none is supplied will return the username or email address depending on the ACCOUNTS_WITHOUT_USERNAMES settings.
Explain what the following Python 3 code does def get_full_name_or_username(self): if self.first_name or self.last_name: # We will return this as translated string. Maybe there are some # countries that first display the last name. name = _(u"%(first_name)s %(last_name)s") % ...
As a python code expert, you are capable of creating scripts from specifications.
Verify sanity for a : class :. Config instance.
Given the following Python 3 function, write the documentation def validate_config(config): non_null_params = ['space_id', 'access_token'] for param in non_null_params: if getattr(config, param) is None: raise Exception('Configuration for \"{0}\" must not be empty.'.format(pa...
As a Python code composer, you craft elegant and concise scripts.
Construct a : class :. Request instance for the given resource type.
Here you have a function in Python 3, explain what it does def fetch(self, resource_class): if issubclass(resource_class, Entry): params = None content_type = getattr(resource_class, '__content_type__', None) if content_type is not None: params = {'content_typ...
As a Python code analyst, you investigate and solve complex coding mysteries
Resolve a link to a CDA resource.
How would you explain what the following Python 3 function does def resolve(self, link_resource_type, resource_id, array=None): result = None if array is not None: container = array.items_mapped.get(link_resource_type) result = container.get(resource_id) if result is No...
As a Python code composer, you craft elegant and concise scripts.
Convenience method for resolving links given a dictionary object.
Can you tell what is the following Python 3 function doing def resolve_dict_link(self, dct, array=None): sys = dct.get('sys') return self.resolve(sys['linkType'], sys['id'], array) if sys is not None else None
You are a Python code architect, reviewing and designing scalable and efficient code
Invoke the given request using the associated Dispatcher.
Can you generate a brief explanation for the following Python 3 code def invoke(self, request): url = '{0}/{1}'.format(self.base_url, request.remote_path) r = self.httpclient.get(url, params=request.params, headers=self.get_headers()) if 200 <= r.status_code < 300: return self.resour...
As a Python code analyst, you investigate and solve complex coding mysteries
def all(self): """Attempt to retrieve all available resources matching this request. :return: Result instance as returned by the :class:`.Dispatcher`. """ result = self.invoke() if self.resolve_links: result.resolve_links() return result
How would you code a function in Python 3 to attempt to retrieve all available resources matching this request.
You are a Python code architect, reviewing and designing scalable and efficient code
def first(self): """Attempt to retrieve only the first resource matching this request. :return: Result instance, or `None` if there are no matching resources. """ self.params['limit'] = 1 result = self.all() return result.items[0] if result.total > 0 else None
Can you implement a function in Python 3 that attempts to retrieve only the first resource matching this request.
As a Python code composer, you craft elegant and concise scripts.
def where(self, params): """Set a dict of parameters to be passed to the API when invoking this request. :param params: (dict) query parameters. :return: this :class:`.RequestArray` instance for convenience. """ self.params = dict(self.params, **params) # params overrides self...
Write a Python 3 function that can set a dict of parameters to be passed to the API when invoking this request.
You are a Python code generator, capable of creating scripts from specifications.
def active_url(context, urls, css=None): """ Highlight menu item based on url tag. Returns a css class if ``request.path`` is in given ``url``. :param url: Django url to be reversed. :param css: Css class to be returned for highlighting. Return active if none set. """...
Can you implement a function in Python 3 that highlights menu item based on url tag.
You are a Python code analyst, evaluating scripts for potential improvements.
Highlight menu item based on request. path.
Make a summary of the following Python 3 code def active_path(context, pattern, css=None): request = context['request'] #pattern = "^" + pattern + "$" if re.search(pattern, request.path): return css if css else 'active' return ''
As a Python code translator, you convert algorithms and pseudocode into Python.
Retrieve the value of an option in the configuration.
Here you have a function in Python 3, explain what it does def get(self, item_name): if self.prefix: item_name = self.prefix + self.seperator + item_name item_names = item_name.split(self.seperator) node = self._storage for item_name in item_names: node = node[item_name] return node
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_if_exists(self, item_name, default_value=None): """ Retrieve the value of an option if it exists, otherwise return *default_value* instead of raising an error: :param str item_name: The name of the option to retrieve. :param default_value: The value to return if *item_name* does not exist. :return:...
Create a Python 3 function to retrieve the value of an option if it exists otherwise return default_value instead of raising an error.
As a Python code translator, you convert algorithms and pseudocode into Python.
def has_option(self, option_name): """ Check that an option exists. :param str option_name: The name of the option to check. :return: True of the option exists in the configuration. :rtype: bool """ if self.prefix: option_name = self.prefix + self.seperator + option_name item_names = option_name.spl...
Implement a function in Python 3 to check that an option exists in the configuration.
As a Python code composer, you craft elegant and concise scripts.
Checks that an option exists and that it contains sub options.
Can you generate the documentation for the following Python 3 function def has_section(self, section_name): if not self.has_option(section_name): return False return isinstance(self.get(section_name), dict)
As a python code expert, you are capable of creating scripts from specifications.
def set(self, item_name, item_value): """ Sets the value of an option in the configuration. :param str item_name: The name of the option to set. :param item_value: The value of the option to set. """ if self.prefix: item_name = self.prefix + self.seperator + item_name item_names = item_name.split(self...
Write a Python 3 function for setting the value of an option in the configuration.
As a Python code translator, you convert algorithms and pseudocode into Python.
This method returns a dictionary of missing and incompatible settings.
Explain what the following Python 3 code does def get_missing(self, verify_file): vconf = Configuration(verify_file) missing = {} for setting, setting_type in vconf.get('settings').items(): if not self.has_option(setting): missing['missing'] = missing.get('settings', []) missing['missing'].append(setti...
As a Python code analyst, you investigate and solve complex coding mysteries
def save(self): """ Save the current configuration to disk. """ with open(self.configuration_file, 'w') as file_h: file_h.write(self._serializer('dumps', self._storage))
How would you implement a function in Python 3 that saves the current configuration to disk.
As a Python code analyst, you investigate and solve complex coding mysteries
def replace_lines(regexer, handler, lines): """Uses replacement handler to perform replacements on lines of text First we strip off all whitespace We run the replacement on a clean 'content' string Finally we replace the original content with the replaced version This ensures that we retain the cor...
Write a Python 3 script for using regexer to perform replacements on lines of text
As a Python code composer, you craft elegant and concise scripts.
def write_targets(targets, **params): """Writes version info into version file""" handler = ReplacementHandler(**params) for target, regexer in regexer_for_targets(targets): with open(target) as fh: lines = fh.readlines() lines = replace_lines(regexer, handler, lines) wit...
Create a Python 3 function to write version info into version file
As a python code expert, you are capable of creating scripts from specifications.
Yields a list of target files with their correct regex
Here you have a function in Python 3, explain what it does def regexer_for_targets(targets): for target in targets: path, file_ext = os.path.splitext(target) regexer = config.regexers[file_ext] yield target, regexer
As a Python code composer, you craft elegant and concise scripts.
Given some lines of text extract key - value pairs from them
Can you generate the documentation for the following Python 3 function def extract_keypairs(lines, regexer): updates = {} for line in lines: # for consistency we must match the replacer and strip whitespace / newlines match = regexer.match(line.strip()) if not match: continue...
As a python code expert, you are capable of creating scripts from specifications.
def read_targets(targets): """Reads generic key-value pairs from input files""" results = {} for target, regexer in regexer_for_targets(targets): with open(target) as fh: results.update(extract_keypairs(fh.readlines(), regexer)) return results
How would you implement a function in Python 3 that reads generic key - value pairs from input files
You are a Python code analyst, evaluating scripts for potential improvements.
def detect_file_triggers(trigger_patterns): """The existence of files matching configured globs will trigger a version bump""" triggers = set() for trigger, pattern in trigger_patterns.items(): matches = glob.glob(pattern) if matches: _LOG.debug("trigger: %s bump from %r\n\t%s", ...
Create a Python 3 function to detect which files will trigger a version bump
You are a Python code architect, reviewing and designing scalable and efficient code
Get all significant figures to bump
Make a summary of the following Python 3 code def get_all_triggers(bump, file_triggers): triggers = set() if file_triggers: triggers = triggers.union(detect_file_triggers(config.trigger_patterns)) if bump: _LOG.debug("trigger: %s bump requested", bump) triggers.add(bump) return t...
As a python code expert, you are capable of creating scripts from specifications.
def get_lock_behaviour(triggers, all_data, lock): """Binary state lock protects from version increments if set""" updates = {} lock_key = config._forward_aliases.get(Constants.VERSION_LOCK_FIELD) # if we are explicitly setting or locking the version, then set the lock field True anyway if lock: ...
Can you write a function in Python 3 where it gets the lock behaviour for the current version of the current page.
As a Python code analyst, you investigate and solve complex coding mysteries
def get_final_version_string(release_mode, semver, commit_count=0): """Generates update dictionary entries for the version string""" version_string = ".".join(semver) maybe_dev_version_string = version_string updates = {} if release_mode: # in production, we have something like `1.2.3`, as w...
Can you create a Python 3 function that generates the final version string for the current version string.
As a Python code analyst, you investigate and solve complex coding mysteries
Gets current repository info from git
Make a summary of the following Python 3 code def get_dvcs_info(): cmd = "git rev-list --count HEAD" commit_count = str( int(subprocess.check_output(shlex.split(cmd)).decode("utf8").strip()) ) cmd = "git rev-parse HEAD" commit = str(subprocess.check_output(shlex.split(cmd)).decode("utf8").st...
As a python code expert, you are capable of creating scripts from specifications.
def log_cmd(context, sampleinfo, sacct, quiet, config): """Log an analysis. CONFIG: MIP config file for an analysis """ log_analysis = LogAnalysis(context.obj['store']) try: new_run = log_analysis(config, sampleinfo=sampleinfo, sacct=sacct) except MissingFileError as error: clic...
Write a Python 3 script for logging an analysis. CONFIG: MIP config file for an analysis
As a Python code composer, you craft elegant and concise scripts.
Start a new analysis.
Make a summary of the following Python 3 code def start(context, mip_config, email, priority, dryrun, command, start_with, family): mip_cli = MipCli(context.obj['script']) mip_config = mip_config or context.obj['mip_config'] email = email or environ_email() kwargs = dict(config=mip_config, family=family...
As a python code expert, you are capable of creating scripts from specifications.
def scan(context, root_dir): """Scan a directory for analyses.""" root_dir = root_dir or context.obj['root'] config_files = Path(root_dir).glob('*/analysis/*_config.yaml') for config_file in config_files: LOG.debug("found analysis config: %s", config_file) with config_file.open() as stre...
Write a Python 3 function that can scan a directory for analyses.
You are a Python code analyst, evaluating scripts for potential improvements.
Add a new user or display information about an existing user.
Explain what the following Python 3 code does def user(context, name, email): existing_user = context.obj['store'].user(email) if existing_user: click.echo(existing_user.to_dict()) elif name: new_user = context.obj['store'].add_user(name, email) click.echo(click.style(f"New user adde...
You are a Python code architect, reviewing and designing scalable and efficient code
def cancel(context, jobs, analysis_id): """Cancel all jobs in a run.""" analysis_obj = context.obj['store'].analysis(analysis_id) if analysis_obj is None: click.echo('analysis not found') context.abort() elif analysis_obj.status != 'running': click.echo(f"analysis not running: {a...
Create a Python 3 function for canceling all jobs in a run.
You are a Python code generator, capable of creating scripts from specifications.
Get the addresses of a given list of names.
Here you have a function in Python 3, explain what it does def get_pub_addresses(names=None, timeout=10, nameserver="localhost"): addrs = [] if names is None: names = ["", ] for name in names: then = datetime.now() + timedelta(seconds=timeout) while datetime.now() < then: ...
You are a Python code analyst, evaluating scripts for potential improvements.
Get the address of a given publisher name from the nameserver.
Explain what the following Python 3 code does def get_pub_address(name, timeout=10, nameserver="localhost"): # Socket to talk to server socket = get_context().socket(REQ) try: socket.setsockopt(LINGER, timeout * 1000) socket.connect("tcp://" + nameserver + ":" + str(PORT)) logger.de...
As a Python code composer, you craft elegant and concise scripts.
Get the addresses of the active modules for a given publisher name.
Explain what the following Python 3 code does def get_active_address(name, arec): addrs = arec.get(name) if addrs: return Message("/oper/ns", "info", addrs) else: return Message("/oper/ns", "info", "")
You are a Python code analyst, evaluating scripts for potential improvements.
def run(self, *args): """Run the listener and answer to requests. """ del args arec = AddressReceiver(max_age=self._max_age, multicast_enabled=self._multicast_enabled) arec.start() port = PORT try: with nslock: ...
Write a Python 3 script for running the listener and answer to requests.
As a Python code translator, you convert algorithms and pseudocode into Python.
Stop the name server.
Here you have a function in Python 3, explain what it does def stop(self): self.listener.setsockopt(LINGER, 1) self.loop = False with nslock: self.listener.close()
You are a Python code generator, capable of creating scripts from specifications.
Parse the requirements file for package information to determine if all requirements are met.
How would you explain what the following Python 3 function does def check_requirements(requirements, ignore=None): ignore = (ignore or []) not_satisfied = [] working_set = pkg_resources.working_set installed_packages = dict((p.project_name, p) for p in working_set) # pylint: disable=E1133 if isinstance(requireme...
You are a Python code generator, capable of creating scripts from specifications.
def segments_to_numpy(segments): """given a list of 4-element tuples, transforms it into a numpy array""" segments = numpy.array(segments, dtype=SEGMENT_DATATYPE, ndmin=2) # each segment in a row segments = segments if SEGMENTS_DIRECTION == 0 else numpy.transpose(segments) return segments
Can you implement a function in Python 3 that gives a list of 4 - element tuples transforms it into a numpy array
You are a Python code generator, capable of creating scripts from specifications.
def region_from_segment(image, segment): """given a segment (rectangle) and an image, returns it's corresponding subimage""" x, y, w, h = segment return image[y:y + h, x:x + w]
Create a Python 3 function to give a rectangle and an image returns it s corresponding subimage
You are a Python code analyst, evaluating scripts for potential improvements.
Ingest the ePESSTO Marshall transient stream into the sherlock - catalogues database
Here you have a function in Python 3, explain what it does def ingest(self): self.log.debug('starting the ``get`` method') # A YAML DICTIONARY OF sherlock-catalogues TABLE NAME AND THE SELECT # QUERY TO LIFT THE DATA FROM THE MARSHALL yamlFilePath = '/'.join(string.split(__file__, '/') ...
You are a Python code generator, capable of creating scripts from specifications.
create a list of dictionaries containing all the rows in the marshall stream
Can you generate a brief explanation for the following Python 3 code def _create_dictionary_of_marshall( self, marshallQuery, marshallTable): """create a list of dictionaries containing all the rows in the marshall stream **Key Arguments:** - ``marshallQu...
You are a Python code generator, capable of creating scripts from specifications.
def ingest(self): """Import the ned_d catalogue into the catalogues database The method first generates a list of python dictionaries from the ned_d datafile, imports this list of dictionaries into a database table and then generates the HTMIDs for that table. **Usage:** See clas...
Can you create a Python 3 function that imports the ned_d catalogue into the catalogues database and creates the HTMIDs for that table.
You are a Python code generator, capable of creating scripts from specifications.
def _create_dictionary_of_ned_d( self): """create a list of dictionaries containing all the rows in the ned_d catalogue **Return:** - ``dictList`` - a list of dictionaries containing all the rows in the ned_d catalogue .. todo :: - update key arguments valu...
Write a Python 3 function that can create a list of dictionaries containing all the rows in the ned_d catalogue
You are a Python code generator, capable of creating scripts from specifications.
def _clean_up_columns( self): """clean up columns of the NED table .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text - update docstring text ...
Implement a Python 3 function for cleaning up the columns of the NED table
You are a Python code generator, capable of creating scripts from specifications.
def _get_metadata_for_galaxies( self): """get metadata for galaxies .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text - update docstring text ...
Implement a Python 3 function for getting metadata for a set of galaxies
You are a Python code analyst, evaluating scripts for potential improvements.
def _get_3000_galaxies_needing_metadata( self): """ get 3000 galaxies needing metadata **Return:** - ``len(self.theseIds)`` -- the number of NED IDs returned .. todo :: - update key arguments values and definitions with defaults - update return ...
Implement a function in Python 3 to get 3000 galaxies needing metadata
You are a Python code generator, capable of creating scripts from specifications.
query ned and add results to database
Given the following Python 3 function, write the documentation def _query_ned_and_add_results_to_database( self, batchCount): """ query ned and add results to database **Key Arguments:** - ``batchCount`` - the index number of the batch sent to NED .. todo ::...
You are a Python code architect, reviewing and designing scalable and efficient code
def _update_sdss_coverage( self): """ update sdss coverage .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text - update docstring text - ch...
Implement a function in Python 3 to update SDSS coverage for the current key - item
You are a Python code generator, capable of creating scripts from specifications.
Run a command on the remote host.
Make a summary of the following Python 3 code def run(self, command, **kwargs): return RemoteTask(self.hostname, command, identity_file=self._identity_file, **kwargs)
As a python code expert, you are capable of creating scripts from specifications.
Sends a file to a remote host with rsync.
Here you have a function in Python 3, explain what it does def send_file(self, file_name, remote_destination=None, **kwargs): if not remote_destination: remote_destination = file_name return SubprocessTask( self._rsync_cmd() + ['-ut', file_name, '%s:%s' % (self.hostn...
You are a Python code generator, capable of creating scripts from specifications.
Get a file from a remote host with rsync.
Can you tell what is the following Python 3 function doing def get_file(self, file_name, local_destination=None, **kwargs): if not local_destination: local_destination = file_name return SubprocessTask( self._rsync_cmd() + ['-ut', '%s:%s' % (self.hostname, file_name)...
As a Python code analyst, you investigate and solve complex coding mysteries
Make a MIP config.
Make a summary of the following Python 3 code def make_config(self, data: dict): self.validate_config(data) config_data = self.prepare_config(data) return config_data
As a python code expert, you are capable of creating scripts from specifications.
Convert to MIP config format.
Given the following Python 3 function, write the documentation def validate_config(data: dict) -> dict: errors = ConfigSchema().validate(data) if errors: for field, messages in errors.items(): if isinstance(messages, dict): for level, sample_errors in mess...
You are a Python code architect, reviewing and designing scalable and efficient code
def prepare_config(data: dict) -> dict: """Prepare the config data.""" data_copy = deepcopy(data) # handle single sample cases with 'unknown' phenotype if len(data_copy['samples']) == 1: if data_copy['samples'][0]['phenotype'] == 'unknown': LOG.info("setting '...
Write a Python 3 function for preparing the config data.
As a Python code translator, you convert algorithms and pseudocode into Python.
Save a config to the expected location.
Can you generate the documentation for the following Python 3 function def save_config(self, data: dict) -> Path: out_dir = Path(self.families_dir) / data['family'] out_dir.mkdir(parents=True, exist_ok=True) out_path = out_dir / 'pedigree.yaml' dump = ruamel.yaml.round_trip_dump(data, in...
As a Python code translator, you convert algorithms and pseudocode into Python.
This function is used exclusively by create_broadcast.
Can you generate the documentation for the following Python 3 function def _broadcast(src_processor, src_atr_name, dest_processors, dest_atr_name, transform_function): value = getattr(src_processor, src_atr_name) value = transform_function(value) for d in dest_processors: setattr(d, dest_atr_name, v...
As a Python code translator, you convert algorithms and pseudocode into Python.
def create_broadcast(src_atr_name, dest_processors, dest_atr_name=None, transform_function=lambda x: x): """ This method creates a function, intended to be called as a Processor posthook, that copies some of the processor's attributes to other processors """ from functools import partial if ...
Write a Python 3 script to create a function intended to be called as a Processor posthook that copies some of the processor s attributes to other processors
You are a Python code generator, capable of creating scripts from specifications.
returns a dictionary with the processor s stored parameters
Make a summary of the following Python 3 code def get_parameters(self): parameter_names = self.PARAMETERS.keys() # TODO: Unresolved reference for processor parameter_values = [getattr(processor, n) for n in parameter_names] return dict(zip(parameter_names, parameter_values))
You are a Python code generator, capable of creating scripts from specifications.
sets the processor stored parameters
Can you tell what is the following Python 3 function doing def set_parameters(self, **args): for k, v in self.PARAMETERS.items(): new_value = args.get(k) if new_value != None: if not _same_type(new_value, v): raise Exception( "O...
You are a Python code architect, reviewing and designing scalable and efficient code
gets from all wrapped processors
How would you explain what the following Python 3 function does def get_parameters(self): d = {} for p in self.processors: parameter_names = list(p.PARAMETERS.keys()) parameter_values = [getattr(p, n) for n in parameter_names] d.update(dict(zip(parameter_names, parame...
You are a Python code analyst, evaluating scripts for potential improvements.
def set_parameters(self, **args): """sets to all wrapped processors""" not_used = set() not_given = set() for p in self.processors: nu, ng = p.set_parameters(**args) not_used = not_used.union(nu) not_given = not_given.union(ng) return not_used,...
Write a Python 3 script for setting to all wrapped processors
You are a Python code generator, capable of creating scripts from specifications.
Render the content of the current page.
Explain what the following Python 3 code does def render(self, filename): self.elapsed_time = -time() dpi = 100 fig = figure(figsize=(16, 9), dpi=dpi) with self.writer.saving(fig, filename, dpi): for frame_id in xrange(self.frames + 1): self.renderFrame(frame_...
As a Python code composer, you craft elegant and concise scripts.
def report(self): """Prints in standard output report about animation rendering. Namely, it prints seconds spent, number of frames and step size that is used in functional animation. """ message = 'Elapsed in {0} seconds with {1} frames and {2} step.' print(message.format(self.el...
Write a Python 3 script to print in standard output report about animation rendering.
As a Python code translator, you convert algorithms and pseudocode into Python.
def add(self, address, topics=None): """Add *address* to the subscribing list for *topics*. It topics is None we will subscibe to already specified topics. """ with self._lock: if address in self.addresses: return False topics = self._magickfy_to...
Implement a function in Python 3 to add a new address to the subscribing list for topics.
You are a Python code generator, capable of creating scripts from specifications.
Remove a topic from the subscribing list for topics*.
Make a summary of the following Python 3 code def remove(self, address): with self._lock: try: subscriber = self.addr_sub[address] except KeyError: return False LOGGER.info("Subscriber removing address %s", str(address)) if self.pol...
As a Python code analyst, you investigate and solve complex coding mysteries
def update(self, addresses): """Updating with a set of addresses. """ if isinstance(addresses, six.string_types): addresses = [addresses, ] s0_, s1_ = set(self.addresses), set(addresses) sr_, sa_ = s0_.difference(s1_), s1_.difference(s0_) for a__ in sr_: ...
Implement a Python 3 function for updating with a set of addresses.
As a Python code translator, you convert algorithms and pseudocode into Python.
Add a SUB socket to receive the specified topics.
Can you tell what is the following Python 3 function doing def add_hook_sub(self, address, topics, callback): LOGGER.info("Subscriber adding SUB hook %s for topics %s", str(address), str(topics)) socket = get_context().socket(SUB) for t__ in self._magickfy_topics(topics): ...
You are a Python code architect, reviewing and designing scalable and efficient code
Add a PULL socket to be used to pull the current version of the current process.
Make a summary of the following Python 3 code def add_hook_pull(self, address, callback): LOGGER.info("Subscriber adding PULL hook %s", str(address)) socket = get_context().socket(PULL) socket.connect(address) self._add_hook(socket, callback)
As a Python code translator, you convert algorithms and pseudocode into Python.
Generic hook. The passed socket has to be "receive only".
Given the following Python 3 function, write the documentation def _add_hook(self, socket, callback): self._hooks.append(socket) self._hooks_cb[socket] = callback if self.poller: self.poller.register(socket, POLLIN)
As a Python code translator, you convert algorithms and pseudocode into Python.