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 _findSubsetProteins(proteins, protToPeps, pepToProts): """Find proteins which peptides are a sub-set, but not a same-set to other proteins. :param proteins: ...
proteinsEqual = lambda prot1, prot2: protToPeps[prot1] == protToPeps[prot2] subGroups = list() for protein in proteins: peptideCounts = Counter() for peptide in protToPeps[protein]: proteins = pepToProts[peptide] peptideCounts.update(proteins) peptideCount =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _findRedundantProteins(protToPeps, pepToProts, proteins=None): """Returns a set of proteins with redundant peptide evidence. After removing the redundant pro...
if proteins is None: proteins = viewkeys(protToPeps) pepFrequency = _getValueCounts(pepToProts) protPepCounts = _getValueCounts(protToPeps) getCount = operator.itemgetter(1) getProt = operator.itemgetter(0) #TODO: quick and dirty solution #NOTE: add a test for merged proteins ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _mergeProteinEntries(proteinLists, protToPeps): """Returns a new "protToPeps" dictionary with entries merged that are present in proteinLists. NOTE: The key ...
mergedProtToPeps = dict(protToPeps) for proteins in proteinLists: for protein in proteins: peptides = mergedProtToPeps.pop(protein) mergedProtein = tuple(sorted(proteins)) mergedProtToPeps[mergedProtein] = peptides return mergedProtToPeps
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _reducedProtToPeps(protToPeps, proteins): """Returns a new, reduced "protToPeps" dictionary that does not contain entries present in "proteins". :param protT...
return {k: v for k, v in viewitems(protToPeps) if k not in proteins}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _findUniqueMappingKeys(mapping): """Find mapping keys that only have one entry (value length of 1. :param mapping: dict, for each key contains a set of entri...
uniqueMappingKeys = set() for key, entries in viewitems(mapping): if len(entries) == 1: uniqueMappingKeys.add(key) return uniqueMappingKeys
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _invertMapping(mapping): """Converts a protein to peptide or peptide to protein mapping. :param mapping: dict, for each key contains a set of entries :return...
invertedMapping = ddict(set) for key, values in viewitems(mapping): for value in values: invertedMapping[value].add(key) return invertedMapping
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _mappingGetValueSet(mapping, keys): """Return a combined set of values from the mapping. :param mapping: dict, for each key contains a set of entries returns...
setUnion = set() for k in keys: setUnion = setUnion.union(mapping[k]) return setUnion
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _flattenMergedProteins(proteins): """Return a set where merged protein entries in proteins are flattened. :param proteins: an iterable of proteins, can conta...
proteinSet = set() for protein in proteins: if isinstance(protein, tuple): proteinSet.update(protein) else: proteinSet.add(protein) return proteinSet
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getGroups(self, proteinId): """Return a list of protein groups a protein is associated with."""
return [self.groups[gId] for gId in self._proteinToGroupIds[proteinId]]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addProteinGroup(self, groupRepresentative): """Adds a new protein group and returns the groupId. The groupId is defined using an internal counter, which is i...
groupId = self._getNextGroupId() self.groups[groupId] = ProteinGroup(groupId, groupRepresentative) self.addLeadingToGroups(groupRepresentative, groupId) return groupId
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addLeadingToGroups(self, proteinIds, groupIds): """Add one or multiple leading proteins to one or multiple protein groups. :param proteinIds: a proteinId or ...
for groupId in AUX.toList(groupIds): self.groups[groupId].addLeadingProteins(proteinIds) self._addProteinIdsToGroupMapping(proteinIds, groupId)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addSubsetToGroups(self, proteinIds, groupIds): """Add one or multiple subset proteins to one or multiple protein groups. :param proteinIds: a proteinId or a ...
for groupId in AUX.toList(groupIds): self.groups[groupId].addSubsetProteins(proteinIds) self._addProteinIdsToGroupMapping(proteinIds, groupId)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addSubsumableToGroups(self, proteinIds, groupIds): """Add one or multiple subsumable proteins to one or multiple protein groups. :param proteinIds: a protein...
for groupId in AUX.toList(groupIds): self.groups[groupId].addSubsumableProteins(proteinIds) self._addProteinIdsToGroupMapping(proteinIds, groupId)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _addProteinIdsToGroupMapping(self, proteinIds, groupId): """Add a groupId to one or multiple entries of the internal proteinToGroupId mapping. :param protein...
for proteinId in AUX.toList(proteinIds): self._proteinToGroupIds[proteinId].add(groupId)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _addProteins(self, proteinIds, containerNames): """Add one or multiple proteinIds to the respective container. :param proteinIds: a proteinId or a list of pr...
proteinIds = AUX.toList(proteinIds) for containerName in containerNames: proteinContainer = getattr(self, containerName) proteinContainer.update(proteinIds)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def satisfies(self, other): """Check if the capabilities of a primitive are enough to satisfy a requirement. Should be called on a Requirement that is acting as ...
if other.isnocare: return True if self.isnocare: return False if self.arbitrary: return True if self.constant and not other.arbitrary: return True if self.value is other.value and not other.arbitrary\ and not other.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 _list(self, foldername="INBOX", reverse=False, since=None): """Do structured list output. Sorts the list by date, possibly reversed, filtered from 'since'. T...
folder = self.folder \ if foldername == "INBOX" \ else self._getfolder(foldername) def sortcmp(d): try: return d[1].date except: return -1 lst = folder.items() if not since else folder.items_since(since) 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 ls(self, foldername="INBOX", reverse=False, since=None, grep=None, field=None, stream=sys.stdout): """Do standard text list of the folder to the stream. 'fol...
if foldername == "": foldername = "INBOX" msg_list = self._list(foldername, reverse, since) for folder, mk, m in msg_list: try: # I am very unsure about this defaulting of foldername output_items = ( "%s%s%s" % (folder...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lisp(self, foldername="INBOX", reverse=False, since=None, stream=sys.stdout): """Do JSON list of the folder to the stream. 'since' allows the listing to be d...
def fromval(hdr): if hdr: return parseaddr(hdr) for folder, mk, m in self._list(foldername, reverse, since): try: print(json.dumps({ 'folder': folder.folder or foldername or "INBOX", 'key': "%s%s%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 lsfolders(self, stream=sys.stdout): """List the subfolders"""
for f in self.folder.folders(): print(f.folder.strip("."), file=stream)
<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, msgid): """Yields the message header against each part from the message."""
foldername, msgkey = msgid.split(SEPERATOR) folder = self.folder if foldername == "INBOX" else self._getfolder(foldername) # Now look up the message msg = folder[msgkey] msg.is_seen = True hdr = list(msg.items()) for p in msg.walk(): yield hdr,p ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gettext(self, msgid, stream=sys.stdout, splitter="--text follows this line--\n"): """Get the first text part we can find and print it as a message. This is a...
for hdr,part in self._get(msgid): if part.get_content_type() == "text/plain": for name,val in hdr: # Use the subtype, since we're printing just that - tidy it up first if name.lower() == "content-type": val = part["cont...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getrawpart(self, msgid, stream=sys.stdout): """Get the first part from the message and print it raw. """
for hdr, part in self._get(msgid): pl = part.get_payload(decode=True) if pl != None: print(pl, file=stream) break
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getrawpartid(self, msgid, partid, stream=sys.stdout): """Get a specific part from the message and print it raw. """
parts = [part for hdr,part in self._get(msgid)] part = parts[int(partid)] pl = part.get_payload(decode=True) if pl != None: print(pl, file=stream)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getraw(self, msgid, stream=sys.stdout): """Get the whole message and print it. """
foldername, msgkey = msgid.split(SEPERATOR) folder = self.folder if foldername == "INBOX" else self._getfolder(foldername) msg = folder[msgkey] print(msg.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 getstruct(self, msgid, as_json=False, stream=sys.stdout): """Get and print the whole message. as_json indicates whether to print the part list as JSON or not...
parts = [part.get_content_type() for hdr, part in self._get(msgid)] if as_json: print(json.dumps(parts), file=stream) else: for c in parts: print(c, file=stream)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _extract_alphabet(self, grammar): """ Extract an alphabet from the given grammar. """
alphabet = set([]) for terminal in grammar.Terminals: alphabet |= set([x for x in terminal]) self.alphabet = list(alphabet)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def action(self, column=None, value=None, **kwargs): """ The underlying GICS table provides codes and descriptions identifying the current status or disposition ...
return self._resolve_call('GIC_ACTION', column, value, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def applicant(self, column=None, value=None, **kwargs): """ Find the applicant information for a grant. """
return self._resolve_call('GIC_APPLICANT', column, value, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def authority(self, column=None, value=None, **kwargs): """Provides codes and associated authorizing statutes."""
return self._resolve_call('GIC_AUTHORITY', column, value, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def construction(self, column=None, value=None, **kwargs): """ Identifies monetary, descriptive, and milestone information for Wastewater Treatment construction ...
return self._resolve_call('GIC_CONSTRUCTION', column, value, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def eligible_cost(self, column=None, value=None, **kwargs): """ The assistance dollar amounts by eligible cost category. """
return self._resolve_call('GIC_ELIGIBLE_COST', column, value, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def grant(self, column=None, value=None, **kwargs): """ Provides various award, project, and grant personnel information. """
return self._resolve_call('GIC_GRANT', column, value, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def grant_assistance(self, column=None, value=None, **kwargs): """Many-to-many table connecting grants and assistance."""
return self._resolve_call('GIC_GRANT_ASST_PGM', column, value, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def grant_authority(self, column=None, value=None, **kwargs): """Many-to-many table connecting grants and authority."""
return self._resolve_call('GIC_GRANT_AUTH', column, value, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lab_office(self, column=None, value=None, **kwargs): """Abbreviations, names, and locations of labratories and offices."""
return self._resolve_call('GIC_LAB_OFFICE', column, value, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def milestone(self, column=None, value=None, **kwargs): """ Status codes and related dates of certain grants, """
return self._resolve_call('GIC_MILESTONE', column, value, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def record_type(self, column=None, value=None, **kwargs): """ Codes and descriptions indicating whether an award is for a new project or for the continuation of ...
return self._resolve_call('GIC_RECORD_TYPE', column, value, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def srf_cap(self, column=None, value=None, **kwargs): """ Fiscal dollar amounts for State Revolving Fund Capitalization Grants. """
return self._resolve_call('GIC_SRF_CAP', column, value, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def status(self, column=None, value=None, **kwargs): """ Provides codes and descriptions of project milestones. """
return self._resolve_call('GIC_STATUS', column, value, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def recRemoveTreeFormating(element): """Removes whitespace characters, which are leftovers from previous xml formatting. :param element: an instance of lxml.etre...
children = element.getchildren() if len(children) > 0: for child in children: recRemoveTreeFormating(child) if element.text is not None: if len(element.text.strip()) == 0: element.text = None else: element.text = element.text.strip() if elemen...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def recCopyElement(oldelement): """Generates a copy of an xml element and recursively of all child elements. :param oldelement: an instance of lxml.etree._Elemen...
newelement = ETREE.Element(oldelement.tag, oldelement.attrib) if len(oldelement.getchildren()) > 0: for childelement in oldelement.getchildren(): newelement.append(recCopyElement(childelement)) return newelement
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getParam(xmlelement): """Converts an mzML xml element to a param tuple. :param xmlelement: #TODO docstring :returns: a param tuple or False if the xmlelement...
elementTag = clearTag(xmlelement.tag) if elementTag in ['userParam', 'cvParam', 'referenceableParamGroupRef']: if elementTag == 'cvParam': param = cvParamFromDict(xmlelement.attrib) elif elementTag == 'userParam': param = userParamFromDict(xmlelement.attrib) 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 xmlAddParams(parentelement, params): """Generates new mzML parameter xml elements and adds them to the 'parentelement' as xml children elements. :param paren...
if not params: return None for param in params: if len(param) == 3: cvAttrib = {'cvRef': param[0].split(':')[0], 'accession': param[0], 'name':oboTranslator.getNameWithId(param[0]) } if param[1]: cvAttrib.up...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def interpretBitEncoding(bitEncoding): """Returns a floattype string and a numpy array type. :param bitEncoding: Must be either '64' or '32' :returns: (floattype...
if bitEncoding == '64': floattype = 'd' # 64-bit numpyType = numpy.float64 elif bitEncoding == '32': floattype = 'f' # 32-bit numpyType = numpy.float32 else: errorText = ''.join(['bitEncoding \'', bitEncoding, '\' not defined. ', 'Must 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 calc_partition_function(mass, omega_array, temperature_array): """ Calculates the partition function of your system at each point in time. Parameters mass : ...
Kappa_t= mass*omega_array**2 return _np.sqrt(4*_np.pi**2*_scipy.constants.Boltzmann**2*temperature_array**2/(mass*Kappa_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 calc_mean_and_variance_of_variances(self, NumberOfOscillations): """ Calculates the mean and variance of a set of varainces. This set is obtained by splittin...
SplittedArraySize = int(self.SampleFreq/self.FTrap.n) * NumberOfOscillations VoltageArraySize = len(self.voltage) SnippetsVariances = _np.var(self.voltage[:VoltageArraySize-_np.mod(VoltageArraySize,SplittedArraySize)].reshape(-1,SplittedArraySize),axis=1) return _np.mean(SnippetsVarian...
<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_template_directory(kb_app: kb, sphinx_app: Sphinx, sphinx_env: BuildEnvironment, docnames=List[str], ): """ Add this resource's templates dir to tem...
template_bridge = sphinx_app.builder.templates actions = ResourceAction.get_callbacks(kb_app) for action in actions: f = os.path.dirname(inspect.getfile(action)) template_bridge.loaders.append(SphinxFileSystemLoader(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 add_directives(kb_app: kb, sphinx_app: Sphinx, sphinx_env: BuildEnvironment, docnames=List[str], ): """ For each resource type, register a new Sphinx directi...
for k, v in list(kb_app.config.resources.items()): sphinx_app.add_directive(k, ResourceDirective)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stamp_title(kb_app: kb, sphinx_app: Sphinx, doctree: doctree): """ Walk the tree and extra RST title into resource.title """
# First, find out which resource this is. Won't be easy. resources = sphinx_app.env.resources confdir = sphinx_app.confdir source = PurePath(doctree.attributes['source']) # Get the relative path inside the docs dir, without .rst, then # get the resource docname = str(source.relative_to(co...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_exception(error): """Simple method for handling exceptions raised by `PyBankID`. :param flask_pybankid.FlaskPyBankIDError error: The exception to hand...
response = jsonify(error.to_dict()) response.status_code = error.status_code return response
<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_from_pybankid_exception(cls, exception): """Class method for initiating from a `PyBankID` exception. :param bankid.exceptions.BankIDError exception: :...
return cls( "{0}: {1}".format(exception.__class__.__name__, str(exception)), _exception_class_to_status_code.get(exception.__class__), )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_dict(self): """Create a dict representation of this exception. :return: The dictionary representation. :rtype: dict """
rv = dict(self.payload or ()) rv["message"] = self.message return rv
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def integers(num, minimum, maximum, base=10): # TODO: Ensure numbers within bounds """Random integers within specified interval. The integer generator generates ...
function = 'integers' num, minimum, maximum = list(map(int, [num, minimum, maximum])) # INPUT ERROR CHECKING # Check input values are within range if (1 <= num <= 10 ** 4) is False: print('ERROR: %s is out of range' % num) return if (-10 ** 9 <= minimum <= 10 ** 9) is 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 sequence(minimum, maximum): """Randomize a sequence of integers."""
function = 'sequences' opts = {'min': minimum, 'max': maximum, 'col': 1, 'format': 'plain', 'rnd': 'new'} deal = get_http(RANDOM_URL, function, opts) deal_arr = str_to_arr(deal) return deal_arr
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def string(num, length, digits=False, upper=True, lower=True, unique=False): """Random strings."""
function = 'strings' # Convert arguments to random.org style # for a discussion on the method see: http://bit.ly/TKGkOF digits = convert(digits) upper = convert(upper) lower = convert(lower) unique = convert(unique) opts = {'num': num, 'len': length, 'digits': d...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def quota(ip=None): """Check your quota."""
# TODO: Add arbitrary user defined IP check url = 'http://www.random.org/quota/?format=plain' data = urlopen(url) credit = int(data.read().strip()) if data.code == 200: return credit else: return "ERROR: Server responded with code %s" % data.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 get_http(base_url, function, opts): """HTTP request generator."""
url = (os.path.join(base_url, function) + '/?' + urlencode(opts)) data = urlopen(url) if data.code != 200: raise ValueError("Random.rg returned server code: " + str(data.code)) return data.read()
<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(*p): """Build a file path from paths and return the contents."""
with open(os.path.join(*p), 'r') as fi: return fi.read()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute(self, processProtocol, command, env={}, path=None, uid=None, gid=None, usePTY=0, childFDs=None): """Form a command and start a process in the desired...
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(self, command, env={}, path=None, uid=None, gid=None, usePTY=0, childFDs=None): """Execute a command and return the results of the completed run. """
deferred = defer.Deferred() processProtocol = _SummaryProcessProtocol(deferred) d = defer.maybeDeferred(self.execute, processProtocol, command, env, path, uid, gid, usePTY, childFDs) d.addErrback(deferred.errback) return deferred
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getOutput(self, command, env={}, path=None, uid=None, gid=None, usePTY=0, childFDs=None): """Execute a command and get the output of the finished process. ""...
deferred = defer.Deferred() processProtocol = _SummaryProcessProtocol(deferred) self.execute(processProtocol, command, env, path, uid, gid, usePTY, childFDs) @deferred.addCallback def getStdOut(tuple_): stdout, _stderr, _returnCode = tuple_ ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getExitCode(self, command, env={}, path=None, uid=None, gid=None, usePTY=0, childFDs=None): """Execute a command and get the return code of the finished proc...
deferred = defer.Deferred() processProtocol = _SummaryProcessProtocol(deferred) self.execute(processProtocol, command, env, path, uid, gid, usePTY, childFDs) @deferred.addCallback def getStdOut(tuple_): _stdout, _stderr, exitCode = tuple_ ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_task(original_task): """ Validates task and adds default values for missing options using the following steps. 1. If there is no input list specifie...
task = original_task._asdict() # Default values for inputs and outputs if 'inputs' not in task or task['inputs'] is None: task['inputs'] = ['*'] # Outputs list cannot be empty if ('outputs' not in task or task['outputs'] is None or len(task['outputs']) == 0): 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 run_task(task, workspace): """ Runs the task and updates the workspace with results. Parameters task - dict Task Description Examples: {'task': task_func, 'i...
data = copy.copy(workspace) task = validate_task(task) # Prepare input to task inputs = [input_parser(key, data) for key in task.inputs] if inspect.isgeneratorfunction(task.fn): # Multiple output task # Assuming number of outputs are equal to number of return values 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 run_hook(name, workspace, hooks): """Runs all hooks added under the give name. Parameters name - str Name of the hook to invoke workspace - dict Workspace th...
data = copy.copy(workspace) for hook_listener in hooks.get(name, []): # Hook functions may mutate the data and returns nothing hook_listener(data) return 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 add_task(self, fn, inputs=None, outputs=None): """ Adds a task to the workflow. Returns self to facilitate chaining method calls """
# self.tasks.append({'task': task, 'inputs': inputs, 'outputs': outputs}) self.tasks.append(Task(fn, inputs, outputs)) return self
<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_hook(self, name, function): """ Adds a function to be called for hook of a given name. The function gets entire workspace as input and does not return an...
if not callable(function): return ValueError('Hook function should be callable') if name not in self.hooks: self.hooks[name] = [] self.hooks[name].append(function) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dns(self): """DNS details."""
dns = { 'elb': self.dns_elb(), 'elb_region': self.dns_elb_region(), 'global': self.dns_global(), 'region': self.dns_region(), 'instance': self.dns_instance(), } return dns
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def s3_app_bucket(self, include_region=False): """Generate s3 application bucket name. Args: include_region (bool): Include region in the name generation. """
if include_region: s3_app_bucket = self.format['s3_app_region_bucket'].format(**self.data) else: s3_app_bucket = self.format['s3_app_bucket'].format(**self.data) return s3_app_bucket
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shared_s3_app_bucket(self, include_region=False): """Generate shared s3 application bucket name. Args: include_region (bool): Include region in the name gen...
if include_region: shared_s3_app_bucket = self.format['shared_s3_app_region_bucket'].format(**self.data) else: shared_s3_app_bucket = self.format['shared_s3_app_bucket'].format(**self.data) return shared_s3_app_bucket
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iam(self): """Generate iam details."""
iam = { 'group': self.format['iam_group'].format(**self.data), 'lambda_role': self.format['iam_lambda_role'].format(**self.data), 'policy': self.format['iam_policy'].format(**self.data), 'profile': self.format['iam_profile'].format(**self.data), 'role...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def archaius(self): """Generate archaius bucket path."""
bucket = self.format['s3_bucket'].format(**self.data) path = self.format['s3_bucket_path'].format(**self.data) archaius_name = self.format['s3_archaius_name'].format(**self.data) archaius = {'s3': archaius_name, 'bucket': bucket, 'path': path} return archaius
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def jenkins(self): """Generate jenkins job details."""
job_name = self.format['jenkins_job_name'].format(**self.data) job = {'name': job_name} return job
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gitlab(self): """Generate gitlab details."""
main_name = self.format['git_repo'].format(**self.data) qe_name = self.format['git_repo_qe'].format(**self.data) config_name = self.format['git_repo_configs'].format(**self.data) git = { 'config': config_name, 'main': main_name, 'qe': qe_name, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_value_matched_by_regex(field_name, regex_matches, string): """Ensure value stored in regex group exists."""
try: value = regex_matches.group(field_name) if value is not None: return value except IndexError: pass raise MissingFieldError(string, field_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 positive_int(val): """Parse `val` into a positive integer."""
if isinstance(val, float): raise ValueError('"{}" must not be a float'.format(val)) val = int(val) if val >= 0: return val raise ValueError('"{}" must be positive'.format(val))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def strictly_positive_int_or_none(val): """Parse `val` into either `None` or a strictly positive integer."""
val = positive_int_or_none(val) if val is None or val > 0: return val raise ValueError('"{}" must be strictly positive'.format(val))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _attributeLinesToDict(attributeLines): """Converts a list of obo 'Term' lines to a dictionary. :param attributeLines: a list of obo 'Term' lines. Each line c...
attributes = dict() for line in attributeLines: attributeId, attributeValue = line.split(':', 1) attributes[attributeId.strip()] = attributeValue.strip() return 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 _termIsObsolete(oboTerm): """Determine wheter an obo 'Term' entry is marked as obsolete. :param oboTerm: a dictionary as return by :func:`maspy.ontology._att...
isObsolete = False if u'is_obsolete' in oboTerm: if oboTerm[u'is_obsolete'].lower() == u'true': isObsolete = True return isObsolete
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def discover_handler_classes(handlers_package): """ Looks for handler classes within handler path module. Currently it's not looking deep into nested module. :pa...
if handlers_package is None: return # Add working directory into PYTHONPATH to import developer packages sys.path.insert(0, os.getcwd()) package = import_module(handlers_package) # Continue searching for module if package is not a module if hasattr(package, '__path__'): for _...
<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_multi_word_keywords(features): """This returns an OrderedDict containing the multi word keywords in order of length. This is so the tokenizer will match ...
keys = { 'is not': Token(TokenTypes.NOT_EQUAL, 'is not'), } return OrderedDict(sorted(list(keys.items()), key=lambda t: len(t[0]), reverse=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 inside_try(func, options={}): """ decorator to silence exceptions, for logging we want a "safe" fail of the functions """
if six.PY2: name = func.func_name else: name = func.__name__ @wraps(func) def silenceit(*args, **kwargs): """ the function func to be silenced is wrapped inside a try catch and returned, exceptions are logged exceptions are returned in an error dict take...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start(self): """ Start the server and run forever. """
Server().start(self.options,self.handler_function, self.__class__.component_type)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sort_entries(self): """Get whether reverse is True or False. Return the sorted data."""
return sorted(self.data, key=self.sort_func, reverse=self.get_reverse())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def visible_fields(self): """ Returns the reduced set of visible fields to output from the form. This method respects the provided ``fields`` configuration _and_...
form_visible_fields = self.form.visible_fields() if self.render_fields: fields = self.render_fields else: fields = [field.name for field in form_visible_fields] filtered_fields = [field for field in fields if field not in self.exclude_fields] return [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 get_fieldsets(self, fieldsets=None): """ This method returns a generator which yields fieldset instances. The method uses the optional fieldsets argument to ...
fieldsets = fieldsets or self.fieldsets if not fieldsets: raise StopIteration # Search for primary marker in at least one of the fieldset kwargs. has_primary = any(fieldset.get('primary') for fieldset in fieldsets) for fieldset_kwargs in fieldsets: fie...
<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_chunks(Array, Chunksize): """Generator that yields chunks of size ChunkSize"""
for i in range(0, len(Array), Chunksize): yield Array[i:i + Chunksize]
<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_data_from_bin_file(fileName): """ Loads the binary data stored in the a binary file and extracts the data for each channel that was saved, along with th...
with open(fileName, mode='rb') as file: # b is important -> binary fileContent = file.read() (ChannelData, LenOf1Channel, NumOfChannels, SampleTime) = read_data_from_bytes(fileContent) return ChannelData, LenOf1Channel, NumOfChannels, SampleTime
<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_data_from_bytes(fileContent): """ Takes the binary data stored in the binary string provided and extracts the data for each channel that was saved, alon...
TotalDataLen = struct.unpack('Q', fileContent[:8])[0] # Unsigned long long NumOfChannels = struct.unpack('I', fileContent[8:12])[0] # unsigned Long SampleTime = struct.unpack('d', fileContent[12:20])[0] AllChannelData = struct.unpack("f" * ((len(fileContent) -20) // 4), fileContent[20:]) # ignor...
<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_coord_box(centre_x, centre_y, distance): """Get the square boundary coordinates for a given centre and distance"""
"""Todo: return coordinates inside a circle, rather than a square""" return { 'top_left': (centre_x - distance, centre_y + distance), 'top_right': (centre_x + distance, centre_y + distance), 'bottom_left': (centre_x - distance, centre_y - distance), 'bottom_right': (centre_x + d...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fleet_ttb(unit_type, quantity, factories, is_techno=False, is_dict=False, stasis_enabled=False): """ Calculate the time taken to construct a given fleet """
unit_weights = { UNIT_SCOUT: 1, UNIT_DESTROYER: 13, UNIT_BOMBER: 10, UNIT_CRUISER: 85, UNIT_STARBASE: 1, } govt_weight = 80 if is_dict else 100 prod_weight = 85 if is_techno else 100 weighted_qty = unit_weights[unit_type] * quantity ttb = (weighted_qty...
<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_fasta(data): # pragma: no cover """ Load sequences in Fasta format. This generator function yields a Sequence object for each sequence record in a GFF3...
name, seq = None, [] for line in data: line = line.rstrip() if line.startswith('>'): if name: yield Sequence(name, ''.join(seq)) name, seq = line, [] else: seq.append(line) if name: yield Sequence(name, ''.join(seq))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _reset(self): """Clear internal data structure."""
self.records = list() self.featsbyid = dict() self.featsbyparent = dict() self.countsbytype = dict()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_by_label(self, label): """ Return the first item with a specific label, or None. """
return next((x for x in self if x.label == label), 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 getGenericAnswers(self, name, instruction, prompts): """Called when the server requests keyboard interactive authentication """
responses = [] for prompt, _echo in prompts: password = self.getPassword(prompt) responses.append(password) return defer.succeed(responses)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pairwise(iterable): """ Generate consecutive pairs of elements from the given iterable. """
iterator = iter(iterable) try: first = next(iterator) except StopIteration: return for element in iterator: yield first, element first = element
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def https_policy_from_config(config): """ Create an ``IPolicyForHTTPS`` which can authenticate a Kubernetes API server. :param KubeConfig config: A Kubernetes co...
server = config.cluster["server"] base_url = URL.fromText(native_string_to_unicode(server)) ca_certs = pem.parse(config.cluster["certificate-authority"].bytes()) if not ca_certs: raise ValueError("No certificate authority certificate found.") ca_cert = ca_certs[0] try: # Valid...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def authenticate_with_certificate_chain(reactor, base_url, client_chain, client_key, ca_cert): """ Create an ``IAgent`` which can issue authenticated requests to...
if base_url.scheme != u"https": raise ValueError( "authenticate_with_certificate() makes sense for HTTPS, not {!r}".format( base_url.scheme ), ) netloc = NetLocation(host=base_url.host, port=base_url.port) policy = ClientCertificatePolicyForHTTPS( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def authenticate_with_certificate(reactor, base_url, client_cert, client_key, ca_cert): """ See ``authenticate_with_certificate_chain``. :param pem.Certificate c...
return authenticate_with_certificate_chain( reactor, base_url, [client_cert], client_key, ca_cert, )