_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q252800
RandomDistributedScalarEncoder._overlapOK
validation
def _overlapOK(self, i, j, overlap=None): """ Return True if the given overlap between bucket indices i and j are acceptable. If overlap is not specified, calculate it from the bucketMap """ if overlap is None: overlap = self._countOverlapIndices(i, j) if abs(i-j) < self.w:
python
{ "resource": "" }
q252801
RandomDistributedScalarEncoder._initializeBucketMap
validation
def _initializeBucketMap(self, maxBuckets, offset): """ Initialize the bucket map assuming the given number of maxBuckets. """ # The first bucket index will be _maxBuckets / 2 and bucket indices will be # allowed to grow lower or higher as long as they don't become negative. # _maxBuckets is req...
python
{ "resource": "" }
q252802
SDRClassifierFactory.create
validation
def create(*args, **kwargs): """ Create a SDR classifier factory. The implementation of the SDR Classifier can be specified with the "implementation" keyword argument. The SDRClassifierFactory uses the implementation as specified in `Default NuPIC Configuration <default-config.html>`_. """...
python
{ "resource": "" }
q252803
TemporalMemoryMonitorMixin.mmGetMetricFromTrace
validation
def mmGetMetricFromTrace(self, trace): """ Convenience method to compute a metric over an indices trace, excluding resets. @param (IndicesTrace) Trace of indices @return (Metric) Metric over trace excluding resets
python
{ "resource": "" }
q252804
TemporalMemoryMonitorMixin.mmGetMetricSequencesPredictedActiveCellsPerColumn
validation
def mmGetMetricSequencesPredictedActiveCellsPerColumn(self): """ Metric for number of predicted => active cells per column for each sequence @return (Metric) metric """ self._mmComputeTransitionTraces() numCellsPerColumn = []
python
{ "resource": "" }
q252805
TemporalMemoryMonitorMixin.mmGetMetricSequencesPredictedActiveCellsShared
validation
def mmGetMetricSequencesPredictedActiveCellsShared(self): """ Metric for number of sequences each predicted => active cell appears in Note: This metric is flawed when it comes to high-order sequences. @return (Metric) metric """ self._mmComputeTransitionTraces() numSequencesForCell = defa...
python
{ "resource": "" }
q252806
TemporalMemoryMonitorMixin.mmPrettyPrintConnections
validation
def mmPrettyPrintConnections(self): """ Pretty print the connections in the temporal memory. TODO: Use PrettyTable. @return (string) Pretty-printed text """ text = "" text += ("Segments: (format => " "(#) [(source cell=permanence ...), ...]\n") text += "------------...
python
{ "resource": "" }
q252807
TemporalMemoryMonitorMixin.mmPrettyPrintSequenceCellRepresentations
validation
def mmPrettyPrintSequenceCellRepresentations(self, sortby="Column"): """ Pretty print the cell representations for sequences in the history. @param sortby (string) Column of table to sort by @return (string) Pretty-printed text """ self._mmComputeTransitionTraces() table = PrettyTable(["Pa...
python
{ "resource": "" }
q252808
createTemporalAnomaly
validation
def createTemporalAnomaly(recordParams, spatialParams=_SP_PARAMS, temporalParams=_TM_PARAMS, verbosity=_VERBOSITY): """Generates a Network with connected RecordSensor, SP, TM. This function takes care of generating regions and the canonical links. The network...
python
{ "resource": "" }
q252809
add
validation
def add(reader, writer, column, start, stop, value): """Adds a value over a range of rows. Args: reader: A FileRecordStream object with input data. writer: A FileRecordStream object to write output data to. column: The column of data to modify. start: The first row in the range to modify. end: ...
python
{ "resource": "" }
q252810
scale
validation
def scale(reader, writer, column, start, stop, multiple): """Multiplies a value over a range of rows. Args: reader: A FileRecordStream object with input data. writer: A FileRecordStream object to write output data to. column: The column of data to modify. start: The first row in the range to modif...
python
{ "resource": "" }
q252811
copy
validation
def copy(reader, writer, start, stop, insertLocation=None, tsCol=None): """Copies a range of values to a new location in the data set. Args: reader: A FileRecordStream object with input data. writer: A FileRecordStream object to write output data to. start: The first row in the range to copy. stop:...
python
{ "resource": "" }
q252812
sample
validation
def sample(reader, writer, n, start=None, stop=None, tsCol=None, writeSampleOnly=True): """Samples n rows. Args: reader: A FileRecordStream object with input data. writer: A FileRecordStream object to write output data to. n: The number of elements to sample. start: The first row in the ...
python
{ "resource": "" }
q252813
ScalarEncoder._getFirstOnBit
validation
def _getFirstOnBit(self, input): """ Return the bit offset of the first bit to be set in the encoder output. For periodic encoders, this can be a negative number when the encoded output wraps around. """ if input == SENTINEL_VALUE_FOR_MISSING_DATA: return [None] else: if input < self.m...
python
{ "resource": "" }
q252814
ScalarEncoder._generateRangeDescription
validation
def _generateRangeDescription(self, ranges): """generate description from a text description of the ranges""" desc = "" numRanges = len(ranges) for i in xrange(numRanges): if ranges[i][0] != ranges[i][1]:
python
{ "resource": "" }
q252815
BacktrackingTM.reset
validation
def reset(self,): """ Reset the state of all cells. This is normally used between sequences while training. All internal states are reset to 0. """ if self.verbosity >= 3: print "\n==== RESET =====" self.lrnActiveState['t-1'].fill(0) self.lrnActiveState['t'].fill(0) self.lrnP...
python
{ "resource": "" }
q252816
BacktrackingTM._updateStatsInferEnd
validation
def _updateStatsInferEnd(self, stats, bottomUpNZ, predictedState, colConfidence): """ Called at the end of learning and inference, this routine will update a number of stats in our _internalStats dictionary, including our computed prediction score. :param stats ...
python
{ "resource": "" }
q252817
BacktrackingTM.printState
validation
def printState(self, aState): """ Print an integer array that is the same shape as activeState. :param aState: TODO: document """ def formatRow(var, i): s = '' for c in range(self.numberOfCols): if c > 0 and c % 10
python
{ "resource": "" }
q252818
BacktrackingTM.printConfidence
validation
def printConfidence(self, aState, maxCols = 20): """ Print a floating point array that is the same shape as activeState. :param aState: TODO: document :param maxCols: TODO: document """ def formatFPRow(var, i): s = '' for c in range(min(maxCols, self.numberOfCols)):
python
{ "resource": "" }
q252819
BacktrackingTM.printColConfidence
validation
def printColConfidence(self, aState, maxCols = 20): """ Print up to maxCols number from a flat floating point array. :param aState: TODO: document :param maxCols: TODO: document """ def formatFPRow(var): s = '' for c in range(min(maxCols, self.numberOfCols)):
python
{ "resource": "" }
q252820
BacktrackingTM.printParameters
validation
def printParameters(self): """ Print the parameter settings for the TM. """ print "numberOfCols=", self.numberOfCols print "cellsPerColumn=", self.cellsPerColumn print "minThreshold=", self.minThreshold print "newSynapseCount=", self.newSynapseCount print "activationThreshold=", self.act...
python
{ "resource": "" }
q252821
BacktrackingTM.printComputeEnd
validation
def printComputeEnd(self, output, learn=False): """ Called at the end of inference to print out various diagnostic information based on the current verbosity level. :param output: TODO: document :param learn: TODO: document """ if self.verbosity >= 3: print "----- computeEnd summary: ...
python
{ "resource": "" }
q252822
BacktrackingTM._updateAvgLearnedSeqLength
validation
def _updateAvgLearnedSeqLength(self, prevSeqLength): """Update our moving average of learned sequence length.""" if self.lrnIterationIdx < 100:
python
{ "resource": "" }
q252823
BacktrackingTM._inferPhase1
validation
def _inferPhase1(self, activeColumns, useStartCells): """ Update the inference active state from the last set of predictions and the current bottom-up. This looks at: - ``infPredictedState['t-1']`` This modifies: - ``infActiveState['t']`` :param activeColumns: (list) active bot...
python
{ "resource": "" }
q252824
BacktrackingTM._inferPhase2
validation
def _inferPhase2(self): """ Phase 2 for the inference state. The computes the predicted state, then checks to insure that the predicted state is not over-saturated, i.e. look too close like a burst. This indicates that there were so many separate paths learned from the current input columns to the p...
python
{ "resource": "" }
q252825
BacktrackingTM._learnBacktrackFrom
validation
def _learnBacktrackFrom(self, startOffset, readOnly=True): """ A utility method called from learnBacktrack. This will backtrack starting from the given startOffset in our prevLrnPatterns queue. It returns True if the backtrack was successful and we managed to get predictions all the way up to the c...
python
{ "resource": "" }
q252826
BacktrackingTM._learnBacktrack
validation
def _learnBacktrack(self): """ This "backtracks" our learning state, trying to see if we can lock onto the current set of inputs by assuming the sequence started up to N steps ago on start cells. This will adjust @ref lrnActiveState['t'] if it does manage to lock on to a sequence that started e...
python
{ "resource": "" }
q252827
BacktrackingTM._learnPhase1
validation
def _learnPhase1(self, activeColumns, readOnly=False): """ Compute the learning active state given the predicted state and the bottom-up input. :param activeColumns list of active bottom-ups :param readOnly True if being called from backtracking logic. This tells us no...
python
{ "resource": "" }
q252828
BacktrackingTM._learnPhase2
validation
def _learnPhase2(self, readOnly=False): """ Compute the predicted segments given the current set of active cells. :param readOnly True if being called from backtracking logic. This tells us not to increment any segment duty cycles or queue up any up...
python
{ "resource": "" }
q252829
BacktrackingTM.compute
validation
def compute(self, bottomUpInput, enableLearn, enableInference=None): """ Handle one compute, possibly learning. .. note:: It is an error to have both ``enableLearn`` and ``enableInference`` set to False .. note:: By default, we don't compute the inference output when learning ...
python
{ "resource": "" }
q252830
BacktrackingTM._trimSegmentsInCell
validation
def _trimSegmentsInCell(self, colIdx, cellIdx, segList, minPermanence, minNumSyns): """ This method goes through a list of segments for a given cell and deletes all synapses whose permanence is less than minPermanence and deletes any segments that have less than minNumSyns syna...
python
{ "resource": "" }
q252831
BacktrackingTM.trimSegments
validation
def trimSegments(self, minPermanence=None, minNumSyns=None): """ This method deletes all synapses whose permanence is less than minPermanence and deletes any segments that have less than minNumSyns synapses remaining. :param minPermanence: (float) Any syn whose permanence is 0 or < ``mi...
python
{ "resource": "" }
q252832
BacktrackingTM._cleanUpdatesList
validation
def _cleanUpdatesList(self, col, cellIdx, seg): """ Removes any update that would be for the given col, cellIdx, segIdx. NOTE: logically, we need to do this when we delete segments, so that if an update refers to a segment that was just deleted, we also remove that update from the update list. Howe...
python
{ "resource": "" }
q252833
BacktrackingTM._getBestMatchingCell
validation
def _getBestMatchingCell(self, c, activeState, minThreshold): """ Find weakly activated cell in column with at least minThreshold active synapses. :param c which column to look at :param activeState the active cells :param minThreshold minimum number of synapses required :retur...
python
{ "resource": "" }
q252834
BacktrackingTM._getBestMatchingSegment
validation
def _getBestMatchingSegment(self, c, i, activeState): """ For the given cell, find the segment with the largest number of active synapses. This routine is aggressive in finding the best match. The permanence value of synapses is allowed to be below connectedPerm. The number of active synapses is all...
python
{ "resource": "" }
q252835
BacktrackingTM._getCellForNewSegment
validation
def _getCellForNewSegment(self, colIdx): """ Return the index of a cell in this column which is a good candidate for adding a new segment. When we have fixed size resources in effect, we insure that we pick a cell which does not already have the max number of allowed segments. If none exists, w...
python
{ "resource": "" }
q252836
BacktrackingTM._chooseCellsToLearnFrom
validation
def _chooseCellsToLearnFrom(self, c, i, s, n, activeState): """ Choose n random cells to learn from. This function is called several times while learning with timeStep = t-1, so we cache the set of candidates for that case. It's also called once with timeStep = t, and we cache that set of candidate...
python
{ "resource": "" }
q252837
BacktrackingTM._adaptSegment
validation
def _adaptSegment(self, segUpdate): """ This function applies segment update information to a segment in a cell. Synapses on the active list get their permanence counts incremented by permanenceInc. All other synapses get their permanence counts decremented by permanenceDec. We also increm...
python
{ "resource": "" }
q252838
Segment.addSynapse
validation
def addSynapse(self, srcCellCol, srcCellIdx, perm): """Add a new synapse :param srcCellCol source cell column :param srcCellIdx source cell index within the column :param perm
python
{ "resource": "" }
q252839
getSimplePatterns
validation
def getSimplePatterns(numOnes, numPatterns, patternOverlap=0): """Very simple patterns. Each pattern has numOnes consecutive bits on. The amount of overlap between consecutive patterns is configurable, via the patternOverlap parameter. Parameters: -------------------------------------------------------------...
python
{ "resource": "" }
q252840
buildOverlappedSequences
validation
def buildOverlappedSequences( numSequences = 2, seqLen = 5, sharedElements = [3,4], numOnBitsPerPattern = 3, patternOverlap = 0, seqOverlap = 0, ...
python
{ "resource": "" }
q252841
buildSequencePool
validation
def buildSequencePool(numSequences = 10, seqLen = [2,3,4], numPatterns = 5, numOnBitsPerPattern = 3, patternOverlap = 0, **kwargs ): """ Create a bunch of sequences of various lengths, a...
python
{ "resource": "" }
q252842
createTMs
validation
def createTMs(includeCPP = True, includePy = True, numCols = 100, cellsPerCol = 4, activationThreshold = 3, minThreshold = 3, newSynapseCount = 3, initialPerm = 0.6, permanenceInc = 0.1, permane...
python
{ "resource": "" }
q252843
assertNoTMDiffs
validation
def assertNoTMDiffs(tms): """ Check for diffs among the TM instances in the passed in tms dict and raise an assert if any are detected Parameters: --------------------------------------------------------------------- tms: dict of TM instances """ if len(tms) == 1:
python
{ "resource": "" }
q252844
needsquoting
validation
def needsquoting(c, quotetabs, header): """Decide whether a particular character needs to be quoted. The 'quotetabs' flag indicates whether embedded tabs and spaces should be quoted. Note that line-ending tabs and spaces are always encoded, as per RFC 1521. """ if c in ' \t':
python
{ "resource": "" }
q252845
quote
validation
def quote(c): """Quote a single character.""" i = ord(c)
python
{ "resource": "" }
q252846
encode
validation
def encode(input, output, quotetabs, header = 0): """Read 'input', apply quoted-printable encoding, and write to 'output'. 'input' and 'output' are files with readline() and write() methods. The 'quotetabs' flag indicates whether embedded tabs and spaces should be quoted. Note that line-ending tabs an...
python
{ "resource": "" }
q252847
unhex
validation
def unhex(s): """Get the integer value of a hexadecimal number.""" bits = 0 for c in s: if '0' <= c <= '9': i = ord('0') elif 'a' <= c <= 'f': i = ord('a')-10
python
{ "resource": "" }
q252848
b64encode
validation
def b64encode(s, altchars=None): """Encode a string using Base64. s is the string to encode. Optional altchars must be a string of at least length 2 (additional characters are ignored) which specifies an alternative alphabet for the '+' and '/' characters. This allows an application to e.g. gener...
python
{ "resource": "" }
q252849
b64decode
validation
def b64decode(s, altchars=None): """Decode a Base64 encoded string. s is the string to decode. Optional altchars must be a string of at least length 2 (additional characters are ignored) which specifies the alternative alphabet used instead of the '+' and '/' characters. The decoded string is ret...
python
{ "resource": "" }
q252850
b32encode
validation
def b32encode(s): """Encode a string using Base32. s is the string to encode. The encoded string is returned. """ parts = [] quanta, leftover = divmod(len(s), 5) # Pad the last quantum with zero bits if necessary if leftover: s += ('\0' * (5 - leftover)) quanta += 1 for...
python
{ "resource": "" }
q252851
b32decode
validation
def b32decode(s, casefold=False, map01=None): """Decode a Base32 encoded string. s is the string to decode. Optional casefold is a flag specifying whether a lowercase alphabet is acceptable as input. For security purposes, the default is False. RFC 3548 allows for optional mapping of the digit 0...
python
{ "resource": "" }
q252852
b16decode
validation
def b16decode(s, casefold=False): """Decode a Base16 encoded string. s is the string to decode. Optional casefold is a flag specifying whether a lowercase alphabet is acceptable as input. For security purposes, the default is False. The decoded string is returned. A TypeError is raised if s is ...
python
{ "resource": "" }
q252853
encode
validation
def encode(input, output): """Encode a file.""" while True: s = input.read(MAXBINSIZE) if not s: break while len(s) < MAXBINSIZE: ns = input.read(MAXBINSIZE-len(s))
python
{ "resource": "" }
q252854
decode
validation
def decode(input, output): """Decode a file.""" while True: line = input.readline() if not line:
python
{ "resource": "" }
q252855
encodestring
validation
def encodestring(s): """Encode a string into multiple lines of base-64 data.""" pieces = [] for i in range(0, len(s), MAXBINSIZE): chunk = s[i
python
{ "resource": "" }
q252856
Range.chain
validation
def chain(self, expanded_from): """ Returns a range identical to this one, but indicating that it was expanded from the range `expanded_from`. """
python
{ "resource": "" }
q252857
Range.begin
validation
def begin(self): """ Returns a zero-length range located just before the beginning of this range. """
python
{ "resource": "" }
q252858
Range.end
validation
def end(self): """ Returns a zero-length range located just after the end of this range. """
python
{ "resource": "" }
q252859
Range.column
validation
def column(self): """ Returns a zero-based column number of the beginning of this range. """
python
{ "resource": "" }
q252860
Range.line
validation
def line(self): """ Returns the line number of the beginning of this range. """
python
{ "resource": "" }
q252861
Range.source_lines
validation
def source_lines(self): """ Returns the lines of source code containing the entirety of this range. """
python
{ "resource": "" }
q252862
compare
validation
def compare(left, right, compare_locs=False): """ An AST comparison function. Returns ``True`` if all fields in ``left`` are equal to fields in ``right``; if ``compare_locs`` is true, all locations should match as well. """ if type(left) != type(right): return False if isinstance(le...
python
{ "resource": "" }
q252863
Transformer.generic_visit
validation
def generic_visit(self, node): """Called if no explicit visitor function exists for a node.""" for field_name in node._fields:
python
{ "resource": "" }
q252864
float_unpack
validation
def float_unpack(Q, size, le): """Convert a 32-bit or 64-bit integer created by float_pack into a Python float.""" if size == 8: MIN_EXP = -1021 # = sys.float_info.min_exp MAX_EXP = 1024 # = sys.float_info.max_exp MANT_DIG = 53 # = sys.float_info.mant_dig BITS = 64 elif size == 4: MIN...
python
{ "resource": "" }
q252865
float_pack
validation
def float_pack(x, size): """Convert a Python float x into a 64-bit unsigned integer with the same byte representation.""" if size == 8: MIN_EXP = -1021 # = sys.float_info.min_exp MAX_EXP = 1024 # = sys.float_info.max_exp MANT_DIG = 53 # = sys.float_info.mant_dig BITS = 64 elif size == 4: ...
python
{ "resource": "" }
q252866
Engine.context
validation
def context(self, *notes): """ A context manager that appends ``note`` to every diagnostic processed by this engine.
python
{ "resource": "" }
q252867
format_list
validation
def format_list(extracted_list): """Format a list of traceback entry tuples for printing. Given a list of tuples as returned by extract_tb() or extract_stack(), return a list of strings ready for printing. Each string in the resulting list corresponds to the item with the same index in the argument...
python
{ "resource": "" }
q252868
print_tb
validation
def print_tb(tb, limit=None, file=None): """Print up to 'limit' stack trace entries from the traceback 'tb'. If 'limit' is omitted or None, all entries are printed. If 'file' is omitted or None, the output goes to sys.stderr; otherwise 'file' should be an open file or file-like object with a write() ...
python
{ "resource": "" }
q252869
print_exception
validation
def print_exception(etype, value, tb, limit=None, file=None): """Print exception up to 'limit' stack trace entries from 'tb' to 'file'. This differs from print_tb() in the following ways: (1) if traceback is not None, it prints a header "Traceback (most recent call last):"; (2) it prints the exception ...
python
{ "resource": "" }
q252870
format_exception
validation
def format_exception(etype, value, tb, limit = None): """Format a stack trace and the exception information. The arguments have the same meaning as the corresponding arguments to print_exception(). The return value is a list of strings, each ending in a newline and some containing internal newlines. ...
python
{ "resource": "" }
q252871
format_exception_only
validation
def format_exception_only(etype, value): """Format the exception part of a traceback. The arguments are the exception type and value such as given by sys.last_type and sys.last_value. The return value is a list of strings, each ending in a newline. Normally, the list contains a single string; howe...
python
{ "resource": "" }
q252872
print_stack
validation
def print_stack(f=None, limit=None, file=None): """Print a stack trace from its invocation point. The optional 'f' argument can be used to specify an alternate stack frame at which to start. The optional 'limit' and 'file' arguments have the same meaning as for print_exception(). """ if f is No...
python
{ "resource": "" }
q252873
extract_stack
validation
def extract_stack(f=None, limit = None): """Extract the raw traceback from the current stack frame. The return value has the same format as for extract_tb(). The optional 'f' and 'limit' arguments have the same meaning as for print_stack(). Each item in the list is a quadruple (filename, line num...
python
{ "resource": "" }
q252874
Random.seed
validation
def seed(self, a=None): """Initialize internal state of the random number generator. None or no argument seeds from current time or from an operating system specific randomness source if available. If a is not None or is an int or long, hash(a) is used instead. Hash
python
{ "resource": "" }
q252875
Random.shuffle
validation
def shuffle(self, x, random=None): """x, random=random.random -> shuffle list x in place; return None. Optional arg random is a 0-argument function returning a random float in [0.0, 1.0); by default, the standard random.random.
python
{ "resource": "" }
q252876
_slotnames
validation
def _slotnames(cls): """Return a list of slot names for a given class. This needs to find slots defined by the class and its bases, so we can't simply return the __slots__ attribute. We must walk down the Method Resolution Order and concatenate the __slots__ of each class found there. (This assum...
python
{ "resource": "" }
q252877
add_extension
validation
def add_extension(module, name, code): """Register an extension code.""" code = int(code) if not 1 <= code <= 0x7fffffff: raise ValueError, "code out of range" key = (module, name) if (_extension_registry.get(key) == code and _inverted_registry.get(code) == key):
python
{ "resource": "" }
q252878
remove_extension
validation
def remove_extension(module, name, code): """Unregister an extension code. For testing only.""" key = (module, name) if (_extension_registry.get(key) != code or _inverted_registry.get(code) != key): raise ValueError("key %s is not registered with code %s" %
python
{ "resource": "" }
q252879
update_wrapper
validation
def update_wrapper(wrapper, wrapped, assigned = WRAPPER_ASSIGNMENTS, updated = WRAPPER_UPDATES): """Update a wrapper function to look like the wrapped function wrapper is the function to be updated wrapped is the original function assign...
python
{ "resource": "" }
q252880
cmp_to_key
validation
def cmp_to_key(mycmp): """Convert a cmp= function into a key= function""" class K(object): __slots__ = ['obj'] def __init__(self, obj, *args): self.obj = obj def __lt__(self, other): return mycmp(self.obj, other.obj) < 0 def __gt__(self, other): ...
python
{ "resource": "" }
q252881
unquote
validation
def unquote(s): """Remove quotes from a string.""" if len(s) > 1: if s.startswith('"') and s.endswith('"'): return s[1:-1].replace('\\\\', '\\').replace('\\"', '"')
python
{ "resource": "" }
q252882
formatdate
validation
def formatdate(timeval=None): """Returns time format preferred for Internet standards. Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123 According to RFC 1123, day and month names must always be in English. If not for that, this code could use strftime(). It can't because strftime() ...
python
{ "resource": "" }
q252883
Message.readheaders
validation
def readheaders(self): """Read header lines. Read header lines up to the entirely blank line that terminates them. The (normally blank) line that ends the headers is skipped, but not included in the returned list. If a non-header line ends the headers, (which is an error), an a...
python
{ "resource": "" }
q252884
Message.isheader
validation
def isheader(self, line): """Determine whether a given line is a legal header. This method should return the header name, suitably canonicalized. You may override this method in order to use Message parsing on tagged
python
{ "resource": "" }
q252885
Message.getfirstmatchingheader
validation
def getfirstmatchingheader(self, name): """Get the first header line matching name. This is similar to getallmatchingheaders, but it returns only the first matching header (and its continuation lines). """ name = name.lower() + ':' n = len(name) lst = [] ...
python
{ "resource": "" }
q252886
Message.getheader
validation
def getheader(self, name, default=None): """Get the header value for a name. This is the normal interface: it returns a stripped version of the
python
{ "resource": "" }
q252887
Message.getheaders
validation
def getheaders(self, name): """Get all values for a header. This returns a list of values for headers given more than once; each value in the result list is stripped in the same way as the result of getheader(). If the header is not given, return an empty list. """ resu...
python
{ "resource": "" }
q252888
Message.getaddrlist
validation
def getaddrlist(self, name): """Get a list of addresses from a header. Retrieves a list of addresses from a header, where each address is a tuple as returned by getaddr(). Scans all named headers, so it works properly with multiple To: or Cc: headers for example. """ ra...
python
{ "resource": "" }
q252889
AddrlistClass.gotonext
validation
def gotonext(self): """Parse up to the start of the next address.""" while self.pos < len(self.field): if self.field[self.pos] in self.LWS + '\n\r': self.pos = self.pos + 1
python
{ "resource": "" }
q252890
AddrlistClass.getaddrlist
validation
def getaddrlist(self): """Parse all addresses. Returns a list containing all of the addresses. """ result = [] ad = self.getaddress()
python
{ "resource": "" }
q252891
AddrlistClass.getaddrspec
validation
def getaddrspec(self): """Parse an RFC 2822 addr-spec.""" aslist = [] self.gotonext() while self.pos < len(self.field): if self.field[self.pos] == '.': aslist.append('.') self.pos += 1 elif self.field[self.pos] == '"': ...
python
{ "resource": "" }
q252892
AddrlistClass.getdomain
validation
def getdomain(self): """Get the complete domain name from an address.""" sdlist = [] while self.pos < len(self.field): if self.field[self.pos] in self.LWS: self.pos += 1 elif self.field[self.pos] == '(':
python
{ "resource": "" }
q252893
AddrlistClass.getdelimited
validation
def getdelimited(self, beginchar, endchars, allowcomments = 1): """Parse a header fragment delimited by special characters. `beginchar' is the start character for the fragment. If self is not looking at an instance of `beginchar' then getdelimited returns the empty string. `en...
python
{ "resource": "" }
q252894
AddrlistClass.getphraselist
validation
def getphraselist(self): """Parse a sequence of RFC 2822 phrases. A phrase is a sequence of words, which are in turn either RFC 2822 atoms or quoted-strings. Phrases are canonicalized by squeezing all runs of continuous whitespace into one space. """ plist = [] ...
python
{ "resource": "" }
q252895
_days_in_month
validation
def _days_in_month(year, month): "year, month -> number of days in that month in that year." assert 1 <= month <= 12, month if month
python
{ "resource": "" }
q252896
_ymd2ord
validation
def _ymd2ord(year, month, day): "year, month, day -> ordinal, considering 01-Jan-0001 as day 1." assert 1 <= month <= 12, 'month must be in 1..12' dim = _days_in_month(year, month) assert 1 <=
python
{ "resource": "" }
q252897
date.fromordinal
validation
def fromordinal(cls, n): """Contruct a date from a proleptic Gregorian ordinal. January 1 of year 1 is day 1. Only the year, month and day are
python
{ "resource": "" }
q252898
date.isoformat
validation
def isoformat(self): """Return the date formatted according to ISO. This is 'YYYY-MM-DD'. References: - http://www.w3.org/TR/NOTE-datetime
python
{ "resource": "" }
q252899
date.replace
validation
def replace(self, year=None, month=None, day=None): """Return a new date with new values for the specified fields.""" if year is None: year = self._year if month is None:
python
{ "resource": "" }