signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def get_tags(self, rev=None):
raise NotImplementedError()<EOL>
Get the tags for the specified revision (or the current revision if none is specified).
f9128:c0:m9
def get_repo_tags(self):
raise NotImplementedError()<EOL>
Get all tags for the repository.
f9128:c0:m10
def get_parent_tags(self, rev=None):
try:<EOL><INDENT>parent_rev = one(self.get_parent_revs(rev))<EOL><DEDENT>except Exception:<EOL><INDENT>return None<EOL><DEDENT>return self.get_tags(parent_rev)<EOL>
Return the tags for the parent revision (or None if no single parent can be identified).
f9128:c0:m11
def get_parent_revs(self, rev=None):
raise NotImplementedError<EOL>
Get the parent revision for the specified revision (or the current revision if none is specified).
f9128:c0:m12
def is_modified(self):
raise NotImplementedError()<EOL>
Does the current working copy have modifications
f9128:c0:m13
def find_all_files(self):
files = self.find_files()<EOL>subrepo_files = (<EOL>posixpath.join(subrepo.location, filename)<EOL>for subrepo in self.subrepos()<EOL>for filename in subrepo.find_files()<EOL>)<EOL>return itertools.chain(files, subrepo_files)<EOL>
Find files including those in subrepositories.
f9128:c0:m14
def version(self):
lines = iter(self._invoke('<STR_LIT:version>').splitlines())<EOL>version = next(lines).strip()<EOL>return self._parse_version(version)<EOL>
Return the underlying version
f9130:c0:m1
def find_files(self):
all_files = self._invoke('<STR_LIT>', '<STR_LIT>', '<STR_LIT:.>').splitlines()<EOL>from_root = os.path.relpath(self.location, self.find_root())<EOL>loc_rel_paths = [<EOL>os.path.relpath(path, from_root)<EOL>for path in all_files]<EOL>return loc_rel_paths<EOL>
Find versioned files in self.location
f9130:c1:m1
def get_tags(self, rev=None):
rev_num = self._get_rev_num(rev)<EOL>return (<EOL>set(self._read_tags_for_rev(rev_num))<EOL>if not rev_num.endswith('<STR_LIT:+>')<EOL>else set([])<EOL>)<EOL>
Get the tags for the given revision specifier (or the current revision if not specified).
f9130:c1:m3
def _read_tags_for_rev(self, rev_num):
return (tr.tag for tr in self._read_tags_for_revset(rev_num))<EOL>
Return the tags for revision sorted by when the tags were created (latest first)
f9130:c1:m4
def _read_tags_for_revset(self, spec):
cmd = [<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT:default>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', spec]<EOL>res = self._invoke(*cmd)<EOL>header_pattern = re.compile(r'<STR_LIT>')<EOL>match_res = map(header_pattern.match, res.splitlines())<EOL>matched_lines = filter(None, match_res)<EOL>matches = (match.groupdict() for match in matched_lines)<EOL>for match in matches:<EOL><INDENT>if match['<STR_LIT>'] == '<STR_LIT>':<EOL><INDENT>id, sep, rev = match['<STR_LIT:value>'].partition('<STR_LIT::>')<EOL><DEDENT>if match['<STR_LIT>'] == '<STR_LIT>':<EOL><INDENT>tag = match['<STR_LIT:value>']<EOL>yield TaggedRevision(tag, rev)<EOL><DEDENT><DEDENT>
Return TaggedRevision for each tag/rev combination in the revset spec
f9130:c1:m5
def _get_rev_num(self, rev=None):
<EOL>cmd = ['<STR_LIT>', '<STR_LIT>']<EOL>cmd.extend(['<STR_LIT>', '<STR_LIT>'])<EOL>if rev:<EOL><INDENT>cmd.extend(['<STR_LIT>', rev])<EOL><DEDENT>res = self._invoke(*cmd)<EOL>return res.strip()<EOL>
Determine the revision number for a given revision specifier.
f9130:c1:m6
def _get_tags_by_num(self):
by_revision = operator.attrgetter('<STR_LIT>')<EOL>tags = sorted(self.get_tags(), key=by_revision)<EOL>revision_tags = itertools.groupby(tags, key=by_revision)<EOL>def get_id(rev):<EOL><INDENT>return rev.split('<STR_LIT::>', <NUM_LIT:1>)[<NUM_LIT:0>]<EOL><DEDENT>return dict(<EOL>(get_id(rev), [tr.tag for tr in tr_list])<EOL>for rev, tr_list in revision_tags<EOL>)<EOL>
Return a dictionary mapping revision number to tags for that number.
f9130:c1:m7
def get_ancestral_tags(self, rev='<STR_LIT:.>'):
spec = '<STR_LIT>'.format(**vars())<EOL>return self._read_tags_for_revset(spec)<EOL>
Like get_repo_tags, but only get those tags ancestral to the current changeset.
f9130:c1:m9
def get_tags(self, rev=None):
rev = rev or '<STR_LIT>'<EOL>return set(self._invoke('<STR_LIT>', '<STR_LIT>', rev).splitlines())<EOL>
Return the tags for the current revision as a set
f9130:c2:m4
def is_modified(self):
return False<EOL>
Is the current state modified? (currently stubbed assuming no)
f9130:c2:m6
def iter_subclasses(cls, _seen=None):
if not isinstance(cls, type):<EOL><INDENT>raise TypeError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % cls<EOL>)<EOL><DEDENT>if _seen is None:<EOL><INDENT>_seen = set()<EOL><DEDENT>try:<EOL><INDENT>subs = cls.__subclasses__()<EOL><DEDENT>except TypeError: <EOL><INDENT>subs = cls.__subclasses__(cls)<EOL><DEDENT>for sub in subs:<EOL><INDENT>if sub in _seen:<EOL><INDENT>continue<EOL><DEDENT>_seen.add(sub)<EOL>yield sub<EOL>for sub in iter_subclasses(sub, _seen):<EOL><INDENT>yield sub<EOL><DEDENT><DEDENT>
Generator over all subclasses of a given class, in depth-first order. >>> bool in list(iter_subclasses(int)) True >>> class A(object): pass >>> class B(A): pass >>> class C(A): pass >>> class D(B,C): pass >>> class E(D): pass >>> >>> for cls in iter_subclasses(A): ... print(cls.__name__) B D E C >>> # get ALL (new-style) classes currently defined >>> res = [cls.__name__ for cls in iter_subclasses(object)] >>> 'type' in res True >>> 'tuple' in res True >>> len(res) > 100 True
f9131:m0
def one(iterable, too_short=None, too_long=None):
it = iter(iterable)<EOL>try:<EOL><INDENT>value = next(it)<EOL><DEDENT>except StopIteration:<EOL><INDENT>raise too_short or ValueError('<STR_LIT>')<EOL><DEDENT>try:<EOL><INDENT>next(it)<EOL><DEDENT>except StopIteration:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>raise too_long or ValueError('<STR_LIT>')<EOL><DEDENT>return value<EOL>
Return the first item from *iterable*, which is expected to contain only that item. Raise an exception if *iterable* is empty or has more than one item. :func:`one` is useful for ensuring that an iterable contains only one item. For example, it can be used to retrieve the result of a database query that is expected to return a single row. If *iterable* is empty, ``ValueError`` will be raised. You may specify a different exception with the *too_short* keyword: >>> it = [] >>> one(it) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... ValueError: too many items in iterable (expected 1)' >>> too_short = IndexError('too few items') >>> one(it, too_short=too_short) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... IndexError: too few items Similarly, if *iterable* contains more than one item, ``ValueError`` will be raised. You may specify a different exception with the *too_long* keyword: >>> it = ['too', 'many'] >>> one(it) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... ValueError: too many items in iterable (expected 1)' >>> too_long = RuntimeError >>> one(it, too_long=too_long) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... RuntimeError Note that :func:`one` attempts to advance *iterable* twice to ensure there is only one item. If there is more than one, both items will be discarded. See :func:`spy` or :func:`peekable` to check iterable contents less destructively.
f9131:m1
def _get_font_size(document, style):
font_size = style.get_font_size()<EOL>if font_size == -<NUM_LIT:1>:<EOL><INDENT>if style.based_on:<EOL><INDENT>based_on = document.styles.get_by_id(style.based_on)<EOL>if based_on:<EOL><INDENT>return _get_font_size(document, based_on)<EOL><DEDENT><DEDENT><DEDENT>return font_size<EOL>
Get font size defined for this style. It will try to get font size from it's parent style if it is not defined by original style. :Args: - document (:class:`ooxml.doc.Document`): Document object - style (:class:`ooxml.doc.Style`): Style object :Returns: Returns font size as a number. -1 if it can not get font size.
f9136:m0
def _get_numbering(document, numid, ilvl):
try:<EOL><INDENT>abs_num = document.numbering[numid]<EOL>return document.abstruct_numbering[abs_num][ilvl]['<STR_LIT>']<EOL><DEDENT>except:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>
Returns type for the list. :Returns: Returns type for the list. Returns "bullet" by default or in case of an error.
f9136:m2
def _get_numbering_tag(fmt):
if fmt == '<STR_LIT>':<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>return '<STR_LIT>'<EOL>
Returns HTML tag defined for this kind of numbering. :Args: - fmt (str): Type of numbering :Returns: Returns "ol" for numbered lists and "ul" for everything else.
f9136:m3
def _get_parent(root):
elem = root<EOL>while True:<EOL><INDENT>elem = elem.getparent()<EOL>if elem.tag in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>return elem<EOL><DEDENT><DEDENT>
Returns root element for a list. :Args: root (Element): lxml element of current location :Returns: lxml element representing list
f9136:m4
def close_list(ctx, root):
try:<EOL><INDENT>n = len(ctx.in_list)<EOL>if n <= <NUM_LIT:0>:<EOL><INDENT>return root<EOL><DEDENT>elem = root<EOL>while n > <NUM_LIT:0>:<EOL><INDENT>while True:<EOL><INDENT>if elem.tag in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']: <EOL><INDENT>elem = elem.getparent()<EOL>break<EOL><DEDENT>elem = elem.getparent()<EOL><DEDENT>n -= <NUM_LIT:1><EOL><DEDENT>ctx.in_list = []<EOL>return elem<EOL><DEDENT>except:<EOL><INDENT>return None<EOL><DEDENT>
Close already opened list if needed. This will try to see if it is needed to close already opened list. :Args: - ctx (:class:`Context`): Context object - root (Element): lxml element representing current position. :Returns: lxml element where future content should be placed.
f9136:m5
def open_list(ctx, document, par, root, elem):
_ls = None<EOL>if par.ilvl != ctx.ilvl or par.numid != ctx.numid:<EOL><INDENT>if ctx.ilvl is not None and (par.ilvl > ctx.ilvl):<EOL><INDENT>fmt = _get_numbering(document, par.numid, par.ilvl)<EOL>if par.ilvl > <NUM_LIT:0>:<EOL><INDENT>_b = list(root)[-<NUM_LIT:1>]<EOL>_ls = etree.SubElement(_b, _get_numbering_tag(fmt))<EOL>root = _ls<EOL><DEDENT>else:<EOL><INDENT>_ls = etree.SubElement(root, _get_numbering_tag(fmt))<EOL>root = _ls<EOL><DEDENT>fire_hooks(ctx, document, par, _ls, ctx.get_hook(_get_numbering_tag(fmt)))<EOL>ctx.in_list.append((par.numid, par.ilvl))<EOL><DEDENT>elif ctx.ilvl is not None and par.ilvl < ctx.ilvl:<EOL><INDENT>fmt = _get_numbering(document, ctx.numid, ctx.ilvl)<EOL>try:<EOL><INDENT>while True:<EOL><INDENT>numid, ilvl = ctx.in_list[-<NUM_LIT:1>]<EOL>if numid == par.numid and ilvl == par.ilvl:<EOL><INDENT>break<EOL><DEDENT>root = _get_parent(root)<EOL>ctx.in_list.pop()<EOL><DEDENT><DEDENT>except:<EOL><INDENT>pass<EOL>
Open list if it is needed and place current element as first member of a list. :Args: - ctx (:class:`Context`): Context object - document (:class:`ooxml.doc.Document`): Document object - par (:class:`ooxml.doc.Paragraph`): Paragraph element - root (Element): lxml element of current location - elem (Element): lxml element representing current element we are trying to insert :Returns: lxml element where future content should be placed.
f9136:m6
def serialize_break(ctx, document, elem, root):
if elem.break_type == u'<STR_LIT>':<EOL><INDENT>_div = etree.SubElement(root, '<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>_div = etree.SubElement(root, '<STR_LIT>')<EOL>if ctx.options['<STR_LIT>']:<EOL><INDENT>_div.set('<STR_LIT>', '<STR_LIT>')<EOL><DEDENT><DEDENT>fire_hooks(ctx, document, elem, _div, ctx.get_hook('<STR_LIT>'))<EOL>return root<EOL>
Serialize break element.
f9136:m7
def serialize_math(ctx, document, elem, root):
_div = etree.SubElement(root, '<STR_LIT>')<EOL>if ctx.options['<STR_LIT>']:<EOL><INDENT>_div.set('<STR_LIT>', '<STR_LIT>')<EOL><DEDENT>_div.text = '<STR_LIT>'<EOL>fire_hooks(ctx, document, elem, _div, ctx.get_hook('<STR_LIT>'))<EOL>return root<EOL>
Serialize math element. Math objects are not supported at the moment. This is wht we only show error message.
f9136:m8
def serialize_link(ctx, document, elem, root):
_a = etree.SubElement(root, '<STR_LIT:a>')<EOL>for el in elem.elements:<EOL><INDENT>_ser = ctx.get_serializer(el)<EOL>if _ser:<EOL><INDENT>_td = _ser(ctx, document, el, _a)<EOL><DEDENT>else:<EOL><INDENT>if isinstance(el, doc.Text):<EOL><INDENT>children = list(_a)<EOL>if len(children) == <NUM_LIT:0>:<EOL><INDENT>_text = _a.text or u'<STR_LIT>'<EOL>_a.text = u'<STR_LIT>'.format(_text, el.value())<EOL><DEDENT>else:<EOL><INDENT>_text = children[-<NUM_LIT:1>].tail or u'<STR_LIT>'<EOL>children[-<NUM_LIT:1>].tail = u'<STR_LIT>'.format(_text, el.value())<EOL><DEDENT><DEDENT><DEDENT><DEDENT>if elem.rid in document.relationships[ctx.options['<STR_LIT>']]:<EOL><INDENT>_a.set('<STR_LIT>', document.relationships[ctx.options['<STR_LIT>']][elem.rid].get('<STR_LIT:target>', '<STR_LIT>'))<EOL><DEDENT>fire_hooks(ctx, document, elem, _a, ctx.get_hook('<STR_LIT:a>'))<EOL>return root<EOL>
Serilaze link element. This works only for external links at the moment.
f9136:m9
def serialize_image(ctx, document, elem, root):
_img = etree.SubElement(root, '<STR_LIT>')<EOL>if elem.rid in document.relationships[ctx.options['<STR_LIT>']]:<EOL><INDENT>img_src = document.relationships[ctx.options['<STR_LIT>']][elem.rid].get('<STR_LIT:target>', '<STR_LIT>')<EOL>img_name, img_extension = os.path.splitext(img_src)<EOL>_img.set('<STR_LIT:src>', '<STR_LIT>'.format(elem.rid, img_extension))<EOL><DEDENT>fire_hooks(ctx, document, elem, _img, ctx.get_hook('<STR_LIT>'))<EOL>return root<EOL>
Serialize image element. This is not abstract enough.
f9136:m10
def fire_hooks(ctx, document, elem, element, hooks):
if not hooks:<EOL><INDENT>return<EOL><DEDENT>for hook in hooks:<EOL><INDENT>hook(ctx, document, elem, element)<EOL><DEDENT>
Fire hooks on newly created element. For each newly created element we will try to find defined hooks and execute them. :Args: - ctx (:class:`Context`): Context object - document (:class:`ooxml.doc.Document`): Document object - elem (:class:`ooxml.doc.Element`): Element which we serialized - element (Element): lxml element which we created - hooks (list): List of hooks
f9136:m11
def has_style(node):
elements = ['<STR_LIT:b>', '<STR_LIT:i>', '<STR_LIT:u>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>return any([True for elem in elements if elem in node.rpr])<EOL>
Tells us if node element has defined styling. :Args: - node (:class:`ooxml.doc.Element`): Element :Returns: True or False
f9136:m12
def get_style_fontsize(node):
if hasattr(node, '<STR_LIT>'):<EOL><INDENT>if '<STR_LIT>' in node.rpr:<EOL><INDENT>return int(node.rpr['<STR_LIT>']) / <NUM_LIT:2><EOL><DEDENT><DEDENT>return <NUM_LIT:0><EOL>
Returns font size defined by this element. :Args: - node (:class:`ooxml.doc.Element`): Node element :Returns: Font size as int number or 0 if it is not defined
f9136:m13
def get_style_css(ctx, node, embed=True, fontsize=-<NUM_LIT:1>):
style = []<EOL>if not node:<EOL><INDENT>return<EOL><DEDENT>if fontsize in [-<NUM_LIT:1>, <NUM_LIT:2>]:<EOL><INDENT>if '<STR_LIT>' in node.rpr:<EOL><INDENT>size = int(node.rpr['<STR_LIT>']) / <NUM_LIT:2><EOL>if ctx.options['<STR_LIT>']:<EOL><INDENT>if ctx.options['<STR_LIT>']: <EOL><INDENT>multiplier = size-ctx.options['<STR_LIT>']<EOL>scale = <NUM_LIT:100> + int(math.trunc(<NUM_LIT>*multiplier))<EOL>style.append('<STR_LIT>'.format(scale))<EOL><DEDENT>else:<EOL><INDENT>style.append('<STR_LIT>'.format(size))<EOL><DEDENT><DEDENT><DEDENT><DEDENT>if fontsize in [-<NUM_LIT:1>, <NUM_LIT:1>]:<EOL><INDENT>if not embed:<EOL><INDENT>if '<STR_LIT:b>' in node.rpr:<EOL><INDENT>style.append('<STR_LIT>')<EOL><DEDENT>if '<STR_LIT:i>' in node.rpr:<EOL><INDENT>style.append('<STR_LIT>')<EOL><DEDENT>if '<STR_LIT:u>' in node.rpr:<EOL><INDENT>style.append('<STR_LIT>')<EOL><DEDENT><DEDENT>if '<STR_LIT>' in node.rpr:<EOL><INDENT>style.append('<STR_LIT>')<EOL><DEDENT>if '<STR_LIT>' in node.rpr:<EOL><INDENT>style.append('<STR_LIT>')<EOL><DEDENT>if '<STR_LIT>' in node.rpr:<EOL><INDENT>if node.rpr['<STR_LIT>'] != '<STR_LIT>':<EOL><INDENT>style.append('<STR_LIT>'.format(node.rpr['<STR_LIT>']))<EOL><DEDENT><DEDENT>if '<STR_LIT>' in node.ppr:<EOL><INDENT>align = node.ppr['<STR_LIT>']<EOL>if align.lower() == '<STR_LIT>':<EOL><INDENT>align = '<STR_LIT>'<EOL><DEDENT>style.append('<STR_LIT>'.format(align))<EOL><DEDENT>if '<STR_LIT>' in node.ppr:<EOL><INDENT>if '<STR_LIT:left>' in node.ppr['<STR_LIT>']:<EOL><INDENT>size = int(node.ppr['<STR_LIT>']['<STR_LIT:left>']) / <NUM_LIT:10><EOL>style.append('<STR_LIT>'.format(size))<EOL><DEDENT>if '<STR_LIT:right>' in node.ppr['<STR_LIT>']:<EOL><INDENT>size = int(node.ppr['<STR_LIT>']['<STR_LIT:right>']) / <NUM_LIT:10><EOL>style.append('<STR_LIT>'.format(size))<EOL><DEDENT>if '<STR_LIT>' in node.ppr['<STR_LIT>']:<EOL><INDENT>size = int(node.ppr['<STR_LIT>']['<STR_LIT>']) / <NUM_LIT:10><EOL>style.append('<STR_LIT>'.format(size))<EOL><DEDENT><DEDENT><DEDENT>if len(style) == <NUM_LIT:0>:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>return '<STR_LIT>'.join(style) + '<STR_LIT:;>'<EOL>
Returns as string defined CSS for this node. Defined CSS can be different if it is embeded or no. When it is embeded styling for bold,italic and underline will not be defined with CSS. In that case we use defined tags <b>,<i>,<u> from the content. :Args: - ctx (:class:`Context`): Context object - node (:class:`ooxml.doc.Element`): Node element - embed (book): True by default. :Returns: Returns as string defined CSS for this node
f9136:m14
def get_style(document, elem):
try:<EOL><INDENT>return document.styles.get_by_id(elem.style_id)<EOL><DEDENT>except AttributeError:<EOL><INDENT>return None<EOL><DEDENT>
Get the style for this node element. :Args: - document (:class:`ooxml.doc.Document`): Document object - elem (:class:`ooxml.doc.Element`): Node element :Returns: Returns :class:`ooxml.doc.Style` object or None if it is not found.
f9136:m15
def get_style_name(style):
return style.style_id<EOL>
Returns style if for specific style.
f9136:m16
def get_all_styles(document, style):
classes = []<EOL>while True:<EOL><INDENT>classes.insert(<NUM_LIT:0>, get_style_name(style))<EOL>if style.based_on:<EOL><INDENT>style = document.styles.get_by_id(style.based_on)<EOL><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT>return classes<EOL>
Returns list of styles on which specified style is based on. :Args: - document (:class:`ooxml.doc.Document`): Document object - style (:class:`ooxml.doc.Style`): Style object :Returns: List of style objects.
f9136:m17
def get_css_classes(document, style):
lst = [st.lower() for st in get_all_styles(document, style)[-<NUM_LIT:1>:]] +['<STR_LIT>'.format(st.lower()) for st in get_all_styles(document, style)[-<NUM_LIT:1>:]]<EOL>return '<STR_LIT:U+0020>'.join(lst)<EOL>
Returns CSS classes for this style. This function will check all the styles specified style is based on and return their CSS classes. :Args: - document (:class:`ooxml.doc.Document`): Document object - style (:class:`ooxml.doc.Style`): Style object :Returns: String representing all the CSS classes for this element. >>> get_css_classes(doc, st) 'header1 normal'
f9136:m18
def serialize_paragraph(ctx, document, par, root, embed=True):
style = get_style(document, par)<EOL>elem = etree.Element('<STR_LIT:p>')<EOL>if ctx.options['<STR_LIT>']:<EOL><INDENT>_style = get_style_css(ctx, par)<EOL>if _style != '<STR_LIT>':<EOL><INDENT>elem.set('<STR_LIT>', _style)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>_style = '<STR_LIT>'<EOL><DEDENT>if style:<EOL><INDENT>elem.set('<STR_LIT:class>', get_css_classes(document, style))<EOL><DEDENT>max_font_size = get_style_fontsize(par)<EOL>if style:<EOL><INDENT>max_font_size = _get_font_size(document, style)<EOL><DEDENT>for el in par.elements:<EOL><INDENT>_serializer = ctx.get_serializer(el)<EOL>if _serializer:<EOL><INDENT>_serializer(ctx, document, el, elem)<EOL><DEDENT>if isinstance(el, doc.Text):<EOL><INDENT>children = list(elem)<EOL>_text_style = get_style_css(ctx, el)<EOL>_text_class = el.rpr.get('<STR_LIT>', '<STR_LIT>').lower()<EOL>if _text_class == '<STR_LIT>':<EOL><INDENT>__s = get_style(document, par)<EOL>if __s is not None:<EOL><INDENT>_text_class = get_style_name(__s).lower()<EOL><DEDENT><DEDENT>if get_style_fontsize(el) > max_font_size:<EOL><INDENT>max_font_size = get_style_fontsize(el)<EOL><DEDENT>if '<STR_LIT>' in el.rpr:<EOL><INDENT>new_element = etree.Element('<STR_LIT>')<EOL>new_element.text = el.value()<EOL><DEDENT>elif '<STR_LIT>' in el.rpr:<EOL><INDENT>new_element = etree.Element('<STR_LIT>')<EOL>new_element.text = el.value() <EOL><DEDENT>elif '<STR_LIT:b>' in el.rpr or '<STR_LIT:i>' in el.rpr or '<STR_LIT:u>' in el.rpr: <EOL><INDENT>new_element = None<EOL>_element = None<EOL>def _add_formatting(f, new_element, _element):<EOL><INDENT>if f in el.rpr:<EOL><INDENT>_t = etree.Element(f)<EOL>if new_element is not None:<EOL><INDENT>_element.append(_t)<EOL>_element = _t<EOL><DEDENT>else:<EOL><INDENT>new_element = _t<EOL>_element = new_element<EOL><DEDENT><DEDENT>return new_element, _element<EOL><DEDENT>new_element, _element = _add_formatting('<STR_LIT:b>', new_element, _element)<EOL>new_element, _element = _add_formatting('<STR_LIT:i>', new_element, _element)<EOL>new_element, _element = _add_formatting('<STR_LIT:u>', new_element, _element)<EOL>_element.text = el.value()<EOL>for comment_id in ctx.opened_comments:<EOL><INDENT>document.comments[comment_id].text += '<STR_LIT:U+0020>' + el.value()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>new_element = etree.Element('<STR_LIT>')<EOL>new_element.text = el.value()<EOL>if ctx.options['<STR_LIT>']:<EOL><INDENT>try:<EOL><INDENT>new_element.set('<STR_LIT:class>', _text_class)<EOL><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>for comment_id in ctx.opened_comments:<EOL><INDENT>if comment_id in document.comments:<EOL><INDENT>document.comments[comment_id].text += '<STR_LIT:U+0020>' + el.value()<EOL><DEDENT><DEDENT><DEDENT>if ctx.options['<STR_LIT>']:<EOL><INDENT>if _text_style != '<STR_LIT>' and _style != _text_style:<EOL><INDENT>new_element.set('<STR_LIT>', _text_style)<EOL><DEDENT><DEDENT>was_inserted = False<EOL>if len(children) > <NUM_LIT:0>:<EOL><INDENT>_child_style = children[-<NUM_LIT:1>].get('<STR_LIT>') or '<STR_LIT>'<EOL>_child_class = children[-<NUM_LIT:1>].get('<STR_LIT:class>', '<STR_LIT>')<EOL>if new_element.tag == children[-<NUM_LIT:1>].tag and ((_text_class == _child_class or _child_class == '<STR_LIT>') and (_text_style == _child_style or _child_style == '<STR_LIT>')) and children[-<NUM_LIT:1>].tail is None:<EOL><INDENT>txt = children[-<NUM_LIT:1>].text or '<STR_LIT>'<EOL>txt2 = new_element.text or '<STR_LIT>'<EOL>children[-<NUM_LIT:1>].text = u'<STR_LIT>'.format(txt, txt2) <EOL>was_inserted = True<EOL><DEDENT>if not was_inserted:<EOL><INDENT>if _style == _text_style and new_element.tag == '<STR_LIT>' and (_text_class == _child_class or _child_class == '<STR_LIT>'):<EOL><INDENT>_e = children[-<NUM_LIT:1>]<EOL>txt = _e.tail or '<STR_LIT>'<EOL>_e.tail = u'<STR_LIT>'.format(txt, new_element.text)<EOL>was_inserted = True<EOL><DEDENT>if not was_inserted and new_element.tag == '<STR_LIT>' and (_text_class != _child_class):<EOL><INDENT>_e = children[-<NUM_LIT:1>]<EOL>txt = _e.tail or '<STR_LIT>'<EOL>_e.tail = u'<STR_LIT>'.format(txt, new_element.text)<EOL>was_inserted = True <EOL><DEDENT><DEDENT><DEDENT>if not was_inserted:<EOL><INDENT>_child_class = new_element.get('<STR_LIT:class>', '<STR_LIT>')<EOL>try:<EOL><INDENT>_child_class = children[-<NUM_LIT:1>].get('<STR_LIT:class>', '<STR_LIT>')<EOL><DEDENT>except:<EOL><INDENT>_child_class = '<STR_LIT>'<EOL><DEDENT>if _style == _text_style and new_element.tag == '<STR_LIT>' and (_text_class == _child_class):<EOL><INDENT>txt = elem.text or '<STR_LIT>'<EOL>elem.text = u'<STR_LIT>'.format(txt, new_element.text)<EOL><DEDENT>else:<EOL><INDENT>if new_element.text != u'<STR_LIT>':<EOL><INDENT>elem.append(new_element)<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>if not par.is_dropcap() and par.ilvl == None:<EOL><INDENT>if style:<EOL><INDENT>if ctx.header.is_header(par, max_font_size, elem, style=style):<EOL><INDENT>elem.tag = ctx.header.get_header(par, style, elem)<EOL>if par.ilvl == None: <EOL><INDENT>root = close_list(ctx, root)<EOL>ctx.ilvl, ctx.numid = None, None<EOL><DEDENT>if root is not None:<EOL><INDENT>root.append(elem)<EOL><DEDENT>fire_hooks(ctx, document, par, elem, ctx.get_hook('<STR_LIT:h>'))<EOL>return root<EOL><DEDENT><DEDENT>else:<EOL><INDENT>Commented part where we only checked for heading if font size<EOL>was bigger than default font size. In many cases this did not<EOL>work out well.<EOL>if max_font_size > ctx.header.default_font_size:<EOL>
Serializes paragraph element. This is the most important serializer of them all.
f9136:m19
def serialize_symbol(ctx, document, el, root):
span = etree.SubElement(root, '<STR_LIT>')<EOL>span.text = el.value()<EOL>fire_hooks(ctx, document, el, span, ctx.get_hook('<STR_LIT>'))<EOL>return root<EOL>
Serialize special symbols.
f9136:m20
def serialize_footnote(ctx, document, el, root):
footnote_num = el.rid<EOL>if el.rid not in ctx.footnote_list:<EOL><INDENT>ctx.footnote_id += <NUM_LIT:1><EOL>ctx.footnote_list[el.rid] = ctx.footnote_id<EOL><DEDENT>footnote_num = ctx.footnote_list[el.rid]<EOL>note = etree.SubElement(root, '<STR_LIT>')<EOL>link = etree.SubElement(note, '<STR_LIT:a>')<EOL>link.set('<STR_LIT>', '<STR_LIT:#>')<EOL>link.text = u'<STR_LIT:{}>'.format(footnote_num)<EOL>fire_hooks(ctx, document, el, note, ctx.get_hook('<STR_LIT>'))<EOL>return root<EOL>
Serializes footnotes.
f9136:m21
def serialize_comment(ctx, document, el, root):
<EOL>if el.comment_type == '<STR_LIT:end>':<EOL><INDENT>ctx.opened_comments.remove(el.cid)<EOL><DEDENT>else:<EOL><INDENT>if el.comment_type != '<STR_LIT>':<EOL><INDENT>ctx.opened_comments.append(el.cid)<EOL><DEDENT>if ctx.options['<STR_LIT>']:<EOL><INDENT>link = etree.SubElement(root, '<STR_LIT:a>')<EOL>link.set('<STR_LIT>', '<STR_LIT:#>')<EOL>link.set('<STR_LIT:class>', '<STR_LIT>') <EOL>link.set('<STR_LIT:id>', '<STR_LIT>' + el.cid) <EOL>link.text = '<STR_LIT>'<EOL>fire_hooks(ctx, document, el, link, ctx.get_hook('<STR_LIT>'))<EOL><DEDENT><DEDENT>return root<EOL>
Serializes comment.
f9136:m22
def serialize_endnote(ctx, document, el, root):
footnote_num = el.rid<EOL>if el.rid not in ctx.endnote_list:<EOL><INDENT>ctx.endnote_id += <NUM_LIT:1><EOL>ctx.endnote_list[el.rid] = ctx.endnote_id<EOL><DEDENT>footnote_num = ctx.endnote_list[el.rid]<EOL>note = etree.SubElement(root, '<STR_LIT>')<EOL>link = etree.SubElement(note, '<STR_LIT:a>')<EOL>link.set('<STR_LIT>', '<STR_LIT:#>')<EOL>link.text = u'<STR_LIT:{}>'.format(footnote_num)<EOL>fire_hooks(ctx, document, el, note, ctx.get_hook('<STR_LIT>'))<EOL>return root<EOL>
Serializes endnotes.
f9136:m23
def serialize_smarttag(ctx, document, el, root):
if ctx.options['<STR_LIT>']:<EOL><INDENT>_span = etree.SubElement(root, '<STR_LIT>', {'<STR_LIT:class>': '<STR_LIT>', '<STR_LIT>': el.element})<EOL><DEDENT>else:<EOL><INDENT>_span = root<EOL><DEDENT>for elem in el.elements:<EOL><INDENT>_ser = ctx.get_serializer(elem)<EOL>if _ser:<EOL><INDENT>_td = _ser(ctx, document, elem, _span)<EOL><DEDENT>else:<EOL><INDENT>if isinstance(elem, doc.Text):<EOL><INDENT>children = list(_span)<EOL>if len(children) == <NUM_LIT:0>:<EOL><INDENT>_text = _span.text or u'<STR_LIT>'<EOL>_span.text = u'<STR_LIT>'.format(_text, elem.text)<EOL><DEDENT>else:<EOL><INDENT>_text = children[-<NUM_LIT:1>].tail or u'<STR_LIT>'<EOL>children[-<NUM_LIT:1>].tail = u'<STR_LIT>'.format(_text, elem.text)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>fire_hooks(ctx, document, el, _span, ctx.get_hook('<STR_LIT>'))<EOL>return root<EOL>
Serializes smarttag.
f9136:m24
def serialize_table(ctx, document, table, root):
<EOL>if root is None:<EOL><INDENT>return root<EOL><DEDENT>if ctx.ilvl != None:<EOL><INDENT>root = close_list(ctx, root)<EOL>ctx.ilvl, ctx.numid = None, None<EOL><DEDENT>_table = etree.SubElement(root, '<STR_LIT>')<EOL>_table.set('<STR_LIT>', '<STR_LIT:1>')<EOL>_table.set('<STR_LIT:width>', '<STR_LIT>')<EOL>style = get_style(document, table)<EOL>if style:<EOL><INDENT>_table.set('<STR_LIT:class>', get_css_classes(document, style))<EOL><DEDENT>for rows in table.rows:<EOL><INDENT>_tr = etree.SubElement(_table, '<STR_LIT>')<EOL>for cell in rows:<EOL><INDENT>_td = etree.SubElement(_tr, '<STR_LIT>')<EOL>if cell.grid_span != <NUM_LIT:1>:<EOL><INDENT>_td.set('<STR_LIT>', str(cell.grid_span))<EOL><DEDENT>if cell.row_span != <NUM_LIT:1>:<EOL><INDENT>_td.set('<STR_LIT>', str(cell.row_span))<EOL><DEDENT>for elem in cell.elements:<EOL><INDENT>if isinstance(elem, doc.Paragraph):<EOL><INDENT>_ser = ctx.get_serializer(elem)<EOL>_td = _ser(ctx, document, elem, _td, embed=False)<EOL><DEDENT><DEDENT>if ctx.ilvl != None:<EOL><INDENT>root = close_list(ctx, root)<EOL>
Serializes table element.
f9136:m25
def serialize_textbox(ctx, document, txtbox, root):
_div = etree.SubElement(root, '<STR_LIT>')<EOL>_div.set('<STR_LIT:class>', '<STR_LIT>')<EOL>for elem in txtbox.elements:<EOL><INDENT>_ser = ctx.get_serializer(elem)<EOL>if _ser:<EOL><INDENT>_ser(ctx, document, elem, _div)<EOL><DEDENT><DEDENT>fire_hooks(ctx, document, txtbox, _div, ctx.get_hook('<STR_LIT>'))<EOL>return root<EOL>
Serialize textbox element.
f9136:m26
def serialize_styles(document, prefix='<STR_LIT>', options=None):
all_styles = []<EOL>css_content = '<STR_LIT>'<EOL>for style_id in document.used_styles:<EOL><INDENT>all_styles += get_all_styles(document, document.styles.get_by_id(style_id))<EOL><DEDENT>def _generate(ctx, style_id, n):<EOL><INDENT>style = document.styles.get_by_id(style_id)<EOL>style_css = get_style_css(ctx, style, embed=False)<EOL>return "<STR_LIT>".format("<STR_LIT:U+002C>".join(['<STR_LIT>'.format(prefix, x) for x in n]), style_css)<EOL><DEDENT>ctx = Context(document, options=options)<EOL>for style_type, style_id in six.iteritems(document.styles.default_styles): <EOL><INDENT>if style_type == '<STR_LIT>':<EOL><INDENT>n = ["<STR_LIT>"]<EOL>css_content += _generate(ctx, style_id, n)<EOL><DEDENT>elif style_type == '<STR_LIT>':<EOL><INDENT>n = ["<STR_LIT:p>", "<STR_LIT>"] <EOL>css_content += _generate(ctx, style_id, n) <EOL><DEDENT>elif style_type == '<STR_LIT>':<EOL><INDENT>n = ["<STR_LIT>"]<EOL>css_content += _generate(ctx, style_id, n) <EOL><DEDENT>elif style_type == '<STR_LIT>':<EOL><INDENT>n = ["<STR_LIT>", "<STR_LIT>"]<EOL>css_content += _generate(ctx, style_id, n)<EOL><DEDENT><DEDENT>for style_id in set(all_styles):<EOL><INDENT>style = document.styles.get_by_id(style_id)<EOL>styles = []<EOL>while True:<EOL><INDENT>styles.insert(<NUM_LIT:0>, style)<EOL>if style.based_on:<EOL><INDENT>style = document.styles.get_by_id(style.based_on)<EOL><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT>content = "<STR_LIT:\n>".join([get_style_css(ctx, st, embed=False, fontsize=<NUM_LIT:1>) for st in styles])<EOL>css_content += "<STR_LIT>".format(prefix, style_id.lower(), content)<EOL>content = "<STR_LIT:\n>".join([get_style_css(ctx, st, embed=False, fontsize=<NUM_LIT:2>) for st in styles])<EOL>css_content += "<STR_LIT>".format(prefix, style_id.lower(), content)<EOL><DEDENT>return css_content<EOL>
:Args: - document (:class:`ooxml.doc.Document`): Document object - prefix (str): Optional prefix used for - options (dict): Optional dictionary with :class:`Context` options :Returns: CSS styles as string. >>> serialize_styles(doc) p { color: red; } >>> serialize_styles(doc, '#editor') #editor p { color: red; }
f9136:m27
def serialize_elements(document, elements, options=None):
ctx = Context(document, options)<EOL>tree_root = root = etree.Element('<STR_LIT>')<EOL>for elem in elements:<EOL><INDENT>_ser = ctx.get_serializer(elem)<EOL>if _ser:<EOL><INDENT>root = _ser(ctx, document, elem, root)<EOL><DEDENT><DEDENT>return etree.tostring(tree_root, pretty_print=ctx.options.get('<STR_LIT>', True), encoding="<STR_LIT:utf-8>", xml_declaration=False)<EOL>
Serialize list of elements into HTML string. :Args: - document (:class:`ooxml.doc.Document`): Document object - elements (list): List of elements - options (dict): Optional dictionary with :class:`Context` options :Returns: Returns HTML representation of the document.
f9136:m28
def serialize(document, options=None):
return serialize_elements(document, document.elements, options)<EOL>
Serialize entire document into HTML string. :Args: - document (:class:`ooxml.doc.Document`): Document object - options (dict): Optional dictionary with :class:`Context` options :Returns: Returns HTML representation of the document.
f9136:m29
def is_header(self, elem, font_size, node, style=None):
<EOL>if hasattr(style, '<STR_LIT>'):<EOL><INDENT>fnt_size = _get_font_size(self.doc, style)<EOL>from .importer import calculate_weight<EOL>weight = calculate_weight(self.doc, elem)<EOL>if weight > <NUM_LIT:50>:<EOL><INDENT>return False<EOL><DEDENT>if fnt_size in self.doc.possible_headers_style: <EOL><INDENT>return True<EOL><DEDENT>return font_size in self.doc.possible_headers<EOL><DEDENT>else:<EOL><INDENT>list_of_sizes = {}<EOL>for el in elem.elements:<EOL><INDENT>try:<EOL><INDENT>fs = get_style_fontsize(el)<EOL>weight = len(el.value()) if el.value() else <NUM_LIT:0><EOL>list_of_sizes[fs] = list_of_sizes.setdefault(fs, <NUM_LIT:0>) + weight<EOL><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>sorted_list_of_sizes = list(collections.OrderedDict(sorted(six.iteritems(list_of_sizes), key=lambda t: t[<NUM_LIT:0>])))<EOL>font_size_to_check = font_size<EOL>if len(sorted_list_of_sizes) > <NUM_LIT:0>:<EOL><INDENT>if sorted_list_of_sizes[<NUM_LIT:0>] != font_size:<EOL><INDENT>return sorted_list_of_sizes[<NUM_LIT:0>] in self.doc.possible_headers<EOL><DEDENT><DEDENT>return font_size in self.doc.possible_headers<EOL><DEDENT>
Used for checking if specific element is a header or not. :Returns: True or False
f9136:c0:m2
def get_header(self, elem, style, node):
font_size = style<EOL>if hasattr(elem, '<STR_LIT>'):<EOL><INDENT>if elem.possible_header:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT><DEDENT>if not style:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>if hasattr(style, '<STR_LIT>'):<EOL><INDENT>font_size = _get_font_size(self.doc, style)<EOL><DEDENT>try:<EOL><INDENT>if font_size in self.doc.possible_headers_style:<EOL><INDENT>return '<STR_LIT>'.format(self.doc.possible_headers_style.index(font_size)+<NUM_LIT:1>)<EOL><DEDENT>return '<STR_LIT>'.format(self.doc.possible_headers.index(font_size)+<NUM_LIT:1>)<EOL><DEDENT>except ValueError:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>
Returns HTML tag representing specific header for this element. :Returns: String representation of HTML tag.
f9136:c0:m3
def get_hook(self, name):
return self.options['<STR_LIT>'].get(name, None)<EOL>
Get reference to a specific hook. :Args: - name (str): Hook name :Returns: List with defined hooks. None if it is not found.
f9136:c1:m1
def get_serializer(self, node):
return self.options['<STR_LIT>'].get(type(node), None)<EOL>if type(node) in self.options['<STR_LIT>']:<EOL><INDENT>return self.options['<STR_LIT>'][type(node)]<EOL><DEDENT>return None<EOL>
Returns serializer for specific element. :Args: - node (:class:`ooxml.doc.Element`): Element object :Returns: Returns reference to a function which will be used for serialization.
f9136:c1:m2
def text_length(elem):
if not elem:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>value = elem.value()<EOL>try:<EOL><INDENT>value = len(value)<EOL><DEDENT>except:<EOL><INDENT>value = <NUM_LIT:0><EOL><DEDENT>try:<EOL><INDENT>for a in elem.elements:<EOL><INDENT>value += len(a.value())<EOL><DEDENT><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT>return value<EOL>
Returns length of the content in this element. Return value is not correct but it is **good enough***.
f9137:m0
def mark_styles(ctx, doc, elements):
not_using_styles = False<EOL>if ctx.options['<STR_LIT>']:<EOL><INDENT>if len(doc.used_styles) < ctx.options['<STR_LIT>'] and len(doc.possible_headers) < ctx.options['<STR_LIT>']:<EOL><INDENT>not_using_styles = True<EOL>doc.possible_headers = [POSSIBLE_HEADER_SIZE] + doc.possible_headers<EOL>logger.info('<STR_LIT>')<EOL><DEDENT><DEDENT>markers = [{'<STR_LIT:name>': '<STR_LIT>', '<STR_LIT>': <NUM_LIT:0>, '<STR_LIT:index>': <NUM_LIT:0>, '<STR_LIT>': <NUM_LIT:0>}]<EOL>for pos, elem in enumerate(elements):<EOL><INDENT>try:<EOL><INDENT>style = doc.styles.get_by_id(elem.style_id)<EOL><DEDENT>except AttributeError:<EOL><INDENT>style = None<EOL><DEDENT>if isinstance(elem, Paragraph):<EOL><INDENT>if elem.is_dropcap():<EOL><INDENT>continue<EOL><DEDENT>for el in elem.elements:<EOL><INDENT>if isinstance(el, Break):<EOL><INDENT>markers.append({'<STR_LIT:name>': '<STR_LIT>', '<STR_LIT>': <NUM_LIT:0>, '<STR_LIT:index>': pos, '<STR_LIT>': <NUM_LIT:0>, '<STR_LIT>': True})<EOL><DEDENT><DEDENT><DEDENT>weight = calculate_weight(doc, elem)<EOL>if weight == <NUM_LIT:0>:<EOL><INDENT>continue<EOL><DEDENT>font_size = -<NUM_LIT:1><EOL>has_found = False<EOL>if isinstance(elem, TOC):<EOL><INDENT>markers.append({'<STR_LIT:name>': '<STR_LIT>', '<STR_LIT>': weight, '<STR_LIT:index>': pos, '<STR_LIT>': fnt_size, '<STR_LIT>': True})<EOL>continue <EOL><DEDENT>if style:<EOL><INDENT>markers.append({'<STR_LIT:name>': elem.style_id, '<STR_LIT>': weight, '<STR_LIT:index>': pos})<EOL>if elem.style_id == '<STR_LIT>':<EOL><INDENT>markers[-<NUM_LIT:1>]['<STR_LIT>'] = True<EOL><DEDENT>has_found = True<EOL><DEDENT>else:<EOL><INDENT>if ctx.options['<STR_LIT>']:<EOL><INDENT>if hasattr(elem, '<STR_LIT>') and '<STR_LIT>' in elem.rpr:<EOL><INDENT>t_length = text_length(elem)<EOL>if t_length < ctx.options['<STR_LIT>'] and t_length >= ctx.options['<STR_LIT>']:<EOL><INDENT>markers.append({'<STR_LIT:name>': '<STR_LIT>', '<STR_LIT>': weight, '<STR_LIT:index>': pos, '<STR_LIT>': int(elem.rpr['<STR_LIT>']) / <NUM_LIT:2>})<EOL>font_size = int(elem.rpr['<STR_LIT>'])/<NUM_LIT:2><EOL>has_found = True<EOL><DEDENT><DEDENT><DEDENT>if ctx.options['<STR_LIT>']:<EOL><INDENT>if not_using_styles:<EOL><INDENT>if hasattr(elem, '<STR_LIT>') and ('<STR_LIT>' in elem.ppr or '<STR_LIT:b>' in elem.rpr or '<STR_LIT:i>' in elem.rpr):<EOL><INDENT>if text_length(elem) < <NUM_LIT:30>:<EOL><INDENT>elements[pos].possible_header = True<EOL>markers.append({'<STR_LIT:name>': '<STR_LIT>', '<STR_LIT>': weight+<NUM_LIT:100>, '<STR_LIT:index>': pos, '<STR_LIT>': POSSIBLE_HEADER_SIZE})<EOL>font_size = POSSIBLE_HEADER_SIZE<EOL>has_found = True<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>if ctx.options['<STR_LIT>']:<EOL><INDENT>if hasattr(elem, '<STR_LIT>'):<EOL><INDENT>for e in elem.elements:<EOL><INDENT>if hasattr(e, '<STR_LIT>') and '<STR_LIT>' in e.rpr:<EOL><INDENT>t_length = text_length(elem)<EOL>if t_length < ctx.options['<STR_LIT>'] and t_length >= ctx.options['<STR_LIT>']: <EOL><INDENT>fnt_size = int(e.rpr['<STR_LIT>'])/<NUM_LIT:2><EOL>if fnt_size != font_size:<EOL><INDENT>markers.append({'<STR_LIT:name>': '<STR_LIT>', '<STR_LIT>': weight, '<STR_LIT:index>': pos, '<STR_LIT>': fnt_size})<EOL>has_found = True<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>if not has_found and len(markers) > <NUM_LIT:0>:<EOL><INDENT>markers[-<NUM_LIT:1>]['<STR_LIT>'] += weight<EOL><DEDENT><DEDENT>return markers<EOL>
Checks all elements and creates a list of diferent markers for styles or different elements.
f9137:m7
def reset(self):
self.zf = zipfile.ZipFile(self.file_name, '<STR_LIT:r>')<EOL>self._doc = None<EOL>
Resets the values.
f9138:c0:m2
def read_from_file(file_name):
from .docxfile import DOCXFile<EOL>dfile = DOCXFile(file_name)<EOL>dfile.parse()<EOL>return dfile<EOL>
Parser OOXML file and returns parsed document. :Args: - file_name (str): Path to OOXML file :Returns: Returns object of type :class:`ooxml.docx.DOCXFile`.
f9139:m0
def get_font_size(self):
if '<STR_LIT>' in self.rpr:<EOL><INDENT>return int(self.rpr['<STR_LIT>'])/<NUM_LIT:2><EOL><DEDENT>return -<NUM_LIT:1><EOL>
Returns font size for this style. Does not check definition in the parent styles. :Returns: Returns font size as integer. Returns -1 if font size is not defined for this style.
f9140:c0:m2
def get_by_name(self, name, style_type = None):
for st in self.styles.values():<EOL><INDENT>if st:<EOL><INDENT>if st.name == name:<EOL><INDENT>return st<EOL><DEDENT><DEDENT><DEDENT>if style_type and not st:<EOL><INDENT>st = self.styles.get(self.default_styles[style_type], None) <EOL><DEDENT>return st<EOL>
Find style by it's descriptive name. :Returns: Returns found style of type :class:`ooxml.doc.Style`.
f9140:c1:m1
def get_by_id(self, style_id, style_type = None):
for st in self.styles.values():<EOL><INDENT>if st:<EOL><INDENT>if st.style_id == style_id:<EOL><INDENT>return st<EOL><DEDENT><DEDENT><DEDENT>if style_type:<EOL><INDENT>return self.styles.get(self.default_styles[style_type], None)<EOL><DEDENT>return None<EOL>
Find style by it's unique identifier :Returns: Returns found style of type :class:`ooxml.doc.Style`.
f9140:c1:m2
def _name(name):
return name.format(**NAMESPACES)<EOL>
Returns full name for the attribute. It checks predefined namespaces used in OOXML documents. >>> _name('{{{w}}}rStyle') '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}rStyle'
f9141:m0
def parse_drawing(document, container, elem):
_blip = elem.xpath('<STR_LIT>', namespaces=NAMESPACES)<EOL>if len(_blip) > <NUM_LIT:0>:<EOL><INDENT>blip = _blip[<NUM_LIT:0>]<EOL>_rid = blip.attrib[_name('<STR_LIT>')]<EOL>img = doc.Image(_rid)<EOL>container.elements.append(img)<EOL><DEDENT>
Parse drawing element. We don't do much with drawing element. We can find embeded image but we don't do more than that.
f9141:m4
def parse_footnote(document, container, elem):
_rid = elem.attrib[_name('<STR_LIT>')]<EOL>foot = doc.Footnote(_rid)<EOL>container.elements.append(foot)<EOL>
Parse the footnote element.
f9141:m5
def parse_endnote(document, container, elem):
_rid = elem.attrib[_name('<STR_LIT>')]<EOL>note = doc.Endnote(_rid)<EOL>container.elements.append(note)<EOL>
Parse the endnote element.
f9141:m6
def parse_text(document, container, element):
txt = None<EOL>alternate = element.find(_name('<STR_LIT>'))<EOL>if alternate is not None:<EOL><INDENT>parse_alternate(document, container, alternate)<EOL><DEDENT>br = element.find(_name('<STR_LIT>'))<EOL>if br is not None:<EOL><INDENT>if _name('<STR_LIT>') in br.attrib:<EOL><INDENT>_type = br.attrib[_name('<STR_LIT>')]<EOL>brk = doc.Break(_type)<EOL><DEDENT>else:<EOL><INDENT>brk = doc.Break()<EOL><DEDENT>container.elements.append(brk)<EOL><DEDENT>t = element.find(_name('<STR_LIT>'))<EOL>if t is not None:<EOL><INDENT>txt = doc.Text(t.text)<EOL>txt.parent = container<EOL>container.elements.append(txt)<EOL><DEDENT>rpr = element.find(_name('<STR_LIT>'))<EOL>if rpr is not None:<EOL><INDENT>parse_previous_properties(document, txt, rpr)<EOL><DEDENT>for r in element.findall(_name('<STR_LIT>')):<EOL><INDENT>parse_text(document, container, r)<EOL><DEDENT>foot = element.find(_name('<STR_LIT>'))<EOL>if foot is not None:<EOL><INDENT>parse_footnote(document, container, foot)<EOL><DEDENT>end = element.find(_name('<STR_LIT>'))<EOL>if end is not None:<EOL><INDENT>parse_endnote(document, container, end)<EOL><DEDENT>sym = element.find(_name('<STR_LIT>'))<EOL>if sym is not None:<EOL><INDENT>_font = sym.attrib[_name('<STR_LIT>')]<EOL>_char = sym.attrib[_name('<STR_LIT>')]<EOL>container.elements.append(doc.Symbol(font=_font, character=_char))<EOL><DEDENT>image = element.find(_name('<STR_LIT>'))<EOL>if image is not None:<EOL><INDENT>parse_drawing(document, container, image)<EOL><DEDENT>refe = element.find(_name('<STR_LIT>'))<EOL>if refe is not None:<EOL><INDENT>_m = doc.Comment(refe.attrib[_name('<STR_LIT>')], '<STR_LIT>')<EOL>container.elements.append(_m)<EOL><DEDENT>return<EOL>
Parse text element.
f9141:m8
def parse_smarttag(document, container, tag_elem):
tag = doc.SmartTag()<EOL>tag.element = tag_elem.attrib[_name('<STR_LIT>')]<EOL>for elem in tag_elem:<EOL><INDENT>if elem.tag == _name('<STR_LIT>'):<EOL><INDENT>parse_text(document, tag, elem)<EOL><DEDENT>if elem.tag == _name('<STR_LIT>'):<EOL><INDENT>parse_smarttag(document, tag, elem)<EOL><DEDENT><DEDENT>container.elements.append(tag)<EOL>return<EOL>
Parse the endnote element.
f9141:m9
def parse_paragraph(document, par):
paragraph = doc.Paragraph()<EOL>paragraph.document = document<EOL>for elem in par:<EOL><INDENT>if elem.tag == _name('<STR_LIT>'):<EOL><INDENT>parse_paragraph_properties(document, paragraph, elem)<EOL><DEDENT>if elem.tag == _name('<STR_LIT>'):<EOL><INDENT>parse_text(document, paragraph, elem)<EOL><DEDENT>if elem.tag == _name('<STR_LIT>'):<EOL><INDENT>_m = doc.Math()<EOL>paragraph.elements.append(_m)<EOL><DEDENT>if elem.tag == _name('<STR_LIT>'):<EOL><INDENT>_m = doc.Math()<EOL>paragraph.elements.append(_m)<EOL><DEDENT>if elem.tag == _name('<STR_LIT>'):<EOL><INDENT>_m = doc.Comment(elem.attrib[_name('<STR_LIT>')], '<STR_LIT:start>')<EOL>paragraph.elements.append(_m)<EOL><DEDENT>if elem.tag == _name('<STR_LIT>'):<EOL><INDENT>_m = doc.Comment(elem.attrib[_name('<STR_LIT>')], '<STR_LIT:end>')<EOL>paragraph.elements.append(_m)<EOL><DEDENT>if elem.tag == _name('<STR_LIT>'):<EOL><INDENT>try:<EOL><INDENT>t = doc.Link(elem.attrib[_name('<STR_LIT>')])<EOL>parse_text(document, t, elem)<EOL>paragraph.elements.append(t)<EOL><DEDENT>except:<EOL><INDENT>logger.error('<STR_LIT>', str(elem.attrib.items()))<EOL><DEDENT><DEDENT>if elem.tag == _name('<STR_LIT>'):<EOL><INDENT>parse_smarttag(document, paragraph, elem)<EOL><DEDENT><DEDENT>return paragraph<EOL>
Parse paragraph element. Some other elements could be found inside of paragraph element (math, links).
f9141:m10
def parse_table_properties(doc, table, prop):
if not table:<EOL><INDENT>return<EOL><DEDENT>style = prop.find(_name('<STR_LIT>'))<EOL>if style is not None:<EOL><INDENT>table.style_id = style.attrib[_name('<STR_LIT>')]<EOL>doc.add_style_as_used(table.style_id)<EOL><DEDENT>
Parse table properties.
f9141:m11
def parse_table_column_properties(doc, cell, prop):
if not cell:<EOL><INDENT>return<EOL><DEDENT>grid = prop.find(_name('<STR_LIT>'))<EOL>if grid is not None:<EOL><INDENT>cell.grid_span = int(grid.attrib[_name('<STR_LIT>')])<EOL><DEDENT>vmerge = prop.find(_name('<STR_LIT>'))<EOL>if vmerge is not None:<EOL><INDENT>if _name('<STR_LIT>') in vmerge.attrib:<EOL><INDENT>cell.vmerge = vmerge.attrib[_name('<STR_LIT>')]<EOL><DEDENT>else:<EOL><INDENT>cell.vmerge = "<STR_LIT>"<EOL><DEDENT><DEDENT>
Parse table column properties.
f9141:m12
def parse_table(document, tbl):
def _change(rows, pos_x):<EOL><INDENT>if len(rows) == <NUM_LIT:1>:<EOL><INDENT>return rows<EOL><DEDENT>count_x = <NUM_LIT:1><EOL>for x in rows[-<NUM_LIT:1>]:<EOL><INDENT>if count_x == pos_x:<EOL><INDENT>x.row_span += <NUM_LIT:1><EOL><DEDENT>count_x += x.grid_span<EOL><DEDENT>return rows<EOL><DEDENT>table = doc.Table()<EOL>tbl_pr = tbl.find(_name('<STR_LIT>'))<EOL>if tbl_pr is not None:<EOL><INDENT>parse_table_properties(document, table, tbl_pr)<EOL><DEDENT>for tr in tbl.xpath('<STR_LIT>', namespaces=NAMESPACES):<EOL><INDENT>columns = []<EOL>pos_x = <NUM_LIT:0><EOL>for tc in tr.xpath('<STR_LIT>', namespaces=NAMESPACES):<EOL><INDENT>cell = doc.TableCell()<EOL>tc_pr = tc.find(_name('<STR_LIT>'))<EOL>if tc_pr is not None:<EOL><INDENT>parse_table_column_properties(doc, cell, tc_pr)<EOL><DEDENT>pos_x += cell.grid_span<EOL>if cell.vmerge is not None and cell.vmerge == "<STR_LIT>":<EOL><INDENT>table.rows = _change(table.rows, pos_x)<EOL><DEDENT>else:<EOL><INDENT>for p in tc.xpath('<STR_LIT>', namespaces=NAMESPACES):<EOL><INDENT>cell.elements.append(parse_paragraph(document, p))<EOL><DEDENT>columns.append(cell)<EOL><DEDENT><DEDENT>table.rows.append(columns)<EOL><DEDENT>return table<EOL>
Parse table element.
f9141:m13
def parse_document(xmlcontent):
document = etree.fromstring(xmlcontent)<EOL>body = document.xpath('<STR_LIT>', namespaces=NAMESPACES)[<NUM_LIT:0>]<EOL>document = doc.Document()<EOL>for elem in body:<EOL><INDENT>if elem.tag == _name('<STR_LIT>'):<EOL><INDENT>document.elements.append(parse_paragraph(document, elem))<EOL><DEDENT>if elem.tag == _name('<STR_LIT>'):<EOL><INDENT>document.elements.append(parse_table(document, elem))<EOL><DEDENT>if elem.tag == _name('<STR_LIT>'):<EOL><INDENT>document.elements.append(doc.TOC())<EOL><DEDENT><DEDENT>return document<EOL>
Parse document with content. Content is placed in file 'document.xml'.
f9141:m14
def parse_relationship(document, xmlcontent, rel_type):
doc = etree.fromstring(xmlcontent)<EOL>for elem in doc:<EOL><INDENT>if elem.tag == _name('<STR_LIT>'):<EOL><INDENT>rel = {'<STR_LIT:target>': elem.attrib['<STR_LIT>'],<EOL>'<STR_LIT:type>': elem.attrib['<STR_LIT>'],<EOL>'<STR_LIT>': elem.attrib.get('<STR_LIT>', '<STR_LIT>')}<EOL>document.relationships[rel_type][elem.attrib['<STR_LIT>']] = rel<EOL><DEDENT><DEDENT>
Parse relationship document. Relationships hold information like external or internal references for links. Relationships are placed in file '_rels/document.xml.rels'.
f9141:m15
def parse_style(document, xmlcontent):
styles = etree.fromstring(xmlcontent)<EOL>_r = styles.xpath('<STR_LIT>', namespaces=NAMESPACES)<EOL>if len(_r) > <NUM_LIT:0>:<EOL><INDENT>rpr = _r[<NUM_LIT:0>].find(_name('<STR_LIT>'))<EOL>if rpr is not None:<EOL><INDENT>st = doc.Style()<EOL>parse_previous_properties(document, st, rpr)<EOL>document.default_style = st<EOL><DEDENT><DEDENT>for style in styles.xpath('<STR_LIT>', namespaces=NAMESPACES):<EOL><INDENT>st = doc.Style()<EOL>st.style_id = style.attrib[_name('<STR_LIT>')]<EOL>style_type = style.attrib[_name('<STR_LIT>')]<EOL>if style_type is not None:<EOL><INDENT>st.style_type = style_type<EOL><DEDENT>if _name('<STR_LIT>') in style.attrib:<EOL><INDENT>is_default = style.attrib[_name('<STR_LIT>')]<EOL>if is_default is not None:<EOL><INDENT>st.is_default = is_default == '<STR_LIT:1>'<EOL><DEDENT><DEDENT>name = style.find(_name('<STR_LIT>'))<EOL>if name is not None:<EOL><INDENT>st.name = name.attrib[_name('<STR_LIT>')]<EOL><DEDENT>based_on = style.find(_name('<STR_LIT>'))<EOL>if based_on is not None:<EOL><INDENT>st.based_on = based_on.attrib[_name('<STR_LIT>')]<EOL><DEDENT>document.styles.styles[st.style_id] = st<EOL>if st.is_default:<EOL><INDENT>document.styles.default_styles[st.style_type] = st.style_id<EOL><DEDENT>rpr = style.find(_name('<STR_LIT>'))<EOL>if rpr is not None:<EOL><INDENT>parse_previous_properties(document, st, rpr)<EOL><DEDENT>ppr = style.find(_name('<STR_LIT>'))<EOL>if ppr is not None:<EOL><INDENT>parse_paragraph_properties(document, st, ppr)<EOL><DEDENT><DEDENT>
Parse styles document. Styles are defined in file 'styles.xml'.
f9141:m16
def parse_comments(document, xmlcontent):
comments = etree.fromstring(xmlcontent)<EOL>document.comments = {}<EOL>for comment in comments.xpath('<STR_LIT>', namespaces=NAMESPACES):<EOL><INDENT>comment_id = comment.attrib[_name('<STR_LIT>')]<EOL>comm = doc.CommentContent(comment_id)<EOL>comm.author = comment.attrib.get(_name('<STR_LIT>'), None)<EOL>comm.date = comment.attrib.get(_name('<STR_LIT>'), None)<EOL>comm.elements = [parse_paragraph(document, para) for para in comment.xpath('<STR_LIT>', namespaces=NAMESPACES)]<EOL>document.comments[comment_id] = comm<EOL><DEDENT>
Parse comments document. Comments are defined in file 'comments.xml'
f9141:m17
def parse_footnotes(document, xmlcontent):
footnotes = etree.fromstring(xmlcontent)<EOL>document.footnotes = {}<EOL>for footnote in footnotes.xpath('<STR_LIT>', namespaces=NAMESPACES):<EOL><INDENT>_type = footnote.attrib.get(_name('<STR_LIT>'), None)<EOL>if _type in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>continue<EOL><DEDENT>paragraphs = [parse_paragraph(document, para) for para in footnote.xpath('<STR_LIT>', namespaces=NAMESPACES)]<EOL>document.footnotes[footnote.attrib[_name('<STR_LIT>')]] = paragraphs<EOL><DEDENT>
Parse footnotes document. Footnotes are defined in file 'footnotes.xml'
f9141:m18
def parse_endnotes(document, xmlcontent):
endnotes = etree.fromstring(xmlcontent)<EOL>document.endnotes = {}<EOL>for note in endnotes.xpath('<STR_LIT>', namespaces=NAMESPACES):<EOL><INDENT>paragraphs = [parse_paragraph(document, para) for para in note.xpath('<STR_LIT>', namespaces=NAMESPACES)]<EOL>document.endnotes[note.attrib[_name('<STR_LIT>')]] = paragraphs<EOL><DEDENT>
Parse endnotes document. Endnotes are defined in file 'endnotes.xml'
f9141:m19
def parse_numbering(document, xmlcontent):
numbering = etree.fromstring(xmlcontent)<EOL>document.abstruct_numbering = {}<EOL>document.numbering = {}<EOL>for abstruct_num in numbering.xpath('<STR_LIT>', namespaces=NAMESPACES):<EOL><INDENT>numb = {}<EOL>for lvl in abstruct_num.xpath('<STR_LIT>', namespaces=NAMESPACES):<EOL><INDENT>ilvl = int(lvl.attrib[_name('<STR_LIT>')])<EOL>fmt = lvl.find(_name('<STR_LIT>'))<EOL>numb[ilvl] = {'<STR_LIT>': fmt.attrib[_name('<STR_LIT>')]}<EOL><DEDENT>document.abstruct_numbering[abstruct_num.attrib[_name('<STR_LIT>')]] = numb<EOL><DEDENT>for num in numbering.xpath('<STR_LIT>', namespaces=NAMESPACES):<EOL><INDENT>num_id = num.attrib[_name('<STR_LIT>')]<EOL>abs_num = num.find(_name('<STR_LIT>'))<EOL>if abs_num is not None:<EOL><INDENT>number_id = abs_num.attrib[_name('<STR_LIT>')]<EOL>document.numbering[int(num_id)] = number_id<EOL><DEDENT><DEDENT>
Parse numbering document. Numbering is defined in file 'numbering.xml'.
f9141:m20
def parse_from_file(file_object):
logger.info('<STR_LIT>', file_object.file_name)<EOL>doc_content = file_object.read_file('<STR_LIT>')<EOL>document = parse_document(doc_content)<EOL>try:<EOL><INDENT>style_content = file_object.read_file('<STR_LIT>')<EOL>parse_style(document, style_content)<EOL><DEDENT>except KeyError:<EOL><INDENT>logger.warning('<STR_LIT>')<EOL><DEDENT>try:<EOL><INDENT>doc_rel_content = file_object.read_file('<STR_LIT>')<EOL>parse_relationship(document, doc_rel_content, '<STR_LIT>')<EOL><DEDENT>except KeyError:<EOL><INDENT>logger.warning('<STR_LIT>')<EOL><DEDENT>try:<EOL><INDENT>doc_rel_content = file_object.read_file('<STR_LIT>')<EOL>parse_relationship(document, doc_rel_content, '<STR_LIT>')<EOL><DEDENT>except KeyError:<EOL><INDENT>logger.warning('<STR_LIT>')<EOL><DEDENT>try:<EOL><INDENT>doc_rel_content = file_object.read_file('<STR_LIT>')<EOL>parse_relationship(document, doc_rel_content, '<STR_LIT>')<EOL><DEDENT>except KeyError:<EOL><INDENT>logger.warning('<STR_LIT>')<EOL><DEDENT>try:<EOL><INDENT>comments_content = file_object.read_file('<STR_LIT>')<EOL>parse_comments(document, comments_content)<EOL><DEDENT>except KeyError:<EOL><INDENT>logger.warning('<STR_LIT>')<EOL><DEDENT>try:<EOL><INDENT>footnotes_content = file_object.read_file('<STR_LIT>')<EOL>parse_footnotes(document, footnotes_content)<EOL><DEDENT>except KeyError:<EOL><INDENT>logger.warning('<STR_LIT>')<EOL><DEDENT>try:<EOL><INDENT>endnotes_content = file_object.read_file('<STR_LIT>')<EOL>parse_endnotes(document, endnotes_content)<EOL><DEDENT>except KeyError:<EOL><INDENT>logger.warning('<STR_LIT>')<EOL><DEDENT>try:<EOL><INDENT>numbering_content = file_object.read_file('<STR_LIT>')<EOL>parse_numbering(document, numbering_content)<EOL><DEDENT>except KeyError:<EOL><INDENT>logger.warning('<STR_LIT>')<EOL><DEDENT>return document<EOL>
Parses existing OOXML file. :Args: - file_object (:class:`ooxml.docx.DOCXFile`): OOXML file object :Returns: Returns parsed document of type :class:`ooxml.doc.Document`
f9141:m21
def __init__(self, *args, **kwargs):
fields = (<EOL>forms.CharField(),<EOL>forms.CharField(),<EOL>forms.CharField(),<EOL>)<EOL>super().__init__(fields, *args, **kwargs)<EOL>
Sets up the MultiValueField
f9148:c0:m0
def compress(self, data_list):
if data_list:<EOL><INDENT>hashed = self.widget.hash_answer(answer=data_list[<NUM_LIT:0>], timestamp=data_list[<NUM_LIT:1>])<EOL>timestamp = time.time()<EOL>if float(data_list[<NUM_LIT:1>]) < timestamp - DURATION:<EOL><INDENT>raise ValidationError("<STR_LIT>", code='<STR_LIT>')<EOL><DEDENT>elif hashed != data_list[<NUM_LIT:2>]:<EOL><INDENT>raise ValidationError("<STR_LIT>", code='<STR_LIT>')<EOL><DEDENT>return data_list[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>
Validates the captcha answer and returns the result If no data is provided, this method will simply return None. Otherwise, it will validate that the provided answer and timestamp hash to the supplied hash value, and that the timestamp is within the configured time that captchas are considered valid.
f9148:c0:m1
@property<EOL><INDENT>def label(self):<DEDENT>
return self.widget._question<EOL>
The captcha field's label is the captcha question itself
f9148:c0:m2
@label.setter<EOL><INDENT>def label(self, value):<DEDENT>
pass<EOL>
The question is generated by the widget and cannot be externally set
f9148:c0:m3
def _getsetting(setting, default):
setting = _DJANGO_SETTING_PREFIX + setting<EOL>try:<EOL><INDENT>return getattr(settings, setting)<EOL><DEDENT>except:<EOL><INDENT>return default<EOL><DEDENT>
Get `setting` if set, fallback to `default` if not This method tries to return the value of the specified setting from Django's settings module, after prefixing the name with _DJANGO_SETTING_PREFIX. If this fails for any reason, the value supplied in `default` will be returned instead.
f9150:m0
def _setsetting(setting, default):
value = _getsetting(setting, default)<EOL>setattr(_self, setting, value)<EOL>
Dynamically sets the variable named in `setting` This method uses `_getsetting()` to either fetch the setting from Django's settings module, or else fallback to the default value; it then sets a variable in this module with the returned value.
f9150:m1
def __init__(self, attrs=None):
widgets = (<EOL>forms.TextInput(attrs=attrs),<EOL>forms.HiddenInput(),<EOL>forms.HiddenInput()<EOL>)<EOL>super().__init__(widgets, attrs)<EOL>
Initialize the various widgets in this MultiWidget
f9151:c0:m0
def decompress(self, value):
return self._values<EOL>
Don't actually parse out the values, just get ours
f9151:c0:m1
def format_output(self, rendered_widgets):
return '<STR_LIT>'.join(rendered_widgets)<EOL>
All we want to do is stick all the widgets together
f9151:c0:m2
def render(self, name, value, attrs=None):
value = self._values<EOL>return super().render(name, value, attrs)<EOL>
Override the render() method to replace value with our current values This approach is based on the approach that Django's PasswordInput widget uses to ensure that passwords are not re-rendered in forms, except instead of prohibiting initial values we set them to those for our generated captcha.
f9151:c0:m3
def generate_captcha(self):
<EOL>self._question, answer = self._generate_question()<EOL>timestamp = time.time()<EOL>hashed = self.hash_answer(answer, timestamp)<EOL>self._values = ['<STR_LIT>', timestamp, hashed]<EOL>
Generated a fresh captcha This method randomly generates a simple captcha question. It then generates a timestamp for the current time, and signs the answer cryptographically to protect against tampering and replay attacks.
f9151:c0:m4
def _generate_question(self):
x = random.randint(<NUM_LIT:1>, <NUM_LIT:10>)<EOL>y = random.randint(<NUM_LIT:1>, <NUM_LIT:10>)<EOL>operator = random.choice(('<STR_LIT:+>', '<STR_LIT:->', '<STR_LIT:*>',))<EOL>if operator == '<STR_LIT:+>':<EOL><INDENT>answer = x + y<EOL><DEDENT>elif operator == '<STR_LIT:->':<EOL><INDENT>if x < y:<EOL><INDENT>x, y = y, x<EOL><DEDENT>answer = x - y<EOL><DEDENT>else:<EOL><INDENT>x = math.ceil(x/<NUM_LIT:2>)<EOL>y = math.ceil(y/<NUM_LIT:2>)<EOL>answer = x * y<EOL>operator = '<STR_LIT>'<EOL><DEDENT>question = '<STR_LIT>'.format(x, operator, y)<EOL>return mark_safe(question), answer<EOL>
Generate a random arithmetic question This method randomly generates a simple addition, subtraction, or multiplication question with two integers between 1 and 10, and then returns both question (formatted as a string) and answer.
f9151:c0:m5
def hash_answer(self, answer, timestamp):
<EOL>timestamp = str(timestamp)<EOL>answer = str(answer)<EOL>hashed = '<STR_LIT>'<EOL>for _ in range(ITERATIONS):<EOL><INDENT>hashed = salted_hmac(timestamp, answer).hexdigest()<EOL><DEDENT>return hashed<EOL>
Cryptographically hash the answer with the provided timestamp This method allows the widget to securely generate time-sensitive signatures that will both prevent tampering with the answer as well as provide some protection against replay attacks by limiting how long a given signature is valid for. Using this same method, the field can validate the submitted answer against the signature also provided in the form.
f9151:c0:m6
def captchaform(field_name):
def wrapper(orig_form):<EOL><INDENT>"""<STR_LIT>"""<EOL>orig_init = orig_form.__init__<EOL>def new_init(self, *args, **kwargs):<EOL><INDENT>"""<STR_LIT>"""<EOL>orig_init(self, *args, **kwargs)<EOL>self.fields[field_name].widget.generate_captcha()<EOL><DEDENT>captcha = CaptchaField()<EOL>orig_form.__init__ = new_init<EOL>orig_form.base_fields.update({field_name: captcha})<EOL>orig_form.declared_fields.update({field_name: captcha})<EOL>return orig_form<EOL><DEDENT>return wrapper<EOL>
Decorator to add a simple captcha to a form To use this decorator, you must specify the captcha field's name as an argument to the decorator. For example: @captchaform('captcha') class MyForm(Form): pass This would add a new form field named 'captcha' to the Django form MyForm. Nothing else is needed; the captcha field and widget expect to be left fully to their own devices, and tinkering with them may produce the unexpected. It is also possible using this decorator to add multiple captchas to your forms: @captchaform('captchatwo') @captchaform('captchaone') class MyForm(Form): pass Note that the captchas are added to your fields in the inverse order that the decorators appear in your source; in this example, 'captchaone' appears first in the form, followed by 'captchatwo'.
f9152:m0
@click.group()<EOL>@click.option('<STR_LIT>', default="<STR_LIT>", help="<STR_LIT>")<EOL>@click.option('<STR_LIT>', is_flag=True, help="<STR_LIT>")<EOL>@click.pass_context<EOL>def cli(ctx, config, debug):
ctx.obj['<STR_LIT>'] = config<EOL>ctx.obj['<STR_LIT>'] = stex.SnakeTeX(config_file=config, debug=debug)<EOL>
SnakTeX command line interface - write LaTeX faster through templating.
f9154:m0
def object_counter():
class_names = dingos_class_map.keys()<EOL>class_names.sort()<EOL>result = []<EOL>for class_name in class_names:<EOL><INDENT>objects_in_db = dingos_class_map[class_name].objects.all()<EOL>result.append((class_name, objects_in_db.count()))<EOL><DEDENT>return result<EOL>
Returns a tuple that contains counts of how many objects of each model defined in dingos.models are in the database.
f9159:m0
def object_count_delta(count1, count2):
result = []<EOL>for i in range(<NUM_LIT:0>, len(count1)):<EOL><INDENT>if (count2[i][<NUM_LIT:1>] - count1[i][<NUM_LIT:1>]) != <NUM_LIT:0>:<EOL><INDENT>result.append((count1[i][<NUM_LIT:0>], count2[i][<NUM_LIT:1>] - count1[i][<NUM_LIT:1>]))<EOL><DEDENT><DEDENT>return result<EOL>
Calculates the difference between to object counts.
f9159:m1
def deltaCalc(func):
def inner(*args, **kwargs):<EOL><INDENT>count_pre = object_counter()<EOL>result = func(*args, **kwargs)<EOL>count_post = object_counter()<EOL>delta = object_count_delta(count_pre, count_post)<EOL>return (delta, result)<EOL><DEDENT>return inner<EOL>
This is a decorator that wraps functions for test purposes with a count of objects in the database. It returns the delta of the objects for each model class along with the result of the tested function.
f9159:m2
def xml_import(self,<EOL>filepath=None,<EOL>xml_content=None,<EOL>markings=None,<EOL>identifier_ns_uri=None,<EOL>initialize_importer=True,<EOL>**kwargs):
if initialize_importer:<EOL><INDENT>self.__init__()<EOL><DEDENT>if not markings:<EOL><INDENT>markings = []<EOL><DEDENT>if identifier_ns_uri:<EOL><INDENT>self.identifier_ns_uri = identifier_ns_uri<EOL><DEDENT>import_result = MantisImporter.xml_import(xml_fname=filepath,<EOL>xml_content=xml_content,<EOL>ns_mapping=self.namespace_dict,<EOL>embedded_predicate=self.openioc_embedding_pred,<EOL>id_and_revision_extractor=self.id_and_revision_extractor,<EOL>transformer=self.transformer,<EOL>keep_attrs_in_created_reference=False,<EOL>)<EOL>id_and_rev_info = import_result['<STR_LIT>']<EOL>elt_name = import_result['<STR_LIT>']<EOL>elt_dict = import_result['<STR_LIT>']<EOL>embedded_objects = import_result['<STR_LIT>']<EOL>default_ns = self.namespace_dict.get(elt_dict.get('<STR_LIT>',None),'<STR_LIT>')<EOL>family_info_dict = search_by_re_list(self.RE_LIST_NS_TYPE_FROM_NS_URL,default_ns)<EOL>if family_info_dict:<EOL><INDENT>self.iobject_family_name="<STR_LIT>" % family_info_dict['<STR_LIT>']<EOL>self.iobject_family_revision_name=family_info_dict['<STR_LIT>']<EOL><DEDENT>pending_stack = deque()<EOL>pending_stack.append((id_and_rev_info, elt_name,elt_dict))<EOL>while embedded_objects:<EOL><INDENT>embedded_object = embedded_objects.pop()<EOL>id_and_rev_info = embedded_object['<STR_LIT>']<EOL>elt_name = embedded_object['<STR_LIT>']<EOL>elt_dict = embedded_object['<STR_LIT>']<EOL>pending_stack.append((id_and_rev_info,elt_name,elt_dict))<EOL><DEDENT>if id_and_rev_info['<STR_LIT>']:<EOL><INDENT>ts = id_and_rev_info['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>ts = self.create_timestamp<EOL><DEDENT>while pending_stack:<EOL><INDENT>(id_and_rev_info, elt_name, elt_dict) = pending_stack.pop()<EOL>iobject_type_name = elt_name<EOL>iobject_type_namespace_uri = self.namespace_dict.get(elt_dict.get('<STR_LIT>',None),DINGOS_GENERIC_FAMILY_NAME)<EOL>MantisImporter.create_iobject(iobject_family_name = self.iobject_family_name,<EOL>iobject_family_revision_name= self.iobject_family_revision_name,<EOL>iobject_type_name=iobject_type_name,<EOL>iobject_type_namespace_uri=iobject_type_namespace_uri,<EOL>iobject_type_revision_name= '<STR_LIT>',<EOL>iobject_data=elt_dict,<EOL>uid=id_and_rev_info['<STR_LIT:id>'],<EOL>identifier_ns_uri= self.identifier_ns_uri,<EOL>timestamp = ts,<EOL>create_timestamp = self.create_timestamp,<EOL>markings=markings,<EOL>config_hooks = {'<STR_LIT>' : self.fact_handler_list(),<EOL>'<STR_LIT>' : self.datatype_extractor,<EOL>'<STR_LIT>' : self.attr_ignore_predicate},<EOL>namespace_dict=self.namespace_dict,<EOL>)<EOL><DEDENT>
Import an OpenIOC indicator xml (root element 'ioc') from file <filepath> or from a string <xml_content> You can provide: - a list of markings with which all generated Information Objects will be associated (e.g., in order to provide provenance function) - The uri of a namespace of the identifiers for the generated information objects. This namespace identifiers the 'owner' of the object. For example, if importing IOCs published by Mandiant (e.g., as part of the APT1 report), chose an namespace such as 'mandiant.com' or similar (and be consistent about it, when importing other stuff published by Mandiant). The kwargs are not read -- they are present to allow the use of the DingoImportCommand class for easy definition of commandline import commands (the class passes all command line arguments to the xml_import function, so without the **kwargs parameter, an error would occur.
f9160:c0:m1
def id_and_revision_extractor(self,xml_elt):
result = {'<STR_LIT:id>':None,<EOL>'<STR_LIT>': None}<EOL>attributes = extract_attributes(xml_elt,prefix_key_char='<STR_LIT:@>')<EOL>if '<STR_LIT>' in attributes:<EOL><INDENT>result['<STR_LIT:id>']=attributes['<STR_LIT>']<EOL><DEDENT>if '<STR_LIT>' in attributes:<EOL><INDENT>naive = parse_datetime(attributes['<STR_LIT>'].strip())<EOL>if naive:<EOL><INDENT>if not timezone.is_aware(naive):<EOL><INDENT>aware = timezone.make_aware(naive,timezone.utc)<EOL><DEDENT>else:<EOL><INDENT>aware = naive<EOL><DEDENT>result['<STR_LIT>']= aware<EOL><DEDENT><DEDENT>return result<EOL>
Function for determing an identifier (and, where applicable, timestamp/revision information) for extracted embedded content; to be used for DINGO's xml-import hook 'id_and_revision_extractor'. This function is called - for the top-level node of the XML to be imported. - for each node at which an embedded object is extracted from the XML (when this occurs is governed by the following function, the embedding_pred It must return an identifier and, where applicable, a revision and or timestamp; in the form of a dictionary {'id':<identifier>, 'timestamp': <timestamp>}. How you format the identifier is up to you, because you will have to adopt the code in function xml_import such that the Information Objects are created with the proper identifier (consisting of qualifying namespace and uri.) In OpenIOC, the identifier is contained in the 'id' attribute of an element; the top-level 'ioc' element carries a timestamp in the 'last-modified' attribute. Note: the xml_elt is an XMLNode defined by the Python libxml2 bindings. If you have never worked with these, have a look at - Mike Kneller's brief intro: http://mikekneller.com/kb/python/libxml2python/part1 - the functions in django-dingos core.xml_utils module
f9160:c0:m2
def openioc_embedding_pred(self,parent, child, ns_mapping):
<EOL>child_attributes = extract_attributes(child,prefix_key_char='<STR_LIT>')<EOL>if ('<STR_LIT:id>' in child_attributes and child.name == '<STR_LIT>'):<EOL><INDENT>grandchild = child.children<EOL>type_info = None<EOL>while grandchild is not None:<EOL><INDENT>if grandchild.name == '<STR_LIT>':<EOL><INDENT>context_attributes = extract_attributes(grandchild,prefix_key_char='<STR_LIT>')<EOL>if '<STR_LIT>' in context_attributes:<EOL><INDENT>type_info = context_attributes['<STR_LIT>']<EOL><DEDENT>break<EOL><DEDENT>grandchild = grandchild.next<EOL><DEDENT>if type_info:<EOL><INDENT>return type_info<EOL><DEDENT>else:<EOL><INDENT>return True<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT>
Predicate for recognizing inlined content in an XML; to be used for DINGO's xml-import hook 'embedded_predicate'. The question this predicate must answer is whether the child should be extracted into a separate object. The function returns either - False (the child is not to be extracted) - True (the child is extracted but nothing can be inferred about what kind of object is extracted) - a string giving some indication about the object type (if nothing else is known: the name of the element, often the namespace of the embedded object) - a dictionary, of the following form:: {'id_and_revision_info' : { 'id': something/None, 'ts': something/None, ... other information you want to record for this object for later usage, }, 'embedded_ns': False/True/some indication about object type as string} Note: the 'parent' and 'child' arguments are XMLNodes as defined by the Python libxml2 bindings. If you have never worked with these, have a look at - Mike Kneller's brief intro: http://mikekneller.com/kb/python/libxml2python/part1 - the functions in django-dingos core.xml_utils module
f9160:c0:m3
def transformer(self,elt_name,contents):
<EOL>if elt_name != '<STR_LIT>':<EOL><INDENT>return (elt_name,contents)<EOL><DEDENT>else:<EOL><INDENT>result = DingoObjDict()<EOL>leaf = DingoObjDict()<EOL>(document_type,search_term) = contents['<STR_LIT>']['<STR_LIT>'].split("<STR_LIT:/>",<NUM_LIT:1>)<EOL>search_term = search_term.split('<STR_LIT:/>')<EOL>search_value = contents['<STR_LIT>']['<STR_LIT>']<EOL>value_type = contents['<STR_LIT>']['<STR_LIT>']<EOL>search_condition = contents['<STR_LIT>']<EOL>leaf['<STR_LIT>'] = value_type<EOL>leaf['<STR_LIT>'] = search_condition<EOL>leaf['<STR_LIT>'] = search_value<EOL>item_id = contents['<STR_LIT>']<EOL>result['<STR_LIT>'] = item_id<EOL>set_dict(result,leaf,'<STR_LIT>',*search_term)<EOL><DEDENT>return (document_type,result)<EOL>
The OpenIOC indicator contains the actual observable bits of an indicator in the following form:: <IndicatorItem id="b9ef2559-cc59-4463-81d9-52800545e16e" condition="contains"> <Context document="FileItem" search="FileItem/PEInfo/Sections/Section/Name" type="mir"/> <Content type="string">.stub</Content> </IndicatorItem> We would rather have a key-value pairing of the following form (with the 'contains' attribute somewhere at the side:: FileItem/PEInfo/Sections/Section/Name = .stub In order to achieve this, we create a DingoObjDict that corresponds to an XML that would look like follows:: <FileItem id="b9ef2559-cc59-4463-81d9-52800545e16e"> <PEInfo> <Sections> <Section> <Name condition='contains' type='string'> .stub </Name> </Section> </Sections> </PEInfo> </FileItem> This is carried out by the transformer function, which is passed to the generic XML importer and executed for each element when converting the element into a dictionary structure.
f9160:c0:m4
def reference_handler(self,iobject, fact, attr_info, add_fact_kargs):
(namespace_uri,uid) = (self.identifier_ns_uri,attr_info['<STR_LIT>'])<EOL>timestamp = attr_info['<STR_LIT>']<EOL>(target_mantis_obj, existed) = MantisImporter.create_iobject(<EOL>uid=uid,<EOL>identifier_ns_uri=namespace_uri,<EOL>timestamp=timestamp)<EOL>logger.debug("<STR_LIT>" % (namespace_uri,uid,existed))<EOL>add_fact_kargs['<STR_LIT>'] = Identifier.objects.get(uid=uid,namespace__uri=namespace_uri)<EOL>return True<EOL>
Handler for facts that contain a reference to a fact. See below in the comment regarding the fact_handler_list for a description of the signature of handler functions. As shown below in the handler list, this handler is called when a attribute with key '@idref' on the fact's node is detected -- this attribute signifies that this fact does not contain a value but points to another object. Thus, we try to retrieve that object from the database. If it exists, fine -- if not, then the call to 'create_iobject' returns a PLACEHOLDER object. We further create/refer to the fitting fact data type: we want the fact data type to express that the fact is a reference to an object.
f9160:c0:m5
def fact_handler_list(self):
return [(lambda fact, attr_info: "<STR_LIT>" in attr_info.keys(),<EOL>self.reference_handler)]<EOL>
The fact handler list consists of a pairs of predicate and handler function If the predicate returns 'True' for a fact to be added to an Information Object, the handler function is executed and may modify the parameters that will be passed to the function creating the fact. The signature of a predicate is as follows: - Inputs: - fact dictionary of the following form:: { 'node_id': 'N001:L000:N000:A000', 'term': 'Hashes/Hash/Simple_Hash_Value', 'attribute': 'condition' / False, 'value': u'Equals' } - attr_info: A dictionary with mapping of XML attributes concerning the node in question (note that the keys do *not* have a leading '@' unless it is an internally generated attribute by Dingo. - Output: Based on these inputs, the predicate must return True or False. If True is returned, the associated handler function is run. The signature of a handler function is as follows: - Inputs: - info_object: the information object to which the fact is to be added - fact: the fact dictionary of the following form:: { 'node_id': 'N001:L000:N000:A000', 'term': 'Hashes/Hash/Simple_Hash_Value', 'attribute': 'condition' / False, 'value': u'Equals' } - attr_info: A dictionary with mapping of XML attributes concerning the node in question (note that the keys do *not* have a leading '@' unless it is an internally generated attribute by Dingo. - add_fact_kargs: The arguments with which the fact will be generated after all handler functions have been called. The dictionary contains the following keys:: 'fact_dt_kind' : <FactDataType.NO_VOCAB/VOCAB_SINGLE/...> 'fact_dt_namespace_name': <human-readable shortname for namespace uri> 'fact_dt_namespace_uri': <namespace uri for datataype namespace> 'fact_term_name' : <Fact Term such as 'Header/Subject/Address'> 'fact_term_attribute': <Attribute key such as 'category' for fact terms describing an attribute> 'values' : <list of FactValue objects that are the values of the fact to be generated> 'node_id_name' : <node identifier such as 'N000:N000:A000' - Outputs: The handler function outputs either True or False: If False is returned, then the fact will *not* be generated. Please be aware that if you use this option, then there will be 'missing' numbers in the sequence of node ids. Thus, if you want to suppress the creation of facts for attributes, rather use the hooking function 'attr_ignore_predicate' As side effect, the function can make changes to the dictionary passed in parameter 'add_fact_kargs' and thus change the fact that will be created.
f9160:c0:m6