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 find_candidates(document): """ Finds cadidate nodes for the readable version of the article. Here's we're going to remove unlikely nodes, find scores on the ...
nodes_to_score = set() should_remove = set() for node in document.iter(): if is_unlikely_node(node): logger.debug( "We should drop unlikely: %s %r", node.tag, node.attrib) should_remove.add(node) elif is_bad_link(node): logger.debug( ...
<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_bad_link(node): """ Helper to determine if the node is link that is useless. We've hit articles with many multiple links that should be cleaned out becaus...
if node.tag != "a": return False name = node.get("name") href = node.get("href") if name and not href: return True if href: href_parts = href.split("#") if len(href_parts) == 2 and len(href_parts[1]) > 25: return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def candidates(self): """Generates list of candidates from the DOM."""
dom = self.dom if dom is None or len(dom) == 0: return None candidates, unlikely_candidates = find_candidates(dom) drop_nodes_with_parents(unlikely_candidates) return candidates
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _readable(self): """The readable parsed article"""
if not self.candidates: logger.info("No candidates found in document.") return self._handle_no_candidates() # right now we return the highest scoring candidate content best_candidates = sorted( (c for c in self.candidates.values()), key=attrgette...
<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_no_candidates(self): """ If we fail to find a good candidate we need to find something else. """
# since we've not found a good candidate we're should help this if self.dom is not None and len(self.dom): dom = prep_article(self.dom) dom = build_base_document(dom, self._return_fragment) return self._remove_orphans( dom.get_element_by_id("readabili...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def fastaIterator(fastaFN): ''' Iterator that yields tuples containing a sequence label and the sequence itself @param fastaFN - the FASTA filename to open and parse @return - an iterator yielding tuples of the form (label, sequence) from the FASTA file ''' if fastaFN[len(fastaFN)-3:] == '.gz': ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def loadBWT(bwtDir, logger=None): ''' Generic load function, this is recommended for anyone wishing to use this code as it will automatically detect compression and assign the appropriate class preferring the decompressed version if both exist. @return - a MultiStringBWT, CompressedBWT, or none if neith...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def createMSBWTFromSeqs(seqArray, mergedDir, numProcs, areUniform, logger): ''' This function takes a series of sequences and creates the BWT using the technique from Cox and Bauer @param seqArray - a list of '$'-terminated sequences to be in the MSBWT @param mergedFN - the final destination filename fo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def createMSBWTFromFastq(fastqFNs, outputDir, numProcs, areUniform, logger): ''' This function takes fasta filenames and creates the BWT using the technique from Cox and Bauer by simply loading all string prior to computation @param fastqFNs - a list of fastq filenames to extract sequences from @par...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def createMSBWTFromBam(bamFNs, outputDir, numProcs, areUniform, logger): ''' This function takes a fasta filename and creates the BWT using the technique from Cox and Bauer @param bamFNs - a list of BAM filenames to extract sequences from, READS MUST BE SORTED BY NAME @param outputDir - the directory fo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def mergeNewSeqs(seqArray, mergedDir, numProcs, areUniform, logger): ''' This function takes a series of sequences and creates a big BWT by merging the smaller ones Mostly a test function, no real purpose to the tool as of now @param seqArray - a list of '$'-terminated strings to be placed into the 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 compareKmerProfiles(profileFN1, profileFN2): ''' This function takes two kmer profiles and compare them for similarity. @param profileFN1 - the first kmer-profile to compare to @param profileFN2 - the second kmer-profile to compare to @return - a tuple of the form (1-norm, 2-norm, sum of differe...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def parseProfileLine(fp): ''' Helper function for profile parsing @param fp - the file pointer to get the next line from @return - (kmer, kmerCount) as (string, int) ''' nextLine = fp.readline() if nextLine == None or nextLine == '': return (None, None) else: pieces = nex...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def reverseComplement(seq): ''' Helper function for generating reverse-complements ''' revComp = '' complement = {'A':'T', 'C':'G', 'G':'C', 'T':'A', 'N':'N', '$':'$'} for c in reversed(seq): revComp += complement[c] return revComp
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def countOccurrencesOfSeq(self, seq, givenRange=None): ''' This function counts the number of occurrences of the given sequence @param seq - the sequence to search for @param givenRange - the range to start from (if a partial search has already been run), default=whole range @ret...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def recoverString(self, strIndex, withIndex=False): ''' This will return the string that starts at the given index @param strIndex - the index of the string we want to recover @return - string that we found starting at the specified '$' index ''' retNums = [] indi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getOccurrenceOfCharAtIndex(self, sym, index): ''' This functions gets the FM-index value of a character at the specified position @param sym - the character to find the occurrence level @param index - the index we want to find the occurrence level at @return - the number of o...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def loadMsbwt(self, dirName, logger): ''' This functions loads a BWT file and constructs total counts, indexes start positions, and constructs an FM index in memory @param dirName - the directory to load, inside should be '<DIR>/comp_msbwt.npy' or it will fail ''' #open the 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 getCharAtIndex(self, index): ''' Used for searching, this function masks the complexity behind retrieving a specific character at a specific index in our compressed BWT. @param index - the index to retrieve the character from @param return - return the character in our BWT th...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getBWTRange(self, start, end): ''' This function masks the complexity of retrieving a chunk of the BWT from the compressed format @param start - the beginning of the range to retrieve @param end - the end of the range in normal python notation (bwt[end] is not part of the return) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def decompressBlocks(self, startBlock, endBlock): ''' This is mostly a helper function to get BWT range, but I wanted it to be a separate thing for use possibly in decompression @param startBlock - the index of the start block we will decode @param endBlock - the index of the fi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decode_html(html): """ Converts bytes stream containing an HTML page into Unicode. Tries to guess character encoding from meta tag of by "chardet" library. "...
if isinstance(html, unicode): return html match = CHARSET_META_TAG_PATTERN.search(html) if match: declared_encoding = match.group(1).decode("ASCII") # proceed unknown encoding as if it wasn't found at all with ignored(LookupError): return html.decode(declared_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 build_document(html_content, base_href=None): """Requires that the `html_content` not be None"""
assert html_content is not None if isinstance(html_content, unicode): html_content = html_content.encode("utf8", "xmlcharrefreplace") try: document = document_fromstring(html_content, parser=UTF8_PARSER) except (ParserError, XMLSyntaxError): raise ValueError("Failed to parse 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 _parse_properties(self): """Nodes have properties, which are facts like the name, description, url etc. Loop through each of them and set it as attributes on...
props_dict = self.data.get('properties', {}) for prop_name in self.KNOWN_PROPERTIES: if prop_name in props_dict: setattr(self, prop_name, props_dict.get(prop_name)) else: setattr(self, prop_name, 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 _parse_relationship(self): """Nodes have Relationships, and similarly to properties, we set it as an attribute on the Organization so we can make calls like ...
rs_dict = self.data.get('relationships', {}) for rs_name in self.KNOWN_RELATIONSHIPS: if rs_name in rs_dict: setattr( self, rs_name, Relationship(rs_name, rs_dict.get(rs_name))) else: # fill in other relationships with None 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 open(self): """ Reset time and counts. """
self.startTime = datetime.datetime.now() self.offset = 0 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 update(self, sent): """ Update self and parent with intermediate progress. """
self.offset = sent now = datetime.datetime.now() elapsed = (now - self.startTime).total_seconds() if elapsed > 0: mbps = (sent * 8 / (10 ** 6)) / elapsed else: mbps = None self._display(sent, now, self.name, mbps)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _display(self, sent, now, chunk, mbps): """ Display intermediate progress. """
if self.parent is not None: self.parent._display(self.parent.offset + sent, now, chunk, mbps) return elapsed = now - self.startTime if sent > 0 and self.total is not None and sent <= self.total: eta = (self.total - sent) * elapsed.total_seconds() / sent ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close(self): """ Stop overwriting display, or update parent. """
if self.parent: self.parent.update(self.parent.offset + self.offset) return self.output.write("\n") self.output.flush()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _printUUID(uuid, detail='word'): """ Return friendly abbreviated string for uuid. """
if not isinstance(detail, int): detail = detailNum[detail] if detail > detailNum['word']: return uuid if uuid is None: return None return "%s...%s" % (uuid[:4], uuid[-4:])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def skipDryRun(logger, dryRun, level=logging.DEBUG): """ Return logging function. When logging function called, will return True if action should be skipped. Log...
# This is an undocumented "feature" of logging module: # logging.log() requires a numeric level # logging.getLevelName() maps names to numbers if not isinstance(level, int): level = logging.getLevelName(level) return ( functools.partial(_logDryRun, logger, level) if dryRun e...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def listVolumes(self): """ Return list of all volumes in this Store's selected directory. """
for (vol, paths) in self.paths.items(): for path in paths: if path.startswith('/'): continue if path == '.': continue if self.userVolume is not None and os.path.basename(path) != self.userVolume: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getSendPath(self, volume): """ Get a path appropriate for sending the volume from this Store. The path may be relative or absolute in this Store. """
try: return self._fullPath(next(iter(self.getPaths(volume)))) except StopIteration: return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def selectReceivePath(self, paths): """ From a set of source paths, recommend a destination path. The paths are relative or absolute, in a source Store. The resu...
logger.debug("%s", paths) if not paths: path = os.path.basename(self.userPath) + '/Anon' try: # Relative paths are preferred path = [p for p in paths if not p.startswith("/")][0] except IndexError: # If no relative path, just use the fir...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _relativePath(self, fullPath): """ Return fullPath relative to Store directory. Return fullPath if fullPath is not inside directory. Return None if fullPath ...
if fullPath is None: return None assert fullPath.startswith("/"), fullPath path = os.path.relpath(fullPath, self.userPath) if not path.startswith("../"): return path elif self.ignoreExtraVolumes: return None else: return...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setSize(self, size, sizeIsEstimated): """ Update size. """
self._size = size self._sizeIsEstimated = sizeIsEstimated if self.fromVol is not None and size is not None and not sizeIsEstimated: Diff.theKnownSizes[self.toUUID][self.fromUUID] = size
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sendTo(self, dest, chunkSize): """ Send this difference to the dest Store. """
vol = self.toVol paths = self.sink.getPaths(vol) if self.sink == dest: logger.info("Keep: %s", self) self.sink.keep(self) else: # Log, but don't skip yet, so we can log more detailed skipped actions later skipDryRun(logger, dest.dryrun, '...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def writeInfoLine(self, stream, fromUUID, size): """ Write one line of diff information. """
if size is None or fromUUID is None: return if not isinstance(size, int): logger.warning("Bad size: %s", size) return stream.write(str("%s\t%s\t%d\n" % ( self.uuid, fromUUID, size, )))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def writeInfo(self, stream): """ Write information about diffs into a file stream for use later. """
for (fromUUID, size) in Diff.theKnownSizes[self.uuid].iteritems(): self.writeInfoLine(stream, fromUUID, size)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hasInfo(self): """ Will have information to write. """
count = len([None for (fromUUID, size) in Diff.theKnownSizes[self.uuid].iteritems() if size is not None and fromUUID is not None ]) return count > 0
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def readInfo(stream): """ Read previously-written information about diffs. """
try: for line in stream: (toUUID, fromUUID, size) = line.split() try: size = int(size) except Exception: logger.warning("Bad size: %s", size) continue logger.debug("diff info:...
<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(cls, vol): """ Convert uuid to Volume, if necessary. """
if isinstance(vol, cls): return vol elif vol is None: return None else: return cls(vol, 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 hasEdge(self, diff): """ Test whether edge is in this sink. """
return diff.toVol in [d.toVol for d in self.diffs[diff.fromVol]]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parseKeyName(self, name): """ Returns dict with fullpath, to, from. """
if name.endswith(Store.theInfoExtension): return {'type': 'info'} match = self.keyPattern.match(name) if not match: return None match = match.groupdict() match.update(type='diff') return match
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def humanize(number): """ Return a human-readable string for number. """
# units = ('bytes', 'KB', 'MB', 'GB', 'TB') # base = 1000 units = ('bytes', 'KiB', 'MiB', 'GiB', 'TiB') base = 1024 if number is None: return None pow = int(math.log(number, base)) if number > 0 else 0 pow = min(pow, len(units) - 1) mantissa = number / (base ** pow) return "...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def receive(self, path, diff, showProgress=True): """ Return a context manager for stream that will store a diff. """
directory = os.path.dirname(path) cmd = ["btrfs", "receive", "-e", directory] if Store.skipDryRun(logger, self.dryrun)("Command: %s", cmd): return None if not os.path.exists(directory): os.makedirs(directory) process = subprocess.Popen( cm...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iterDiffs(self): """ Return all diffs used in optimal network. """
nodes = self.nodes.values() nodes.sort(key=lambda node: self._height(node)) for node in nodes: yield node.diff
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _prune(self): """ Get rid of all intermediate nodes that aren't needed. """
done = False while not done: done = True for node in [node for node in self.nodes.values() if node.intermediate]: if not [dep for dep in self.nodes.values() if dep.previous == node.volume]: # logger.debug("Removing unnecessary node %s", node) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __compress_attributes(self, dic): """ This will convert all attributes that are list with only one item string into simple string. It seems that LDAP always ...
result = {} for k, v in dic.iteritems(): if isinstance(v, types.ListType) and len(v) == 1: if k not in ('msExchMailboxSecurityDescriptor', 'msExchSafeSendersHash', 'msExchBlockedSendersHash', 'replicationSignature', 'msExchSafeRecipientsHash', '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 _keepVol(self, vol): """ Mark this volume to be kept in path. """
if vol is None: return if vol in self.extraVolumes: del self.extraVolumes[vol] return if vol not in self.paths: raise Exception("%s not in %s" % (vol, self)) paths = [os.path.basename(path) for path in self.paths[vol]] newPath =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write(self, keyArgs): """ Write specified key arguments into data structure. """
# bytearray doesn't work with fcntl args = array.array('B', (0,) * self.size) self._struct.pack_into(args, 0, *list(self.yieldArgs(keyArgs))) return args
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def popValue(self, argList): """ Take a flat arglist, and pop relevent values and return as a value or tuple. """
# return self._Tuple(*[name for (name, typeObj) in self._types.items()]) return self._Tuple(*[typeObj.popValue(argList) for (name, typeObj) in self._types.items()])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read(self, structure): """ Read and advance. """
start = self.offset self.skip(structure.size) return structure.read(self.buf, start)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def readView(self, newLength=None): """ Return a view of the next newLength bytes, and skip it. """
if newLength is None: newLength = self.len result = self.peekView(newLength) self.skip(newLength) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def peekView(self, newLength): """ Return a view of the next newLength bytes. """
# Note: In Python 2.7, memoryviews can't be written to # by the struct module. (BUG) return memoryview(self.buf)[self.offset:self.offset + newLength]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def readBuffer(self, newLength): """ Read next chunk as another buffer. """
result = Buffer(self.buf, self.offset, newLength) self.skip(newLength) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _IOC(cls, dir, op, structure=None): """ Encode an ioctl id. """
control = cls(dir, op, structure) def do(dev, **args): return control(dev, **args) return do
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def IOWR(cls, op, structure): """ Returns an ioctl Device method with READ and WRITE arguments. """
return cls._IOC(READ | WRITE, op, structure)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bytes2uuid(b): """ Return standard human-friendly UUID. """
if b.strip(chr(0)) == '': return None s = b.encode('hex') return "%s-%s-%s-%s-%s" % (s[0:8], s[8:12], s[12:16], s[16:20], s[20:])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fullPath(self): """ Return full butter path from butter root. """
for ((dirTree, dirID, dirSeq), (dirPath, name)) in self.links.items(): try: path = self.fileSystem.volumes[dirTree].fullPath if path is not None: return path + ("/" if path[-1] != "/" else "") + dirPath + name except Exception: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def linuxPaths(self): """ Return full paths from linux root. The first path returned will be the path through the top-most mount. (Usually the root). """
for ((dirTree, dirID, dirSeq), (dirPath, name)) in self.links.items(): for path in self.fileSystem.volumes[dirTree].linuxPaths: yield path + "/" + dirPath + name if self.fullPath in self.fileSystem.mounts: yield self.fileSystem.mounts[self.fullPath]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def destroy(self): """ Delete this subvolume from the filesystem. """
path = next(iter(self.linuxPaths)) directory = _Directory(os.path.dirname(path)) with directory as device: device.SNAP_DESTROY(name=str(os.path.basename(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 copy(self, path): """ Make another snapshot of this into dirName. """
directoryPath = os.path.dirname(path) if not os.path.exists(directoryPath): os.makedirs(directoryPath) logger.debug('Create copy of %s in %s', os.path.basename(path), directoryPath) with self._snapshot() as source, _Directory(directoryPath) as dest: dest.SNAP_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 subvolumes(self): """ Subvolumes contained in this mount. """
self.SYNC() self._getDevices() self._getRoots() self._getMounts() self._getUsage() volumes = self.volumes.values() volumes.sort(key=(lambda v: v.fullPath)) return volumes
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _rescanSizes(self, force=True): """ Zero and recalculate quota sizes to subvolume sizes will be correct. """
status = self.QUOTA_CTL(cmd=BTRFS_QUOTA_CTL_ENABLE).status logger.debug("CTL Status: %s", hex(status)) status = self.QUOTA_RESCAN_STATUS() logger.debug("RESCAN Status: %s", status) if not status.flags: if not force: return self.QUOTA_RES...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def TLV_GET(attrs, attrNum, format): """ Get a tag-length-value encoded attribute. """
attrView = attrs[attrNum] if format == 's': format = str(attrView.len) + format try: (result,) = struct.unpack_from(format, attrView.buf, attrView.offset) except TypeError: # Working around struct.unpack_from issue #10212 (result,) = struct.unpack_from(format, str(bytear...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def TLV_PUT(attrs, attrNum, format, value): """ Put a tag-length-value encoded attribute. """
attrView = attrs[attrNum] if format == 's': format = str(attrView.len) + format struct.pack_into(format, attrView.buf, attrView.offset, 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 command(name, mode): """ Label a method as a command with name. """
def decorator(fn): commands[name] = fn.__name__ _Client._addMethod(fn.__name__, name, mode) return fn return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def diff(self, diff): """ Serialize to a dictionary. """
if diff is None: return None return dict( toVol=diff.toUUID, fromVol=diff.fromUUID, size=diff.size, sizeIsEstimated=diff.sizeIsEstimated, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _open(self): """ Open connection to remote host. """
if self._process is not None: return cmd = [ 'ssh', self._host, 'sudo', 'buttersink', '--server', '--mode', self._mode, self._directory ] logger.debug("Connecting with: %s", cmd)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _close(self): """ Close connection to remote host. """
if self._process is None: return self.quit() self._process.stdin.close() logger.debug("Waiting for ssh process to finish...") self._process.wait() # Wait for ssh session to finish. # self._process.terminate() # self._process.kill() 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 run(self): """ Run the server. Returns with system error code. """
normalized = os.path.normpath(self.path) + ("/" if self.path.endswith("/") else "") if self.path != normalized: sys.stderr.write("Please use full path '%s'" % (normalized,)) return -1 self.butterStore = ButterStore.ButterStore(None, self.path, self.mode, dryrun=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 _sendResult(self, result): """ Send parseable json result of command. """
# logger.debug("Result: %s", result) try: result = json.dumps(result) except Exception as error: result = json.dumps(self._errorInfo(command, error)) sys.stdout.write(result) sys.stdout.write("\n") sys.stdout.flush()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def version(self): """ Return kernel and btrfs version. """
return dict( buttersink=theVersion, btrfs=self.butterStore.butter.btrfsVersion, linux=platform.platform(), )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send(self, diffTo, diffFrom): """ Do a btrfs send. """
diff = self.toObj.diff(diffTo, diffFrom) self._open(self.butterStore.send(diff))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def receive(self, path, diffTo, diffFrom): """ Receive a btrfs diff. """
diff = self.toObj.diff(diffTo, diffFrom) self._open(self.butterStore.receive(diff, [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 fillVolumesAndPaths(self): """ Get all volumes for initialization. """
return [ (self.toDict.vol(vol), paths) for vol, paths in self.butterStore.paths.items() ]
<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_lists(keys=[], values=[], name='NT'): """ Map namedtuples given a pair of key, value lists. """
mapping = dict(zip(keys, values)) return mapper(mapping, _nt_name=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 load_json(data=None, path=None, name='NT'): """ Map namedtuples with json data. """
if data and not path: return mapper(json.loads(data), _nt_name=name) if path and not data: return mapper(json.load(path), _nt_name=name) if data and path: raise ValueError('expected one source and received two')
<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_yaml(data=None, path=None, name='NT'): """ Map namedtuples with yaml data. """
if data and not path: return mapper(yaml.load(data), _nt_name=name) if path and not data: with open(path, 'r') as f: data = yaml.load(f) return mapper(data, _nt_name=name) if data and path: raise ValueError('expected one source and received two')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mapper(mapping, _nt_name='NT'): """ Convert mappings to namedtuples recursively. """
if isinstance(mapping, Mapping) and not isinstance(mapping, AsDict): for key, value in list(mapping.items()): mapping[key] = mapper(value) return namedtuple_wrapper(_nt_name, **mapping) elif isinstance(mapping, list): return [mapper(item) for item in mapping] return mapp...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ignore(mapping): """ Use ignore to prevent a mapping from being mapped to a namedtuple. """
if isinstance(mapping, Mapping): return AsDict(mapping) elif isinstance(mapping, list): return [ignore(item) for item in mapping] return mapping
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ensure_dir(dir_path): """ If DIR_PATH does not exist, makes it. Failing that, raises Exception. Returns True if dir already existed; False if it had to be ma...
exists = dir_exists(dir_path) if not exists: try: os.makedirs(dir_path) except(Exception,RuntimeError), e: raise Exception("Unable to create directory %s. Cause %s" % (dir_path, e)) return exists
<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_openssl(): """ Validates OpenSSL to ensure it has TLS_FALLBACK_SCSV supported """
try: open_ssl_exe = which("openssl") if not open_ssl_exe: raise Exception("No openssl exe found in path") try: # execute a an invalid command to get output with available options # since openssl does not have a --help option unfortunately exe...
<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_against_current_config(self, current_rs_conf): """ Validates the member document against current rs conf 1- If there is a member in current config w...
# if rs is not configured yet then there is nothing to validate if not current_rs_conf: return my_host = self.get_host() current_member_confs = current_rs_conf['members'] err = None for curr_mem_conf in current_member_confs: if (self.id 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 get_dump_best_secondary(self, max_repl_lag=None): """ Returns the best secondary member to be used for dumping best = passives with least lags, if no passive...
secondary_lag_tuples = [] primary_member = self.get_primary_member() if not primary_member: raise MongoctlException("Unable to determine primary member for" " cluster '%s'" % self.id) master_status = primary_member.get_server().get_membe...
<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_replicaset_initialized(self): """ iterate on all members and check if any has joined the replica """
# it's possible isMaster returns an "incomplete" result if we # query a replica set member while it's loading the replica set config # https://jira.mongodb.org/browse/SERVER-13458 # let's try to detect this state before proceeding # seems like if the "secondary" field is presen...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def match_member_id(self, member_conf, current_member_confs): """ Attempts to find an id for member_conf where fom current members confs there exists a element. ...
if current_member_confs is None: return None for curr_mem_conf in current_member_confs: if is_same_address(member_conf['host'], curr_mem_conf['host']): return curr_mem_conf['_id'] return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_os_dist_info(): """ Returns the distribution info """
distribution = platform.dist() dist_name = distribution[0].lower() dist_version_str = distribution[1] if dist_name and dist_version_str: return dist_name, dist_version_str else: return None, 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 get_mongo_version(self): """ Gets mongo version of the server if it is running. Otherwise return version configured in mongoVersion property """
if self._mongo_version: return self._mongo_version mongo_version = self.read_current_mongo_version() if not mongo_version: mongo_version = self.get_configured_mongo_version() self._mongo_version = mongo_version return self._mongo_version
<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_server_build_info(self): """ issues a buildinfo command """
if self.is_online(): try: return self.get_mongo_client().server_info() except OperationFailure, ofe: log_exception(ofe) if "there are no users authenticated" in str(ofe): # this is a pymongo 3.6.1 regression where the b...
<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_db(self, db, dbname, retry=True): """ Returns True if we manage to auth to the given db, else False. """
log_verbose("Server '%s' attempting to authenticate to db '%s'" % (self.id, dbname)) login_user = self.get_login_user(dbname) username = None password = None auth_success = False if login_user: username = login_user["username"] if "password" 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 needs_repl_key(self): """ We need a repl key if you are auth + a cluster member + version is None or >= 2.0.0 """
cluster = self.get_cluster() return (self.supports_repl_key() and cluster is not None and cluster.get_repl_key() is not 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 exact_or_minor_exe_version_match(executable_name, exe_version_tuples, version): """ IF there is an exact match then use it OTHERWISE try to find a minor vers...
exe = exact_exe_version_match(executable_name, exe_version_tuples, version) if not exe: exe = minor_exe_version_match(executable_name, exe_version_tuples, ver...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def seconds(num): """ Pause for this many seconds """
now = pytime.time() end = now + num until(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 _pre_mongod_server_start(server, options_override=None): """ Does necessary work before starting a server 1- An efficiency step for arbiters running with --n...
lock_file_path = server.get_lock_file_path() no_journal = (server.get_cmd_option("nojournal") or (options_override and "nojournal" in options_override)) if (os.path.exists(lock_file_path) and server.is_arbiter_server() and no_journal): log_warning("WARNI...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare_mongod_server(server): """ Contains post start server operations """
log_info("Preparing server '%s' for use as configured..." % server.id) cluster = server.get_cluster() # setup the local users if server supports that if server.supports_local_users(): users.setup_server_local_users(server) if not server.is_cluster_member() or server.is_standa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _rlimit_min(one_val, nother_val): """Returns the more stringent rlimit value. -1 means no limit."""
if one_val < 0 or nother_val < 0 : return max(one_val, nother_val) else: return min(one_val, nother_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 parse(self, data): """ Converts a NetJSON 'NetworkGraph' object to a NetworkX Graph object,which is then returned. Additionally checks for protocol version, ...
graph = self._init_graph() # ensure is NetJSON NetworkGraph object if 'type' not in data or data['type'] != 'NetworkGraph': raise ParserError('Parse error, not a NetworkGraph object') # ensure required keys are present required_keys = ['protocol', 'version', 'metric'...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse(self, data): """ Converts a OpenVPN JSON to a NetworkX Graph object which is then returned. """
# initialize graph and list of aggregated nodes graph = self._init_graph() server = self._server_common_name # add server (central node) to graph graph.add_node(server) # data may be empty if data is None: clients = [] links = [] e...