_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q239200 | EmulatedDevice.trace_sync | train | def trace_sync(self, data, timeout=5.0):
"""Send tracing data and wait for it to finish.
This awaitable coroutine wraps VirtualIOTileDevice.trace() and turns
the callback into an awaitable object. The appropriate usage of this
method is by calling it inside the event loop as:
... | python | {
"resource": ""
} |
q239201 | EmulatedDevice.stream_sync | train | def stream_sync(self, report, timeout=120.0):
"""Send a report and wait for it to finish.
This awaitable coroutine wraps VirtualIOTileDevice.stream() and turns
the callback into an awaitable object. The appropriate usage of this
method is by calling it inside the event loop as:
... | python | {
"resource": ""
} |
q239202 | EmulatedDevice.synchronize_task | train | def synchronize_task(self, func, *args, **kwargs):
"""Run callable in the rpc thread and wait for it to finish.
The callable ``func`` will be passed into the EmulationLoop and run
there. This method will block until ``func`` is finished and
return/raise whatever that callable returns/r... | python | {
"resource": ""
} |
q239203 | EmulatedDevice.load_metascenario | train | def load_metascenario(self, scenario_list):
"""Load one or more scenarios from a list.
Each entry in scenario_list should be a dict containing at least a
name key and an optional tile key and args key. If tile is present
and its value is not None, the scenario specified will be loaded ... | python | {
"resource": ""
} |
q239204 | DataStream.associated_stream | train | def associated_stream(self):
"""Return the corresponding output or storage stream for an important system input.
Certain system inputs are designed as important and automatically
copied to output streams without requiring any manual interaction.
This method returns the corresponding st... | python | {
"resource": ""
} |
q239205 | DataStream.FromString | train | def FromString(cls, string_rep):
"""Create a DataStream from a string representation.
The format for stream designators when encoded as strings is:
[system] (buffered|unbuffered|constant|input|count|output) <integer>
Args:
string_rep (str): The string representation to turn... | python | {
"resource": ""
} |
q239206 | DataStream.FromEncoded | train | def FromEncoded(self, encoded):
"""Create a DataStream from an encoded 16-bit unsigned integer.
Returns:
DataStream: The decoded DataStream object
"""
stream_type = (encoded >> 12) & 0b1111
stream_system = bool(encoded & (1 << 11))
stream_id = (encoded & ((1... | python | {
"resource": ""
} |
q239207 | DataStreamSelector.as_stream | train | def as_stream(self):
"""Convert this selector to a DataStream.
This function will only work if this is a singular selector that
matches exactly one DataStream.
"""
if not self.singular:
raise ArgumentError("Attempted to convert a non-singular selector to a data stre... | python | {
"resource": ""
} |
q239208 | DataStreamSelector.FromStream | train | def FromStream(cls, stream):
"""Create a DataStreamSelector from a DataStream.
Args:
stream (DataStream): The data stream that we want to convert.
"""
if stream.system:
specifier = DataStreamSelector.MatchSystemOnly
else:
specifier = DataStre... | python | {
"resource": ""
} |
q239209 | DataStreamSelector.FromEncoded | train | def FromEncoded(cls, encoded):
"""Create a DataStreamSelector from an encoded 16-bit value.
The binary value must be equivalent to what is produced by
a call to self.encode() and will turn that value back into
a a DataStreamSelector.
Note that the following operation is a no-op... | python | {
"resource": ""
} |
q239210 | DataStreamSelector.FromString | train | def FromString(cls, string_rep):
"""Create a DataStreamSelector from a string.
The format of the string should either be:
all <type>
OR
<type> <id>
Where type is [system] <stream type>, with <stream type>
defined as in DataStream
Args:
rep ... | python | {
"resource": ""
} |
q239211 | DataStreamSelector.matches | train | def matches(self, stream):
"""Check if this selector matches the given stream
Args:
stream (DataStream): The stream to check
Returns:
bool: True if this selector matches the stream
"""
if self.match_type != stream.stream_type:
return False
... | python | {
"resource": ""
} |
q239212 | DataStreamSelector.encode | train | def encode(self):
"""Encode this stream as a packed 16-bit unsigned integer.
Returns:
int: The packed encoded stream
"""
match_id = self.match_id
if match_id is None:
match_id = (1 << 11) - 1
return (self.match_type << 12) | DataStreamSelector.S... | python | {
"resource": ""
} |
q239213 | generate | train | def generate(env):
"""Add Builders and construction variables for m4 to an Environment."""
M4Action = SCons.Action.Action('$M4COM', '$M4COMSTR')
bld = SCons.Builder.Builder(action = M4Action, src_suffix = '.m4')
env['BUILDERS']['M4'] = bld
# .m4 files might include other files, and it would be pre... | python | {
"resource": ""
} |
q239214 | generate | train | def generate(env):
"""Add Builders and construction variables for LaTeX to an Environment."""
env.AppendUnique(LATEXSUFFIXES=SCons.Tool.LaTeXSuffixes)
from . import dvi
dvi.generate(env)
from . import pdf
pdf.generate(env)
bld = env['BUILDERS']['DVI']
bld.add_action('.ltx', LaTeXAuxA... | python | {
"resource": ""
} |
q239215 | Rfc5424SysLogHandler.encode_priority | train | def encode_priority(self, facility, priority):
"""
Encode the facility and priority. You can pass in strings or
integers - if strings are passed, the facility_names and
priority_names mapping dictionaries are used to convert them to
integers.
"""
return (facility ... | python | {
"resource": ""
} |
q239216 | Rfc5424SysLogHandler.close | train | def close(self):
"""
Closes the socket.
"""
self.acquire()
try:
if self.transport is not None:
self.transport.close()
super(Rfc5424SysLogHandler, self).close()
finally:
self.release() | python | {
"resource": ""
} |
q239217 | sonTraceRootPath | train | def sonTraceRootPath():
"""
function for finding external location
"""
import sonLib.bioio
i = os.path.abspath(sonLib.bioio.__file__)
return os.path.split(os.path.split(os.path.split(i)[0])[0])[0] | python | {
"resource": ""
} |
q239218 | linOriginRegression | train | def linOriginRegression(points):
"""
computes a linear regression starting at zero
"""
j = sum([ i[0] for i in points ])
k = sum([ i[1] for i in points ])
if j != 0:
return k/j, j, k
return 1, j, k | python | {
"resource": ""
} |
q239219 | close | train | def close(i, j, tolerance):
"""
check two float values are within a bound of one another
"""
return i <= j + tolerance and i >= j - tolerance | python | {
"resource": ""
} |
q239220 | filterOverlappingAlignments | train | def filterOverlappingAlignments(alignments):
"""Filter alignments to be non-overlapping.
"""
l = []
alignments = alignments[:]
sortAlignments(alignments)
alignments.reverse()
for pA1 in alignments:
for pA2 in l:
if pA1.contig1 == pA2.contig1 and getPositiveCoordinateRange... | python | {
"resource": ""
} |
q239221 | binaryTree_depthFirstNumbers | train | def binaryTree_depthFirstNumbers(binaryTree, labelTree=True, dontStopAtID=True):
"""
get mid-order depth first tree numbers
"""
traversalIDs = {}
def traverse(binaryTree, mid=0, leafNo=0):
if binaryTree.internal and (dontStopAtID or binaryTree.iD is None):
midStart = mid
... | python | {
"resource": ""
} |
q239222 | binaryTree_nodeNames | train | def binaryTree_nodeNames(binaryTree):
"""
creates names for the leave and internal nodes
of the newick tree from the leaf labels
"""
def fn(binaryTree, labels):
if binaryTree.internal:
fn(binaryTree.left, labels)
fn(binaryTree.right, labels)
labels[binaryT... | python | {
"resource": ""
} |
q239223 | makeRandomBinaryTree | train | def makeRandomBinaryTree(leafNodeNumber=None):
"""Creates a random binary tree.
"""
while True:
nodeNo = [-1]
def fn():
nodeNo[0] += 1
if random.random() > 0.6:
i = str(nodeNo[0])
return BinaryTree(0.00001 + random.random()*0.8, True, f... | python | {
"resource": ""
} |
q239224 | getRandomBinaryTreeLeafNode | train | def getRandomBinaryTreeLeafNode(binaryTree):
"""Get random binary tree node.
"""
if binaryTree.internal == True:
if random.random() > 0.5:
return getRandomBinaryTreeLeafNode(binaryTree.left)
else:
return getRandomBinaryTreeLeafNode(binaryTree.right)
else:
... | python | {
"resource": ""
} |
q239225 | transformByDistance | train | def transformByDistance(wV, subModel, alphabetSize=4):
"""
transform wV by given substitution matrix
"""
nc = [0.0]*alphabetSize
for i in xrange(0, alphabetSize):
j = wV[i]
k = subModel[i]
for l in xrange(0, alphabetSize):
nc[l] += j * k[l]
return nc | python | {
"resource": ""
} |
q239226 | normaliseWV | train | def normaliseWV(wV, normFac=1.0):
"""
make char probs divisible by one
"""
f = sum(wV) / normFac
return [ i/f for i in wV ] | python | {
"resource": ""
} |
q239227 | felsensteins | train | def felsensteins(binaryTree, subMatrices, ancestorProbs, leaves, alphabetSize):
"""
calculates the un-normalised probabilties of each non-gap residue position
"""
l = {}
def upPass(binaryTree):
if binaryTree.internal: #is internal binaryTree
i = branchUp(binaryTree.left)
... | python | {
"resource": ""
} |
q239228 | annotateTree | train | def annotateTree(bT, fn):
"""
annotate a tree in an external array using the given function
"""
l = [None]*bT.traversalID.midEnd
def fn2(bT):
l[bT.traversalID.mid] = fn(bT)
if bT.internal:
fn2(bT.left)
fn2(bT.right)
fn2(bT)
return l | python | {
"resource": ""
} |
q239229 | remodelTreeRemovingRoot | train | def remodelTreeRemovingRoot(root, node):
"""
Node is mid order number
"""
import bioio
assert root.traversalID.mid != node
hash = {}
def fn(bT):
if bT.traversalID.mid == node:
assert bT.internal == False
return [ bT ]
elif bT.internal:
i = ... | python | {
"resource": ""
} |
q239230 | moveRoot | train | def moveRoot(root, branch):
"""
Removes the old root and places the new root at the mid point along the given branch
"""
import bioio
if root.traversalID.mid == branch:
return bioio.newickTreeParser(bioio.printBinaryTree(root, True))
def fn2(tree, seq):
if seq is not None:
... | python | {
"resource": ""
} |
q239231 | checkGeneTreeMatchesSpeciesTree | train | def checkGeneTreeMatchesSpeciesTree(speciesTree, geneTree, processID):
"""
Function to check ids in gene tree all match nodes in species tree
"""
def fn(tree, l):
if tree.internal:
fn(tree.left, l)
fn(tree.right, l)
else:
l.append(processID(tree.iD))
... | python | {
"resource": ""
} |
q239232 | calculateProbableRootOfGeneTree | train | def calculateProbableRootOfGeneTree(speciesTree, geneTree, processID=lambda x : x):
"""
Goes through each root possible branch making it the root.
Returns tree that requires the minimum number of duplications.
"""
#get all rooted trees
#run dup calc on each tree
#return tree with fewest num... | python | {
"resource": ""
} |
q239233 | redirectLoggerStreamHandlers | train | def redirectLoggerStreamHandlers(oldStream, newStream):
"""Redirect the stream of a stream handler to a different stream
"""
for handler in list(logger.handlers): #Remove old handlers
if handler.stream == oldStream:
handler.close()
logger.removeHandler(handler)
for handle... | python | {
"resource": ""
} |
q239234 | popen | train | def popen(command, tempFile):
"""Runs a command and captures standard out in the given temp file.
"""
fileHandle = open(tempFile, 'w')
logger.debug("Running the command: %s" % command)
sts = subprocess.call(command, shell=True, stdout=fileHandle, bufsize=-1)
fileHandle.close()
if sts != 0:
... | python | {
"resource": ""
} |
q239235 | popenCatch | train | def popenCatch(command, stdinString=None):
"""Runs a command and return standard out.
"""
logger.debug("Running the command: %s" % command)
if stdinString != None:
process = subprocess.Popen(command, shell=True,
stdin=subprocess.PIPE, stdout=subprocess.PIPE, bu... | python | {
"resource": ""
} |
q239236 | getTotalCpuTimeAndMemoryUsage | train | def getTotalCpuTimeAndMemoryUsage():
"""Gives the total cpu time and memory usage of itself and its children.
"""
me = resource.getrusage(resource.RUSAGE_SELF)
childs = resource.getrusage(resource.RUSAGE_CHILDREN)
totalCpuTime = me.ru_utime+me.ru_stime+childs.ru_utime+childs.ru_stime
totalMemory... | python | {
"resource": ""
} |
q239237 | saveInputs | train | def saveInputs(savedInputsDir, listOfFilesAndDirsToSave):
"""Copies the list of files to a directory created in the save inputs dir,
and returns the name of this directory.
"""
logger.info("Saving the inputs: %s to the directory: %s" % (" ".join(listOfFilesAndDirsToSave), savedInputsDir))
assert os.... | python | {
"resource": ""
} |
q239238 | nameValue | train | def nameValue(name, value, valueType=str, quotes=False):
"""Little function to make it easier to make name value strings for commands.
"""
if valueType == bool:
if value:
return "--%s" % name
return ""
if value is None:
return ""
if quotes:
return "--%s '%... | python | {
"resource": ""
} |
q239239 | makeSubDir | train | def makeSubDir(dirName):
"""Makes a given subdirectory if it doesn't already exist, making sure it us public.
"""
if not os.path.exists(dirName):
os.mkdir(dirName)
os.chmod(dirName, 0777)
return dirName | python | {
"resource": ""
} |
q239240 | getTempFile | train | def getTempFile(suffix="", rootDir=None):
"""Returns a string representing a temporary file, that must be manually deleted
"""
if rootDir is None:
handle, tmpFile = tempfile.mkstemp(suffix)
os.close(handle)
return tmpFile
else:
tmpFile = os.path.join(rootDir, "tmp_" + get... | python | {
"resource": ""
} |
q239241 | getTempDirectory | train | def getTempDirectory(rootDir=None):
"""
returns a temporary directory that must be manually deleted. rootDir will be
created if it does not exist.
"""
if rootDir is None:
return tempfile.mkdtemp()
else:
if not os.path.exists(rootDir):
try:
os.makedirs(... | python | {
"resource": ""
} |
q239242 | catFiles | train | def catFiles(filesToCat, catFile):
"""Cats a bunch of files into one file. Ensures a no more than maxCat files
are concatenated at each step.
"""
if len(filesToCat) == 0: #We must handle this case or the cat call will hang waiting for input
open(catFile, 'w').close()
return
maxCat = ... | python | {
"resource": ""
} |
q239243 | prettyXml | train | def prettyXml(elem):
""" Return a pretty-printed XML string for the ElementTree Element.
"""
roughString = ET.tostring(elem, "utf-8")
reparsed = minidom.parseString(roughString)
return reparsed.toprettyxml(indent=" ") | python | {
"resource": ""
} |
q239244 | fastaEncodeHeader | train | def fastaEncodeHeader(attributes):
"""Decodes the fasta header
"""
for i in attributes:
assert len(str(i).split()) == 1
return "|".join([ str(i) for i in attributes ]) | python | {
"resource": ""
} |
q239245 | fastaWrite | train | def fastaWrite(fileHandleOrFile, name, seq, mode="w"):
"""Writes out fasta file
"""
fileHandle = _getFileHandle(fileHandleOrFile, mode)
valid_chars = {x for x in string.ascii_letters + "-"}
try:
assert any([isinstance(seq, unicode), isinstance(seq, str)])
except AssertionError:
r... | python | {
"resource": ""
} |
q239246 | fastqRead | train | def fastqRead(fileHandleOrFile):
"""Reads a fastq file iteratively
"""
fileHandle = _getFileHandle(fileHandleOrFile)
line = fileHandle.readline()
while line != '':
if line[0] == '@':
name = line[1:-1]
seq = fileHandle.readline()[:-1]
plus = fileHandle.read... | python | {
"resource": ""
} |
q239247 | _getMultiFastaOffsets | train | def _getMultiFastaOffsets(fasta):
"""Reads in columns of multiple alignment and returns them iteratively
"""
f = open(fasta, 'r')
i = 0
j = f.read(1)
l = []
while j != '':
i += 1
if j == '>':
i += 1
while f.read(1) != '\n':
i += 1
... | python | {
"resource": ""
} |
q239248 | fastaReadHeaders | train | def fastaReadHeaders(fasta):
"""Returns a list of fasta header lines, excluding
"""
headers = []
fileHandle = open(fasta, 'r')
line = fileHandle.readline()
while line != '':
assert line[-1] == '\n'
if line[0] == '>':
headers.append(line[1:-1])
line = fileHandl... | python | {
"resource": ""
} |
q239249 | fastaAlignmentRead | train | def fastaAlignmentRead(fasta, mapFn=(lambda x : x), l=None):
"""
reads in columns of multiple alignment and returns them iteratively
"""
if l is None:
l = _getMultiFastaOffsets(fasta)
else:
l = l[:]
seqNo = len(l)
for i in xrange(0, seqNo):
j = open(fasta, 'r')
... | python | {
"resource": ""
} |
q239250 | fastaAlignmentWrite | train | def fastaAlignmentWrite(columnAlignment, names, seqNo, fastaFile,
filter=lambda x : True):
"""
Writes out column alignment to given file multi-fasta format
"""
fastaFile = open(fastaFile, 'w')
columnAlignment = [ i for i in columnAlignment if filter(i) ]
for seq in xrange... | python | {
"resource": ""
} |
q239251 | getRandomSequence | train | def getRandomSequence(length=500):
"""Generates a random name and sequence.
"""
fastaHeader = ""
for i in xrange(int(random.random()*100)):
fastaHeader = fastaHeader + random.choice([ 'A', 'C', '0', '9', ' ', '\t' ])
return (fastaHeader, \
"".join([ random.choice([ 'A', 'C', 'T',... | python | {
"resource": ""
} |
q239252 | mutateSequence | train | def mutateSequence(seq, distance):
"""Mutates the DNA sequence for use in testing.
"""
subProb=distance
inProb=0.05*distance
deProb=0.05*distance
contProb=0.9
l = []
bases = [ 'A', 'C', 'T', 'G' ]
i=0
while i < len(seq):
if random.random() < subProb:
l.append(... | python | {
"resource": ""
} |
q239253 | newickTreeParser | train | def newickTreeParser(newickTree, defaultDistance=DEFAULT_DISTANCE, \
sortNonBinaryNodes=False, reportUnaryNodes=False):
"""
lax newick tree parser
"""
newickTree = newickTree.replace("(", " ( ")
newickTree = newickTree.replace(")", " ) ")
newickTree = newickTree.replace(":",... | python | {
"resource": ""
} |
q239254 | pWMRead | train | def pWMRead(fileHandle, alphabetSize=4):
"""reads in standard position weight matrix format,
rows are different types of base, columns are individual residues
"""
lines = fileHandle.readlines()
assert len(lines) == alphabetSize
l = [ [ float(i) ] for i in lines[0].split() ]
for line in lines... | python | {
"resource": ""
} |
q239255 | pWMWrite | train | def pWMWrite(fileHandle, pWM, alphabetSize=4):
"""Writes file in standard PWM format, is reverse of pWMParser
"""
for i in xrange(0, alphabetSize):
fileHandle.write("%s\n" % ' '.join([ str(pWM[j][i]) for j in xrange(0, len(pWM)) ])) | python | {
"resource": ""
} |
q239256 | cigarRead | train | def cigarRead(fileHandleOrFile):
"""Reads a list of pairwise alignments into a pairwise alignment structure.
Query and target are reversed!
"""
fileHandle = _getFileHandle(fileHandleOrFile)
#p = re.compile("cigar:\\s+(.+)\\s+([0-9]+)\\s+([0-9]+)\\s+([\\+\\-\\.])\\s+(.+)\\s+([0-9]+)\\s+([0-9]+)\\s+(... | python | {
"resource": ""
} |
q239257 | cigarWrite | train | def cigarWrite(fileHandle, pairwiseAlignment, withProbs=True):
"""Writes out the pairwiseAlignment to the file stream.
Query and target are reversed from normal order.
"""
if len(pairwiseAlignment.operationList) == 0:
logger.info("Writing zero length pairwiseAlignment to file!")
strand1 = ... | python | {
"resource": ""
} |
q239258 | getRandomPairwiseAlignment | train | def getRandomPairwiseAlignment():
"""Gets a random pairwiseAlignment.
"""
i, j, k, l = _getRandomSegment()
m, n, o, p = _getRandomSegment()
score = random.choice(xrange(-1000, 1000))
return PairwiseAlignment(i, j, k, l, m, n, o, p, score, getRandomOperationList(abs(k - j), abs(o - n))) | python | {
"resource": ""
} |
q239259 | addEdgeToGraph | train | def addEdgeToGraph(parentNodeName, childNodeName, graphFileHandle, colour="black", length="10", weight="1", dir="none", label="", style=""):
"""Links two nodes in the graph together.
"""
graphFileHandle.write('edge[color=%s,len=%s,weight=%s,dir=%s,label="%s",style=%s];\n' % (colour, length, weight, dir, lab... | python | {
"resource": ""
} |
q239260 | TempFileTree.destroyTempFile | train | def destroyTempFile(self, tempFile):
"""Removes the temporary file in the temp file dir, checking its in the temp file tree.
"""
#Do basic assertions for goodness of the function
assert os.path.isfile(tempFile)
assert os.path.commonprefix((self.rootDir, tempFile)) == self.rootDir... | python | {
"resource": ""
} |
q239261 | TempFileTree.destroyTempDir | train | def destroyTempDir(self, tempDir):
"""Removes a temporary directory in the temp file dir, checking its in the temp file tree.
The dir will be removed regardless of if it is empty.
"""
#Do basic assertions for goodness of the function
assert os.path.isdir(tempDir)
assert o... | python | {
"resource": ""
} |
q239262 | TempFileTree.destroyTempFiles | train | def destroyTempFiles(self):
"""Destroys all temp temp file hierarchy, getting rid of all files.
"""
os.system("rm -rf %s" % self.rootDir)
logger.debug("Temp files created: %s, temp files actively destroyed: %s" % (self.tempFilesCreated, self.tempFilesDestroyed)) | python | {
"resource": ""
} |
q239263 | mutable_json_field | train | def mutable_json_field( # pylint: disable=keyword-arg-before-vararg
enforce_string=False, # type: bool
enforce_unicode=False, # type: bool
json=json, # type: typing.Union[types.ModuleType, typing.Any]
*args, # type: typing.Any
**kwargs # type: typing.Any
): # type: (...) -> JSONField
"""M... | python | {
"resource": ""
} |
q239264 | JSONField.load_dialect_impl | train | def load_dialect_impl(self, dialect): # type: (DefaultDialect) -> TypeEngine
"""Select impl by dialect."""
if self.__use_json(dialect):
return dialect.type_descriptor(self.__json_type)
return dialect.type_descriptor(sqlalchemy.UnicodeText) | python | {
"resource": ""
} |
q239265 | JSONField.process_bind_param | train | def process_bind_param(self, value, dialect): # type: (typing.Any, DefaultDialect) -> typing.Union[str, typing.Any]
"""Encode data, if required."""
if self.__use_json(dialect) or value is None:
return value
return self.__json_codec.dumps(value, ensure_ascii=not self.__enforce_unico... | python | {
"resource": ""
} |
q239266 | JSONField.process_result_value | train | def process_result_value(
self,
value, # type: typing.Union[str, typing.Any]
dialect # type: DefaultDialect
): # type: (...) -> typing.Any
"""Decode data, if required."""
if self.__use_json(dialect) or value is None:
return value
return self.__json_cod... | python | {
"resource": ""
} |
q239267 | MailboxDataInterface.get | train | async def get(self, uid: int, cached_msg: CachedMessage = None,
requirement: FetchRequirement = FetchRequirement.METADATA) \
-> Optional[MessageT]:
"""Return the message with the given UID.
Args:
uid: The message UID.
cached_msg: The last known cach... | python | {
"resource": ""
} |
q239268 | MailboxDataInterface.update_flags | train | async def update_flags(self, messages: Sequence[MessageT],
flag_set: FrozenSet[Flag], mode: FlagOp) -> None:
"""Update the permanent flags of each messages.
Args:
messages: The message objects.
flag_set: The set of flags for the update operation.
... | python | {
"resource": ""
} |
q239269 | MailboxDataInterface.find | train | async def find(self, seq_set: SequenceSet, selected: SelectedMailbox,
requirement: FetchRequirement = FetchRequirement.METADATA) \
-> AsyncIterable[Tuple[int, MessageT]]:
"""Find the active message UID and message pairs in the mailbox that
are contained in the given sequen... | python | {
"resource": ""
} |
q239270 | MailboxDataInterface.find_deleted | train | async def find_deleted(self, seq_set: SequenceSet,
selected: SelectedMailbox) -> Sequence[int]:
"""Return all the active message UIDs that have the ``\\Deleted`` flag.
Args:
seq_set: The sequence set of the possible messages.
selected: The selected mai... | python | {
"resource": ""
} |
q239271 | ParsedHeaders.content_type | train | def content_type(self) -> Optional[ContentTypeHeader]:
"""The ``Content-Type`` header."""
try:
return cast(ContentTypeHeader, self[b'content-type'][0])
except (KeyError, IndexError):
return None | python | {
"resource": ""
} |
q239272 | ParsedHeaders.date | train | def date(self) -> Optional[DateHeader]:
"""The ``Date`` header."""
try:
return cast(DateHeader, self[b'date'][0])
except (KeyError, IndexError):
return None | python | {
"resource": ""
} |
q239273 | ParsedHeaders.subject | train | def subject(self) -> Optional[UnstructuredHeader]:
"""The ``Subject`` header."""
try:
return cast(UnstructuredHeader, self[b'subject'][0])
except (KeyError, IndexError):
return None | python | {
"resource": ""
} |
q239274 | ParsedHeaders.from_ | train | def from_(self) -> Optional[Sequence[AddressHeader]]:
"""The ``From`` header."""
try:
return cast(Sequence[AddressHeader], self[b'from'])
except KeyError:
return None | python | {
"resource": ""
} |
q239275 | ParsedHeaders.sender | train | def sender(self) -> Optional[Sequence[SingleAddressHeader]]:
"""The ``Sender`` header."""
try:
return cast(Sequence[SingleAddressHeader], self[b'sender'])
except KeyError:
return None | python | {
"resource": ""
} |
q239276 | ParsedHeaders.reply_to | train | def reply_to(self) -> Optional[Sequence[AddressHeader]]:
"""The ``Reply-To`` header."""
try:
return cast(Sequence[AddressHeader], self[b'reply-to'])
except KeyError:
return None | python | {
"resource": ""
} |
q239277 | ParsedHeaders.to | train | def to(self) -> Optional[Sequence[AddressHeader]]:
"""The ``To`` header."""
try:
return cast(Sequence[AddressHeader], self[b'to'])
except KeyError:
return None | python | {
"resource": ""
} |
q239278 | ParsedHeaders.cc | train | def cc(self) -> Optional[Sequence[AddressHeader]]:
"""The ``Cc`` header."""
try:
return cast(Sequence[AddressHeader], self[b'cc'])
except KeyError:
return None | python | {
"resource": ""
} |
q239279 | ParsedHeaders.bcc | train | def bcc(self) -> Optional[Sequence[AddressHeader]]:
"""The ``Bcc`` header."""
try:
return cast(Sequence[AddressHeader], self[b'bcc'])
except KeyError:
return None | python | {
"resource": ""
} |
q239280 | ParsedHeaders.in_reply_to | train | def in_reply_to(self) -> Optional[UnstructuredHeader]:
"""The ``In-Reply-To`` header."""
try:
return cast(UnstructuredHeader, self[b'in-reply-to'][0])
except (KeyError, IndexError):
return None | python | {
"resource": ""
} |
q239281 | ParsedHeaders.message_id | train | def message_id(self) -> Optional[UnstructuredHeader]:
"""The ``Message-Id`` header."""
try:
return cast(UnstructuredHeader, self[b'message-id'][0])
except (KeyError, IndexError):
return None | python | {
"resource": ""
} |
q239282 | ParsedHeaders.content_disposition | train | def content_disposition(self) -> Optional[ContentDispositionHeader]:
"""The ``Content-Disposition`` header."""
try:
return cast(ContentDispositionHeader,
self[b'content-disposition'][0])
except (KeyError, IndexError):
return None | python | {
"resource": ""
} |
q239283 | ParsedHeaders.content_language | train | def content_language(self) -> Optional[UnstructuredHeader]:
"""The ``Content-Language`` header."""
try:
return cast(UnstructuredHeader, self[b'content-language'][0])
except (KeyError, IndexError):
return None | python | {
"resource": ""
} |
q239284 | ParsedHeaders.content_location | train | def content_location(self) -> Optional[UnstructuredHeader]:
"""The ``Content-Location`` header."""
try:
return cast(UnstructuredHeader, self[b'content-location'][0])
except (KeyError, IndexError):
return None | python | {
"resource": ""
} |
q239285 | ParsedHeaders.content_id | train | def content_id(self) -> Optional[UnstructuredHeader]:
"""The ``Content-Id`` header."""
try:
return cast(UnstructuredHeader, self[b'content-id'][0])
except (KeyError, IndexError):
return None | python | {
"resource": ""
} |
q239286 | ParsedHeaders.content_description | train | def content_description(self) -> Optional[UnstructuredHeader]:
"""The ``Content-Description`` header."""
try:
return cast(UnstructuredHeader, self[b'content-description'][0])
except (KeyError, IndexError):
return None | python | {
"resource": ""
} |
q239287 | ParsedHeaders.content_transfer_encoding | train | def content_transfer_encoding(self) \
-> Optional[ContentTransferEncodingHeader]:
"""The ``Content-Transfer-Encoding`` header."""
try:
return cast(ContentTransferEncodingHeader,
self[b'content-transfer-encoding'][0])
except (KeyError, IndexError):
... | python | {
"resource": ""
} |
q239288 | Params.copy | train | def copy(self, *, continuations: List[memoryview] = None,
expected: Sequence[Type['Parseable']] = None,
list_expected: Sequence[Type['Parseable']] = None,
command_name: bytes = None,
uid: bool = None,
charset: str = None,
tag: bytes = None,
... | python | {
"resource": ""
} |
q239289 | Capability.string | train | def string(self) -> bytes:
"""The capabilities string without the enclosing square brackets."""
if self._raw is not None:
return self._raw
self._raw = raw = BytesFormat(b' ').join(
[b'CAPABILITY', b'IMAP4rev1'] + self.capabilities)
return raw | python | {
"resource": ""
} |
q239290 | Response.text | train | def text(self) -> bytes:
"""The response text."""
if self.condition:
if self.code:
return BytesFormat(b'%b %b %b') \
% (self.condition, self.code, self._text)
else:
return BytesFormat(b'%b %b') % (self.condition, self._text)
... | python | {
"resource": ""
} |
q239291 | Response.add_untagged | train | def add_untagged(self, *responses: 'Response') -> None:
"""Add an untagged response. These responses are shown before the
parent response.
Args:
responses: The untagged responses to add.
"""
for resp in responses:
try:
merge_key = resp.me... | python | {
"resource": ""
} |
q239292 | Response.add_untagged_ok | train | def add_untagged_ok(self, text: MaybeBytes,
code: Optional[ResponseCode] = None) -> None:
"""Add an untagged ``OK`` response.
See Also:
:meth:`.add_untagged`, :class:`ResponseOk`
Args:
text: The response text.
code: Optional response ... | python | {
"resource": ""
} |
q239293 | Response.is_terminal | train | def is_terminal(self) -> bool:
"""True if the response contained an untagged ``BYE`` response
indicating that the session should be terminated.
"""
for resp in self._untagged:
if resp.is_terminal:
return True
return False | python | {
"resource": ""
} |
q239294 | SequenceSet.is_all | train | def is_all(self) -> bool:
"""True if the sequence set starts at ``1`` and ends at the maximum
value.
This may be used to optimize cases of checking for a value in the set,
avoiding the need to provide ``max_value`` in :meth:`.flatten` or
:meth:`.iter`.
"""
first... | python | {
"resource": ""
} |
q239295 | SequenceSet.flatten | train | def flatten(self, max_value: int) -> FrozenSet[int]:
"""Return a set of all values contained in the sequence set.
Args:
max_value: The maximum value, in place of any ``*``.
"""
return frozenset(self.iter(max_value)) | python | {
"resource": ""
} |
q239296 | SequenceSet.build | train | def build(cls, seqs: Iterable[int], uid: bool = False) -> 'SequenceSet':
"""Build a new sequence set that contains the given values using as
few groups as possible.
Args:
seqs: The sequence values to build.
uid: True if the sequences refer to message UIDs.
"""
... | python | {
"resource": ""
} |
q239297 | ListTree.update | train | def update(self, *names: str) -> 'ListTree':
"""Add all the mailbox names to the tree, filling in any missing nodes.
Args:
names: The names of the mailboxes.
"""
for name in names:
parts = name.split(self._delimiter)
self._root.add(*parts)
re... | python | {
"resource": ""
} |
q239298 | ListTree.set_marked | train | def set_marked(self, name: str, marked: bool = False,
unmarked: bool = False) -> None:
"""Add or remove the ``\\Marked`` and ``\\Unmarked`` mailbox
attributes.
Args:
name: The name of the mailbox.
marked: True if the ``\\Marked`` attribute should be ad... | python | {
"resource": ""
} |
q239299 | ListTree.get | train | def get(self, name: str) -> Optional[ListEntry]:
"""Return the named entry in the list tree.
Args:
name: The entry name.
"""
parts = name.split(self._delimiter)
try:
node = self._find(self._root, *parts)
except KeyError:
return None
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.