text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unique_list(input_, key=lambda x:x): """Return the unique elements from the input, in order."""
seen = set() output = [] for x in input_: keyx = key(x) if keyx not in seen: seen.add(keyx) output.append(x) return output
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_environ_list(name, default=None): """Return the split colon-delimited list from an environment variable. Returns an empty list if the variable didn't exist. """
packed = os.environ.get(name) if packed is not None: return packed.split(':') elif default is not None: return default else: return []
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_indel(reference_bases, alternate_bases): """ Return whether or not the variant is an INDEL """
if len(reference_bases) > 1: return True for alt in alternate_bases: if alt is None: return True elif len(alt) != len(reference_bases): return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_snp(reference_bases, alternate_bases): """ Return whether or not the variant is a SNP """
if len(reference_bases) > 1: return False for alt in alternate_bases: if alt is None: return False if alt not in ['A', 'C', 'G', 'T', 'N', '*']: return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_deletion(reference_bases, alternate_bases): """ Return whether or not the INDEL is a deletion """
# if multiple alts, it is unclear if we have a transition if len(alternate_bases) > 1: return False if is_indel(reference_bases, alternate_bases): # just one alt allele alt_allele = alternate_bases[0] if alt_allele is None: return True if len(reference_bases) > len(alt_allele): return True else: return False else: return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def overlapping(self, other): """Do these variants overlap in the reference"""
return ( other.start in self.ref_range) or ( self.start in other.ref_range)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_pgurl(self, url): """ Given a Postgres url, return a dict with keys for user, password, host, port, and database. """
parsed = urlsplit(url) return { 'user': parsed.username, 'password': parsed.password, 'database': parsed.path.lstrip('/'), 'host': parsed.hostname, 'port': parsed.port or 5432, }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def value_change(self, model, name, info): """The model is changed and the view must be updated"""
msg = self.model.get_message(info.new) self.view.set_msg(msg) return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset_current_row(self, *args, **kwargs): """Reset the selected rows value to its default value :returns: None :rtype: None :raises: None """
i = self.configobj_treev.currentIndex() m = self.configobj_treev.model() m.restore_default(i)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_configs(self): """Load all config files and return the configobjs :returns: a list of configobjs :raises: None It always loads the coreconfig. Then it looks for all configs inside the PLUGIN_CONFIG_DIR. It will find the corresponding spec of the plugins. If there is a spec, but no ini, it will also be loaded! """
# all loaded configs are stored in confs confs = [] # always load core config. it is not part of the plugin configs try: confs.append(iniconf.get_core_config()) except ConfigError, e: log.error("Could not load Core config! Reason was: %s" % e) # get config specs that lie in the plugin path # we have to watch the order we gather the specs # plugins can override each other, so can config specs # it depends on the order of the JUKEBOX_PLUGIN_PATH specs = {} pathenv = os.environ.get('JUKEBOX_PLUGIN_PATH', '') paths = pathenv.split(';') paths.append(constants.BUILTIN_PLUGIN_PATH) for p in reversed(paths): if p: files = self.find_inifiles(p) for ini in files: base = os.path.basename(ini) specs[base] = ini configs = {} files = self.find_inifiles(PLUGIN_CONFIG_DIR) for ini in files: base = os.path.basename(ini) configs[base] = ini # find matching pairs of configs and specs # and load them for k in configs: spec = specs.pop(k, None) conf = configs[k] try: confs.append(iniconf.load_config(conf, spec)) except ConfigError, e: log.error("Could not load config %s, Reason was: %s" % (k ,e)) # the remaining configspecs can be used to create # empty configs for k in specs: spec = specs[k] conf = os.path.join(PLUGIN_CONFIG_DIR, k) try: confs.append(iniconf.load_config(conf, spec)) except ConfigError, e: log.error("Could not load config %s, Reason was: %s" % (k ,e)) return confs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_inifile(self, current, previous): """Set the configobj to the current index of the files_lv This is a slot for the currentChanged signal :param current: the modelindex of a inifilesmodel that should be set for the configobj_treev :type current: QModelIndex :param previous: the previous selected index :type previous: QModelIndex :returns: None :raises: None """
c = self.inimodel.data(current, self.inimodel.confobjRole) self.confobjmodel = ConfigObjModel(c) self.configobj_treev.setModel(self.confobjmodel) self.configobj_treev.expandAll() self.confobjmodel.dataChanged.connect(self.iniedited)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iniedited(self, *args, **kwargs): """Set the current index of inimodel to modified :returns: None :rtype: None :raises: None """
self.inimodel.set_index_edited(self.files_lv.currentIndex(), True)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def closeEvent(self, event): """Handles closing of the window. If configs were edited, ask user to continue. :param event: the close event :type event: QCloseEvent :returns: None :rtype: None :raises: None """
if self.inimodel.get_edited(): r = self.doc_modified_prompt() if r == QtGui.QMessageBox.Yes: event.accept() else: event.ignore() else: event.accept()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def doc_modified_prompt(self, ): """Create a message box, that asks the user to continue although files have been modified :returns: value of the standard button of qmessagebox that has been pressed. Either Yes or Cancel. :rtype: QtGui.QMessageBox.StandardButton :raises: None """
msgbox = QtGui.QMessageBox() msgbox.setWindowTitle("Discard changes?") msgbox.setText("Documents have been modified.") msgbox.setInformativeText("Do you really want to exit? Changes will be lost!") msgbox.setStandardButtons(msgbox.Yes | msgbox.Cancel) msgbox.setDefaultButton(msgbox.Cancel) msgbox.exec_() return msgbox.result()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_current_config(self, ): """Saves the currently displayed config :returns: None :rtype: None :raises: None This resets the edited status of the file to False. Also asks the user to continue if config is invalid. """
# check if all configs validate correctly btn = None for row in range(self.inimodel.rowCount()): i = self.inimodel.index(row, 0) r = self.inimodel.validate(i) if r is not True: btn = self.invalid_prompt() break if btn == QtGui.QMessageBox.Cancel: return current = self.files_lv.currentIndex() c = self.inimodel.data(current, self.inimodel.confobjRole) c.write() self.inimodel.set_index_edited(current, False)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_virtualenv_path(self, requirements_option: RequirementsOptions, requirements_hash: Optional[str]) -> Path: """ Returns the path to the virtualenv the current state of the repository. """
if requirements_option == RequirementsOptions.no_requirements: venv_name = "no_requirements" else: venv_name = requirements_hash return Path(self._arca.base_dir) / "venvs" / venv_name
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_or_create_environment(self, repo: str, branch: str, git_repo: Repo, repo_path: Path) -> str: """ Handles the requirements in the target repository, returns a path to a executable of the virtualenv. """
return str(self.get_or_create_venv(repo_path).resolve() / "bin" / "python")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def annotate_mapper(**decargs): """Add input and output watermarks to processed events."""
def decorator(func): """Annotate events with entry and/or exit timestamps.""" def wrapper(event, *args, **kwargs): """Add enter and exit annotations to the processed event.""" funcname = ":".join([func.__module__, func.__name__]) enter_ts = time.time() out = func(event, *args, **kwargs) enter_key = funcname + "|enter" out = annotate_event(out, enter_key, ts=enter_ts, **decargs) exit_key = funcname + "|exit" out = annotate_event(out, exit_key, ts=time.time(), **decargs) return out return wrapper return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def annotate_filter(**decargs): """Add input and output watermarks to filtered events."""
def decorator(func): """Annotate events with entry and/or exit timestamps.""" def wrapper(event, *args, **kwargs): """Add enter and exit annotations to the processed event.""" funcname = ":".join([func.__module__, func.__name__]) enter_key = funcname + "|enter" annotate_event(event, enter_key, **decargs) out = func(event, *args, **kwargs) exit_key = funcname + "|exit" annotate_event(event, exit_key, **decargs) return out return wrapper return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _error_repr(error): """A compact unique representation of an error."""
error_repr = repr(error) if len(error_repr) > 200: error_repr = hash(type(error)) return error_repr
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def annotation_has_expired(event, key, timeout): """Check if an event error has expired."""
anns = get_annotations(event, key) if anns: return (time.time() - anns[0]["ts"]) > timeout else: return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def replace_event_annotations(event, newanns): """Replace event annotations with the provided ones."""
_humilis = event.get("_humilis", {}) if not _humilis: event["_humilis"] = {"annotation": newanns} else: event["_humilis"]["annotation"] = newanns
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def annotate_event(ev, key, ts=None, namespace=None, **kwargs): """Add an annotation to an event."""
ann = {} if ts is None: ts = time.time() ann["ts"] = ts ann["key"] = key if namespace is None and "HUMILIS_ENVIRONMENT" in os.environ: namespace = "{}:{}:{}".format( os.environ.get("HUMILIS_ENVIRONMENT"), os.environ.get("HUMILIS_LAYER"), os.environ.get("HUMILIS_STAGE")) if namespace is not None: ann["namespace"] = namespace ann.update(kwargs) _humilis = ev.get("_humilis", {}) if not _humilis: ev["_humilis"] = {"annotation": [ann]} else: ev["_humilis"]["annotation"] = _humilis.get("annotation", []) # Clean up previous annotations with the same key delete_annotations(ev, key) ev["_humilis"]["annotation"].append(ann) return ev
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_annotations(event, key, namespace=None, matchfunc=None): """Produce the list of annotations for a given key."""
if matchfunc is None: matchfunc = _is_equal if isinstance(key, Exception): key = _error_repr(key) return [ann for ann in event.get("_humilis", {}).get("annotation", []) if (matchfunc(key, ann["key"]) and (namespace is None or ann.get("namespace") == namespace))]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_annotations(event, key, namespace=None, matchfunc=None): """Delete all event annotations with a matching key."""
if matchfunc is None: matchfunc = _is_equal if isinstance(key, Exception): key = _error_repr(key) newanns = [ann for ann in event.get("_humilis", {}).get("annotation", []) if not (matchfunc(key, ann["key"]) and (namespace is None or ann.get("namespace") == namespace))] replace_event_annotations(event, newanns)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_function_annotations(event, funcname, type=None, namespace=None): """Produce a list of function annotations in in this event."""
if type: postfix = "|" + type else: postfix = "|.+" def matchfunc(key, annkey): """Check if the provider regex matches an annotation key.""" return re.match(key, annkey) is not None return get_annotations(event, funcname + postfix, namespace=namespace, matchfunc=matchfunc)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_task(self, keywords, context, rule): """Map a function to a list of keywords Parameters keywords : iterable of str sequence of strings which should trigger the given function context : Context A Context object created using desired function rule : tuple A tuple of integers, which act as relative indices using which data is extracted to be passed to the function passed via context. """
for keyword in keywords: self._tasks[keyword] = {'context': context, 'rule': rule}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_modifier(self, modifier, keywords, relative_pos, action, parameter=None): """Modify existing tasks based on presence of a keyword. Parameters modifier : str A string value which would trigger the given Modifier. keywords : iterable of str sequence of strings which are keywords for some task, which has to be modified. relative_pos : int Relative position of the task which should be modified in the presence of `modifier`. It's value can never be 0. Data fields should also be considered when calculating the relative position. action : str String value representing the action which should be performed on the task. Action represents calling a arbitrary function to perform th emodification. parameter : object value required by the `action`.(Default None) """
if relative_pos == 0: raise ValueError("relative_pos cannot be 0") modifier_dict = self._modifiers.get(modifier, {}) value = (action, parameter, relative_pos) for keyword in keywords: action_list = list(modifier_dict.get(keyword, [])) action_list.append(value) modifier_dict[keyword] = tuple(action_list) self._modifiers[modifier] = modifier_dict
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse(self, text): """Parse the string `text` and return a tuple of left over Data fields. Parameters text : str A string to be parsed Returns ------- result : tuple A tuple of left over Data after processing """
self._parsed_list = [] self._most_recent_report = [] self._token_list = text.lower().split() modifier_index_list = [] for item in self._token_list: if(self._is_token_data_callback(item)): self._parsed_list.append(self._clean_data_callback(item)) if item in self._tasks: d = {} d['context'] = self._tasks[item]['context'] d['rule'] = self._tasks[item]['rule'] d['task'] = item self._parsed_list.append(d) if item in self._modifiers: modifier_index_list.append((len(self._parsed_list), item)) self._apply_modifiers(modifier_index_list) return self._evaluate()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connectionLost(self, reason): """ Called when the response body has been completely delivered. @param reason: Either a twisted.web.client.ResponseDone exception or a twisted.web.http.PotentialDataLoss exception. """
self.remaining.reset() try: result = json.load(self.remaining) except Exception, e: self.finished.errback(e) return returnValue = result if self.heartbeater: self.heartbeater.nextToken = result['token'] returnValue = (result, self.heartbeater) self.finished.callback(returnValue)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def request(self, method, path, options=None, payload=None, heartbeater=None, retry_count=0): """ Make a request to the Service Registry API. @param method: HTTP method ('POST', 'GET', etc.). @type method: C{str} @param path: Path to be appended to base URL ('/sessions', etc.). @type path: C{str} @param options: Options to be encoded as query parameters in the URL. @type options: C{dict} @param payload: Optional body @type payload: C{dict} @param heartbeater: Optional heartbeater passed in when creating a session. @type heartbeater: L{HeartBeater} """
def _request(authHeaders, options, payload, heartbeater, retry_count): tenantId = authHeaders['X-Tenant-Id'] requestUrl = self.baseUrl + tenantId + path if options: requestUrl += '?' + urlencode(options) payload = StringProducer(json.dumps(payload)) if payload else None d = self.agent.request(method=method, uri=requestUrl, headers=None, bodyProducer=payload) d.addCallback(self.cbRequest, method, path, options, payload, heartbeater, retry_count) return d d = self.agent.getAuthHeaders() d.addCallback(_request, options, payload, heartbeater, retry_count) return d
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _initialized(self, partitioner): """Store the partitioner and reset the internal state. Now that we successfully got an actual :class:`kazoo.recipe.partitioner.SetPartitioner` object, we store it and reset our internal ``_state`` to ``None``, causing the ``state`` property to defer to the partitioner's state. """
self._partitioner = partitioner self._thimble = Thimble(self.reactor, self.pool, partitioner, _blocking_partitioner_methods) self._state = None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def inject_arca(self, arca): """ Apart from the usual validation stuff it also creates log file for this instance. """
super().inject_arca(arca) import vagrant self.log_path = Path(self._arca.base_dir) / "logs" / (str(uuid4()) + ".log") self.log_path.parent.mkdir(exist_ok=True, parents=True) logger.info("Storing vagrant log in %s", self.log_path) self.log_cm = vagrant.make_file_cm(self.log_path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_vagrant(self, vagrant_file): """ Creates a Vagrantfile in the target dir, with only the base image pulled. Copies the runner script to the directory so it's accessible from the VM. """
if self.inherit_image: image_name, image_tag = str(self.inherit_image).split(":") else: image_name = self.get_arca_base_name() image_tag = self.get_python_base_tag(self.get_python_version()) logger.info("Creating Vagrantfile located in %s, base image %s:%s", vagrant_file, image_name, image_tag) repos_dir = (Path(self._arca.base_dir) / 'repos').resolve() vagrant_file.parent.mkdir(exist_ok=True, parents=True) vagrant_file.write_text(dedent(f""" # -*- mode: ruby -*- # vi: set ft=ruby : Vagrant.configure("2") do |config| config.vm.box = "{self.box}" config.ssh.insert_key = true config.vm.provision "docker" do |d| d.pull_images "{image_name}:{image_tag}" end config.vm.synced_folder ".", "/vagrant" config.vm.synced_folder "{repos_dir}", "/srv/repos" config.vm.provider "{self.provider}" end """)) (vagrant_file.parent / "runner.py").write_text(self.RUNNER.read_text())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fabric_task(self): """ Returns a fabric task which executes the script in the Vagrant VM """
from fabric import api @api.task def run_script(container_name, definition_filename, image_name, image_tag, repository, timeout): """ Sequence to run inside the VM. Starts up the container if the container is not running (and copies over the data and the runner script) Then the definition is copied over and the script launched. If the VM is gonna be shut down then kills the container as well. """ workdir = str((Path("/srv/data") / self.cwd).resolve()) cmd = "sh" if self.inherit_image else "bash" api.run(f"docker pull {image_name}:{image_tag}") container_running = int(api.run(f"docker ps --format '{{.Names}}' -f name={container_name} | wc -l")) container_stopped = int(api.run(f"docker ps -a --format '{{.Names}}' -f name={container_name} | wc -l")) if container_running == 0: if container_stopped: api.run(f"docker rm -f {container_name}") api.run(f"docker run " f"--name {container_name} " f"--workdir \"{workdir}\" " f"-dt {image_name}:{image_tag} " f"{cmd} -i") api.run(f"docker exec {container_name} mkdir -p /srv/scripts") api.run(f"docker cp /srv/repos/{repository} {container_name}:/srv/branch") api.run(f"docker exec --user root {container_name} bash -c 'mv /srv/branch/* /srv/data'") api.run(f"docker exec --user root {container_name} rm -rf /srv/branch") api.run(f"docker cp /vagrant/runner.py {container_name}:/srv/scripts/") api.run(f"docker cp /vagrant/{definition_filename} {container_name}:/srv/scripts/") output = api.run( " ".join([ "docker", "exec", container_name, "python", "/srv/scripts/runner.py", f"/srv/scripts/{definition_filename}", ]), timeout=math.ceil(timeout) ) if not self.keep_container_running: api.run(f"docker kill {container_name}") return output return run_script
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ensure_vm_running(self, vm_location): """ Gets or creates a Vagrantfile in ``vm_location`` and calls ``vagrant up`` if the VM is not running. """
import vagrant if self.vagrant is None: vagrant_file = vm_location / "Vagrantfile" if not vagrant_file.exists(): self.init_vagrant(vagrant_file) self.vagrant = vagrant.Vagrant(vm_location, quiet_stdout=self.quiet, quiet_stderr=self.quiet, out_cm=self.log_cm, err_cm=self.log_cm) status = [x for x in self.vagrant.status() if x.name == "default"][0] if status.state != "running": try: self.vagrant.up() except subprocess.CalledProcessError: raise BuildError("Vagrant VM couldn't up launched. See output for details.")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self, repo: str, branch: str, task: Task, git_repo: Repo, repo_path: Path): """ Starts up a VM, builds an docker image and gets it to the VM, runs the script over SSH, returns result. Stops the VM if ``keep_vm_running`` is not set. """
from fabric import api from fabric.exceptions import CommandTimeout # start up or get running VM vm_location = self.get_vm_location() self.ensure_vm_running(vm_location) logger.info("Running with VM located at %s", vm_location) # pushes the image to the registry so it can be pulled in the VM self.check_docker_access() # init client self.get_image_for_repo(repo, branch, git_repo, repo_path) requirements_option, requirements_hash = self.get_requirements_information(repo_path) # getting things needed for execution over SSH image_tag = self.get_image_tag(requirements_option, requirements_hash, self.get_dependencies()) image_name = self.use_registry_name task_filename, task_json = self.serialized_task(task) (vm_location / task_filename).write_text(task_json) container_name = self.get_container_name(repo, branch, git_repo) # setting up Fabric api.env.hosts = [self.vagrant.user_hostname_port()] api.env.key_filename = self.vagrant.keyfile() api.env.disable_known_hosts = True # useful for when the vagrant box ip changes. api.env.abort_exception = BuildError # raises SystemExit otherwise api.env.shell = "/bin/sh -l -c" if self.quiet: api.output.everything = False else: api.output.everything = True # executes the task try: res = api.execute(self.fabric_task, container_name=container_name, definition_filename=task_filename, image_name=image_name, image_tag=image_tag, repository=str(repo_path.relative_to(Path(self._arca.base_dir).resolve() / 'repos')), timeout=task.timeout) return Result(res[self.vagrant.user_hostname_port()].stdout) except CommandTimeout: raise BuildTimeoutError(f"The task timeouted after {task.timeout} seconds.") except BuildError: # can be raised by :meth:`Result.__init__` raise except Exception as e: logger.exception(e) raise BuildError("The build failed", extra_info={ "exception": e }) finally: # stops or destroys the VM if it should not be kept running if not self.keep_vm_running: if self.destroy: self.vagrant.destroy() shutil.rmtree(self.vagrant.root, ignore_errors=True) self.vagrant = None else: self.vagrant.halt()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stop_vm(self): """ Stops or destroys the VM used to launch tasks. """
if self.vagrant is not None: if self.destroy: self.vagrant.destroy() shutil.rmtree(self.vagrant.root, ignore_errors=True) self.vagrant = None else: self.vagrant.halt()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def url_content(url, cache_duration=None, from_cache_on_error=False): """ Get content for the given URL :param str url: The URL to get content from :param int cache_duration: Optionally cache the content for the given duration to avoid downloading too often. :param bool from_cache_on_error: Return cached content on any HTTP request error if available. """
cache_file = _url_content_cache_file(url) if cache_duration: if os.path.exists(cache_file): stat = os.stat(cache_file) cached_time = stat.st_mtime if time.time() - cached_time < cache_duration: with open(cache_file) as fp: return fp.read() try: response = requests.get(url, timeout=5) response.raise_for_status() content = response.text except Exception as e: if from_cache_on_error and os.path.exists(cache_file): with open(cache_file) as fp: return fp.read() else: raise e.__class__("An error occurred when getting content for %s: %s" % (url, e)) if cache_duration or from_cache_on_error: with open(cache_file, 'w') as fp: fp.write(content) return content
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def route(**kwargs): """ Route a request to different views based on http verb. Kwargs should be 'GET', 'POST', 'PUT', 'DELETE' or 'ELSE', where the first four map to a view to route to for that type of request method/verb, and 'ELSE' maps to a view to pass the request to if the given request method/verb was not specified. """
def routed(request, *args2, **kwargs2): method = request.method if method in kwargs: req_method = kwargs[method] return req_method(request, *args2, **kwargs2) elif 'ELSE' in kwargs: return kwargs['ELSE'](request, *args2, **kwargs2) else: raise Http404() return routed
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log(message=None, out=sys.stdout): """Log a message before passing through to the wrapped function. This is useful if you want to determine whether wrappers are passing down the pipeline to the functions they wrap, or exiting early, usually with some kind of exception. Example: example_view = decorate(username_matches_request_user, log("The username matched"), json_api_call, example) """
def decorator(view_fn): @wraps(view_fn) def f(*args, **kwargs): print(message, file=out) return view_fn(*args, **kwargs) return f return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render_template(template): """ takes a template to render to and returns a function that takes an object to render the data for this template. If callable_or_dict is callable, it will be called with the request and any additional arguments to produce the template paramaters. This is useful for a view-like function that returns a dict-like object instead of an HttpResponse. Otherwise, callable_or_dict is used as the parameters for the rendered response. """
def outer_wrapper(callable_or_dict=None, statuscode=None, **kwargs): def wrapper(request, *args, **wrapper_kwargs): if callable(callable_or_dict): params = callable_or_dict(request, *args, **wrapper_kwargs) else: params = callable_or_dict # If we want to return some other response type we can, # that simply overrides the default behavior if params is None or isinstance(params, dict): resp = render(request, template, params, **kwargs) else: resp = params if statuscode: resp.status_code = statuscode return resp return wrapper return outer_wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def json_api_call(req_function): """ Wrap a view-like function that returns an object that is convertable from json """
@wraps(req_function) def newreq(request, *args, **kwargs): outp = req_function(request, *args, **kwargs) if issubclass(outp.__class__, HttpResponse): return outp else: return '%s' % json.dumps(outp, cls=LazyEncoder) return string_to_response("application/json")(newreq)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def string_to_response(content_type): """ Wrap a view-like function that returns a string and marshalls it into an HttpResponse with the given Content-Type If the view raises an HttpBadRequestException, it will be converted into an HttpResponseBadRequest. """
def outer_wrapper(req_function): @wraps(req_function) def newreq(request, *args, **kwargs): try: outp = req_function(request, *args, **kwargs) if issubclass(outp.__class__, HttpResponse): response = outp else: response = HttpResponse() response.write(outp) response['Content-Length'] = str(len(response.content)) response['Content-Type'] = content_type except HttpBadRequestException as bad_request: response = HttpResponseBadRequest(bad_request.message) return response return newreq return outer_wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def username_matches_request_user(view_fn): """Checks if the username matches the request user, and if so replaces username with the actual user object. Returns 404 if the username does not exist, and 403 if it doesn't match. """
@wraps(view_fn) def wrapper(request, username, *args, **kwargs): User = get_user_model() user = get_object_or_404(User, username=username) if user != request.user: return HttpResponseForbidden() else: return view_fn(request, user, *args, **kwargs) return wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_boolean(self, input_string): """ Return boolean type user input """
if input_string in ('--write_roc', '--plot', '--compare'): # was the flag set? try: index = self.args.index(input_string) + 1 except ValueError: # it wasn't, args are optional, so return the appropriate default return False # the flag was set, so return the True return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_fixture(filename, kind, post_processor=None): """ Loads a file into entities of a given class, run the post_processor on each instance before it's saved """
def _load(od, kind, post_processor, parent=None, presets={}): """ Loads a single dictionary (od) into an object, overlays the values in presets, persists it and calls itself on the objects in __children__* keys """ if hasattr(kind, 'keys'): # kind is a map objtype = kind[od['__kind__']] else: objtype = kind obj_id = od.get('__id__') if obj_id is not None: obj = objtype(id=obj_id, parent=parent) else: obj = objtype(parent=parent) # Iterate over the non-special attributes and overlay the presets for attribute_name in [k for k in od.keys() if not k.startswith('__') and not k.endswith('__')] + presets.keys(): attribute_type = objtype.__dict__[attribute_name] attribute_value = _sensible_value(attribute_type, presets.get( attribute_name, od.get(attribute_name))) obj.__dict__['_values'][attribute_name] = attribute_value if post_processor: post_processor(obj) # Saving obj is required to continue with the children obj.put() loaded = [obj] # Process ancestor-based __children__ for item in od.get('__children__', []): loaded.extend(_load(item, kind, post_processor, parent=obj.key)) # Process other __children__[key]__ items for child_attribute_name in [k for k in od.keys() if k.startswith('__children__') and k != '__children__']: attribute_name = child_attribute_name.split('__')[-2] for child in od[child_attribute_name]: loaded.extend(_load(child, kind, post_processor, presets={attribute_name: obj.key})) return loaded tree = json.load(open(filename)) loaded = [] # Start with the top-level of the tree for item in tree: loaded.extend(_load(item, kind, post_processor)) return loaded
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_resource(mod, view, **kwargs): """Register the resource on the resource name or a custom url"""
resource_name = view.__name__.lower()[:-8] endpoint = kwargs.get('endpoint', "{}_api".format(resource_name)) plural_resource_name = inflect.engine().plural(resource_name) path = kwargs.get('url', plural_resource_name).strip('/') url = '/{}'.format(path) setattr(view, '_url', url) # need this for 201 location header view_func = view.as_view(endpoint) mod.add_url_rule(url, view_func=view_func, methods=['GET', 'POST', 'OPTIONS']) mod.add_url_rule('{}/<obj_id>'.format(url), view_func=view_func, methods=['GET', 'PATCH', 'PUT', 'DELETE', 'OPTIONS'])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_participants_for_gradebook(gradebook_id, person=None): """ Returns a list of gradebook participants for the passed gradebook_id and person. """
if not valid_gradebook_id(gradebook_id): raise InvalidGradebookID(gradebook_id) url = "/rest/gradebook/v1/book/{}/participants".format(gradebook_id) headers = {} if person is not None: headers["X-UW-Act-as"] = person.uwnetid data = get_resource(url, headers) participants = [] for pt in data["participants"]: participants.append(_participant_from_json(pt)) return participants
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_participants_for_section(section, person=None): """ Returns a list of gradebook participants for the passed section and person. """
section_label = encode_section_label(section.section_label()) url = "/rest/gradebook/v1/section/{}/participants".format(section_label) headers = {} if person is not None: headers["X-UW-Act-as"] = person.uwnetid data = get_resource(url, headers) participants = [] for pt in data["participants"]: participants.append(_participant_from_json(pt)) return participants
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_python(self, value, context=None): """Convert the value to a real python object"""
value = value.copy() res = {} errors = [] for field, schema in self._fields.items(): name = schema.get_attr('name', field) if name in value: try: res[field] = schema.to_python( value.pop(name), context=context ) except exceptions.ValidationErrors as ex: self._update_errors_by_exception(errors, ex, name) self._raise_exception_when_errors(errors, value) res.update(value) return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_raw(self, value, context=None): """Convert the value to a JSON compatible value"""
if value is None: return None res = {} value = value.copy() errors = [] for field in list(set(value) & set(self._fields)): schema = self._fields.get(field) name = schema.get_attr('name', field) try: res[name] = \ schema.to_raw(value.pop(field), context=context) except exceptions.ValidationErrors as ex: self._update_errors_by_exception(errors, ex, name) self._raise_exception_when_errors(errors, value) res.update(value) return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_jsonschema(self, context=None): """Ensure the generic schema, remove `types` :return: Gives back the schema :rtype: dict """
schema = super(Enum, self).get_jsonschema(context=None) schema.pop('type') if self.get_attr('enum'): schema['enum'] = self.get_attr('enum') return schema
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_references(references, components): """ Sets references to multiple components. To set references components must implement [[IReferenceable]] interface. If they don't the call to this method has no effect. :param references: the references to be set. :param components: a list of components to set the references to. """
if components == None: return for component in components: Referencer.set_references_for_one(references, component)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _reduce_opacity(self): """ Reduce opacity for watermark image. """
if self.image.mode != 'RGBA': image = self.image.convert('RGBA') else: image = self.image.copy() alpha = image.split()[3] alpha = ImageEnhance.Brightness(alpha).enhance(self.opacity) image.putalpha(alpha) self.image = image
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def instructions(self): """ Retrieve the instructions for the rule. """
if self._instructions is None: # Compile the rule into an Instructions instance; we do # this lazily to amortize the cost of the compilation, # then cache that result for efficiency... self._instructions = parser.parse_rule(self.name, self.text) return self._instructions
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_pages(): '''returns list of urllib file objects''' pages =[] counter = 1 print "Checking for themes..." while(True): page = urllib.urlopen('http://dotshare.it/category/terms/colors/p/%d/' % counter) print "Page%d: %s" % (counter, "OK" if (page.code < 400) else "Fail!") if page.code >= 400: break pages.append(page) counter += 1 print "Found %d pages." % (counter - 1) return pages
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_urls(htmlDoc, limit=200): '''takes in html document as string, returns links to dots''' soup = BeautifulSoup( htmlDoc ) anchors = soup.findAll( 'a' ) urls = {} counter = 0 for i,v in enumerate( anchors ): href = anchors[i].get( 'href' ) if ('dots' in href and counter < limit): href = href.split('/')[2] text = anchors[i].text.split(' ')[0].replace('/', '_') urls[ text ] = href counter += 1 return urls
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_themes(urls): '''takes in dict of names and urls, downloads and saves files''' length = len(urls) counter = 1 widgets = ['Fetching themes:', Percentage(), ' ', Bar(marker='-'), ' ', ETA()] pbar = ProgressBar( widgets=widgets, maxval=length ).start() for i in urls.keys(): href = 'http://dotshare.it/dots/%s/0/raw/' % urls[i] theme = urllib.urlopen(href).read() f = open(THEMEDIR + i, 'w') f.write(theme) f.close() pbar.update(counter) counter += 1 pbar.finish()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_section_path(section): """Return a list with keys to access the section from root :param section: A Section :type section: Section :returns: list of strings in the order to access the given section from root :raises: None """
keys = [] p = section for i in range(section.depth): keys.insert(0, p.name) p = p.parent return keys
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_default_values(section, key, validator=None): """Raise an MissingDefaultError if a value in section does not have a default values :param section: the section of a configspec :type section: section :param key: a key of the section :type key: str :param validator: a Validator object to get the default values :type validator: Validator :returns: None :raises: MissingDefaultError Use this in conjunction with the walk method of a ConfigObj. The ConfigObj should be the configspec! When you want to use a custom validator, try:: configinstance.walk(check_default_values, validator=validatorinstance) """
if validator is None: validator = Validator() try: validator.get_default_value(section[key]) except KeyError: #dv = set(section.default_values.keys()) # set of all defined default values #scalars = set(section.scalars) # set of all keys #if dv != scalars: parents = get_section_path(section) msg = 'The Key %s in the section %s is missing a default: %s' % (key, parents, section[key]) log.debug(msg) raise ConfigError(msg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fix_errors(config, validation): """Replace errors with their default values :param config: a validated ConfigObj to fix :type config: ConfigObj :param validation: the resuts of the validation :type validation: ConfigObj :returns: The altered config (does alter it in place though) :raises: None """
for e in flatten_errors(config, validation): sections, key, err = e sec = config for section in sections: sec = sec[section] if key is not None: sec[key] = sec.default_values.get(key, sec[key]) else: sec.walk(set_to_default) return config
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_to_default(section, key): """Set the value of the given seciton and key to default :param section: the section of a configspec :type section: section :param key: a key of the section :type key: str :returns: None :raises: None """
section[key] = section.default_values.get(key, section[key])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clean_config(config): """Check if all values have defaults and replace errors with their default value :param config: the configobj to clean :type config: ConfigObj :returns: None :raises: ConfigError The object is validated, so we need a spec file. All failed values will be replaced by their default values. If default values are not specified in the spec, a MissingDefaultError will be raised. If the replaced values still fail validation, a ValueError is raised. This can occur if the default is of the wrong type. If the object does not have a config spec, this function does nothing. You are on your own then. """
if config.configspec is None: return vld = Validator() validation = config.validate(vld, copy=True) config.configspec.walk(check_default_values, validator=vld) fix_errors(config, validation) validation = config.validate(vld, copy=True) if not (validation == True): # NOQA seems unpythonic but this validation evaluates that way only msg = 'The config could not be fixed. Make sure that all default values have the right type!' log.debug(msg) raise ConfigError(msg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_config(f, spec): """Return the ConfigObj for the specified file :param f: the config file path :type f: str :param spec: the path to the configspec :type spec: str :returns: the loaded ConfigObj :rtype: ConfigObj :raises: ConfigError """
dirname = os.path.dirname(f) if not os.path.exists(dirname): os.makedirs(dirname) c = ConfigObj(infile=f, configspec=spec, interpolation=False, create_empty=True) try: clean_config(c) except ConfigError, e: msg = "Config %s could not be loaded. Reason: %s" % (c.filename, e) log.debug(msg) raise ConfigError(msg) return c
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_config(): """ Validate the config """
configuration = MyParser() configuration.read(_config) d = configuration.as_dict() if 'jira' not in d: raise custom_exceptions.NotConfigured # Special handling of the boolean for error reporting d['jira']['error_reporting'] = configuration.getboolean('jira', 'error_reporting') return d
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _save_config(jira_url, username, password, error_reporting): """ Saves the username and password to the config """
# Delete what is there before we re-write. New user means new everything os.path.exists(_config) and os.remove(_config) config = ConfigParser.SafeConfigParser() config.read(_config) if not config.has_section('jira'): config.add_section('jira') if 'http' not in jira_url: jira_url = 'http://' + jira_url try: resp = urllib.urlopen(jira_url) url = urlparse.urlparse(resp.url) jira_url = url.scheme + "://" + url.netloc except IOError, e: print "It doesn't appear that {0} is responding to a request.\ Please make sure that you typed the hostname, \ i.e. jira.atlassian.com.\n{1}".format(jira_url, e) sys.exit(1) config.set('jira', 'url', jira_url) config.set('jira', 'username', username) config.set('jira', 'password', base64.b64encode(password)) config.set('jira', 'error_reporting', str(error_reporting)) with open(_config, 'w') as ini: os.chmod(_config, 0600) config.write(ini)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_cookies_as_dict(): """ Get cookies as a dict """
config = ConfigParser.SafeConfigParser() config.read(_config) if config.has_section('cookies'): cookie_dict = {} for option in config.options('cookies'): option_key = option.upper() if option == 'jsessionid' else option cookie_dict[option_key] = config.get('cookies', option) return cookie_dict
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_cli(subparsers): """Given a parser, load the CLI subcommands"""
for command_name in available_commands(): module = '{}.{}'.format(__package__, command_name) loader, description = _import_loader(module) parser = subparsers.add_parser(command_name, description=description) command = loader(parser) if command is None: raise RuntimeError('Failed to load "{}".'.format(command_name)) parser.set_defaults(cmmd=command)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _build_command_chain(self, command): """ Builds execution chain including all intercepters and the specified command. :param command: the command to build a chain. """
next = command for intercepter in reversed(self._intercepters): next = InterceptedCommand(intercepter, next) self._commands_by_name[next.get_name()] = next
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def notify(self, correlation_id, event, value): """ Fires event specified by its name and notifies all registered IEventListener listeners :param correlation_id: (optional) transaction id to trace execution through call chain. :param event: the name of the event that is to be fired. :param value: the event arguments (parameters). """
e = self.find_event(event) if e != None: e.notify(correlation_id, value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_nullable_boolean(value): """ Converts value into boolean or returns None when conversion is not possible. :param value: the value to convert. :return: boolean value or None when convertion is not supported. """
# Shortcuts if value == None: return None if type(value) == type(True): return value str_value = str(value).lower() # All true values if str_value in ['1', 'true', 't', 'yes', 'y']: return True # All false values if str_value in ['0', 'frue', 'f', 'no', 'n']: return False # Everything else: return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_boolean_with_default(value, default_value): """ Converts value into boolean or returns default value when conversion is not possible :param value: the value to convert. :param default_value: the default value :return: boolean value or default when conversion is not supported. """
result = BooleanConverter.to_nullable_boolean(value) return result if result != None else default_value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def user_lists(self, username, member_type="USER"): """ Look up all the lists that the user is a member of. Args: username (str): The MIT username of the user member_type(str): The type of user, "USER" or "STRING" Returns: list of strings: names of the lists that this user is a member of """
return self.client.service.getUserLists(username, member_type, self.proxy_id)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def user_list_membership(self, username, member_type="USER", recursive=True, max_return_count=999): """ Get info for lists a user is a member of. This is similar to :meth:`user_lists` but with a few differences: #. It returns list info objects instead of list names. #. It has an option to fully resolve a user's list hierarchy. That is, if a user is a member of a nested list, this method can retrieve both the nested list and the parent lists that contain the nested list. Args: username (str): The MIT username of the user member_type(str): The type of user, "USER" or "STRING" recursive(bool): Whether to fully resolve the list hierarchy max_return_count(int): limit the number of items returned Returns: list of dicts: info dicts, one per list. """
return self.client.service.getUserListMembership( username, member_type, recursive, max_return_count, self.proxy_id )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_members(self, name, type="USER", recurse=True, max_results=1000): """ Look up all the members of a list. Args: name (str): The name of the list type (str): The type of results to return. "USER" to get users, "LIST" to get lists. recurse (bool): Presumably, whether to recurse into member lists when retrieving users. max_results (int): Maximum number of results to return. Returns: list of strings: names of the members of the list """
results = self.client.service.getListMembership( name, type, recurse, max_results, self.proxy_id, ) return [item["member"] for item in results]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_attributes(self, name): """ Look up the attributes of a list. Args: name (str): The name of the list Returns: dict: attributes of the list """
result = self.client.service.getListAttributes(name, self.proxy_id) if isinstance(result, list) and len(result) == 1: return result[0] return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_member_to_list(self, username, listname, member_type="USER"): """ Add a member to an existing list. Args: username (str): The username of the user to add listname (str): The name of the list to add the user to member_type (str): Normally, this should be "USER". If you are adding a list as a member of another list, set this to "LIST", instead. """
return self.client.service.addMemberToList( listname, username, member_type, self.proxy_id )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_list( self, name, description="Created by mit_moira client", is_active=True, is_public=True, is_hidden=True, is_group=False, is_nfs_group=False, is_mail_list=False, use_mailman=False, mailman_server="" ): """ Create a new list. Args: name (str): The name of the new list description (str): A short description of this list is_active (bool): Should the new list be active? An inactive list cannot be used. is_public (bool): Should the new list be public? If a list is public, anyone may join without requesting permission. If not, the owners control entry to the list. is_hidden (bool): Should the new list be hidden? Presumably, a hidden list doesn't show up in search queries. is_group (bool): Something about AFS? is_nfs_group (bool): Presumably, create an `NFS group <https://en.wikipedia.org/wiki/Network_File_System>`_ for this group? I don't actually know what this does. is_mail_list (bool): Presumably, create a mailing list. use_mailman (bool): Presumably, use `GNU Mailman <https://en.wikipedia.org/wiki/GNU_Mailman>`_ to manage the mailing list. mailman_server (str): The Mailman server to use, if ``use_mailman`` is True. """
attrs = { "aceName": "mit_moira", "aceType": "LIST", "activeList": is_active, "description": description, "gid": "", "group": is_group, "hiddenList": is_hidden, "listName": name, "mailList": is_mail_list, "mailman": use_mailman, "mailmanServer": mailman_server, "memaceName": "mit_moira", "memaceType": "USER", "modby": "", "modtime": "", "modwith": "", "nfsgroup": is_nfs_group, "publicList": is_public, } return self.client.service.createList(attrs, self.proxy_id)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add(self, model): """raises an exception if the model cannot be added"""
def foo(m, p, i): if m[i][0].name == model.name: raise ValueError("Model already exists") return # checks if already existing self.foreach(foo) self.append((model,)) return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def vectorize_dialogues(self, dialogues): """ Take in a list of dialogues and vectorize them all """
return np.array([self.vectorize_dialogue(d) for d in dialogues])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def devectorize_utterance(self, utterance): """ Take in a sequence of indices and transform it back into a tokenized utterance """
utterance = self.swap_pad_and_zero(utterance) return self.ie.inverse_transform(utterance).tolist()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def vectorize_batch_ohe(self, batch): """ One-hot vectorize a whole batch of dialogues """
return np.array([self.vectorize_dialogue_ohe(dia) for dia in batch])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def vectorize_utterance_ohe(self, utterance): """ Take in a tokenized utterance and transform it into a sequence of one-hot vectors """
for i, word in enumerate(utterance): if not word in self.vocab_list: utterance[i] = '<unk>' ie_utterance = self.swap_pad_and_zero(self.ie.transform(utterance)) ohe_utterance = np.array(self.ohe.transform(ie_utterance.reshape(len(ie_utterance), 1))) return ohe_utterance
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def devectorize_utterance_ohe(self, ohe_utterance): """ Take in a sequence of one-hot vectors and transform it into a tokenized utterance """
ie_utterance = [argmax(w) for w in ohe_utterance] utterance = self.ie.inverse_transform(self.swap_pad_and_zero(ie_utterance)) return utterance
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup_jukebox_logger(): """Setup the jukebox top-level logger with handlers The logger has the name ``jukebox`` and is the top-level logger for all other loggers of jukebox. It does not propagate to the root logger, because it also has a StreamHandler and that might cause double output. The logger default level is defined in the constants :data:`jukeboxcore.constants.DEFAULT_LOGGING_LEVEL` but can be overwritten by the environment variable \"JUKEBOX_LOG_LEVEL\" :returns: None :rtype: None :raises: None """
log = logging.getLogger("jb") log.propagate = False handler = logging.StreamHandler(sys.stdout) fmt = "%(levelname)-8s:%(name)s: %(message)s" formatter = logging.Formatter(fmt) handler.setFormatter(formatter) log.addHandler(handler) level = DEFAULT_LOGGING_LEVEL log.setLevel(level)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_logger(name, level=None): """ Return a setup logger for the given name :param name: The name for the logger. It is advised to use __name__. The logger name will be prepended by \"jb.\". :type name: str :param level: the logging level, e.g. logging.DEBUG, logging.INFO etc :type level: int :returns: Logger :rtype: logging.Logger :raises: None The logger default level is defined in the constants :data:`jukeboxcore.constants.DEFAULT_LOGGING_LEVEL` but can be overwritten by the environment variable \"JUKEBOX_LOG_LEVEL\" """
log = logging.getLogger("jb.%s" % name) if level is not None: log.setLevel(level) return log
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def parse_cartouche_text(lines): '''Parse text in cartouche format and return a reStructuredText equivalent Args: lines: A sequence of strings representing the lines of a single docstring as read from the source by Sphinx. This string should be in a format that can be parsed by cartouche. Returns: A list of lines containing the transformed docstring as reStructuredText as produced by cartouche. Raises: RuntimeError: If the docstring cannot be parsed. ''' indent_lines = unindent(lines) indent_lines = pad_blank_lines(indent_lines) indent_lines = first_paragraph_indent(indent_lines) indent_paragraphs = gather_lines(indent_lines) parse_tree = group_paragraphs(indent_paragraphs) syntax_tree = extract_structure(parse_tree) result = syntax_tree.render_rst() ensure_terminal_blank(result) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def unindent(lines): '''Convert an iterable of indented lines into a sequence of tuples. The first element of each tuple is the indent in number of characters, and the second element is the unindented string. Args: lines: A sequence of strings representing the lines of text in a docstring. Returns: A list of tuples where each tuple corresponds to one line of the input list. Each tuple has two entries - the first is an integer giving the size of the indent in characters, the second is the unindented text. ''' unindented_lines = [] for line in lines: unindented_line = line.lstrip() indent = len(line) - len(unindented_line) unindented_lines.append((indent, unindented_line)) return unindented_lines
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def parse_exception(line): '''Parse the first line of a Cartouche exception description. Args: line (str): A single line Cartouche exception description. Returns: A 2-tuple containing the exception type and the first line of the description. ''' m = RAISES_REGEX.match(line) if m is None: raise CartoucheSyntaxError('Cartouche: Invalid argument syntax "{line}" for Raises block'.format(line=line)) return m.group(2), m.group(1)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def group_paragraphs(indent_paragraphs): ''' Group paragraphs so that more indented paragraphs become children of less indented paragraphs. ''' # The tree consists of tuples of the form (indent, [children]) where the # children may be strings or other tuples root = Node(0, [], None) current_node = root previous_indent = -1 for indent, lines in indent_paragraphs: if indent > previous_indent: current_node = create_child_node(current_node, indent, lines) elif indent == previous_indent: current_node = create_sibling_node(current_node, indent, lines) elif indent < previous_indent: current_node = create_uncle_node(current_node, indent, lines) previous_indent = indent return root
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def first_paragraph_indent(indent_texts): '''Fix the indentation on the first paragraph. This occurs because the first line of a multi-line docstring following the opening quote usually has no indent. Args: indent_texts: The lines of the docstring as an iterable over 2-tuples each containing an integer indent level as the first element and the text as the second element. Return: A list of 2-tuples, each containing an integer indent level as the first element and the text as the second element. ''' opening_indent = determine_opening_indent(indent_texts) result = [] input = iter(indent_texts) for indent, text in input: if indent == 0: result.append((opening_indent, text)) else: result.append((indent, text)) break for indent, text in input: result.append((indent, text)) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def determine_opening_indent(indent_texts): '''Determine the opening indent level for a docstring. The opening indent level is the indent level is the first non-zero indent level of a non-empty line in the docstring. Args: indent_texts: The lines of the docstring as an iterable over 2-tuples each containing an integer indent level as the first element and the text as the second element. Returns: The opening indent level as an integer. ''' num_lines = len(indent_texts) if num_lines < 1: return 0 assert num_lines >= 1 first_line_indent = indent_texts[0][0] if num_lines == 1: return first_line_indent assert num_lines >= 2 second_line_indent = indent_texts[1][0] second_line_text = indent_texts[1][1] if len(second_line_text) == 0: return first_line_indent return second_line_indent
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def rewrite_autodoc(app, what, name, obj, options, lines): '''Convert lines from Cartouche to Sphinx format. The function to be called by the Sphinx autodoc extension when autodoc has read and processed a docstring. This function modified its ``lines`` argument *in place* replacing Cartouche syntax input into Sphinx reStructuredText output. Args: apps: The Sphinx application object. what: The type of object which the docstring belongs to. One of 'module', 'class', 'exception', 'function', 'method', 'attribute' name: The fully qualified name of the object. obj: The object itself. options: The options given to the directive. An object with attributes ``inherited_members``, ``undoc_members``, ``show_inheritance`` and ``noindex`` that are ``True`` if the flag option of the same name was given to the auto directive. lines: The lines of the docstring. Will be modified *in place*. Raises: CartoucheSyntaxError: If the docstring is malformed. ''' try: lines[:] = parse_cartouche_text(lines) except CartoucheSyntaxError as syntax_error: args = syntax_error.args arg0 = args[0] if args else '' arg0 += " in docstring for {what} {name} :".format(what=what, name=name) arg0 += "\n=== BEGIN DOCSTRING ===\n{lines}\n=== END DOCSTRING ===\n".format(lines='\n'.join(lines)) #noinspection PyPropertyAccess syntax_error.args = (arg0,) + args[1:] raise
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_exe(arch='x86'): """Get the path to an exe launcher provided by this package. The options for arch are currently 'x86' and 'x64'. """
if arch == 'x86': return os.path.join(_pkg_dir, 'cli-32.exe') elif arch == 'x64': return os.path.join(_pkg_dir, 'cli-64.exe') raise ValueError('Unrecognised arch: %r' % arch)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load(): """ | Load the configuration file. | Add dynamically configuration to the module. :rtype: None """
config = ConfigParser.RawConfigParser(DEFAULTS) config.readfp(open(CONF_PATH)) for section in config.sections(): globals()[section] = {} for key, val in config.items(section): globals()[section][key] = val
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def declfuncs(self): """generator on all declaration of functions"""
for f in self.body: if (hasattr(f, '_ctype') and isinstance(f._ctype, FuncType) and not hasattr(f, 'body')): yield f
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def implfuncs(self): """generator on all implemented functions"""
for f in self.body: if (hasattr(f, '_ctype') and isinstance(f._ctype, FuncType) and hasattr(f, 'body')): yield f
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def defvars(self): """generator on all definition of variable"""
for f in self.body: if (hasattr(f, '_ctype') and f._name != '' and not isinstance(f._ctype, FuncType) and f._ctype._storage != Storages.TYPEDEF): yield f
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deftypes(self): """generator on all definition of type"""
for f in self.body: if (hasattr(f, '_ctype') and (f._ctype._storage == Storages.TYPEDEF or (f._name == '' and isinstance(f._ctype, ComposedType)))): yield f