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 removeIndividual(self): """ Removes an individual from this repo """
self._openRepo() dataset = self._repo.getDatasetByName(self._args.datasetName) individual = dataset.getIndividualByName(self._args.individualName) def func(): self._updateRepo(self._repo.removeIndividual, individual) self._confirmDelete("Individual", individual.getL...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addPeer(self): """ Adds a new peer into this repo """
self._openRepo() try: peer = peers.Peer( self._args.url, json.loads(self._args.attributes)) except exceptions.BadUrlException: raise exceptions.RepoManagerException("The URL for the peer was " "malformed."...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def removePeer(self): """ Removes a peer by URL from this repo """
self._openRepo() def func(): self._updateRepo(self._repo.removePeer, self._args.url) self._confirmDelete("Peer", self._args.url, func)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def removeOntology(self): """ Removes an ontology from the repo. """
self._openRepo() ontology = self._repo.getOntologyByName(self._args.ontologyName) def func(): self._updateRepo(self._repo.removeOntology, ontology) self._confirmDelete("Ontology", ontology.getName(), func)
<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): """ Adds an rnaQuantification into this repo """
self._openRepo() dataset = self._repo.getDatasetByName(self._args.datasetName) biosampleId = "" if self._args.biosampleName: biosample = dataset.getBiosampleByName(self._args.biosampleName) biosampleId = biosample.getId() if self._args.name is 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 initRnaQuantificationSet(self): """ Initialize an empty RNA quantification set """
store = rnaseq2ga.RnaSqliteStore(self._args.filePath) store.createTables()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addRnaQuantificationSet(self): """ Adds an rnaQuantificationSet into this repo """
self._openRepo() dataset = self._repo.getDatasetByName(self._args.datasetName) if self._args.name is None: name = getNameFromPath(self._args.filePath) else: name = self._args.name rnaQuantificationSet = rna_quantification.SqliteRnaQuantificationSet( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def removeRnaQuantificationSet(self): """ Removes an rnaQuantificationSet from this repo """
self._openRepo() dataset = self._repo.getDatasetByName(self._args.datasetName) rnaQuantSet = dataset.getRnaQuantificationSetByName( self._args.rnaQuantificationSetName) def func(): self._updateRepo(self._repo.removeRnaQuantificationSet, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rnaseq2ga(quantificationFilename, sqlFilename, localName, rnaType, dataset=None, featureType="gene", description="", programs="", featureSetNames="", readGrou...
readGroupSetName = "" if readGroupSetNames: readGroupSetName = readGroupSetNames.strip().split(",")[0] featureSetIds = "" readGroupIds = "" if dataset: featureSetIdList = [] if featureSetNames: for annotationName in featureSetNames.split(","): fea...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def createIndices(self): """ Index columns that are queried. The expression index can take a long time. """
sql = '''CREATE INDEX name_index ON Expression (name)''' self._cursor.execute(sql) self._dbConn.commit() sql = '''CREATE INDEX expression_index ON Expression (expression)''' self._cursor.execute(sql) self._dbConn.commit()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def writeExpression(self, rnaQuantificationId, quantfilename): """ Reads the quantification results file and adds entries to the specified database. """
isNormalized = self._isNormalized units = self._units with open(quantfilename, "r") as quantFile: quantificationReader = csv.reader(quantFile, delimiter=b"\t") header = next(quantificationReader) expressionLevelColNum = self.setColNum( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _fetchSequence(ac, startIndex=None, endIndex=None): """Fetch sequences from NCBI using the eself interface. An interbase interval may be optionally provided ...
urlFmt = ( "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?" "db=nucleotide&id={ac}&rettype=fasta&retmode=text") if startIndex is None or endIndex is None: url = urlFmt.format(ac=ac) else: urlFmt += "&seq_start={start}&seq_stop={stop}" url = urlFmt.format(a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def createBamHeader(self, baseHeader): """ Creates a new bam header based on the specified header from the parent BAM file. """
header = dict(baseHeader) newSequences = [] for index, referenceInfo in enumerate(header['SQ']): if index < self.numChromosomes: referenceName = referenceInfo['SN'] # The sequence dictionary in the BAM file has to match up # with the s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def createRepo(self): """ Creates the repository for all the data we've just downloaded. """
repo = datarepo.SqlDataRepository(self.repoPath) repo.open("w") repo.initialise() referenceSet = references.HtslibReferenceSet("GRCh37-subset") referenceSet.populateFromFile(self.fastaFilePath) referenceSet.setDescription("Subset of GRCh37 used for demonstration") ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _configure_backend(app): """A helper function used just to help modularize the code a bit."""
# Allocate the backend # We use URLs to specify the backend. Currently we have file:// URLs (or # URLs with no scheme) for the SqlDataRepository, and special empty:// and # simulated:// URLs for empty or simulated data sources. dataSource = urlparse.urlparse(app.config["DATA_SOURCE"], "file") ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getFlaskResponse(responseString, httpStatus=200): """ Returns a Flask response object for the specified data and HTTP status. """
return flask.Response(responseString, status=httpStatus, mimetype=MIMETYPE)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handleHttpPost(request, endpoint): """ Handles the specified HTTP POST request, which maps to the specified protocol handler endpoint and protocol request cl...
if request.mimetype and request.mimetype != MIMETYPE: raise exceptions.UnsupportedMediaTypeException() request = request.get_data() if request == '' or request is None: request = '{}' responseStr = endpoint(request) return getFlaskResponse(responseStr)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handleException(exception): """ Handles an exception that occurs somewhere in the process of handling a request. """
serverException = exception if not isinstance(exception, exceptions.BaseServerException): with app.test_request_context(): app.log_exception(exception) serverException = exceptions.getServerError(exception) error = serverException.toProtocolElement() # If the exception is be...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def checkAuthentication(): """ The request will have a parameter 'key' if it came from the command line client, or have a session key of 'key' if it's the browse...
if app.oidcClient is None: return if flask.request.endpoint == 'oidcCallback': return key = flask.session.get('key') or flask.request.args.get('key') if key is None or not app.cache.get(key): if 'key' in flask.request.args: raise exceptions.NotAuthenticatedException(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handleFlaskGetRequest(id_, flaskRequest, endpoint): """ Handles the specified flask request for one of the GET URLs Invokes the specified endpoint to generat...
if flaskRequest.method == "GET": return handleHttpGet(id_, endpoint) else: raise exceptions.MethodNotAllowedException()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handleFlaskPostRequest(flaskRequest, endpoint): """ Handles the specified flask request for one of the POST URLS Invokes the specified endpoint to generate a...
if flaskRequest.method == "POST": return handleHttpPost(flaskRequest, endpoint) elif flaskRequest.method == "OPTIONS": return handleHttpOptions() else: raise exceptions.MethodNotAllowedException()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getVariantAnnotationSets(self, datasetId): """ Returns the list of ReferenceSets for this server. """
# TODO this should be displayed per-variant set, not per dataset. variantAnnotationSets = [] dataset = app.backend.getDataRepository().getDataset(datasetId) for variantSet in dataset.getVariantSets(): variantAnnotationSets.extend( variantSet.getVariantAnnotat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def auth_decorator(app=None): """ This decorator wraps a view function so that it is protected when Auth0 is enabled. This means that any request will be expecte...
def requires_auth(f): @functools.wraps(f) def decorated(*args, **kwargs): # This decorator will only apply with AUTH0_ENABLED set to True. if app.config.get('AUTH0_ENABLED', False): client_id = app.config.get("AUTH0_CLIENT_ID") client_secret =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def logout(cache): """ Logs out the current session by removing it from the cache. This is expected to only occur when a session has """
cache.set(flask.session['auth0_key'], None) flask.session.clear() 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 addReference(self, reference): """ Adds the specified reference to this ReferenceSet. """
id_ = reference.getId() self._referenceIdMap[id_] = reference self._referenceNameMap[reference.getLocalId()] = reference self._referenceIds.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 setSpeciesFromJson(self, speciesJson): """ Sets the species, an OntologyTerm, to the specified value, given as a JSON string. See the documentation for detai...
try: parsed = protocol.fromJson(speciesJson, protocol.OntologyTerm) except: raise exceptions.InvalidJsonException(speciesJson) self._species = protocol.toJsonDict(parsed)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getReferenceByName(self, name): """ Returns the reference with the specified name. """
if name not in self._referenceNameMap: raise exceptions.ReferenceNameNotFoundException(name) return self._referenceNameMap[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 getReference(self, id_): """ Returns the Reference with the specified ID or raises a ReferenceNotFoundException if it does not exist. """
if id_ not in self._referenceIdMap: raise exceptions.ReferenceNotFoundException(id_) return self._referenceIdMap[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 getMd5Checksum(self): """ Returns the MD5 checksum for this reference set. This checksum is calculated by making a list of `Reference.md5checksum` for all `R...
references = sorted( self.getReferences(), key=lambda ref: ref.getMd5Checksum()) checksums = ''.join([ref.getMd5Checksum() for ref in references]) md5checksum = hashlib.md5(checksums).hexdigest() return md5checksum
<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 GA4GH protocol representation of this ReferenceSet. """
ret = protocol.ReferenceSet() ret.assembly_id = pb.string(self.getAssemblyId()) ret.description = pb.string(self.getDescription()) ret.id = self.getId() ret.is_derived = self.getIsDerived() ret.md5checksum = self.getMd5Checksum() if self.getSpecies(): ...
<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 GA4GH protocol representation of this Reference. """
reference = protocol.Reference() reference.id = self.getId() reference.is_derived = self.getIsDerived() reference.length = self.getLength() reference.md5checksum = self.getMd5Checksum() reference.name = self.getName() if self.getSpecies(): term = prot...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def checkQueryRange(self, start, end): """ Checks to ensure that the query range is valid within this reference. If not, raise ReferenceRangeErrorException. """
condition = ( (start < 0 or end > self.getLength()) or start > end or start == end) if condition: raise exceptions.ReferenceRangeErrorException( self.getId(), start, end)
<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 ReferencSet from the data URL. """
self._dataUrl = dataUrl fastaFile = self.getFastaFile() for referenceName in fastaFile.references: reference = HtslibReference(self, referenceName) # TODO break this up into chunks and calculate the MD5 # in bits (say, 64K chunks?) bases = fastaFi...
<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, referenceSetRecord): """ Populates this reference set from the values in the specified DB row. """
self._dataUrl = referenceSetRecord.dataurl self._description = referenceSetRecord.description self._assemblyId = referenceSetRecord.assemblyid self._isDerived = bool(referenceSetRecord.isderived) self._md5checksum = referenceSetRecord.md5checksum species = referenceSetRe...
<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, referenceRecord): """ Populates this reference from the values in the specified DB row. """
self._length = referenceRecord.length self._isDerived = bool(referenceRecord.isderived) self._md5checksum = referenceRecord.md5checksum species = referenceRecord.species if species is not None and species != 'null': self.setSpeciesFromJson(species) self._sour...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _bindingsToDict(self, bindings): """ Given a binding from the sparql query result, create a dict of plain text """
myDict = {} for key, val in bindings.iteritems(): myDict[key.toPython().replace('?', '')] = val.toPython() return myDict
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _addDataFile(self, filename): """ Given a filename, add it to the graph """
if filename.endswith('.ttl'): self._rdfGraph.parse(filename, format='n3') else: self._rdfGraph.parse(filename, format='xml')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _getDetails(self, uriRef, associations_details): """ Given a uriRef, return a dict of all the details for that Ref use the uriRef as the 'id' of the dict """
associationDetail = {} for detail in associations_details: if detail['subject'] == uriRef: associationDetail[detail['predicate']] = detail['object'] associationDetail['id'] = uriRef return associationDetail
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _formatExternalIdentifiers(self, element, element_type): """ Formats several external identifiers for query """
elementClause = None elements = [] if not issubclass(element.__class__, dict): element = protocol.toJsonDict(element) if element['externalIdentifiers']: for _id in element['externalIdentifiers']: elements.append(self._formatExternalIdentifier( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _formatExternalIdentifier(self, element, element_type): """ Formats a single external identifier for query """
if "http" not in element['database']: term = "{}:{}".format(element['database'], element['identifier']) namespaceTerm = self._toNamespaceURL(term) else: namespaceTerm = "{}{}".format( element['database'], element['identifier']) comparison = '?...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _formatOntologyTerm(self, element, element_type): """ Formats the ontology terms for query """
elementClause = None if isinstance(element, dict) and element.get('terms'): elements = [] for _term in element['terms']: if _term.get('id'): elements.append('?{} = <{}> '.format( element_type, _term['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 _formatOntologyTermObject(self, terms, element_type): """ Formats the ontology term object for query """
elementClause = None if not isinstance(terms, collections.Iterable): terms = [terms] elements = [] for term in terms: if term.term_id: elements.append('?{} = <{}> '.format( element_type, term.term_id)) else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _formatIds(self, element, element_type): """ Formats a set of identifiers for query """
elementClause = None if isinstance(element, collections.Iterable): elements = [] for _id in element: elements.append('?{} = <{}> '.format( element_type, _id)) elementClause = "({})".format(" || ".join(elements)) return elem...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _formatEvidence(self, elements): """ Formats elements passed into parts of a query for filtering """
elementClause = None filters = [] for evidence in elements: if evidence.description: elementClause = 'regex(?{}, "{}")'.format( 'environment_label', evidence.description) if (hasattr(evidence, 'externalIdentifiers') and ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _toGA4GH(self, association, featureSets=[]): """ given an association dict, return a protocol.FeaturePhenotypeAssociation """
# The association dict has the keys: environment, environment # label, evidence, feature label, phenotype and sources. Each # key's value is a dict with the RDF predicates as keys and # subject as values # 1) map a GA4GH FeaturePhenotypeAssociation # from the associati...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _formatFilterQuery(self, request=None, featureSets=[]): """ Generate a formatted sparql query with appropriate filters """
query = self._baseQuery() filters = [] if issubclass(request.__class__, protocol.SearchGenotypePhenotypeRequest): filters += self._filterSearchGenotypePhenotypeRequest( request, featureSets) if issubclass(request.__class__, protocol.Sea...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _filterSearchPhenotypesRequest(self, request): """ Filters request for phenotype search requests """
filters = [] if request.id: filters.append("?phenotype = <{}>".format(request.id)) if request.description: filters.append( 'regex(?phenotype_label, "{}")'.format(request.description)) # OntologyTerms # TODO: refactor this repetitive code ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parseStep(self, line): """ Parse the line describing the mode. One of: variableStep chrom=<reference> [span=<window_size>] fixedStep chrom=<reference> start=...
fields = dict([field.split('=') for field in line.split()[1:]]) if 'chrom' in fields: self._reference = fields['chrom'] else: raise ValueError("Missing chrom field in %s" % line.strip()) if line.startswith("fixedStep"): if 'start' in fields: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def readWiggleLine(self, line): """ Read a wiggle line. If it is a data line, add values to the protocol object. """
if(line.isspace() or line.startswith("#") or line.startswith("browser") or line.startswith("track")): return elif line.startswith("variableStep"): self._mode = self._VARIABLE_STEP self.parseStep(line) return elif line.startswith("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 wiggleFileHandleToProtocol(self, fileHandle): """ Return a continuous protocol object satsifiying the given query parameters from the given wiggle file handl...
for line in fileHandle: self.readWiggleLine(line) return self._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 checkReference(self, reference): """ Check the reference for security. Tries to avoid any characters necessary for doing a script injection. """
pattern = re.compile(r'[\s,;"\'&\\]') if pattern.findall(reference.strip()): 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 readValuesPyBigWig(self, reference, start, end): """ Use pyBigWig package to read a BigWig file for the given range and return a protocol object. pyBigWig re...
if not self.checkReference(reference): raise exceptions.ReferenceNameNotFoundException(reference) if start < 0: start = 0 bw = pyBigWig.open(self._sourceFile) referenceLen = bw.chroms(reference) if referenceLen is None: raise exceptions.Refere...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def readValuesBigWigToWig(self, reference, start, end): """ Read a bigwig file and return a protocol object with values within the query range. This method uses ...
if not self.checkReference(reference): raise exceptions.ReferenceNameNotFoundException(reference) if start < 0: raise exceptions.ReferenceRangeErrorException( reference, start, end) # TODO: CHECK IF QUERY IS BEYOND END cmd = ["bigWigToWig", s...
<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 ContinuousSet as the corresponding ProtocolElement. """
gaContinuousSet = protocol.ContinuousSet() gaContinuousSet.id = self.getId() gaContinuousSet.dataset_id = self.getParentContainer().getId() gaContinuousSet.reference_set_id = pb.string( self._referenceSet.getId()) gaContinuousSet.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 populateFromRow(self, continuousSetRecord): """ Populates the instance variables of this ContinuousSet from the specified DB row. """
self._filePath = continuousSetRecord.dataurl self.setAttributesJson(continuousSetRecord.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 getContinuous(self, referenceName=None, start=None, end=None): """ Method passed to runSearchRequest to fulfill the request to yield continuous protocol obje...
bigWigReader = BigWigDataSource(self._filePath) for continuousObj in bigWigReader.bigWigToProtocol( referenceName, start, end): yield continuousObj
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getContinuousData(self, referenceName=None, start=None, end=None): """ Returns a set number of simulated continuous data. :param referenceName: name of refer...
randomNumberGenerator = random.Random() randomNumberGenerator.seed(self._randomSeed) for i in range(100): gaContinuous = self._generateSimulatedContinuous( randomNumberGenerator) match = ( gaContinuous.start < end and ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ping(self, destination, source=c.PING_SOURCE, ttl=c.PING_TTL, timeout=c.PING_TIMEOUT, size=c.PING_SIZE, count=c.PING_COUNT, vrf=c.PING_VRF): """ Executes pin...
raise NotImplementedError
<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_commands(self, commands): """Only useful for EOS"""
if "eos" in self.profile: return list(self.parent.cli(commands).values())[0] else: raise AttributeError("MockedDriver instance has not attribute '_rpc'")
<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_txt(xml_tree, path, default=''): """ Extracts the text value from an XML tree, using XPath. In case of error, will return a default value. :param xml_tr...
value = '' try: xpath_applied = xml_tree.xpath(path) # will consider the first match only if len(xpath_applied) and xpath_applied[0] is not None: xpath_result = xpath_applied[0] if isinstance(xpath_result, type(xml_tree)): value = xpath_result.text.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 convert(to, who, default=u''): """ Converts data to a specific datatype. In case of error, will return a default value. :param to: datatype to be casted to. ...
if who is None: return default try: return to(who) except: # noqa return default
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mac(raw): """ Converts a raw string to a standardised MAC Address EUI Format. :param raw: the raw string containing the value of the MAC Address :return: a s...
if raw.endswith(':'): flat_raw = raw.replace(':', '') raw = '{flat_raw}{zeros_stuffed}'.format( flat_raw=flat_raw, zeros_stuffed='0'*(12-len(flat_raw)) ) return py23_compat.text_type(EUI(raw, dialect=_MACFormat))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def convert_uptime_string_seconds(uptime): '''Convert uptime strings to seconds. The string can be formatted various ways.''' regex_list = [ # n years, n weeks, n days, n hours, n minutes where each of the fields except minutes # is optional. Additionally, can be either singular or plural ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def str2hashalgo(description): '''Convert the name of a hash algorithm as described in the OATH specifications, to a python object handling the digest algorithm interface, PEP-xxx. :param description the name of the hash algorithm, example :rtype: a hash algorithm class const...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def str2cryptofunction(crypto_function_description): ''' Convert an OCRA crypto function description into a CryptoFunction instance :param crypto_function_description: :returns: the CryptoFunction object :rtype: CryptoFunction ''' s = crypto_function_descriptio...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def hotp(key,counter,format='dec6',hash=hashlib.sha1): ''' Compute a HOTP value as prescribed by RFC4226 :param key: the HOTP secret key given as an hexadecimal string :param counter: the OTP generation counter :param format: the output format, can be: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def totp(key, format='dec6', period=30, t=None, hash=hashlib.sha1): ''' Compute a TOTP value as prescribed by OATH specifications. :param key: the TOTP key given as an hexadecimal string :param format: the output format, can be: - hex, for a variable length ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def from_b32key(b32_key, state=None): '''Some phone app directly accept a partial b32 encoding, we try to emulate that''' try: lenient_b32decode(b32_key) except TypeError: raise ValueError('invalid base32 value') return GoogleAuthenticator('otpauth://totp/xxx?%s' % urlencode(...
<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_slice(self, inputs, new_attr): """onnx slice provides slicing on multiple axis. Adding multiple slice_axis operator for multiple axes from mxnet"""
begin = new_attr.get('begin') end = new_attr.get('end') axes = new_attr.get('axis', tuple(range(len(begin)))) slice_op = mx.sym.slice_axis(inputs[0], axis=axes[0], begin=begin[0], end=end[0]) if len(axes) > 1: for i, axis in enumerate(axes): slice_op ...
<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_outputs(self, op, outputs): """A workaround to handle dropout or similar operator that have more than one out in ONNX. """
if op == 'Dropout': assert len(outputs) == 2, "ONNX have two outputs for dropout layer." outputs = outputs[:-1] return outputs
<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, inputs, **kwargs): """Run model inference and return the result Parameters inputs : numpy array input to run a layer on Returns ------- params : nu...
input_data = np.asarray(inputs[0], dtype='f') # create module, passing cpu context if self.device == 'CPU': ctx = mx.cpu() else: raise NotImplementedError("Only CPU context is supported for now") mod = mx.mod.Module(symbol=self.symbol, data_names=['inpu...
<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_default(self, target): """Helper function to parse default values."""
if not isinstance(target, (list, tuple)): k, v, t = target, None, lambda x: x elif len(target) == 1: k, v, t = target[0], None, lambda x: x elif len(target) == 2: k, v, t = target[0], target[1], lambda x: x elif len(target) > 2: k, v, t = ...
<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_bool(self, value): """Helper function to parse default boolean values."""
if isinstance(value, string_types): return value.strip().lower() in ['true', '1', 't', 'y', 'yes'] return bool(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 _required_attr(self, attr, key): """Wrapper for getting required attributes."""
assert isinstance(attr, dict) if key not in attr: raise AttributeError("Required attribute {} not found.".format(key)) return attr[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 make_graph(node, inputs): """ Created ONNX GraphProto from node"""
initializer = [] tensor_input_info = [] tensor_output_info = [] # Adding input tensor info. for index in range(len(node.input)): tensor_input_info.append( helper.make_tensor_value_info(str(node.input[index]), TensorProto.FLOAT, [1])) # 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 run_node(cls, node, inputs, device='CPU'): # pylint: disable=arguments-differ """Running individual node inference on mxnet engine and return the result to o...
graph = GraphProto() sym, _ = graph.from_onnx(MXNetBackend.make_graph(node, inputs)) data_names = [i for i in sym.get_internals().list_inputs()] data_shapes = [] reduce_op_types = set(['ReduceMin', 'ReduceMax', 'ReduceMean', 'ReduceProd', 'ReduceSu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _revert_caffe2_pad(attr): """Removing extra padding from Caffe2."""
if len(attr) == 4: attr = attr[:2] elif len(attr) == 2: pass else: raise ValueError("Invalid caffe2 type padding: {}".format(attr)) return attr
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def import_model(model_file): """Imports the supplied ONNX model file into MXNet symbol and parameters. Parameters model_file : ONNX model file name Returns ----...
graph = GraphProto() # loads model file and returns ONNX protobuf object model_proto = onnx.load(model_file) sym, params = graph.from_onnx(model_proto.graph) return sym, params
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_hash(filepath): """Public function that reads a local file and generates a SHA256 hash digest for it"""
fr = FileReader(filepath) data = fr.read_bin() return _calculate_sha256(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 generate_tar_files(directory_list): """Public function that reads a list of local directories and generates tar archives from them"""
tar_file_list = [] for directory in directory_list: if dir_exists(directory): _generate_tar(directory) # create the tar archive tar_file_list.append(directory + '.tar') # append the tar archive filename to the returned tar_file_list list else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_tar_files(file_list): """Public function that removes temporary tar archive files in a local directory"""
for f in file_list: if file_exists(f) and f.endswith('.tar'): os.remove(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 _generate_tar(dir_path): """Private function that reads a local directory and generates a tar archive from it"""
try: with tarfile.open(dir_path + '.tar', 'w') as tar: tar.add(dir_path) except tarfile.TarError as e: stderr("Error: tar archive creation failed [" + str(e) + "]", exit=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 encrypt_file(self, inpath, force_nocompress=False, force_compress=False, armored=False, checksum=False): """public method for single file encryption with opt...
if armored: if force_compress: command_stub = self.command_maxcompress_armored elif force_nocompress: command_stub = self.command_nocompress_armored else: if self._is_compress_filetype(inpath): command_stub ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encrypt_files(self, file_list, force_nocompress=False, force_compress=False, armored=False, checksum=False): """public method for multiple file encryption wi...
for the_file in file_list: self.encrypt_file(the_file, force_nocompress, force_compress, armored, checksum)
<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_compress_filetype(self, inpath): """private method that performs magic number and size check on file to determine whether to compress the file"""
# check for common file type suffixes in order to avoid the need for file reads to check magic number for binary vs. text file if self._is_common_binary(inpath): return False elif self._is_common_text(inpath): return True else: # files > 10kB get chec...
<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_common_binary(self, inpath): """private method to compare file path mime type to common binary file types"""
# make local variables for the available char numbers in the suffix types to be tested two_suffix = inpath[-3:] three_suffix = inpath[-4:] four_suffix = inpath[-5:] # test for inclusion in the instance variable common_binaries (defined in __init__) if two_suffix...
<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_common_text(self, inpath): """private method to compare file path mime type to common text file types"""
# make local variables for the available char numbers in the suffix types to be tested one_suffix = inpath[-2:] two_suffix = inpath[-3:] three_suffix = inpath[-4:] four_suffix = inpath[-5:] # test for inclusion in the instance variable common_text (defined in __...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def knn_impute_few_observed( X, missing_mask, k, verbose=False, print_interval=100): """ Seems to be the fastest kNN implementation. Pre-sorts each rows neighbor...
start_t = time.time() n_rows, n_cols = X.shape # put the missing mask in column major order since it's accessed # one column at a time missing_mask_column_major = np.asarray(missing_mask, order="F") observed_mask_column_major = ~missing_mask_column_major X_column_major = X.copy(order="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 knn_initialize( X, missing_mask, verbose=False, min_dist=1e-6, max_dist_multiplier=1e6): """ Fill X with NaN values if necessary, construct the n_samples x n...
X_row_major = X.copy("C") if missing_mask.sum() != np.isnan(X_row_major).sum(): # if the missing values have already been zero-filled need # to put NaN's back in the data matrix for the distances function X_row_major[missing_mask] = np.nan D = all_pairs_normalized_distances(X_row_ma...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def all_pairs_normalized_distances_reference(X): """ Reference implementation of normalized all-pairs distance, used for testing the more efficient implementatio...
n_samples, n_cols = X.shape # matrix of mean squared difference between between samples D = np.ones((n_samples, n_samples), dtype="float32") * np.inf for i in range(n_samples): diffs = X - X[i, :].reshape((1, n_cols)) missing_diffs = np.isnan(diffs) missing_counts_per_row = miss...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def knn_impute_reference( X, missing_mask, k, verbose=False, print_interval=100): """ Reference implementation of kNN imputation logic. """
n_rows, n_cols = X.shape X_result, D, effective_infinity = \ knn_initialize(X, missing_mask, verbose=verbose) for i in range(n_rows): for j in np.where(missing_mask[i, :])[0]: distances = D[i, :].copy() # any rows that don't have the value we're currently trying ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def dashboard(request): "Counts, aggregations and more!" end_time = now() start_time = end_time - timedelta(days=7) defaults = {'start': start_time, 'end': end_time} form = DashboardForm(data=request.GET or defaults) if form.is_valid(): start_time = form.cleaned_data['start'] en...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def geoip_data(self): """Attempt to retrieve MaxMind GeoIP data based on visitor's IP."""
if not HAS_GEOIP or not TRACK_USING_GEOIP: return if not hasattr(self, '_geoip_data'): self._geoip_data = None try: gip = GeoIP(cache=GEOIP_CACHE_TYPE) self._geoip_data = gip.city(self.ip_address) except GeoIPException: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _make_obj(obj): """Takes an object and returns a corresponding API class. The names and values of the data will match exactly with those found in the online ...
if isinstance(obj, dict): if 'url' in obj.keys(): url = obj['url'] id_ = int(url.split('/')[-2]) # ID of the data. endpoint = url.split('/')[-3] # Where the data is located. return APIResource(endpoint, id_, lazy_load=True) return APIMetadata(...
<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(self): """Function to collect reference data and connect it to the instance as attributes. Internal function, does not usually need to be called by the...
data = get_data(self.endpoint, self.id_, force_lookup=self.__force_lookup) # Make our custom objects from the data. for key, val in data.items(): if key == 'location_area_encounters' \ and self.endpoint == 'pokemon': params = val.split('/')[-3...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def safe_make_dirs(path, mode=0o777): """Create a leaf directory and all intermediate ones in a safe way. A wrapper to os.makedirs() that handles existing leaf d...
try: os.makedirs(path, mode) except OSError as error: if error.errno != 17: # File exists raise return 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 get_default_cache(): """Get the default cache location. Adheres to the XDG Base Directory specification, as described in https://standards.freedesktop.org/ba...
xdg_cache_home = os.environ.get('XDG_CACHE_HOME') or \ os.path.join(os.path.expanduser('~'), '.cache') return os.path.join(xdg_cache_home, 'pokebase')
<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_cache(new_path=None): """Simple function to change the cache location. `new_path` can be an absolute or relative path. If the directory does not exist ye...
global CACHE_DIR, API_CACHE, SPRITE_CACHE if new_path is None: new_path = get_default_cache() CACHE_DIR = safe_make_dirs(os.path.abspath(new_path)) API_CACHE = os.path.join(CACHE_DIR, 'api.cache') SPRITE_CACHE = safe_make_dirs(os.path.join(CACHE_DIR, 'sprite')) return CACHE_DIR, API...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def attach(self, lun_or_snap, skip_hlu_0=False): """ Attaches lun, snap or member snap of cg snap to host. Don't pass cg snapshot in as `lun_or_snap`. :param lun...
# `UnityResourceAlreadyAttachedError` check was removed due to there # is a host cache existing in Cinder driver. If the lun was attached to # the host and the info was stored in the cache, wrong hlu would be # returned. # And attaching a lun to a host twice would success, if 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 has_hlu(self, lun_or_snap, cg_member=None): """Returns True if `lun_or_snap` is attached to the host. :param lun_or_snap: can be lun, lun snap, cg snap or a ...
hlu = self.get_hlu(lun_or_snap, cg_member=cg_member) return hlu is not None