INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Return an |_SofMarker| instance for the SOFn marker at *offset* in
stream. | def from_stream(cls, stream, marker_code, offset):
"""
Return an |_SofMarker| instance for the SOFn marker at *offset* in
stream.
"""
# field off type notes
# ------------------ --- ----- ----------------------------
# segment length 0 ... |
The ``<w:tc>`` element appearing at grid column *idx*. Raises
|ValueError| if no ``w:tc`` element begins at that grid column. | def tc_at_grid_col(self, idx):
"""
The ``<w:tc>`` element appearing at grid column *idx*. Raises
|ValueError| if no ``w:tc`` element begins at that grid column.
"""
grid_col = 0
for tc in self.tc_lst:
if grid_col == idx:
return tc
g... |
Return a new `w:tbl` element having *rows* rows and *cols* columns
with *width* distributed evenly between the columns. | def new_tbl(cls, rows, cols, width):
"""
Return a new `w:tbl` element having *rows* rows and *cols* columns
with *width* distributed evenly between the columns.
"""
return parse_xml(cls._tbl_xml(rows, cols, width)) |
Set the value of `w:tblPr/w:tblStyle/@w:val` (a table style id) to
*styleId*. If *styleId* is None, remove the `w:tblStyle` element. | def tblStyle_val(self, styleId):
"""
Set the value of `w:tblPr/w:tblStyle/@w:val` (a table style id) to
*styleId*. If *styleId* is None, remove the `w:tblStyle` element.
"""
tblPr = self.tblPr
tblPr._remove_tblStyle()
if styleId is None:
return
... |
Return |False| if there is a ``<w:tblLayout>`` child with ``w:type``
attribute set to ``'fixed'``. Otherwise return |True|. | def autofit(self):
"""
Return |False| if there is a ``<w:tblLayout>`` child with ``w:type``
attribute set to ``'fixed'``. Otherwise return |True|.
"""
tblLayout = self.tblLayout
if tblLayout is None:
return True
return False if tblLayout.type == 'fixed... |
The row index that marks the bottom extent of the vertical span of
this cell. This is one greater than the index of the bottom-most row
of the span, similar to how a slice of the cell's rows would be
specified. | def bottom(self):
"""
The row index that marks the bottom extent of the vertical span of
this cell. This is one greater than the index of the bottom-most row
of the span, similar to how a slice of the cell's rows would be
specified.
"""
if self.vMerge is not None:... |
Generate a reference to each of the block-level content elements in
this cell, in the order they appear. | def iter_block_items(self):
"""
Generate a reference to each of the block-level content elements in
this cell, in the order they appear.
"""
block_item_tags = (qn('w:p'), qn('w:tbl'), qn('w:sdt'))
for child in self:
if child.tag in block_item_tags:
... |
Remove all content child elements, preserving the ``<w:tcPr>``
element if present. Note that this leaves the ``<w:tc>`` element in
an invalid state because it doesn't contain at least one block-level
element. It's up to the caller to add a ``<w:p>``child element as the
last content eleme... | def clear_content(self):
"""
Remove all content child elements, preserving the ``<w:tcPr>``
element if present. Note that this leaves the ``<w:tc>`` element in
an invalid state because it doesn't contain at least one block-level
element. It's up to the caller to add a ``<w:p>``ch... |
Return the top-left ``<w:tc>`` element of a new span formed by
merging the rectangular region defined by using this tc element and
*other_tc* as diagonal corners. | def merge(self, other_tc):
"""
Return the top-left ``<w:tc>`` element of a new span formed by
merging the rectangular region defined by using this tc element and
*other_tc* as diagonal corners.
"""
top, left, height, width = self._span_dimensions(other_tc)
top_tc ... |
The top-most row index in the vertical span of this cell. | def top(self):
"""
The top-most row index in the vertical span of this cell.
"""
if self.vMerge is None or self.vMerge == ST_Merge.RESTART:
return self._tr_idx
return self._tc_above.top |
Add the width of *other_tc* to this cell. Does nothing if either this
tc or *other_tc* does not have a specified width. | def _add_width_of(self, other_tc):
"""
Add the width of *other_tc* to this cell. Does nothing if either this
tc or *other_tc* does not have a specified width.
"""
if self.width and other_tc.width:
self.width += other_tc.width |
The grid column at which this cell begins. | def _grid_col(self):
"""
The grid column at which this cell begins.
"""
tr = self._tr
idx = tr.tc_lst.index(self)
preceding_tcs = tr.tc_lst[:idx]
return sum(tc.grid_span for tc in preceding_tcs) |
Grow this cell to *width* grid columns and *height* rows by expanding
horizontal spans and creating continuation cells to form vertical
spans. | def _grow_to(self, width, height, top_tc=None):
"""
Grow this cell to *width* grid columns and *height* rows by expanding
horizontal spans and creating continuation cells to form vertical
spans.
"""
def vMerge_val(top_tc):
if top_tc is not self:
... |
True if this cell contains only a single empty ``<w:p>`` element. | def _is_empty(self):
"""
True if this cell contains only a single empty ``<w:p>`` element.
"""
block_items = list(self.iter_block_items())
if len(block_items) > 1:
return False
p = block_items[0] # cell must include at least one <w:p> element
if len(p... |
Append the content of this cell to *other_tc*, leaving this cell with
a single empty ``<w:p>`` element. | def _move_content_to(self, other_tc):
"""
Append the content of this cell to *other_tc*, leaving this cell with
a single empty ``<w:p>`` element.
"""
if other_tc is self:
return
if self._is_empty:
return
other_tc._remove_trailing_empty_p()
... |
Remove the last content element from this cell if it is an empty
``<w:p>`` element. | def _remove_trailing_empty_p(self):
"""
Remove the last content element from this cell if it is an empty
``<w:p>`` element.
"""
block_items = list(self.iter_block_items())
last_content_elm = block_items[-1]
if last_content_elm.tag != qn('w:p'):
return
... |
Return a (top, left, height, width) 4-tuple specifying the extents of
the merged cell formed by using this tc and *other_tc* as opposite
corner extents. | def _span_dimensions(self, other_tc):
"""
Return a (top, left, height, width) 4-tuple specifying the extents of
the merged cell formed by using this tc and *other_tc* as opposite
corner extents.
"""
def raise_on_inverted_L(a, b):
if a.top == b.top and a.bottom... |
Incorporate and then remove `w:tc` elements to the right of this one
until this cell spans *grid_width*. Raises |ValueError| if
*grid_width* cannot be exactly achieved, such as when a merged cell
would drive the span width greater than *grid_width* or if not enough
grid columns are avail... | def _span_to_width(self, grid_width, top_tc, vMerge):
"""
Incorporate and then remove `w:tc` elements to the right of this one
until this cell spans *grid_width*. Raises |ValueError| if
*grid_width* cannot be exactly achieved, such as when a merged cell
would drive the span width... |
Extend the horizontal span of this `w:tc` element to incorporate the
following `w:tc` element in the row and then delete that following
`w:tc` element. Any content in the following `w:tc` element is
appended to the content of *top_tc*. The width of the following
`w:tc` element is added t... | def _swallow_next_tc(self, grid_width, top_tc):
"""
Extend the horizontal span of this `w:tc` element to incorporate the
following `w:tc` element in the row and then delete that following
`w:tc` element. Any content in the following `w:tc` element is
appended to the content of *t... |
The tc element immediately below this one in its grid column. | def _tc_below(self):
"""
The tc element immediately below this one in its grid column.
"""
tr_below = self._tr_below
if tr_below is None:
return None
return tr_below.tc_at_grid_col(self._grid_col) |
The tr element prior in sequence to the tr this cell appears in.
Raises |ValueError| if called on a cell in the top-most row. | def _tr_above(self):
"""
The tr element prior in sequence to the tr this cell appears in.
Raises |ValueError| if called on a cell in the top-most row.
"""
tr_lst = self._tbl.tr_lst
tr_idx = tr_lst.index(self._tr)
if tr_idx == 0:
raise ValueError('no tr... |
The tr element next in sequence after the tr this cell appears in, or
|None| if this cell appears in the last row. | def _tr_below(self):
"""
The tr element next in sequence after the tr this cell appears in, or
|None| if this cell appears in the last row.
"""
tr_lst = self._tbl.tr_lst
tr_idx = tr_lst.index(self._tr)
try:
return tr_lst[tr_idx+1]
except IndexE... |
Decorating a class with @alias('FOO', 'BAR', ..) allows the class to
be referenced by each of the names provided as arguments. | def alias(*aliases):
"""
Decorating a class with @alias('FOO', 'BAR', ..) allows the class to
be referenced by each of the names provided as arguments.
"""
def decorator(cls):
# alias must be set in globals from caller's frame
caller = sys._getframe(1)
globals_dict = caller.f... |
The RestructuredText documentation page for the enumeration. This is
the only API member for the class. | def page_str(self):
"""
The RestructuredText documentation page for the enumeration. This is
the only API member for the class.
"""
tmpl = '.. _%s:\n\n%s\n\n%s\n\n----\n\n%s'
components = (
self._ms_name, self._page_title, self._intro_text,
self._m... |
Docstring of the enumeration, formatted for documentation page. | def _intro_text(self):
"""Docstring of the enumeration, formatted for documentation page."""
try:
cls_docstring = self._clsdict['__doc__']
except KeyError:
cls_docstring = ''
if cls_docstring is None:
return ''
return textwrap.dedent(cls_docs... |
Return an individual member definition formatted as an RST glossary
entry, wrapped to fit within 78 columns. | def _member_def(self, member):
"""
Return an individual member definition formatted as an RST glossary
entry, wrapped to fit within 78 columns.
"""
member_docstring = textwrap.dedent(member.docstring).strip()
member_docstring = textwrap.fill(
member_docstring,... |
A single string containing the aggregated member definitions section
of the documentation page | def _member_defs(self):
"""
A single string containing the aggregated member definitions section
of the documentation page
"""
members = self._clsdict['__members__']
member_defs = [
self._member_def(member) for member in members
if member.name is n... |
Dispatch ``.add_to_enum()`` call to each member so it can do its
thing to properly add itself to the enumeration class. This
delegation allows member sub-classes to add specialized behaviors. | def _add_enum_members(meta, clsdict):
"""
Dispatch ``.add_to_enum()`` call to each member so it can do its
thing to properly add itself to the enumeration class. This
delegation allows member sub-classes to add specialized behaviors.
"""
enum_members = clsdict['__members_... |
Return a sequence containing the enumeration values that are valid
assignment values. Return-only values are excluded. | def _collect_valid_settings(meta, clsdict):
"""
Return a sequence containing the enumeration values that are valid
assignment values. Return-only values are excluded.
"""
enum_members = clsdict['__members__']
valid_settings = []
for member in enum_members:
... |
Raise |ValueError| if *value* is not an assignable value. | def validate(cls, value):
"""
Raise |ValueError| if *value* is not an assignable value.
"""
if value not in cls._valid_settings:
raise ValueError(
"%s not a member of %s enumeration" % (value, cls.__name__)
) |
Return the enumeration member corresponding to the XML value
*xml_val*. | def from_xml(cls, xml_val):
"""
Return the enumeration member corresponding to the XML value
*xml_val*.
"""
if xml_val not in cls._xml_to_member:
raise InvalidXmlError(
"attribute value '%s' not valid for this type" % xml_val
)
retu... |
Return the XML value of the enumeration value *enum_val*. | def to_xml(cls, enum_val):
"""
Return the XML value of the enumeration value *enum_val*.
"""
if enum_val not in cls._member_to_xml:
raise ValueError(
"value '%s' not in enumeration %s" % (enum_val, cls.__name__)
)
return cls._member_to_xml[... |
Add a member name to the class dict *clsdict* containing the value of
this member object. Where the name of this object is None, do
nothing; this allows out-of-band values to be defined without adding
a name to the class dict. | def register_name(self, clsdict):
"""
Add a member name to the class dict *clsdict* containing the value of
this member object. Where the name of this object is None, do
nothing; this allows out-of-band values to be defined without adding
a name to the class dict.
"""
... |
Compile XML mappings in addition to base add behavior. | def add_to_enum(self, clsdict):
"""
Compile XML mappings in addition to base add behavior.
"""
super(XmlMappedEnumMember, self).add_to_enum(clsdict)
self.register_xml_mapping(clsdict) |
Add XML mappings to the enumeration class state for this member. | def register_xml_mapping(self, clsdict):
"""
Add XML mappings to the enumeration class state for this member.
"""
member_to_xml = self._get_or_add_member_to_xml(clsdict)
member_to_xml[self.value] = self.xml_value
xml_to_member = self._get_or_add_xml_to_member(clsdict)
... |
Return a |Document| object loaded from *docx*, where *docx* can be
either a path to a ``.docx`` file (a string) or a file-like object. If
*docx* is missing or ``None``, the built-in default document "template"
is loaded. | def Document(docx=None):
"""
Return a |Document| object loaded from *docx*, where *docx* can be
either a path to a ``.docx`` file (a string) or a file-like object. If
*docx* is missing or ``None``, the built-in default document "template"
is loaded.
"""
docx = _default_docx_path() if docx is... |
Return the path to the built-in default .docx package. | def _default_docx_path():
"""
Return the path to the built-in default .docx package.
"""
_thisdir = os.path.split(__file__)[0]
return os.path.join(_thisdir, 'templates', 'default-docx-template') |
|float| or |Length| value specifying the space between baselines in
successive lines of the paragraph. A value of |None| indicates line
spacing is inherited from the style hierarchy. A float value, e.g.
``2.0`` or ``1.75``, indicates spacing is applied in multiples of
line heights. A |Le... | def line_spacing(self):
"""
|float| or |Length| value specifying the space between baselines in
successive lines of the paragraph. A value of |None| indicates line
spacing is inherited from the style hierarchy. A float value, e.g.
``2.0`` or ``1.75``, indicates spacing is applied... |
A member of the :ref:`WdLineSpacing` enumeration indicating how the
value of :attr:`line_spacing` should be interpreted. Assigning any of
the :ref:`WdLineSpacing` members :attr:`SINGLE`, :attr:`DOUBLE`, or
:attr:`ONE_POINT_FIVE` will cause the value of :attr:`line_spacing`
to be updated ... | def line_spacing_rule(self):
"""
A member of the :ref:`WdLineSpacing` enumeration indicating how the
value of :attr:`line_spacing` should be interpreted. Assigning any of
the :ref:`WdLineSpacing` members :attr:`SINGLE`, :attr:`DOUBLE`, or
:attr:`ONE_POINT_FIVE` will cause the val... |
Return the line spacing value calculated from the combination of
*spacing_line* and *spacing_lineRule*. Returns a |float| number of
lines when *spacing_lineRule* is ``WD_LINE_SPACING.MULTIPLE``,
otherwise a |Length| object of absolute line height is returned.
Returns |None| when *spacing... | def _line_spacing(spacing_line, spacing_lineRule):
"""
Return the line spacing value calculated from the combination of
*spacing_line* and *spacing_lineRule*. Returns a |float| number of
lines when *spacing_lineRule* is ``WD_LINE_SPACING.MULTIPLE``,
otherwise a |Length| object of... |
Return the line spacing rule value calculated from the combination of
*line* and *lineRule*. Returns special members of the
:ref:`WdLineSpacing` enumeration when line spacing is single, double,
or 1.5 lines. | def _line_spacing_rule(line, lineRule):
"""
Return the line spacing rule value calculated from the combination of
*line* and *lineRule*. Returns special members of the
:ref:`WdLineSpacing` enumeration when line spacing is single, double,
or 1.5 lines.
"""
if lineR... |
Return a new ``<w:num>`` element having numId of *num_id* and having
a ``<w:abstractNumId>`` child with val attribute set to
*abstractNum_id*. | def new(cls, num_id, abstractNum_id):
"""
Return a new ``<w:num>`` element having numId of *num_id* and having
a ``<w:abstractNumId>`` child with val attribute set to
*abstractNum_id*.
"""
num = OxmlElement('w:num')
num.numId = num_id
abstractNumId = CT_De... |
Return a newly added CT_Num (<w:num>) element referencing the
abstract numbering definition identified by *abstractNum_id*. | def add_num(self, abstractNum_id):
"""
Return a newly added CT_Num (<w:num>) element referencing the
abstract numbering definition identified by *abstractNum_id*.
"""
next_num_id = self._next_numId
num = CT_Num.new(next_num_id, abstractNum_id)
return self._insert_... |
Return the ``<w:num>`` child element having ``numId`` attribute
matching *numId*. | def num_having_numId(self, numId):
"""
Return the ``<w:num>`` child element having ``numId`` attribute
matching *numId*.
"""
xpath = './w:num[@w:numId="%d"]' % numId
try:
return self.xpath(xpath)[0]
except IndexError:
raise KeyError('no <w:... |
The first ``numId`` unused by a ``<w:num>`` element, starting at
1 and filling any gaps in numbering between existing ``<w:num>``
elements. | def _next_numId(self):
"""
The first ``numId`` unused by a ``<w:num>`` element, starting at
1 and filling any gaps in numbering between existing ``<w:num>``
elements.
"""
numId_strs = self.xpath('./w:num/@w:numId')
num_ids = [int(numId_str) for numId_str in numId_... |
Return a newly added |_Relationship| instance. | def add_relationship(self, reltype, target, rId, is_external=False):
"""
Return a newly added |_Relationship| instance.
"""
rel = _Relationship(rId, reltype, target, self._baseURI, is_external)
self[rId] = rel
if not is_external:
self._target_parts_by_rId[rId]... |
Return relationship of *reltype* to *target_part*, newly added if not
already present in collection. | def get_or_add(self, reltype, target_part):
"""
Return relationship of *reltype* to *target_part*, newly added if not
already present in collection.
"""
rel = self._get_matching(reltype, target_part)
if rel is None:
rId = self._next_rId
rel = self.... |
Return rId of external relationship of *reltype* to *target_ref*,
newly added if not already present in collection. | def get_or_add_ext_rel(self, reltype, target_ref):
"""
Return rId of external relationship of *reltype* to *target_ref*,
newly added if not already present in collection.
"""
rel = self._get_matching(reltype, target_ref, is_external=True)
if rel is None:
rId =... |
Serialize this relationship collection into XML suitable for storage
as a .rels file in an OPC package. | def xml(self):
"""
Serialize this relationship collection into XML suitable for storage
as a .rels file in an OPC package.
"""
rels_elm = CT_Relationships.new()
for rel in self.values():
rels_elm.add_rel(
rel.rId, rel.reltype, rel.target_ref, r... |
Return relationship of matching *reltype*, *target*, and
*is_external* from collection, or None if not found. | def _get_matching(self, reltype, target, is_external=False):
"""
Return relationship of matching *reltype*, *target*, and
*is_external* from collection, or None if not found.
"""
def matches(rel, reltype, target, is_external):
if rel.reltype != reltype:
... |
Return single relationship of type *reltype* from the collection.
Raises |KeyError| if no matching relationship is found. Raises
|ValueError| if more than one matching relationship is found. | def _get_rel_of_type(self, reltype):
"""
Return single relationship of type *reltype* from the collection.
Raises |KeyError| if no matching relationship is found. Raises
|ValueError| if more than one matching relationship is found.
"""
matching = [rel for rel in self.valu... |
Next available rId in collection, starting from 'rId1' and making use
of any gaps in numbering, e.g. 'rId2' for rIds ['rId1', 'rId3']. | def _next_rId(self):
"""
Next available rId in collection, starting from 'rId1' and making use
of any gaps in numbering, e.g. 'rId2' for rIds ['rId1', 'rId3'].
"""
for n in range(1, len(self)+2):
rId_candidate = 'rId%d' % n # like 'rId19'
if rId_candidate... |
Return a new ``CT_DecimalNumber`` element having tagname *nsptagname*
and ``val`` attribute set to *val*. | def new(cls, nsptagname, val):
"""
Return a new ``CT_DecimalNumber`` element having tagname *nsptagname*
and ``val`` attribute set to *val*.
"""
return OxmlElement(nsptagname, attrs={qn('w:val'): str(val)}) |
Return a new ``CT_String`` element with tagname *nsptagname* and
``val`` attribute set to *val*. | def new(cls, nsptagname, val):
"""
Return a new ``CT_String`` element with tagname *nsptagname* and
``val`` attribute set to *val*.
"""
elm = OxmlElement(nsptagname)
elm.val = val
return elm |
Return a style object of the appropriate |BaseStyle| subclass, according
to the type of *style_elm*. | def StyleFactory(style_elm):
"""
Return a style object of the appropriate |BaseStyle| subclass, according
to the type of *style_elm*.
"""
style_cls = {
WD_STYLE_TYPE.PARAGRAPH: _ParagraphStyle,
WD_STYLE_TYPE.CHARACTER: _CharacterStyle,
WD_STYLE_TYPE.TABLE: _TableStyle,
... |
The UI name of this style. | def name(self):
"""
The UI name of this style.
"""
name = self._element.name_val
if name is None:
return None
return BabelFish.internal2ui(name) |
Member of :ref:`WdStyleType` corresponding to the type of this style,
e.g. ``WD_STYLE_TYPE.PARAGRAPH``. | def type(self):
"""
Member of :ref:`WdStyleType` corresponding to the type of this style,
e.g. ``WD_STYLE_TYPE.PARAGRAPH``.
"""
type = self._element.type
if type is None:
return WD_STYLE_TYPE.PARAGRAPH
return type |
|_ParagraphStyle| object representing the style to be applied
automatically to a new paragraph inserted after a paragraph of this
style. Returns self if no next paragraph style is defined. Assigning
|None| or *self* removes the setting such that new paragraphs are
created using this same... | def next_paragraph_style(self):
"""
|_ParagraphStyle| object representing the style to be applied
automatically to a new paragraph inserted after a paragraph of this
style. Returns self if no next paragraph style is defined. Assigning
|None| or *self* removes the setting such tha... |
Integer value of revision property. | def revision_number(self):
"""
Integer value of revision property.
"""
revision = self.revision
if revision is None:
return 0
revision_str = revision.text
try:
revision = int(revision_str)
except ValueError:
# non-intege... |
Set revision property to string value of integer *value*. | def revision_number(self, value):
"""
Set revision property to string value of integer *value*.
"""
if not isinstance(value, int) or value < 1:
tmpl = "revision property requires positive int, got '%s'"
raise ValueError(tmpl % value)
revision = self.get_or... |
Return element returned by 'get_or_add_' method for *prop_name*. | def _get_or_add(self, prop_name):
"""
Return element returned by 'get_or_add_' method for *prop_name*.
"""
get_or_add_method_name = 'get_or_add_%s' % prop_name
get_or_add_method = getattr(self, get_or_add_method_name)
element = get_or_add_method()
return element |
Return a |datetime| instance that is offset from datetime *dt* by
the timezone offset specified in *offset_str*, a string like
``'-07:00'``. | def _offset_dt(cls, dt, offset_str):
"""
Return a |datetime| instance that is offset from datetime *dt* by
the timezone offset specified in *offset_str*, a string like
``'-07:00'``.
"""
match = cls._offset_pattern.match(offset_str)
if match is None:
ra... |
Set date/time value of child element having *prop_name* to *value*. | def _set_element_datetime(self, prop_name, value):
"""
Set date/time value of child element having *prop_name* to *value*.
"""
if not isinstance(value, datetime):
tmpl = (
"property requires <type 'datetime.datetime'> object, got %s"
)
... |
Set string value of *name* property to *value*. | def _set_element_text(self, prop_name, value):
"""Set string value of *name* property to *value*."""
if not is_string(value):
value = str(value)
if len(value) > 255:
tmpl = (
"exceeded 255 char limit for property, got:\n\n'%s'"
)
r... |
Return the text in the element matching *property_name*, or an empty
string if the element is not present or contains no text. | def _text_of_element(self, property_name):
"""
Return the text in the element matching *property_name*, or an empty
string if the element is not present or contains no text.
"""
element = getattr(self, property_name)
if element is None:
return ''
if el... |
Return |Gif| instance having header properties parsed from GIF image
in *stream*. | def from_stream(cls, stream):
"""
Return |Gif| instance having header properties parsed from GIF image
in *stream*.
"""
px_width, px_height = cls._dimensions_from_stream(stream)
return cls(px_width, px_height, 72, 72) |
Return contents of file corresponding to *pack_uri* in package
directory. | def blob_for(self, pack_uri):
"""
Return contents of file corresponding to *pack_uri* in package
directory.
"""
path = os.path.join(self._path, pack_uri.membername)
with open(path, 'rb') as f:
blob = f.read()
return blob |
Return rels item XML for source with *source_uri*, or None if the
item has no rels item. | def rels_xml_for(self, source_uri):
"""
Return rels item XML for source with *source_uri*, or None if the
item has no rels item.
"""
try:
rels_xml = self.blob_for(source_uri.rels_uri)
except IOError:
rels_xml = None
return rels_xml |
Return rels item XML for source with *source_uri* or None if no rels
item is present. | def rels_xml_for(self, source_uri):
"""
Return rels item XML for source with *source_uri* or None if no rels
item is present.
"""
try:
rels_xml = self.blob_for(source_uri.rels_uri)
except KeyError:
rels_xml = None
return rels_xml |
Write *blob* to this zip package with the membername corresponding to
*pack_uri*. | def write(self, pack_uri, blob):
"""
Write *blob* to this zip package with the membername corresponding to
*pack_uri*.
"""
self._zipf.writestr(pack_uri.membername, blob) |
Return |Bmp| instance having header properties parsed from the BMP
image in *stream*. | def from_stream(cls, stream):
"""
Return |Bmp| instance having header properties parsed from the BMP
image in *stream*.
"""
stream_rdr = StreamReader(stream, LITTLE_ENDIAN)
px_width = stream_rdr.read_long(0x12)
px_height = stream_rdr.read_long(0x16)
horz... |
Stands for "qualified name", a utility function to turn a namespace
prefixed tag name into a Clark-notation qualified tag name for lxml. For
example, ``qn('p:cSld')`` returns ``'{http://schemas.../main}cSld'``. | def qn(tag):
"""
Stands for "qualified name", a utility function to turn a namespace
prefixed tag name into a Clark-notation qualified tag name for lxml. For
example, ``qn('p:cSld')`` returns ``'{http://schemas.../main}cSld'``.
"""
prefix, tagroot = tag.split(':')
uri = nsmap[prefix]
ret... |
Unconditionally replace or add *sectPr* as a grandchild in the
correct sequence. | def set_sectPr(self, sectPr):
"""
Unconditionally replace or add *sectPr* as a grandchild in the
correct sequence.
"""
pPr = self.get_or_add_pPr()
pPr._remove_sectPr()
pPr._insert_sectPr(sectPr) |
Remove all child elements, except the ``<w:pPr>`` element if present. | def clear_content(self):
"""
Remove all child elements, except the ``<w:pPr>`` element if present.
"""
for child in self[:]:
if child.tag == qn('w:pPr'):
continue
self.remove(child) |
Return a |PackageReader| instance loaded with contents of *pkg_file*. | def from_file(pkg_file):
"""
Return a |PackageReader| instance loaded with contents of *pkg_file*.
"""
phys_reader = PhysPkgReader(pkg_file)
content_types = _ContentTypeMap.from_xml(phys_reader.content_types_xml)
pkg_srels = PackageReader._srels_for(phys_reader, PACKAGE_U... |
Generate a 4-tuple `(partname, content_type, reltype, blob)` for each
of the serialized parts in the package. | def iter_sparts(self):
"""
Generate a 4-tuple `(partname, content_type, reltype, blob)` for each
of the serialized parts in the package.
"""
for s in self._sparts:
yield (s.partname, s.content_type, s.reltype, s.blob) |
Generate a 2-tuple `(source_uri, srel)` for each of the relationships
in the package. | def iter_srels(self):
"""
Generate a 2-tuple `(source_uri, srel)` for each of the relationships
in the package.
"""
for srel in self._pkg_srels:
yield (PACKAGE_URI, srel)
for spart in self._sparts:
for srel in spart.srels:
yield (sp... |
Return |_SerializedRelationships| instance populated with
relationships for source identified by *source_uri*. | def _srels_for(phys_reader, source_uri):
"""
Return |_SerializedRelationships| instance populated with
relationships for source identified by *source_uri*.
"""
rels_xml = phys_reader.rels_xml_for(source_uri)
return _SerializedRelationships.load_from_xml(
sourc... |
Return a new |_ContentTypeMap| instance populated with the contents
of *content_types_xml*. | def from_xml(content_types_xml):
"""
Return a new |_ContentTypeMap| instance populated with the contents
of *content_types_xml*.
"""
types_elm = parse_xml(content_types_xml)
ct_map = _ContentTypeMap()
for o in types_elm.overrides:
ct_map._add_override(... |
|PackURI| instance containing partname targeted by this relationship.
Raises ``ValueError`` on reference if target_mode is ``'External'``.
Use :attr:`target_mode` to check before referencing. | def target_partname(self):
"""
|PackURI| instance containing partname targeted by this relationship.
Raises ``ValueError`` on reference if target_mode is ``'External'``.
Use :attr:`target_mode` to check before referencing.
"""
if self.is_external:
msg = ('targ... |
Return |_SerializedRelationships| instance loaded with the
relationships contained in *rels_item_xml*. Returns an empty
collection if *rels_item_xml* is |None|. | def load_from_xml(baseURI, rels_item_xml):
"""
Return |_SerializedRelationships| instance loaded with the
relationships contained in *rels_item_xml*. Returns an empty
collection if *rels_item_xml* is |None|.
"""
srels = _SerializedRelationships()
if rels_item_xml ... |
Return a |PackURI| instance containing the absolute pack URI formed by
translating *relative_ref* onto *baseURI*. | def from_rel_ref(baseURI, relative_ref):
"""
Return a |PackURI| instance containing the absolute pack URI formed by
translating *relative_ref* onto *baseURI*.
"""
joined_uri = posixpath.join(baseURI, relative_ref)
abs_uri = posixpath.abspath(joined_uri)
return Pac... |
The extension portion of this pack URI, e.g. ``'xml'`` for
``'/word/document.xml'``. Note the period is not included. | def ext(self):
"""
The extension portion of this pack URI, e.g. ``'xml'`` for
``'/word/document.xml'``. Note the period is not included.
"""
# raw_ext is either empty string or starts with period, e.g. '.xml'
raw_ext = posixpath.splitext(self)[1]
return raw_ext[1:... |
Return partname index as integer for tuple partname or None for
singleton partname, e.g. ``21`` for ``'/ppt/slides/slide21.xml'`` and
|None| for ``'/ppt/presentation.xml'``. | def idx(self):
"""
Return partname index as integer for tuple partname or None for
singleton partname, e.g. ``21`` for ``'/ppt/slides/slide21.xml'`` and
|None| for ``'/ppt/presentation.xml'``.
"""
filename = self.filename
if not filename:
return None
... |
Return string containing relative reference to package item from
*baseURI*. E.g. PackURI('/ppt/slideLayouts/slideLayout1.xml') would
return '../slideLayouts/slideLayout1.xml' for baseURI '/ppt/slides'. | def relative_ref(self, baseURI):
"""
Return string containing relative reference to package item from
*baseURI*. E.g. PackURI('/ppt/slideLayouts/slideLayout1.xml') would
return '../slideLayouts/slideLayout1.xml' for baseURI '/ppt/slides'.
"""
# workaround for posixpath bu... |
The pack URI of the .rels part corresponding to the current pack URI.
Only produces sensible output if the pack URI is a partname or the
package pseudo-partname '/'. | def rels_uri(self):
"""
The pack URI of the .rels part corresponding to the current pack URI.
Only produces sensible output if the pack URI is a partname or the
package pseudo-partname '/'.
"""
rels_filename = '%s.rels' % self.filename
rels_uri_str = posixpath.joi... |
Return a new ``<Default>`` element with attributes set to parameter
values. | def new(ext, content_type):
"""
Return a new ``<Default>`` element with attributes set to parameter
values.
"""
xml = '<Default xmlns="%s"/>' % nsmap['ct']
default = parse_xml(xml)
default.set('Extension', ext)
default.set('ContentType', content_type)
... |
Return a new ``<Override>`` element with attributes set to parameter
values. | def new(partname, content_type):
"""
Return a new ``<Override>`` element with attributes set to parameter
values.
"""
xml = '<Override xmlns="%s"/>' % nsmap['ct']
override = parse_xml(xml)
override.set('PartName', partname)
override.set('ContentType', cont... |
Return a new ``<Relationship>`` element. | def new(rId, reltype, target, target_mode=RTM.INTERNAL):
"""
Return a new ``<Relationship>`` element.
"""
xml = '<Relationship xmlns="%s"/>' % nsmap['pr']
relationship = parse_xml(xml)
relationship.set('Id', rId)
relationship.set('Type', reltype)
relations... |
Add a child ``<Relationship>`` element with attributes set according
to parameter values. | def add_rel(self, rId, reltype, target, is_external=False):
"""
Add a child ``<Relationship>`` element with attributes set according
to parameter values.
"""
target_mode = RTM.EXTERNAL if is_external else RTM.INTERNAL
relationship = CT_Relationship.new(rId, reltype, targe... |
Add a child ``<Default>`` element with attributes set to parameter
values. | def add_default(self, ext, content_type):
"""
Add a child ``<Default>`` element with attributes set to parameter
values.
"""
default = CT_Default.new(ext, content_type)
self.append(default) |
Add a child ``<Override>`` element with attributes set to parameter
values. | def add_override(self, partname, content_type):
"""
Add a child ``<Override>`` element with attributes set to parameter
values.
"""
override = CT_Override.new(partname, content_type)
self.append(override) |
Return a paragraph newly added to the end of the content in this
container, having *text* in a single run if present, and having
paragraph style *style*. If *style* is |None|, no paragraph style is
applied, which has the same effect as applying the 'Normal' style. | def add_paragraph(self, text='', style=None):
"""
Return a paragraph newly added to the end of the content in this
container, having *text* in a single run if present, and having
paragraph style *style*. If *style* is |None|, no paragraph style is
applied, which has the same effe... |
Return a table of *width* having *rows* rows and *cols* columns,
newly appended to the content in this container. *width* is evenly
distributed between the table columns. | def add_table(self, rows, cols, width):
"""
Return a table of *width* having *rows* rows and *cols* columns,
newly appended to the content in this container. *width* is evenly
distributed between the table columns.
"""
from .table import Table
tbl = CT_Tbl.new_tbl... |
A list containing the tables in this container, in document order.
Read-only. | def tables(self):
"""
A list containing the tables in this container, in document order.
Read-only.
"""
from .table import Table
return [Table(tbl, self) for tbl in self._element.tbl_lst] |
Return a |_Chunk| subclass instance appropriate to *chunk_type* parsed
from *stream_rdr* at *offset*. | def _ChunkFactory(chunk_type, stream_rdr, offset):
"""
Return a |_Chunk| subclass instance appropriate to *chunk_type* parsed
from *stream_rdr* at *offset*.
"""
chunk_cls_map = {
PNG_CHUNK_TYPE.IHDR: _IHDRChunk,
PNG_CHUNK_TYPE.pHYs: _pHYsChunk,
}
chunk_cls = chunk_cls_map.get... |
Integer dots per inch for the width of this image. Defaults to 72
when not present in the file, as is often the case. | def horz_dpi(self):
"""
Integer dots per inch for the width of this image. Defaults to 72
when not present in the file, as is often the case.
"""
pHYs = self._chunks.pHYs
if pHYs is None:
return 72
return self._dpi(pHYs.units_specifier, pHYs.horz_px_pe... |
Integer dots per inch for the height of this image. Defaults to 72
when not present in the file, as is often the case. | def vert_dpi(self):
"""
Integer dots per inch for the height of this image. Defaults to 72
when not present in the file, as is often the case.
"""
pHYs = self._chunks.pHYs
if pHYs is None:
return 72
return self._dpi(pHYs.units_specifier, pHYs.vert_px_p... |
Return a |_Chunks| instance containing the PNG chunks in *stream*. | def from_stream(cls, stream):
"""
Return a |_Chunks| instance containing the PNG chunks in *stream*.
"""
chunk_parser = _ChunkParser.from_stream(stream)
chunks = [chunk for chunk in chunk_parser.iter_chunks()]
return cls(chunks) |
IHDR chunk in PNG image | def IHDR(self):
"""
IHDR chunk in PNG image
"""
match = lambda chunk: chunk.type_name == PNG_CHUNK_TYPE.IHDR # noqa
IHDR = self._find_first(match)
if IHDR is None:
raise InvalidImageStreamError('no IHDR chunk in PNG image')
return IHDR |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.