desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'A hook for subclasses to do some preprocessing of the Markdown, if desired. This is called after basic formatting of the text, but prior to any extras, safe mode, etc. processing.'
def preprocess(self, text):
return text
'Return a dictionary of emacs-style local variables. Parsing is done loosely according to this spec (and according to some in-practice deviations from this): http://www.gnu.org/software/emacs/manual/html_node/emacs/Specifying-File-Variables.html#Specifying-File-Variables'
def _get_emacs_vars(self, text):
emacs_vars = {} SIZE = pow(2, 13) head = text[:SIZE] if ('-*-' in head): match = self._emacs_oneliner_vars_pat.search(head) if match: emacs_vars_str = match.group(1) assert ('\n' not in emacs_vars_str) emacs_var_strs = [s.strip() for s in emacs_vars_st...
'Remove (leading?) tabs from a file. >>> m = Markdown() >>> m._detab("\tfoo") \' foo\' >>> m._detab(" \tfoo") \' foo\' >>> m._detab("\t foo") \' foo\' >>> m._detab(" foo") \' foo\' >>> m._detab(" foo\n\tbar\tblam") \' foo\n bar blam\''
def _detab(self, text):
if (' DCTB ' not in text): return text return self._detab_re.subn(self._detab_sub, text)[0]
'Hashify HTML blocks We only want to do this for block-level HTML tags, such as headers, lists, and tables. That\'s because we still want to wrap <p>s around "paragraphs" that are wrapped in non-block-level tags, such as anchors, phrase emphasis, and spans. The list of tags we\'re looking for is hard-coded. @param raw ...
def _hash_html_blocks(self, text, raw=False):
if ('<' not in text): return text hash_html_block_sub = _curry(self._hash_html_block_sub, raw=raw) text = self._strict_tag_block_re.sub(hash_html_block_sub, text) text = self._liberal_tag_block_re.sub(hash_html_block_sub, text) if ('<hr' in text): _hr_tag_re = _hr_tag_re_from_tab_wid...
'A footnote definition looks like this: [^note-id]: Text of the note. May include one or more indented paragraphs. Where, - The \'note-id\' can be pretty much anything, though typically it is the number of the footnote. - The first paragraph may start on the next line, like so: [^note-id]: Text of the note.'
def _strip_footnote_definitions(self, text):
less_than_tab = (self.tab_width - 1) footnote_def_re = re.compile(('\n ^[ ]{0,%d}\\[\\^(.+)\\]: # id = \\1\n [ \\t]*\n ( ...
'Ensure that Python interactive shell sessions are put in code blocks -- even if not properly indented.'
def _prepare_pyshell_blocks(self, text):
if ('>>>' not in text): return text less_than_tab = (self.tab_width - 1) _pyshell_block_re = re.compile(('\n ^([ ]{0,%d})>>>[ ].*\\n # first line\n ^(\\1.*\\S+.*\\n)* ...
'Copying PHP-Markdown and GFM table syntax. Some regex borrowed from https://github.com/michelf/php-markdown/blob/lib/Michelf/Markdown.php#L2538'
def _do_tables(self, text):
less_than_tab = (self.tab_width - 1) table_re = re.compile(('\n (?:(?<=\\n\\n)|\\A\\n?) # leading blank line\n\n ^[ ]{0,%d}...
'Returns the index of the first non-whitespace character in text after (and including) start'
def _find_non_whitespace(self, text, start):
match = self._whitespace.match(text, start) return match.end()
'Returns the index where the open_c and close_c characters balance out - the same number of open_c and close_c are encountered - or the end of string if it\'s reached before the balance point is found.'
def _find_balanced(self, text, start, open_c, close_c):
i = start l = len(text) count = 1 while ((count > 0) and (i < l)): if (text[i] == open_c): count += 1 elif (text[i] == close_c): count -= 1 i += 1 return i
'Extracts the url and (optional) title from the tail of a link'
def _extract_url_and_title(self, text, start):
idx = self._find_non_whitespace(text, (start + 1)) if (idx == len(text)): return (None, None, None) end_idx = idx has_anglebrackets = (text[idx] == '<') if has_anglebrackets: end_idx = self._find_balanced(text, (end_idx + 1), '<', '>') end_idx = self._find_balanced(text, end_idx,...
'Turn Markdown link shortcuts into XHTML <a> and <img> tags. This is a combination of Markdown.pl\'s _DoAnchors() and _DoImages(). They are done together because that simplified the approach. It was necessary to use a different approach than Markdown.pl because of the lack of atomic matching support in Python\'s regex ...
def _do_links(self, text):
MAX_LINK_TEXT_SENTINEL = 3000 anchor_allowed_pos = 0 curr_pos = 0 while True: try: start_idx = text.index('[', curr_pos) except ValueError: break text_length = len(text) bracket_depth = 0 for p in range((start_idx + 1), min((start_idx + MAX...
'Generate a header id attribute value from the given header HTML content. This is only called if the "header-ids" extra is enabled. Subclasses may override this for different header ids. @param text {str} The text of the header tag @param prefix {str} The requested prefix for header ids. This is the value of the "heade...
def header_id_from_text(self, text, prefix, n):
header_id = _slugify(text) if (prefix and isinstance(prefix, base_string_type)): header_id = ((prefix + '-') + header_id) if (header_id in self._count_from_header_id): self._count_from_header_id[header_id] += 1 header_id += ('-%s' % self._count_from_header_id[header_id]) else: ...
'Get the appropriate \' class="..."\' string (note the leading space), if any, for the given tag.'
def _html_class_str_from_tag(self, tag):
if ('html-classes' not in self.extras): return '' try: html_classes_from_tag = self.extras['html-classes'] except TypeError: return '' else: if (tag in html_classes_from_tag): return (' class="%s"' % html_classes_from_tag[tag]) return ''
'Process Markdown `<pre><code>` blocks.'
def _do_code_blocks(self, text):
code_block_re = re.compile(("\n (?:\\n\\n|\\A\\n?)\n ( # $1 = the code block -- one or more lines, starting with a space/...
'Process ```-fenced unindented code blocks (\'fenced-code-blocks\' extra).'
def _do_fenced_code_blocks(self, text):
return self._fenced_code_block_re.sub(self._fenced_code_block_sub, text)
'Encode/escape certain characters inside Markdown code runs. The point is that in code, these characters are literals, and lose their special Markdown meanings.'
def _encode_code(self, text):
replacements = [('&', '&amp;'), ('<', '&lt;'), ('>', '&gt;')] for (before, after) in replacements: text = text.replace(before, after) hashed = _hash_text(text) self._escape_table[text] = hashed return hashed
'Fancifies \'single quotes\', "double quotes", and apostrophes. Converts --, ---, and ... into en dashes, em dashes, and ellipses. Inspiration is: <http://daringfireball.net/projects/smartypants/> See "test/tm-cases/smarty_pants.text" for a full discussion of the support here and <http://code.google.com/p/python-markdo...
def _do_smart_punctuation(self, text):
if ("'" in text): text = self._do_smart_contractions(text) text = self._opening_single_quote_re.sub('&#8216;', text) text = self._closing_single_quote_re.sub('&#8217;', text) if ('"' in text): text = self._opening_double_quote_re.sub('&#8220;', text) text = self._closing_...
'Caveat emptor: there isn\'t much guarding against link patterns being formed inside other standard Markdown links, e.g. inside a [link def][like this]. Dev Notes: *Could* consider prefixing regexes with a negative lookbehind assertion to attempt to guard against this.'
def _do_link_patterns(self, text):
link_from_hash = {} for (regex, repl) in self.link_patterns: replacements = [] for match in regex.finditer(text): if hasattr(repl, '__call__'): href = repl(match) else: href = match.expand(repl) replacements.append((match.span()...
'Return the HTML for the current TOC. This expects the `_toc` attribute to have been set on this instance.'
def toc_html(self):
if (self._toc is None): return None def indent(): return (' ' * (len(h_stack) - 1)) lines = [] h_stack = [0] for (level, id, name) in self._toc: if (level > h_stack[(-1)]): lines.append(('%s<ul>' % indent())) h_stack.append(level) elif (...
'Return the function\'s docstring.'
def __repr__(self):
return self.func.__doc__
'Unescape markup again into an text_type string. This also resolves known HTML4 and XHTML entities: >>> Markup("Main &raquo; <em>About</em>").unescape() u\'Main \xbb <em>About</em>\''
def unescape(self):
from markupsafe._constants import HTML_ENTITIES def handle_match(m): name = m.group(1) if (name in HTML_ENTITIES): return unichr(HTML_ENTITIES[name]) try: if (name[:2] in ('#x', '#X')): return unichr(int(name[2:], 16)) elif name.startsw...
'Unescape markup into an text_type string and strip all tags. This also resolves known HTML4 and XHTML entities. Whitespace is normalized to one: >>> Markup("Main &raquo; <em>About</em>").striptags() u\'Main \xbb About\''
def striptags(self):
stripped = u' '.join(_striptags_re.sub('', self).split()) return Markup(stripped).unescape()
'Escape the string. Works like :func:`escape` with the difference that for subclasses of :class:`Markup` this function would return the correct subclass.'
@classmethod def escape(cls, s):
rv = escape(s) if (rv.__class__ is not cls): return cls(rv) return rv
'Redirect your users to here to authenticate them.'
@property def authentication_url(self):
params = {'client_id': self.client_id, 'response_type': self.type, 'redirect_uri': self.callback_url} return ((AUTHENTICATION_URL + '?') + urlencode(params))
'Wrapper around requests.request() Prepends BASE_URL to path. Adds self.oauth_token to authorization header. Parses response as JSON and returns it.'
def request(self, path, method='GET', params=None, data=None, files=None, headers=None, raw=False, allow_redirects=True, stream=False):
if (not headers): headers = {} headers['Authorization'] = ('token %s' % self.access_token) if path.startswith(('http://', 'https://')): url = path else: url = (BASE_URL + path) logger.debug('url: %s', url) response = self.session.request(method, url, params=params, ...
'Constructs the object from a dict.'
def __init__(self, resource_dict):
self.id = None self.name = None self.__dict__.update(resource_dict) try: self.created_at = strptime(self.created_at) except Exception: self.created_at = None
'List the files under directory.'
def dir(self):
return self.list(parent_id=self.id)
'handler is only used if value is not string nor unicode, prototype: def handler(value) -> str/unicode'
def __init__(self, key, priority, description, text_handler=None, type=None, filter=None, conversion=None):
assert (MIN_PRIORITY <= priority <= MAX_PRIORITY) assert isinstance(description, unicode) self.metadata = None self.key = key self.description = description self.values = [] if (type and (not isinstance(type, (tuple, list)))): type = (type,) self.type = type self.text_handler...
'Add a new value to data with name \'key\'. Skip duplicates.'
def __setattr__(self, key, value):
if (key not in self.__data): raise KeyError((_("%s has no metadata '%s'") % (self.__class__.__name__, key))) self.__data[key].add(value)
'Read first value of tag with name \'key\'. >>> from datetime import timedelta >>> a = RootMetadata() >>> a.duration = timedelta(seconds=2300) >>> a.get(\'duration\') datetime.timedelta(0, 2300) >>> a.get(\'author\', u\'Anonymous\') u\'Anonymous\''
def get(self, key, default=None, index=0):
item = self.getItem(key, index) if (item is None): if (default is None): raise ValueError(("Metadata has no value '%s' (index %s)" % (key, index))) else: return default return item.value
'Read first value, as unicode string, of tag with name \'key\'. >>> from datetime import timedelta >>> a = RootMetadata() >>> a.duration = timedelta(seconds=2300) >>> a.getText(\'duration\') u\'38 min 20 sec\' >>> a.getText(\'titre\', u\'Unknown\') u\'Unknown\''
def getText(self, key, default=None, index=0):
item = self.getItem(key, index) if (item is not None): return item.text else: return default
'Create a multi-line ASCII string (end of line is "\n") which represents all datas. >>> a = RootMetadata() >>> a.author = "haypo" >>> a.copyright = unicode("© Hachoir", "UTF-8") >>> print a Metadata: - Author: haypo - Copyright: \xa9 Hachoir @see __unicode__() and exportPlaintext()'
def __str__(self):
text = self.exportPlaintext() return '\n'.join((makePrintable(line, 'ASCII') for line in text))
'Create a multi-line Unicode string (end of line is "\n") which represents all datas. >>> a = RootMetadata() >>> a.copyright = unicode("© Hachoir", "UTF-8") >>> print repr(unicode(a)) u\'Metadata:\n- Copyright: \xa9 Hachoir\' @see __str__() and exportPlaintext()'
def __unicode__(self):
return '\n'.join(self.exportPlaintext())
'Convert metadata to multi-line Unicode string and skip datas with priority lower than specified priority. Default priority is Metadata.MAX_PRIORITY. If human flag is True, data key are translated to better human name (eg. "bit_rate" becomes "Bit rate") which may be translated using gettext. If priority is too small, m...
def exportPlaintext(self, priority=None, human=True, line_prefix=u'- ', title=None):
if (priority is not None): priority = max(priority, MIN_PRIORITY) priority = min(priority, MAX_PRIORITY) else: priority = MAX_PRIORITY if (not title): title = self.header text = [('%s:' % title)] for data in sorted(self): if (priority < data.priority): ...
'Add a new group (metadata of a sub-document). Returns False if the group is skipped, True if it has been added.'
def addGroup(self, key, metadata, header=None):
if (not metadata): self.warning(('Skip empty group %s' % key)) return False if key.endswith('[]'): key = key[:(-2)] if (key in self.__key_counter): self.__key_counter[key] += 1 else: self.__key_counter[key] = 1 key += ('[%u]' % sel...
'Use different min/max values depending on value type (datetime with timezone, datetime or date).'
def __call__(self, value):
if (not isinstance(value, self.types)): return True if (hasattr(value, 'tzinfo') and value.tzinfo): return (self.min_tz <= value <= self.max_tz) elif isinstance(value, datetime): return (self.min <= value <= self.max) else: return (self.min_date <= value <= self.max_date)...
'Reset the UniversalDetector and all of its probers back to their initial states. This is called by ``__init__``, so you only need to call this directly in between analyses of different documents.'
def reset(self):
self.result = {'encoding': None, 'confidence': 0.0} self.done = False self._got_data = False self._input_state = InputState.pure_ascii self._last_char = '' if self._esc_charset_prober: self._esc_charset_prober.reset() for prober in self._charset_probers: prober.reset()
'Takes a chunk of a document and feeds it through all of the relevant charset probers. After calling ``feed``, you can check the value of the ``done`` attribute to see if you need to continue feeding the ``UniversalDetector`` more data, or if it has made a prediction (in the ``result`` attribute). .. note:: You should ...
def feed(self, byte_str):
if self.done: return if (not len(byte_str)): return if (not self._got_data): if byte_str.startswith(codecs.BOM_UTF8): self.result = {'encoding': 'UTF-8-SIG', 'confidence': 1.0} elif byte_str.startswith(codecs.BOM_UTF32_LE): self.result = {'encoding': '...
'Stop analyzing the current document and come up with a final prediction. :returns: The ``result`` attribute if a prediction was made, otherwise ``None``.'
def close(self):
if self.done: return self.result if (not self._got_data): self.logger.debug('no data received!') return self.done = True if (self._input_state == InputState.pure_ascii): self.result = {'encoding': 'ascii', 'confidence': 1.0} return self.result if (self._...
'We define three types of bytes: alphabet: english alphabets [a-zA-Z] international: international characters [€-ÿ] marker: everything else [^a-zA-Z€-ÿ] The input buffer can be thought to contain a series of words delimited by markers. This function works to filter all words that contain at least one international char...
@staticmethod def filter_international_words(buf):
filtered = BytesIO() words = re.findall('[a-zA-Z]*[\x80-\xff]+[a-zA-Z]*[^a-zA-Z\x80-\xff]?', buf) for word in words: filtered.write(word[:(-1)]) last_char = word[(-1):] if ((not last_char.isalpha()) and (last_char < '\x80')): last_char = ' ' filtered.write(last...
'Returns a copy of ``buf`` that retains only the sequences of English alphabet and high byte characters that are not between <> characters. Also retains English alphabet and high byte characters immediately before occurrences of >. This filter can be applied to all scripts which contain both English characters and exte...
@staticmethod def filter_with_english_letters(buf):
filtered = BytesIO() in_tag = False prev = 0 for curr in range(len(buf)): buf_char = buf[curr:(curr + 1)] if (buf_char == '>'): in_tag = False elif (buf_char == '<'): in_tag = True if ((buf_char < '\x80') and (not buf_char.isalpha())): ...
'reset analyser, clear any state'
def reset(self):
self._done = False self._total_chars = 0 self._freq_chars = 0
'feed a character with known length'
def feed(self, char, char_len):
if (char_len == 2): order = self.get_order(char) else: order = (-1) if (order >= 0): self._total_chars += 1 if (order < self._table_size): if (512 > self._char_to_freq_order[order]): self._freq_chars += 1
'return confidence based on existing data'
def get_confidence(self):
if ((self._total_chars <= 0) or (self._freq_chars <= self.MINIMUM_DATA_THRESHOLD)): return self.SURE_NO if (self._total_chars != self._freq_chars): r = (self._freq_chars / ((self._total_chars - self._freq_chars) * self.typical_distribution_ratio)) if (r < self.SURE_YES): retu...
'Use a file to store all messages. The UTF-8 encoding will be used. Write an informative message if the file can\'t be created. @param filename: C{L{string}}'
def setFilename(self, filename, append=True):
filename = os.path.expanduser(filename) filename = os.path.realpath(filename) append = os.access(filename, os.F_OK) try: import codecs if append: self.__file = codecs.open(filename, 'a', 'utf-8') else: self.__file = codecs.open(filename, 'w', 'utf-8') ...
'Write a new message : append it in the buffer, display it to the screen (if needed), and write it in the log file (if needed). @param level: Message level. @type level: C{int} @param text: Message content. @type text: C{str} @param ctxt: The caller instance.'
def newMessage(self, level, text, ctxt=None):
if (((level < self.LOG_ERROR) and config.quiet) or ((level <= self.LOG_INFO) and (not config.verbose))): return if config.debug: from hachoir_core.error import getBacktrace backtrace = getBacktrace(None) if backtrace: text += ('\n\n' + backtrace) _text = text ...
'New informative message. @type text: C{str}'
def info(self, text):
self.newMessage(Log.LOG_INFO, text)
'New warning message. @type text: C{str}'
def warning(self, text):
self.newMessage(Log.LOG_WARN, text)
'New error message. @type text: C{str}'
def error(self, text):
self.newMessage(Log.LOG_ERROR, text)
'Constructor: - max_time: Maximum wanted duration of the whole benchmark (default: 5 seconds, minimum: 1 second). - min_count: Minimum number of function calls to get good statistics (defaut: 5, minimum: 1). - progress_time: Time between each "progress" message (default: 1 second, minimum: 250 ms). - max_count: Maximum...
def __init__(self, max_time=5.0, min_count=5, max_count=None, progress_time=1.0):
self.max_time = max(max_time, 1.0) self.min_count = max(min_count, 1) self.max_count = max_count self.progress_time = max(progress_time, 0.25) self.verbose = False self.disable_gc = False
'Format a time delta to string: use humanDurationNanosec()'
def formatTime(self, value):
return humanDurationNanosec((value * 1000000000))
'Display statistics to stdout: - best time (minimum) - average time (arithmetic average) - worst time (maximum) - total time (sum) Use arithmetic avertage instead of geometric average because geometric fails if any value is zero (returns zero) and also because floating point multiplication lose precision with many valu...
def displayStat(self, stat):
average = (stat.getSum() / len(stat)) values = (stat.getMin(), average, stat.getMax(), stat.getSum()) values = tuple((self.formatTime(value) for value in values)) print (_('Benchmark: best=%s average=%s worst=%s total=%s') % values)
'Call func(*args, **kw) as many times as needed to get good statistics. Algorithm: - call the function once - compute needed number of calls - and then call function N times To compute number of calls, parameters are: - time of first function call - minimum number of calls (min_count attribute) - maximum test time (max...
def _run(self, func, args, kw):
stat = BenchmarkStat() diff = self._runOnce(func, args, kw) best = diff stat.append(diff) total_time = diff count = int(floor((self.max_time / diff))) count = max(count, self.min_count) if self.max_count: count = min(count, self.max_count) if (count == 1): return stat...
'Check statistics and raise a BenchmarkError if they are invalid. Example of tests: reject empty stat, reject stat with only nul values.'
def validateStat(self, stat):
if (not stat): raise BenchmarkError('empty statistics') if (not stat.getSum()): raise BenchmarkError('nul statistics')
'Run function func(*args, **kw), validate statistics, and display the result on stdout. Disable garbage collector if asked too.'
def run(self, func, *args, **kw):
if self.disable_gc: try: import gc except ImportError: self.disable_gc = False if self.disable_gc: gc_enabled = gc.isenabled() gc.disable() else: gc_enabled = False stat = self._run(func, args, kw) if gc_enabled: gc.enable() ...
'Search a value by its key and returns its index Returns None if the key doesn\'t exist. >>> d=Dict( (("two", "deux"), ("one", "un")) ) >>> d.index("two") 0 >>> d.index("one") 1 >>> d.index("three") is None True'
def index(self, key):
return self._index.get(key)
'Get item with specified key. To get a value by it\'s index, use mydict.values[index] >>> d=Dict( (("two", "deux"), ("one", "un")) ) >>> d["one"] \'un\''
def __getitem__(self, key):
return self._value_list[self._index[key]]
'Append new value'
def append(self, key, value):
if (key in self._index): raise UniqKeyError((_("Key '%s' already exists") % key)) self._index[key] = len(self._value_list) self._key_list.append(key) self._value_list.append(value)
'Create a generator to iterate on: (key, value). >>> d=Dict( (("two", "deux"), ("one", "un")) ) >>> for key, value in d.iteritems(): ... print "%r: %r" % (key, value) \'two\': \'deux\' \'one\': \'un\''
def iteritems(self):
for index in xrange(len(self)): (yield (self._key_list[index], self._value_list[index]))
'Create an iterator on values'
def itervalues(self):
return iter(self._value_list)
'Create an iterator on keys'
def iterkeys(self):
return iter(self._key_list)
'Replace an existing value with another one >>> d=Dict( (("two", "deux"), ("one", "un")) ) >>> d.replace("one", "three", 3) >>> d {\'two\': \'deux\', \'three\': 3} You can also use the classic form: >>> d[\'three\'] = 4 >>> d {\'two\': \'deux\', \'three\': 4}'
def replace(self, oldkey, newkey, new_value):
index = self._index[oldkey] self._value_list[index] = new_value if (oldkey != newkey): del self._index[oldkey] self._index[newkey] = index self._key_list[index] = newkey
'Delete item at position index. May raise IndexError. >>> d=Dict( ((6, \'six\'), (9, \'neuf\'), (4, \'quatre\')) ) >>> del d[1] >>> d {6: \'six\', 4: \'quatre\'}'
def __delitem__(self, index):
if (index < 0): index += len(self._value_list) if (not (0 <= index < len(self._value_list))): raise IndexError((_('list assignment index out of range (%s/%s)') % (index, len(self._value_list)))) del self._value_list[index] del self._key_list[index] for (key, item_in...
'Insert an item at specified position index. >>> d=Dict( ((6, \'six\'), (9, \'neuf\'), (4, \'quatre\')) ) >>> d.insert(1, \'40\', \'quarante\') >>> d {6: \'six\', \'40\': \'quarante\', 9: \'neuf\', 4: \'quatre\'}'
def insert(self, index, key, value):
if (key in self): raise UniqKeyError((_("Insert error: key '%s' ready exists") % key)) _index = index if (index < 0): index += len(self._value_list) if (not (0 <= index <= len(self._value_list))): raise IndexError((_("Insert error: index '%s' is inva...
'Connect an event handler to an event. Append it to handlers list.'
def connect(self, event_name, handler):
try: self.handlers[event_name].append(handler) except KeyError: self.handlers[event_name] = [handler]
'Raiser an event: call each handler for this event_name.'
def raiseEvent(self, event_name, *args):
if (event_name not in self.handlers): return for handler in self.handlers[event_name]: handler(*args)
'Constructor: see L{Field.__init__} for parameter description'
def __init__(self, parent, name, size, description=None):
Field.__init__(self, parent, name, size, description)
'Constructor: see L{Field.__init__} for parameter description'
def __init__(self, parent, name, description=None):
RawBits.__init__(self, parent, name, 1, description=description)
'Read first number fields if they are not read yet. Returns number of new added fields.'
def readFirstFields(self, number):
number = (number - self.current_length) if (0 < number): return self.readMoreFields(number) else: return 0
'Try to fix last field when we know current field set size. Returns new added field if any, or None.'
def _fixLastField(self):
assert (self._size is not None) message = ['stop parser'] self._field_generator = None while (self._size < self._current_size): field = self._deleteField((len(self._fields) - 1)) message.append(('delete field %s' % field.path)) assert (self._current_size <= self._size) b...
'Parser constructor @param stream: Data input stream (see L{InputStream}) @param description: (optional) String description'
def __init__(self, stream, description=None):
assert (hasattr(self, 'endian') and (self.endian in (BIG_ENDIAN, LITTLE_ENDIAN, MIDDLE_ENDIAN))) GenericFieldSet.__init__(self, None, 'root', stream, description, stream.askSize(self))
'Try to fix last field when we know current field set size. Returns new added field if any, or None.'
def _fixLastField(self):
assert (self._size is not None) message = ['stop parser'] self._field_generator = None while (self._size < self._current_size): field = self._deleteField((len(self._fields) - 1)) message.append(('delete field %s' % field.path)) assert (self._current_size <= self._size) b...
'Set default class attributes, set right address if None address is given. @param parent: Parent field of this field @type parent: L{Field}|None @param name: Name of the field, have to be unique in parent. If it ends with "[]", end will be replaced with "[new_id]" (eg. "raw[]" becomes "raw[0]", next will be "raw[1]", a...
def __init__(self, parent, name, size=None, description=None):
assert issubclass(parent.__class__, Field) assert ((size is None) or (0 <= size)) self._parent = parent if (not name): raise ValueError('empty field name') self._name = name self._address = parent.nextFieldAddress() self._size = size self._description = description
'Method called by code like "if field: (...)". Always returns True'
def __nonzero__(self):
return True
'Constructor @param parent: Parent field set, None for root parser @param name: Name of the field, have to be unique in parent. If it ends with "[]", end will be replaced with "[new_id]" (eg. "raw[]" becomes "raw[0]", next will be "raw[1]", and then "raw[2]", etc.) @type name: str @param stream: Input stream from which...
def __init__(self, parent, name, stream, description=None, size=None):
BasicFieldSet.__init__(self, parent, name, stream, description, size) self._fields = Dict() self._field_generator = self.createFields() self._array_cache = {} self.__is_feeding = False
'Reset a field set: * clear fields ; * restart field generator ; * set current size to zero ; * clear field array count. But keep: name, value, description and size.'
def reset(self):
BasicFieldSet.reset(self) self._fields = Dict() self._field_generator = self.createFields() self._current_size = 0 self._array_cache = {}
'Returns number of fields, may need to create all fields if it\'s not done yet.'
def __len__(self):
if (self._field_generator is not None): self._feedAll() return len(self._fields)
'Add a field to the field set: * add it into _fields * update _current_size May raise a StopIteration() on error'
def _addField(self, field):
if (not issubclass(field.__class__, Field)): raise ParserError(("Field type (%s) is not a subclass of 'Field'!" % field.__class__.__name__)) assert isinstance(field._name, str) if field._name.endswith('[]'): self.setUniqueFieldName(field) if config.debug: ...
'Try to fix last field when we know current field set size. Returns new added field if any, or None.'
def _fixLastField(self):
assert (self._size is not None) message = ['stop parser'] self._field_generator = None while (self._size < self._current_size): field = self._deleteField((len(self._fields) - 1)) message.append(('delete field %s' % field.path)) assert (self._current_size <= self._size) s...
'Try to fix a feeding error. Returns False if error can\'t be fixed, otherwise returns new field if any, or None.'
def _fixFeedError(self, exception):
if ((self._size is None) or (not self.autofix)): return False self.warning(makeUnicode(exception)) return self._fixLastField()
'Return the field if it was found, None else'
def _feedUntil(self, field_name):
if (self.__is_feeding or (self._field_generator and self._field_generator.gi_running)): self.warning(('Unable to get %s (and generator is already running)' % field_name)) return None try: while True: field = self._field_generator.next() sel...
'Read more number fields, or do nothing if parsing is done. Returns number of new added fields.'
def readMoreFields(self, number):
if (self._field_generator is None): return 0 oldlen = len(self._fields) try: for index in xrange(number): self._addField(self._field_generator.next()) except HACHOIR_ERRORS as err: if (self._fixFeedError(err) is False): raise except StopIteration: ...
'Create a generator to iterate on each field, may create new fields when needed'
def __iter__(self):
try: done = 0 while True: if (done == len(self._fields)): if (self._field_generator is None): break self._addField(self._field_generator.next()) for field in self._fields.values[done:]: (yield field) ...
'Create a field to seek to specified address, or None if it\'s not needed. May raise an (ParserError) exception if address is invalid.'
def seekBit(self, address, name='padding[]', description=None, relative=True, null=False):
if relative: nbits = (address - self._current_size) else: nbits = (address - (self.absolute_address + self._current_size)) if (nbits < 0): raise ParserError('Seek error, unable to go back!') if (0 < nbits): if null: return createNullField(self, ...
'Same as seekBit(), but with address in byte.'
def seekByte(self, address, name='padding[]', description=None, relative=True, null=False):
return self.seekBit((address * 8), name, description, relative, null=null)
'Only search in existing fields'
def getFieldByAddress(self, address, feed=True):
if (feed and (self._field_generator is not None)): self._feedAll() if (address < self._current_size): i = lowerBound(self._fields.values, (lambda x: ((x.address + x.size) <= address))) if (i is not None): return self._fields.values[i] return None
'Can only write in existing fields (address < self._current_size)'
def writeFieldsIn(self, old_field, address, new_fields):
total_size = sum((field.size for field in new_fields)) if (old_field.size < total_size): raise ParserError(('Unable to write fields at address %s (too big)!' % address)) replace = [] size = (address - old_field.address) assert (0 <= size) if (0 < size): pa...
'Is the array empty or not?'
def __nonzero__(self):
if self._cache: return True else: return (0 in self)
'Number of fields in the array'
def __len__(self):
total = (self._max_index + 1) if (not self._known_size): for index in itertools.count(total): try: field = self[index] total += 1 except MissingField: break return total
'Get a field of the array. Returns a field, or raise MissingField exception if the field doesn\'t exist.'
def __getitem__(self, index):
try: value = self._cache[index] except KeyError: try: value = self.fieldset[(self._format % index)] except MissingField: self._known_size = True raise self._cache[index] = value self._max_index = max(index, self._max_index) return v...
'Iterate in the fields in their index order: field[0], field[1], ...'
def __iter__(self):
for index in itertools.count(0): try: (yield self[index]) except MissingField: raise StopIteration()
'pattern is None or repeated string'
def __init__(self, parent, name, nbytes, description='Padding', pattern=None):
assert ((pattern is None) or isinstance(pattern, str)) Bytes.__init__(self, parent, name, nbytes, description) self.pattern = pattern self._display_pattern = self.checkPattern()
'Read \'size\' bits at position \'address\' (in bits) from the beginning of the stream.'
def read(self, address, size):
raise NotImplementedError
'Read an integer number'
def readInteger(self, address, signed, nbits, endian):
value = self.readBits(address, nbits, endian) if (signed and ((1 << (nbits - 1)) <= value)): value -= (1 << nbits) return value
'If include_needle is True, add its length to the result. Returns None is needle can\'t be found.'
def searchBytesLength(self, needle, include_needle, start_address=0, end_address=None):
pos = self.searchBytes(needle, start_address, end_address) if (pos is None): return None length = ((pos - start_address) // 8) if include_needle: length += len(needle) return length
'Search some bytes in [start_address;end_address[. Addresses must be aligned to byte. Returns the address of the bytes if found, None else.'
def searchBytes(self, needle, start_address=0, end_address=None):
if (start_address % 8): raise InputStreamError('Unable to search bytes with address with bit granularity') length = len(needle) size = max((3 * length), 4096) buffer = '' if (self._size and ((end_address is None) or (self._size < end_address))): end_address = ...
'Read bytes from the stream at specified address (in bits). Address have to be a multiple of 8. nbytes have to in 1..MAX_READ_NBYTES (64 KB). This method is only supported for StringOuputStream (not on FileOutputStream). Return read bytes as byte string.'
def readBytes(self, address, nbytes):
assert ((address % 8) == 0) assert (1 <= nbytes <= MAX_READ_NBYTES) self._output.flush() oldpos = self._output.tell() try: self._output.seek(0) try: return self._output.read(nbytes) except IOError as err: if (err[0] == EBADF): raise Out...
'Acquire the lock. * If timeout is omitted (or None), wait forever trying to lock the file. * If timeout > 0, try to acquire the lock for that many seconds. If the lock period expires and the file is still locked, raise LockTimeout. * If timeout <= 0, raise AlreadyLocked immediately if the file is already locked.'
def acquire(self, timeout=None):
raise NotImplemented('implement in subclass')
'Release the lock. If the file is not locked, raise NotLocked.'
def release(self):
raise NotImplemented('implement in subclass')
'Context manager support.'
def __enter__(self):
self.acquire() return self