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 parse(self, stream, media_type=None, parser_context=None): """ Parses the incoming bytestream as XML and returns the resulting data. """
assert etree, 'XMLParser requires defusedxml to be installed' parser_context = parser_context or {} encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET) parser = etree.DefusedXMLParser(encoding=encoding) try: tree = etree.parse(stream, parser=parser, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _xml_convert(self, element): """ convert the xml `element` into the corresponding python object """
children = list(element) if len(children) == 0: return self._type_convert(element.text) else: # if the fist child tag is list-item means all children are list-item if children[0].tag == "list-item": data = [] for child in chi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _type_convert(self, value): """ Converts the value returned by the XMl parse into the equivalent Python type """
if value is None: return value try: return datetime.datetime.strptime(value, '%Y-%m-%d %H:%M:%S') except ValueError: pass try: return int(value) except ValueError: pass try: return decimal.Decimal...
<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(self, data, accepted_media_type=None, renderer_context=None): """ Renders `data` into serialized XML. """
if data is None: return '' stream = StringIO() xml = SimplerXMLGenerator(stream, self.charset) xml.startDocument() xml.startElement(self.root_tag_name, {}) self._to_xml(xml, data) xml.endElement(self.root_tag_name) xml.endDocument() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open(self): """Open a connection to the device."""
device_type = 'cisco_ios' if self.transport == 'telnet': device_type = 'cisco_ios_telnet' self.device = ConnectHandler(device_type=device_type, host=self.hostname, username=self.username, ...
<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_tmp_file(config): """Write temp file and for use with inline config and SCP."""
tmp_dir = tempfile.gettempdir() rand_fname = py23_compat.text_type(uuid.uuid4()) filename = os.path.join(tmp_dir, rand_fname) with open(filename, 'wt') as fobj: fobj.write(config) return filename
<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_candidate_wrapper(self, source_file=None, source_config=None, dest_file=None, file_system=None): """ Transfer file to remote device for either merge or...
return_status = False msg = '' if source_file and source_config: raise ValueError("Cannot simultaneously set source_file and source_config") if source_config: if self.inline_transfer: (return_status, msg) = self._inline_tcl_xfer(source_config=sou...
<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_replace_candidate(self, filename=None, config=None): """ SCP file to device filesystem, defaults to candidate_config. Return None or raise exception """
self.config_replace = True return_status, msg = self._load_candidate_wrapper(source_file=filename, source_config=config, dest_file=self.candidate_cfg, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _commit_hostname_handler(self, cmd): """Special handler for hostname change on commit operation."""
current_prompt = self.device.find_prompt().strip() terminating_char = current_prompt[-1] pattern = r"[>#{}]\s*$".format(terminating_char) # Look exclusively for trailing pattern that includes '#' and '>' output = self.device.send_command_expect(cmd, expect_string=pattern) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _gen_full_path(self, filename, file_system=None): """Generate full file path on remote device."""
if file_system is None: return '{}/{}'.format(self.dest_file_system, filename) else: if ":" not in file_system: raise ValueError("Invalid file_system specified: {}".format(file_system)) return '{}/{}'.format(file_system, filename)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _gen_rollback_cfg(self): """Save a configuration that can be used for rollback."""
cfg_file = self._gen_full_path(self.rollback_cfg) cmd = 'copy running-config {}'.format(cfg_file) self._disable_confirm() self.device.send_command_expect(cmd) self._enable_confirm()
<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_file_exists(self, cfg_file): """ Check that the file exists on remote device using full path. cfg_file is full path i.e. flash:/file_name For example ...
cmd = 'dir {}'.format(cfg_file) success_pattern = 'Directory of {}'.format(cfg_file) output = self.device.send_command_expect(cmd) if 'Error opening' in output: return False elif success_pattern in output: 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 _expand_interface_name(self, interface_brief): """ Obtain the full interface name from the abbreviated name. Cache mappings in self.interface_map. """
if self.interface_map.get(interface_brief): return self.interface_map.get(interface_brief) command = 'show int {}'.format(interface_brief) output = self._send_command(command) first_line = output.splitlines()[0] if 'line protocol' in first_line: full_int_...
<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_lldp_neighbors_detail(self, interface=''): """ IOS implementation of get_lldp_neighbors_detail. Calls get_lldp_neighbors. """
lldp = {} lldp_neighbors = self.get_lldp_neighbors() # Filter to specific interface if interface: lldp_data = lldp_neighbors.get(interface) if lldp_data: lldp_neighbors = {interface: lldp_data} else: lldp_neighbors = {...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bgp_time_conversion(bgp_uptime): """ Convert string time to seconds. Examples 00:14:23 00:13:40 00:00:21 00:00:13 00:00:49 1d11h 1d17h 1w0d 8w5d 1y28w never ...
bgp_uptime = bgp_uptime.strip() uptime_letters = set(['w', 'h', 'd']) if 'never' in bgp_uptime: return -1 elif ':' in bgp_uptime: times = bgp_uptime.split(":") times = [int(x) for x in times] hours, minutes, seconds = times re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cli(self, commands): """ Execute a list of commands and return the output in a dictionary format using the command as the key. Example input: ['show clock', ...
cli_output = dict() if type(commands) is not list: raise TypeError('Please enter a valid list of commands!') for command in commands: output = self._send_command(command) if 'Invalid input detected' in output: raise ValueError('Unable to exec...
<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_config(self, retrieve='all'): """Implementation of get_config for IOS. Returns the startup or/and running configuration as dictionary. The keys of the di...
configs = { 'startup': '', 'running': '', 'candidate': '', } if retrieve in ('startup', 'all'): command = 'show startup-config' output = self._send_command(command) configs['startup'] = output if retrieve in ('ru...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read(self): """Read the current value of the accelerometer and return it as a tuple of signed 16-bit X, Y, Z axis values. """
raw = self._device.readList(ADXL345_REG_DATAX0, 6) return struct.unpack('<hhh', raw)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def digital_write(pin_num, value, hardware_addr=0): """Writes the value to the input pin specified. .. note:: This function is for familiarality with users of ot...
_get_pifacedigital(hardware_addr).output_pins[pin_num].value = 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 digital_write_pullup(pin_num, value, hardware_addr=0): """Writes the value to the input pullup specified. .. note:: This function is for familiarality with u...
_get_pifacedigital(hardware_addr).gppub.bits[pin_num].value = 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 get_my_ip(): """Returns this computers IP address as a string."""
ip = subprocess.check_output(GET_IP_CMD, shell=True).decode('utf-8')[:-1] return ip.strip()
<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_output_port(self, new_value, old_value=0): """Sets the output port value to new_value, defaults to old_value."""
print("Setting output port to {}.".format(new_value)) port_value = old_value try: port_value = int(new_value) # dec except ValueError: port_value = int(new_value, 16) # hex finally: self.pifacedigital.output_port.value = port_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 _request_api(self, **kwargs): """Wrap the calls the url, with the given arguments. :param str url: Url to call with the given arguments :param str method: [P...
_url = kwargs.get('url') _method = kwargs.get('method', 'GET') _status = kwargs.get('status', 200) counter = 0 if _method not in ['GET', 'POST']: raise ValueError('Method is not GET or POST') while True: try: res = REQ[_method](_...
<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_infos_with_id(self, uid): """Get info about a user based on his id. :return: JSON """
_logid = uid _user_info_url = USER_INFO_URL.format(logid=_logid) return self._request_api(url=_user_info_url).json()
<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_current_activities(self, login=None, **kwargs): """Get the current activities of user. Either use the `login` param, or the client's login if unset. :ret...
_login = kwargs.get( 'login', login or self._login ) _activity_url = ACTIVITY_URL.format(login=_login) return self._request_api(url=_activity_url).json()
<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_notifications(self, login=None, **kwargs): """Get the current notifications of a user. :return: JSON """
_login = kwargs.get( 'login', login or self._login ) _notif_url = NOTIF_URL.format(login=_login) return self._request_api(url=_notif_url).json()
<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_grades(self, login=None, promotion=None, **kwargs): """Get a user's grades on a single promotion based on his login. Either use the `login` param, or the...
_login = kwargs.get( 'login', login or self._login ) _promotion_id = kwargs.get('promotion', promotion) _grades_url = GRADES_URL.format(login=_login, promo_id=_promotion_id) return self._request_api(url=_grades_url).json()
<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_picture(self, login=None, **kwargs): """Get a user's picture. :param str login: Login of the user to check :return: JSON """
_login = kwargs.get( 'login', login or self._login ) _activities_url = PICTURE_URL.format(login=_login) return self._request_api(url=_activities_url).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 get_projects(self, **kwargs): """Get a user's project. :param str login: User's login (Default: self._login) :return: JSON """
_login = kwargs.get('login', self._login) search_url = SEARCH_URL.format(login=_login) return self._request_api(url=search_url).json()
<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_activities_for_project(self, module=None, **kwargs): """Get the related activities of a project. :param str module: Stages of a given module :return: JSO...
_module_id = kwargs.get('module', module) _activities_url = ACTIVITIES_URL.format(module_id=_module_id) return self._request_api(url=_activities_url).json()
<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_group_for_activity(self, module=None, project=None, **kwargs): """Get groups for activity. :param str module: Base module :param str module: Project whic...
_module_id = kwargs.get('module', module) _project_id = kwargs.get('project', project) _url = GROUPS_URL.format(module_id=_module_id, project_id=_project_id) return self._request_api(url=_url).json()
<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_students(self, **kwargs): """Get users by promotion id. :param int promotion: Promotion ID :return: JSON """
_promotion_id = kwargs.get('promotion') _url = PROMOTION_URL.format(promo_id=_promotion_id) return self._request_api(url=_url).json()
<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_log_events(self, login=None, **kwargs): """Get a user's log events. :param str login: User's login (Default: self._login) :return: JSON """
_login = kwargs.get( 'login', login ) log_events_url = GSA_EVENTS_URL.format(login=_login) return self._request_api(url=log_events_url).json()
<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_events(self, login=None, start_date=None, end_date=None, **kwargs): """Get a user's events. :param str login: User's login (Default: self._login) :param ...
_login = kwargs.get( 'login', login ) log_events_url = EVENTS_URL.format( login=_login, start_date=start_date, end_date=end_date, ) return self._request_api(url=log_events_url).json()
<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_logs(self, login=None, **kwargs): """Get a user's logs. :param str login: User's login (Default: self._login) :return: JSON """
_login = kwargs.get( 'login', login ) log_events_url = GSA_LOGS_URL.format(login=_login) return self._request_api(url=log_events_url).json()
<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(self, collector): """ Registers a collector"""
if not isinstance(collector, Collector): raise TypeError( "Can't register instance, not a valid type of collector") if collector.name in self.collectors: raise ValueError("Collector already exists or name colision") with mutex: self.collecto...
<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_value(self, labels, value): """ Sets a value in the container"""
if labels: self._label_names_correct(labels) with mutex: self.values[labels] = 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 get_all(self): """ Returns a list populated by tuples of 2 elements, first one is a dict with all the labels and the second elemnt is the value of the metric...
with mutex: items = self.values.items() result = [] for k, v in items: # Check if is a single value dict (custom empty key) if not k or k == MetricDict.EMPTY_KEY: key = None else: key = decoder.decode(k) ...
<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, labels, value): """Add adds a single observation to the summary."""
if type(value) not in (float, int): raise TypeError("Summary only works with digits (int, float)") # We have already a lock for data but not for the estimator with mutex: try: e = self.get_value(labels) except KeyError: # 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(self, labels): """ Get gets the data in the form of 0.5, 0.9 and 0.99 percentiles. Also you get sum and count, all in a dict """
return_data = {} # We have already a lock for data but not for the estimator with mutex: e = self.get_value(labels) # Set invariants data (default to 0.50, 0.90 and 0.99) for i in e._invariants: q = i._quantile return_data[q...
<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_child(self, name, attribs=None): """ Returns the first child that matches the given name and attributes. """
if name == '.': if attribs is None or len(attribs) == 0: return self if attribs == self.attribs: return self return self.child_index.get(nodehash(name, attribs))
<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(self, path, data=None): """ Creates the given node, regardless of whether or not it already exists. Returns the new node. """
node = self.current[-1] path = self._splitpath(path) n_items = len(path) for n, item in enumerate(path): tag, attribs = self._splittag(item) # The leaf node is always newly created. if n == n_items-1: node = node.add(Node(tag, attribs...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open(self, path): """ Creates and enters the given node, regardless of whether it already exists. Returns the new node. """
self.current.append(self.create(path)) return self.current[-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 enter(self, path): """ Enters the given node. Creates it if it does not exist. Returns the node. """
self.current.append(self.add(path)) return self.current[-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 best_trial_tid(self, rank=0): """Get tid of the best trial rank=0 means the best model rank=1 means second best """
candidates = [t for t in self.trials if t['result']['status'] == STATUS_OK] if len(candidates) == 0: return None losses = [float(t['result']['loss']) for t in candidates] assert not np.any(np.isnan(losses)) lid = np.where(np.argsort(losses).args...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_history(self, tid, scores=["loss", "f1", "accuracy"], figsize=(15, 3)): """Plot the loss curves"""
history = self.train_history(tid) import matplotlib.pyplot as plt fig = plt.figure(figsize=figsize) for i, score in enumerate(scores): plt.subplot(1, len(scores), i + 1) plt.tight_layout() plt.plot(history[score], label="train") plt.plot(...
<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_model(self, tid, custom_objects=None): """Load saved keras model of the trial. If tid = None, get the best model Not applicable for trials ran in cross ...
if tid is None: tid = self.best_trial_tid() model_path = self.get_trial(tid)["result"]["path"]["model"] return load_model(model_path, custom_objects=custom_objects)
<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_ok_results(self, verbose=True): """Return a list of results with ok status """
if len(self.trials) == 0: return [] not_ok = np.where(np.array(self.statuses()) != "ok")[0] if len(not_ok) > 0 and verbose: print("{0}/{1} trials were not ok.".format(len(not_ok), len(self.trials))) print("Trials: " + str(not_ok)) print("Statuse...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resp2flask(resp): """Convert an oic.utils.http_util instance to Flask."""
if isinstance(resp, Redirect) or isinstance(resp, SeeOther): code = int(resp.status.split()[0]) raise cherrypy.HTTPRedirect(resp.message, code) return resp.message, resp.status, resp.headers
<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_authentication_methods(authn_config, template_env): """Add all authentication methods specified in the configuration."""
routing = {} ac = AuthnBroker() for authn_method in authn_config: cls = make_cls_from_name(authn_method["class"]) instance = cls(template_env=template_env, **authn_method["kwargs"]) ac.add(authn_method["acr"], instance) routing[instance.url_endpoint] = VerifierMiddleware(ins...
<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_endpoints(provider): """Setup the OpenID Connect Provider endpoints."""
app_routing = {} endpoints = [ AuthorizationEndpoint( pyoidcMiddleware(provider.authorization_endpoint)), TokenEndpoint( pyoidcMiddleware(provider.token_endpoint)), UserinfoEndpoint( pyoidcMiddleware(provider.userinfo_endpoint)), RegistrationE...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _webfinger(provider, request, **kwargs): """Handle webfinger requests."""
params = urlparse.parse_qs(request) if params["rel"][0] == OIC_ISSUER: wf = WebFinger() return Response(wf.response(params["resource"][0], provider.baseurl), headers=[("Content-Type", "application/jrd+json")]) else: return BadRequest("Incorrect webfinger.")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def featuresQuery(self, **kwargs): """ Converts a dictionary of keyword arguments into a tuple of SQL select statements and the list of SQL arguments """
# TODO: Optimize by refactoring out string concatenation sql = "" sql_rows = "SELECT * FROM FEATURE WHERE id > 1 " sql_args = () if 'name' in kwargs and kwargs['name']: sql += "AND name = ? " sql_args += (kwargs.get('name'),) if 'geneSymbol' in kw...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def searchFeaturesInDb( self, startIndex=0, maxResults=None, referenceName=None, start=None, end=None, parentId=None, featureTypes=None, name=None, geneSymbol=Non...
# TODO: Refactor out common bits of this and the above count query. sql, sql_args = self.featuresQuery( startIndex=startIndex, maxResults=maxResults, referenceName=referenceName, start=start, end=end, parentId=parentId, featureTypes=featureTypes, name=nam...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getFeatureById(self, featureId): """ Fetch feature by featureID. :param featureId: the FeatureID as found in GFF3 records :return: dictionary representing a ...
sql = "SELECT * FROM FEATURE WHERE id = ?" query = self._dbconn.execute(sql, (featureId,)) ret = query.fetchone() if ret is None: return None return sqlite_backend.sqliteRowToDict(ret)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def toProtocolElement(self): """ Returns the representation of this FeatureSet as the corresponding ProtocolElement. """
gaFeatureSet = protocol.FeatureSet() gaFeatureSet.id = self.getId() gaFeatureSet.dataset_id = self.getParentContainer().getId() gaFeatureSet.reference_set_id = pb.string(self._referenceSet.getId()) gaFeatureSet.name = self._name gaFeatureSet.source_uri = self._sourceUri ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getCompoundIdForFeatureId(self, featureId): """ Returns server-style compound ID for an internal featureId. :param long featureId: id of feature in database ...
if featureId is not None and featureId != "": compoundId = datamodel.FeatureCompoundId( self.getCompoundId(), str(featureId)) else: compoundId = "" return str(compoundId)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getFeature(self, compoundId): """ Fetches a simulated feature by ID. :param compoundId: any non-null string :return: A simulated feature with id set to the s...
if compoundId is None: raise exceptions.ObjectWithIdNotFoundException(compoundId) randomNumberGenerator = random.Random() randomNumberGenerator.seed(self._randomSeed) feature = self._generateSimulatedFeature(randomNumberGenerator) feature.id = str(compoundId) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getFeatures(self, referenceName=None, start=None, end=None, startIndex=None, maxResults=None, featureTypes=None, parentId=None, name=None, geneSymbol=None, nu...
randomNumberGenerator = random.Random() randomNumberGenerator.seed(self._randomSeed) for featureId in range(numFeatures): gaFeature = self._generateSimulatedFeature(randomNumberGenerator) gaFeature.id = self.getCompoundIdForFeatureId(featureId) match = ( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addRnaQuantification(self, rnaQuantification): """ Add an rnaQuantification to this rnaQuantificationSet """
id_ = rnaQuantification.getId() self._rnaQuantificationIdMap[id_] = rnaQuantification self._rnaQuantificationIds.append(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 populateFromFile(self, dataUrl): """ Populates the instance variables of this RnaQuantificationSet from the specified data URL. """
self._dbFilePath = dataUrl self._db = SqliteRnaBackend(self._dbFilePath) self.addRnaQuants()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def populateFromRow(self, quantificationSetRecord): """ Populates the instance variables of this RnaQuantificationSet from the specified DB row. """
self._dbFilePath = quantificationSetRecord.dataurl self.setAttributesJson(quantificationSetRecord.attributes) self._db = SqliteRnaBackend(self._dbFilePath) self.addRnaQuants()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getExpressionLevels( self, threshold=0.0, names=[], startIndex=0, maxResults=0): """ Returns the list of ExpressionLevels in this RNA Quantification. """
rnaQuantificationId = self.getLocalId() with self._db as dataSource: expressionsReturned = dataSource.searchExpressionLevelsInDb( rnaQuantificationId, names=names, threshold=threshold, startIndex=startIndex, max...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def populateFromRow(self, callSetRecord): """ Populates this CallSet from the specified DB row. """
self._biosampleId = callSetRecord.biosampleid self.setAttributesJson(callSetRecord.attributes)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def toProtocolElement(self): """ Returns the representation of this CallSet as the corresponding ProtocolElement. """
variantSet = self.getParentContainer() gaCallSet = protocol.CallSet( biosample_id=self.getBiosampleId()) if variantSet.getCreationTime(): gaCallSet.created = variantSet.getCreationTime() if variantSet.getUpdatedTime(): gaCallSet.updated = variantSet.g...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addVariantAnnotationSet(self, variantAnnotationSet): """ Adds the specified variantAnnotationSet to this dataset. """
id_ = variantAnnotationSet.getId() self._variantAnnotationSetIdMap[id_] = variantAnnotationSet self._variantAnnotationSetIds.append(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 getVariantAnnotationSet(self, id_): """ Returns the AnnotationSet in this dataset with the specified 'id' """
if id_ not in self._variantAnnotationSetIdMap: raise exceptions.AnnotationSetNotFoundException(id_) return self._variantAnnotationSetIdMap[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 addCallSet(self, callSet): """ Adds the specfied CallSet to this VariantSet. """
callSetId = callSet.getId() self._callSetIdMap[callSetId] = callSet self._callSetNameMap[callSet.getLocalId()] = callSet self._callSetIds.append(callSetId) self._callSetIdToIndex[callSet.getId()] = len(self._callSetIds) - 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 addCallSetFromName(self, sampleName): """ Adds a CallSet for the specified sample name. """
callSet = CallSet(self, sampleName) self.addCallSet(callSet)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getCallSetByName(self, name): """ Returns a CallSet with the specified name, or raises a CallSetNameNotFoundException if it does not exist. """
if name not in self._callSetNameMap: raise exceptions.CallSetNameNotFoundException(name) return self._callSetNameMap[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 getCallSet(self, id_): """ Returns a CallSet with the specified id, or raises a CallSetNotFoundException if it does not exist. """
if id_ not in self._callSetIdMap: raise exceptions.CallSetNotFoundException(id_) return self._callSetIdMap[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 toProtocolElement(self): """ Converts this VariantSet into its GA4GH protocol equivalent. """
protocolElement = protocol.VariantSet() protocolElement.id = self.getId() protocolElement.dataset_id = self.getParentContainer().getId() protocolElement.reference_set_id = self._referenceSet.getId() protocolElement.metadata.extend(self.getMetadata()) protocolElement.data...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _createGaVariant(self): """ Convenience method to set the common fields in a GA Variant object from this variant set. """
ret = protocol.Variant() if self._creationTime: ret.created = self._creationTime if self._updatedTime: ret.updated = self._updatedTime ret.variant_set_id = self.getId() return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getVariantId(self, gaVariant): """ Returns an ID string suitable for the specified GA Variant object in this variant set. """
md5 = self.hashVariant(gaVariant) compoundId = datamodel.VariantCompoundId( self.getCompoundId(), gaVariant.reference_name, str(gaVariant.start), md5) return str(compoundId)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getCallSetId(self, sampleName): """ Returns the callSetId for the specified sampleName in this VariantSet. """
compoundId = datamodel.CallSetCompoundId( self.getCompoundId(), sampleName) return str(compoundId)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hashVariant(cls, gaVariant): """ Produces an MD5 hash of the ga variant object to distinguish it from other variants at the same genomic coordinate. """
hash_str = gaVariant.reference_bases + \ str(tuple(gaVariant.alternate_bases)) return hashlib.md5(hash_str).hexdigest()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generateVariant(self, referenceName, position, randomNumberGenerator): """ Generate a random variant for the specified position using the specified random nu...
variant = self._createGaVariant() variant.reference_name = referenceName variant.start = position variant.end = position + 1 # SNPs only for now bases = ["A", "C", "G", "T"] ref = randomNumberGenerator.choice(bases) variant.reference_bases = ref alt = ra...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def populateFromRow(self, variantSetRecord): """ Populates this VariantSet from the specified DB row. """
self._created = variantSetRecord.created self._updated = variantSetRecord.updated self.setAttributesJson(variantSetRecord.attributes) self._chromFileMap = {} # We can't load directly as we want tuples to be stored # rather than lists. for key, value in json.loads...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def populateFromFile(self, dataUrls, indexFiles): """ Populates this variant set using the specified lists of data files and indexes. These must be in the same o...
assert len(dataUrls) == len(indexFiles) for dataUrl, indexFile in zip(dataUrls, indexFiles): varFile = pysam.VariantFile(dataUrl, index_filename=indexFile) try: self._populateFromVariantFile(varFile, dataUrl, indexFile) finally: varFil...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def populateFromDirectory(self, vcfDirectory): """ Populates this VariantSet by examing all the VCF files in the specified directory. This is mainly used for as ...
pattern = os.path.join(vcfDirectory, "*.vcf.gz") dataFiles = [] indexFiles = [] for vcfFile in glob.glob(pattern): dataFiles.append(vcfFile) indexFiles.append(vcfFile + ".tbi") self.populateFromFile(dataFiles, indexFiles)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def checkConsistency(self): """ Perform consistency check on the variant set """
for referenceName, (dataUrl, indexFile) in self._chromFileMap.items(): varFile = pysam.VariantFile(dataUrl, index_filename=indexFile) try: for chrom in varFile.index: chrom, _, _ = self.sanitizeVariantFileFetch(chrom) if not isEmpt...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _populateFromVariantFile(self, varFile, dataUrl, indexFile): """ Populates the instance variables of this VariantSet from the specified pysam VariantFile obj...
if varFile.index is None: raise exceptions.NotIndexedException(dataUrl) for chrom in varFile.index: # Unlike Tabix indices, CSI indices include all contigs defined # in the BCF header. Thus we must test each one to see if # records exist or else they are...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _updateVariantAnnotationSets(self, variantFile, dataUrl): """ Updates the variant annotation set associated with this variant using information in the specif...
# TODO check the consistency of this between VCF files. if not self.isAnnotated(): annotationType = None for record in variantFile.header.records: if record.type == "GENERIC": if record.key == "SnpEffVersion": annotatio...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _updateMetadata(self, variantFile): """ Updates the metadata for his variant set based on the specified variant file """
metadata = self._getMetadataFromVcf(variantFile) if self._metadata is None: self._metadata = metadata
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _checkMetadata(self, variantFile): """ Checks that metadata is consistent """
metadata = self._getMetadataFromVcf(variantFile) if self._metadata is not None and self._metadata != metadata: raise exceptions.InconsistentMetaDataException( variantFile.filename)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _checkCallSetIds(self, variantFile): """ Checks callSetIds for consistency """
if len(self._callSetIdMap) > 0: callSetIds = set([ self.getCallSetId(sample) for sample in variantFile.header.samples]) if callSetIds != set(self._callSetIdMap.keys()): raise exceptions.InconsistentCallSetIdException( v...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _updateCallSetIds(self, variantFile): """ Updates the call set IDs based on the specified variant file. """
if len(self._callSetIdMap) == 0: for sample in variantFile.header.samples: self.addCallSetFromName(sample)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convertVariant(self, record, callSetIds): """ Converts the specified pysam variant record into a GA4GH Variant object. Only calls for the specified list of c...
variant = self._createGaVariant() variant.reference_name = record.contig if record.id is not None: variant.names.extend(record.id.split(';')) variant.start = record.start # 0-based inclusive variant.end = record.stop # 0-based exclusive v...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getPysamVariants(self, referenceName, startPosition, endPosition): """ Returns an iterator over the pysam VCF records corresponding to the specified query. "...
if referenceName in self._chromFileMap: varFileName = self._chromFileMap[referenceName] referenceName, startPosition, endPosition = \ self.sanitizeVariantFileFetch( referenceName, startPosition, endPosition) cursor = self.getFileHandle(var...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getVariants(self, referenceName, startPosition, endPosition, callSetIds=[]): """ Returns an iterator over the specified variants. The parameters correspond t...
if callSetIds is None: callSetIds = self._callSetIds else: for callSetId in callSetIds: if callSetId not in self._callSetIds: raise exceptions.CallSetNotInVariantSetException( callSetId, self.getId()) for record...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getMetadataId(self, metadata): """ Returns the id of a metadata """
return str(datamodel.VariantSetMetadataCompoundId( self.getCompoundId(), 'metadata:' + metadata.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 _createGaVariantAnnotation(self): """ Convenience method to set the common fields in a GA VariantAnnotation object from this variant set. """
ret = protocol.VariantAnnotation() ret.created = self._creationTime ret.variant_annotation_set_id = self.getId() return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def toProtocolElement(self): """ Converts this VariantAnnotationSet into its GA4GH protocol equivalent. """
protocolElement = protocol.VariantAnnotationSet() protocolElement.id = self.getId() protocolElement.variant_set_id = self._variantSet.getId() protocolElement.name = self.getLocalId() protocolElement.analysis.CopyFrom(self.getAnalysis()) self.serializeAttributes(protocolE...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hashVariantAnnotation(cls, gaVariant, gaVariantAnnotation): """ Produces an MD5 hash of the gaVariant and gaVariantAnnotation objects """
treffs = [treff.id for treff in gaVariantAnnotation.transcript_effects] return hashlib.md5( "{}\t{}\t{}\t".format( gaVariant.reference_bases, tuple(gaVariant.alternate_bases), treffs) ).hexdigest()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generateVariantAnnotation(self, variant): """ Generate a random variant annotation based on a given variant. This generator should be seeded with a value tha...
# To make this reproducible, make a seed based on this # specific variant. seed = self._randomSeed + variant.start + variant.end randomNumberGenerator = random.Random() randomNumberGenerator.seed(seed) ann = protocol.VariantAnnotation() ann.variant_annotation_set...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def populateFromRow(self, annotationSetRecord): """ Populates this VariantAnnotationSet from the specified DB row. """
self._annotationType = annotationSetRecord.annotationtype self._analysis = protocol.fromJson( annotationSetRecord.analysis, protocol.Analysis) self._creationTime = annotationSetRecord.created self._updatedTime = annotationSetRecord.updated self.setAttributesJson(anno...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _getAnnotationAnalysis(self, varFile): """ Assembles metadata within the VCF header into a GA4GH Analysis object. :return: protocol.Analysis """
header = varFile.header analysis = protocol.Analysis() formats = header.formats.items() infos = header.info.items() filters = header.filters.items() for prefix, content in [("FORMAT", formats), ("INFO", infos), ("FILTER", filters)]: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convertVariantAnnotation(self, record): """ Converts the specfied pysam variant record into a GA4GH variant annotation object using the specified function to...
variant = self._variantSet.convertVariant(record, []) annotation = self._createGaVariantAnnotation() annotation.variant_id = variant.id gDots = record.info.get(b'HGVS.g') # Convert annotations from INFO field into TranscriptEffect transcriptEffects = [] annotatio...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _attributeStr(self, name): """ Return name=value for a single attribute """
return "{}={}".format( _encodeAttr(name), ",".join([_encodeAttr(v) for v in self.attributes[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 _attributeStrs(self): """ Return name=value, semi-colon-separated string for attributes, including url-style quoting """
return ";".join([self._attributeStr(name) for name in self.attributes.iterkeys()])