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() ... | 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]... | 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:<... | 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-st... | 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 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
... | 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. -... | 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.... | 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)... | 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... | 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... | 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 =... | 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>', '<ST... | 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
... | 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 = si... | 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... | 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 C... | 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... | 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... | 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_... | 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>... | 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, e... | 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_... | 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 ... | 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, e... | :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: ... | 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), e... | 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><IND... | 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 fo... | 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>retur... | 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... | 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>')]... | 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.ele... | 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 == ... | 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.v... | 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()<... | 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('<S... | 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.at... | 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<E... | 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 = c... | 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_pa... | 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... | 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('<ST... | 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_L... | 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_... | 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 con... | 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... | 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... | 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... | 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<EO... | 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.
Nothin... | 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.... | 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 generat... | 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>... | 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 e... | 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_attri... | 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 extracte... | 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_valu... | 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">.s... | 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_fa... | 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 signifie... | 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:
... | f9160:c0:m6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.