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 rest, clean up and return the final best match. """
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( "We should drop bad link: %s %r", node.tag, node.attrib) should_remove.add(node) elif node.tag in SCORABLE_TAGS: nodes_to_score.add(node) return score_candidates(nodes_to_score), should_remove
<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 because they're just there to pollute the space. See tests for examples. """
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=attrgetter("content_score"), reverse=True) printer = PrettyPrinter(indent=2) logger.debug(printer.pformat(best_candidates)) # since we have several candidates, check the winner's siblings # for extra content winner = best_candidates[0] updated_winner = check_siblings(winner, self.candidates) updated_winner.node = prep_article(updated_winner.node) if updated_winner.node is not None: dom = build_base_document( updated_winner.node, self._return_fragment) else: logger.info( 'Had candidates but failed to find a cleaned winning DOM.') dom = self._handle_no_candidates() return self._remove_orphans(dom.get_element_by_id("readabilityBody"))
<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("readabilityBody")) else: logger.info("No document to use.") return build_error_document(self._return_fragment)
<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': fp = gzip.open(fastaFN, 'r') else: fp = open(fastaFN, 'r') label = '' segments = [] line = '' for line in fp: if line[0] == '>': if label != '': yield (label, ''.join(segments)) label = (line.strip('\n')[1:]).split(' ')[0] segments = [] else: segments.append(line.strip('\n')) if label != '' and len(segments) > 0: yield (label, ''.join(segments)) fp.close()
<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 neither can be instantiated ''' if os.path.exists(bwtDir+'/msbwt.npy'): msbwt = MultiStringBWT() msbwt.loadMsbwt(bwtDir, logger) return msbwt elif os.path.exists(bwtDir+'/comp_msbwt.npy'): msbwt = CompressedMSBWT() msbwt.loadMsbwt(bwtDir, logger) return msbwt else: logger.error('Invalid BWT directory.') 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 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 for the BWT @param numProcs - the number of processes it's allowed to use ''' #wipe the auxiliary data stored here MSBWTGen.clearAuxiliaryData(mergedDir) #TODO: do we want a special case for N=1? there was one in early code, but we could just assume users aren't dumb seqFN = mergedDir+'/seqs.npy' offsetFN = mergedDir+'/offsets.npy' #sort the sequences seqCopy = sorted(seqArray) if areUniform: uniformLength = len(seqArray[0]) else: uniformLength = 0 #join into one massive string seqCopy = ''.join(seqCopy) #convert the sequences into uint8s and then save it seqCopy = np.fromstring(seqCopy, dtype='<u1') MSBWTGen.writeSeqsToFiles(seqCopy, seqFN, offsetFN, uniformLength) MSBWTGen.createFromSeqs(seqFN, offsetFN, mergedDir+'/msbwt.npy', numProcs, areUniform, logger)
<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 @param outputDir - the directory for all of the bwt related data @param numProcs - the number of processes it's allowed to use @areUniform - true if all the sequences passed into the function are of equal length ''' #generate the files we will reference and clear out the in memory array before making the BWT logger.info('Saving sorted sequences...') seqFN = outputDir+'/seqs.npy' offsetFN = outputDir+'/offsets.npy' abtFN = outputDir+'/about.npy' bwtFN = outputDir+'/msbwt.npy' MSBWTGen.clearAuxiliaryData(outputDir) preprocessFastqs(fastqFNs, seqFN, offsetFN, abtFN, areUniform, logger) MSBWTGen.createFromSeqs(seqFN, offsetFN, bwtFN, numProcs, areUniform, logger)
<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 for all of the bwt related data @param numProcs - the number of processes it's allowed to use @areUniform - true if all the sequences passed into the function are of equal length ''' #generate the files we will reference and clear out the in memory array before making the BWT logger.info('Saving sorted sequences...') seqFN = outputDir+'/seqs.npy' offsetFN = outputDir+'/offsets.npy' abtFN = outputDir+'/about.npy' bwtFN = outputDir+'/msbwt.npy' MSBWTGen.clearAuxiliaryData(outputDir) preprocessBams(bamFNs, seqFN, offsetFN, abtFN, areUniform, logger) MSBWTGen.createFromSeqs(seqFN, offsetFN, bwtFN, numProcs, areUniform, logger)
<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 array @param mergedFN - the final destination filename for the merged BWT @param numProcs - the number of processors the merge is allowed to create ''' #first wipe away any traces of old information for the case of overwriting a BWT at mergedFN MSBWTGen.clearAuxiliaryData(mergedDir) #create two smaller ones midPoint = len(seqArray)/3 mergedDir1 = mergedDir+'0' mergedDir2 = mergedDir+'1' mergedDir3 = mergedDir+'2' try: shutil.rmtree(mergedDir1) except: pass try: shutil.rmtree(mergedDir2) except: pass try: shutil.rmtree(mergedDir3) except: pass os.makedirs(mergedDir1) os.makedirs(mergedDir2) os.makedirs(mergedDir3) createMSBWTFromSeqs(seqArray[0:midPoint], mergedDir1, numProcs, areUniform, logger) createMSBWTFromSeqs(seqArray[midPoint:2*midPoint], mergedDir2, numProcs, areUniform, logger) createMSBWTFromSeqs(seqArray[2*midPoint:], mergedDir3, numProcs, areUniform, logger) #now do the actual merging MSBWTGen.mergeNewMSBWT(mergedDir, [mergedDir1, mergedDir2, mergedDir3], numProcs, logger)
<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 differences, normalized Dot product) ''' fp1 = open(profileFN1, 'r') fp2 = open(profileFN2, 'r') oneNorm = 0 twoNorm = 0 sumDeltas = 0 dotProduct = 0 tot1 = float(fp1.readline().strip('\n').split(',')[1]) tot2 = float(fp2.readline().strip('\n').split(',')[1]) (seq1, count1) = parseProfileLine(fp1) (seq2, count2) = parseProfileLine(fp2) while seq1 != None or seq2 != None: if seq1 == seq2: delta = abs(count1/tot1-count2/tot2) dotProduct += (count1/tot1)*(count2/tot2) (seq1, count1) = parseProfileLine(fp1) (seq2, count2) = parseProfileLine(fp2) elif seq2 == None or (seq1 != None and seq1 < seq2): delta = count1/tot1 (seq1, count1) = parseProfileLine(fp1) else: delta = count2/tot2 (seq2, count2) = parseProfileLine(fp2) if delta > oneNorm: oneNorm = delta twoNorm += delta*delta sumDeltas += delta fp1.close() fp2.close() twoNorm = math.sqrt(twoNorm) #print '1-norm:\t\t'+str(oneNorm) #print '2-norm:\t\t'+str(twoNorm) #print 'Delta sum:\t'+str(sumDeltas) return (oneNorm, twoNorm, sumDeltas, dotProduct)
<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 = nextLine.strip('\n').split(',') return (pieces[0], int(pieces[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 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 @return - an integer count of the number of times seq occurred in this BWT ''' #init the current range if givenRange == None: if not self.searchCache.has_key(seq[-self.cacheDepth:]): res = self.findIndicesOfStr(seq[-self.cacheDepth:]) self.searchCache[seq[-self.cacheDepth:]] = (int(res[0]), int(res[1])) l, h = self.searchCache[seq[-self.cacheDepth:]] seq = seq[0:-self.cacheDepth] else: l = givenRange[0] h = givenRange[1] #reverse sequence and convert to ints so we can iterate through it revSeq = [self.charToNum[c] for c in reversed(seq)] for c in revSeq: #get the start and end offsets l = self.getOccurrenceOfCharAtIndex(c, l) h = self.getOccurrenceOfCharAtIndex(c, h) #early exit for counts if l == h: return 0 #return the difference return h - l
<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 = [] indices = [] #figure out the first hop backwards currIndex = strIndex prevChar = self.getCharAtIndex(currIndex) currIndex = self.getOccurrenceOfCharAtIndex(prevChar, currIndex) #while we haven't looped back to the start while currIndex != strIndex: #update the string retNums.append(prevChar) if withIndex: indices.append(currIndex) #figure out where to go from here prevChar = self.getCharAtIndex(currIndex) currIndex = self.getOccurrenceOfCharAtIndex(prevChar, currIndex) for i in xrange(0, self.vcLen): if strIndex < self.endIndex[i]: retNums.append(i) break if withIndex: indices.append(strIndex) #reverse the numbers, convert to characters, and join them in to a single sequence ret = ''.join(self.numToChar[retNums[::-1]]) #return what we found if withIndex: return (ret, indices[::-1]) else: return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def 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 occurrences of char before the specified index ''' #sampling method #get the bin we occupy binID = index >> self.bitPower #these two methods seem to have the same approximate run time if (binID << self.bitPower) == index: ret = self.partialFM[binID][sym] else: ret = self.partialFM[binID][sym] + np.bincount(self.bwt[binID << self.bitPower:index], minlength=6)[sym] return int(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 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 with our BWT in it self.dirName = dirName self.bwt = np.load(self.dirName+'/comp_msbwt.npy', 'r') #build auxiliary structures self.constructTotalCounts(logger) self.constructIndexing() self.constructFMIndex(logger)
<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 that's at a particular index (integer format) ''' #get the bin we should start from binID = index >> self.bitPower bwtIndex = self.refFM[binID] #these are the values that indicate how far in we really are trueIndex = np.sum(self.partialFM[binID])-self.offsetSum dist = index-trueIndex #calculate how big of a region we actually need to 'decompress' if binID == self.refFM.shape[0]-1: endRange = self.bwt.shape[0] else: endRange = self.refFM[binID+1]+1 while endRange < self.bwt.shape[0] and (self.bwt[endRange] & self.mask) == (self.bwt[endRange-1] & self.mask): endRange += 1 #extract the symbols and counts associated with each byte letters = np.bitwise_and(self.bwt[bwtIndex:endRange], self.mask) counts = np.right_shift(self.bwt[bwtIndex:endRange], self.letterBits, dtype='<u8') #numpy methods for find the powers i = 1 same = (letters[0:-1] == letters[1:]) while np.count_nonzero(same) > 0: (counts[i:])[same] *= self.numPower i += 1 same = np.bitwise_and(same[0:-1], same[1:]) #these are the true counts after raising to the appropriate power cs = np.cumsum(counts) x = np.searchsorted(cs, dist, 'right') return letters[x]
<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) @return - a range of integers representing the characters in the bwt from start to end ''' #set aside an array block to fill startBlockIndex = start >> self.bitPower endBlockIndex = int(math.floor(float(end)/self.binSize)) trueStart = startBlockIndex*self.binSize #first we will extract the range of blocks return self.decompressBlocks(startBlockIndex, endBlockIndex)[start-trueStart:end-trueStart]
<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 final block we will decode, if they are the same, we decode one block @return - an array of size blockSize*(endBlock-startBlock+1), interpreting that block is up to getBWTRange(...) ''' expectedIndex = startBlock*self.binSize trueIndex = np.sum(self.partialFM[startBlock])-self.offsetSum dist = expectedIndex - trueIndex #find the end of the region of interest startRange = self.refFM[startBlock] if endBlock >= self.refFM.shape[0]-1: endRange = self.bwt.shape[0] returnSize = self.binSize*(endBlock-startBlock)+(self.totalSize % self.binSize) else: endRange = self.refFM[endBlock+1]+1 returnSize = self.binSize*(endBlock-startBlock+1) while endRange < self.bwt.shape[0] and (self.bwt[endRange] & self.mask) == (self.bwt[endRange-1] & self.mask): endRange += 1 ret = np.zeros(dtype='<u1', shape=(returnSize,)) #split the letters and numbers in the compressed bwt letters = np.bitwise_and(self.bwt[startRange:endRange], self.mask) counts = np.right_shift(self.bwt[startRange:endRange], self.letterBits, dtype='<u8') #multiply counts where needed i = 1 same = (letters[0:-1] == letters[1:]) while np.count_nonzero(same) > 0: (counts[i:])[same] *= self.numPower i += 1 same = np.bitwise_and(same[0:-1], same[1:]) #now I have letters and counts, time to fill in the array s = 0 lInd = 0 while dist > 0: if counts[lInd] < dist: dist -= counts[lInd] lInd += 1 else: counts[lInd] -= dist dist = 0 #we're at the correct letter index now while s < ret.shape[0]: if lInd >= letters.shape[0]: pass ret[s:s+counts[lInd]] = letters[lInd] s += counts[lInd] lInd += 1 return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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_encoding, "ignore") # try to enforce UTF-8 firstly with ignored(UnicodeDecodeError): return html.decode("utf8") text = TAG_MARK_PATTERN.sub(to_bytes(" "), html) diff = text.decode("utf8", "ignore").encode("utf8") sizes = len(diff), len(text) # 99% of text is UTF-8 if abs(len(text) - len(diff)) < max(sizes) * 0.01: return html.decode("utf8", "ignore") # try detect encoding encoding = "utf8" encoding_detector = chardet.detect(text) if encoding_detector["encoding"]: encoding = encoding_detector["encoding"] return html.decode(encoding, "ignore")
<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 document contents.") if base_href: document.make_links_absolute(base_href, resolve_base_href=True) else: document.resolve_base_href() return document
<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 this company so that we can make calls like company.name person.description """
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 company.current_team person.degrees """
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 values setattr(self, rs_name, NoneRelationshipSingleton)
<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 eta = datetime.timedelta(seconds=eta) else: eta = None self.output.write( "\r %s: Sent %s%s%s ETA: %s (%s) %s%20s\r" % ( elapsed, util.humanize(sent), "" if self.total is None else " of %s" % (util.humanize(self.total),), "" if self.total is None else " (%d%%)" % (int(100 * sent / self.total),), eta, "" if not mbps else "%.3g Mbps " % (mbps,), chunk or "", " ", ) ) 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 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 will indicate if skipped because of dry run. """
# 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 else functools.partial(logger.log, level) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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: continue yield vol 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 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 result will be absolute, suitable for this destination Store. """
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 first path path = os.path.relpath(list(paths)[0], self.userPath) return self._fullPath(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 _relativePath(self, fullPath): """ Return fullPath relative to Store directory. Return fullPath if fullPath is not inside directory. Return None if fullPath is outside our scope. """
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 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 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, 'INFO')("Xfer: %s", self) receiveContext = dest.receive(self, paths) sendContext = self.sink.send(self) # try: # receiveContext.metadata['btrfsVersion'] = self.btrfsVersion # except AttributeError: # pass transfer(sendContext, receiveContext, chunkSize) if vol.hasInfo(): infoContext = dest.receiveVolumeInfo(paths) if infoContext is None: # vol.writeInfo(sys.stdout) pass else: with infoContext as stream: vol.writeInfo(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 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: %s %s %d", toUUID, fromUUID, size) Diff.theKnownSizes[toUUID][fromUUID] = size except Exception as error: logger.warn("Can't read .bs info file (%s)", error)
<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 "%.4g %s" % (mantissa, units[pow])
<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( cmd, stdin=subprocess.PIPE, stderr=subprocess.PIPE, stdout=DEVNULL, ) _makeNice(process) return _Writer(process, process.stdin, path, diff, showProgress)
<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) del self.nodes[node.volume] done = 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 __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 return lists, even when it doesn t make sense. :param dic: :return: """
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', 'sIDHistory', 'msRTCSIP-UserRoutingGroupId', 'mSMQDigests', 'mSMQSignCertificates', 'msExchMasterAccountSid', 'msExchPreviousAccountSid', 'msExchUMPinChecksum', 'userSMIMECertificate', 'userCertificate', 'userCert', 'msExchDisabledArchiveGUID', 'msExchUMPinChecksum', 'msExchUMSpokenName', 'objectSid', 'objectGUID', 'msExchArchiveGUID', 'thumbnailPhoto', 'msExchMailboxGuid'): try: result[k] = v[0].decode('utf-8') except Exception as e: logging. error("Failed to decode attribute: %s -- %s" % (k, e)) result[k] = v[0] return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _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 = self.selectReceivePath(paths) if self._skipDryRun(logger, 'INFO')("Copy %s to %s", vol, newPath): return self.butterVolumes[vol.uuid].copy(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: logging.debug("Haven't imported %d yet", dirTree) if self.id == BTRFS_FS_TREE_OBJECTID: return "/" else: return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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_CREATE_V2( flags=BTRFS_SUBVOL_RDONLY, name=str(os.path.basename(path)), fd=source.fd, ) with SnapShot(path) as destShot: flags = destShot.SUBVOL_GETFLAGS() destShot.SUBVOL_SETFLAGS(flags=flags.flags & ~BTRFS_SUBVOL_RDONLY) destShot.SET_RECEIVED_SUBVOL( uuid=self.received_uuid or self.uuid, stransid=self.sent_gen or self.current_gen, stime=timeOrNone(self.info.stime) or timeOrNone(self.info.ctime) or 0, flags=0, ) destShot.SUBVOL_SETFLAGS(flags=flags.flags)
<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_RESCAN() logger.warn("Waiting for btrfs quota usage scan...") self.QUOTA_RESCAN_WAIT()
<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(bytearray(attrView.buf)), attrView.offset) 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 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) self._process = subprocess.Popen( cmd, stdin=subprocess.PIPE, stderr=sys.stderr, # stdout=sys.stdout, stdout=subprocess.PIPE, ) version = self.version() logger.info("Remote version: %s", 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 _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._process = 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 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) # self.butterStore.ignoreExtraVolumes = True self.toObj = _Arg2Obj(self.butterStore) self.toDict = _Obj2Dict() self.running = True with self.butterStore: with self: while self.running: self._processCommand() return 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 _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 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 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 made. """
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 execute_command([open_ssl_exe, "s_client", "invalidDummyCommand"]) except subprocess.CalledProcessError as e: if "fallback_scsv" not in e.output: raise Exception("openssl does not support TLS_FALLBACK_SCSV") except Exception as e: raise MongoctlException("Unsupported OpenSSL. %s" % 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 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 with _id equals to my id then ensure hosts addresses resolve to the same host 2- If there is a member in current config with host resolving to my host then ensure that if my id is et then it must equal member._id """
# 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 self.id == curr_mem_conf['_id'] and not is_same_address(my_host, curr_mem_conf['host'])): err = ("Member config is not consistent with current rs " "config. \n%s\n. Both have the sam _id but addresses" " '%s' and '%s' do not resolve to the same host." % (document_pretty_string(curr_mem_conf), my_host, curr_mem_conf['host'] )) elif (is_same_address(my_host, curr_mem_conf['host']) and self.id and self.id != curr_mem_conf['_id']): err = ("Member config is not consistent with current rs " "config. \n%s\n. Both addresses" " '%s' and '%s' resolve to the same host but _ids '%s'" " and '%s' are not equal." % (document_pretty_string(curr_mem_conf), my_host, curr_mem_conf['host'], self.id, curr_mem_conf['_id'])) if err: raise MongoctlException("Invalid member configuration:\n%s \n%s" % (self, err))
<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 passives then least lag """
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_member_rs_status() if not master_status: raise MongoctlException("Unable to determine replicaset status for" " primary member '%s'" % primary_member.get_server().id) for member in self.get_members(): if member.get_server().is_secondary(): repl_lag = member.get_server().get_repl_lag(master_status) if max_repl_lag and repl_lag > max_repl_lag: log_info("Excluding member '%s' because it's repl lag " "(in seconds)%s is more than max %s. " % (member.get_server().id, repl_lag, max_repl_lag)) continue secondary_lag_tuples.append((member,repl_lag)) def best_secondary_comp(x, y): x_mem, x_lag = x y_mem, y_lag = y if x_mem.is_passive(): if y_mem.is_passive(): return x_lag - y_lag else: return -1 elif y_mem.is_passive(): return 1 else: return x_lag - y_lag if secondary_lag_tuples: secondary_lag_tuples.sort(best_secondary_comp) return secondary_lag_tuples[0][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 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 present, but "setName" isn't, # it's a good indicator that we just need to wait a bit # add an uptime check in for good measure for member in self.get_members(): server = member.get_server() if server.has_joined_replica(): 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 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. Returns the id of an element of current confs WHERE member_conf.host and element.host are EQUAL or map to same host """
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 buildinfo command fails on non authenticated client # fall-back to an authenticated client admin_db = self.get_db("admin", no_auth=False) return admin_db.command("buildinfo") except Exception, e: log_exception(e) 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 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 login_user: password = login_user["password"] # have three attempts to authenticate no_tries = 0 while not auth_success and no_tries < 3: if not username: username = read_username(dbname) if not password: password = self.lookup_password(dbname, username) if not password: password = read_password("Enter password for user '%s\%s'"% (dbname, username)) # if auth success then exit loop and memoize login try: auth_success = db.authenticate(username, password) log_verbose("Authentication attempt #%s to db '%s' result: %s" % (no_tries, dbname, auth_success)) except OperationFailure, ofe: if "auth fails" in str(ofe): auth_success = False if auth_success or not retry: break else: log_error("Invalid login!") username = None password = None no_tries += 1 if auth_success: self.set_login_user(dbname, username, password) log_verbose("Authentication Succeeded!") else: log_verbose("Authentication failed") return auth_success
<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 version match """
exe = exact_exe_version_match(executable_name, exe_version_tuples, version) if not exe: exe = minor_exe_version_match(executable_name, exe_version_tuples, version) return 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 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 --no-journal * there is a lock file ==> * server must not have exited cleanly from last run, and does not know how to auto-recover (as a journalled server would) * however: this is an arbiter, therefore * there is no need to repair data files in any way ==> * i can rm this lockfile and start my server """
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("WARNING: Detected a lock file ('%s') for your server '%s'" " ; since this server is an arbiter, there is no need for" " repair or other action. Deleting mongod.lock and" " proceeding..." % (lock_file_path, server.id)) try: os.remove(lock_file_path) except Exception, e: log_exception(e) raise MongoctlException("Error while trying to delete '%s'. " "Cause: %s" % (lock_file_path, 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 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_standalone_config_server(): users.setup_server_users(server) if cluster and server.is_primary(): users.setup_cluster_users(cluster, server)
<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, revision and metric. """
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', 'nodes', 'links'] for key in required_keys: if key not in data: raise ParserError('Parse error, "{0}" key not found'.format(key)) # store metadata self.protocol = data['protocol'] self.version = data['version'] self.revision = data.get('revision') # optional self.metric = data['metric'] # create graph for node in data['nodes']: graph.add_node(node['id'], label=node['label'] if 'label' in node else None, local_addresses=node.get('local_addresses', []), **node.get('properties', {})) for link in data['links']: try: source = link["source"] dest = link["target"] cost = link["cost"] except KeyError as e: raise ParserError('Parse error, "%s" key not found' % e) properties = link.get('properties', {}) graph.add_edge(source, dest, weight=cost, **properties) return graph
<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 = [] else: clients = data.client_list.values() links = data.routing_table.values() # add clients in graph as nodes for client in clients: if client.common_name == 'UNDEF': continue client_properties = { 'label': client.common_name, 'real_address': str(client.real_address.host), 'port': int(client.real_address.port), 'connected_since': client.connected_since.strftime('%Y-%m-%dT%H:%M:%SZ'), 'bytes_received': int(client.bytes_received), 'bytes_sent': int(client.bytes_sent) } local_addresses = [ str(route.virtual_address) for route in data.routing_table.values() if route.real_address == client.real_address ] if local_addresses: client_properties['local_addresses'] = local_addresses graph.add_node(str(client.real_address.host), **client_properties) # add links in routing table to graph for link in links: if link.common_name == 'UNDEF': continue graph.add_edge(server, str(link.real_address.host), weight=1) return graph