code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def clear(self):
"""Remove all paragraphs except one empty one."""
for p in self._txBody.p_lst[1:]:
self._txBody.remove(p)
p = self.paragraphs[0]
p.clear() | Remove all paragraphs except one empty one. | clear | python | scanny/python-pptx | src/pptx/text/text.py | https://github.com/scanny/python-pptx/blob/master/src/pptx/text/text.py | MIT |
def fit_text(
self,
font_family: str = "Calibri",
max_size: int = 18,
bold: bool = False,
italic: bool = False,
font_file: str | None = None,
):
"""Fit text-frame text entirely within bounds of its shape.
Make the text in this text frame fit entirely ... | Fit text-frame text entirely within bounds of its shape.
Make the text in this text frame fit entirely within the bounds of its shape by setting
word wrap on and applying the "best-fit" font size to all the text it contains.
:attr:`TextFrame.auto_size` is set to :attr:`MSO_AUTO_SIZE.NONE`. The... | fit_text | python | scanny/python-pptx | src/pptx/text/text.py | https://github.com/scanny/python-pptx/blob/master/src/pptx/text/text.py | MIT |
def word_wrap(self) -> bool | None:
"""`True` when lines of text in this shape are wrapped to fit within the shape's width.
Read-write. Valid values are True, False, or None. True and False turn word wrap on and
off, respectively. Assigning None to word wrap causes any word wrap setting to be r... | `True` when lines of text in this shape are wrapped to fit within the shape's width.
Read-write. Valid values are True, False, or None. True and False turn word wrap on and
off, respectively. Assigning None to word wrap causes any word wrap setting to be removed
from the text frame, causing it ... | word_wrap | python | scanny/python-pptx | src/pptx/text/text.py | https://github.com/scanny/python-pptx/blob/master/src/pptx/text/text.py | MIT |
def _apply_fit(self, font_family: str, font_size: int, is_bold: bool, is_italic: bool):
"""Arrange text in this text frame to fit inside its extents.
This is accomplished by setting auto size off, wrap on, and setting the font of
all its text to `font_family`, `font_size`, `is_bold`, and `is_it... | Arrange text in this text frame to fit inside its extents.
This is accomplished by setting auto size off, wrap on, and setting the font of
all its text to `font_family`, `font_size`, `is_bold`, and `is_italic`.
| _apply_fit | python | scanny/python-pptx | src/pptx/text/text.py | https://github.com/scanny/python-pptx/blob/master/src/pptx/text/text.py | MIT |
def _best_fit_font_size(
self, family: str, max_size: int, bold: bool, italic: bool, font_file: str | None
) -> int:
"""Return font-size in points that best fits text in this text-frame.
The best-fit font size is the largest integer point size not greater than `max_size` that
allows... | Return font-size in points that best fits text in this text-frame.
The best-fit font size is the largest integer point size not greater than `max_size` that
allows all the text in this text frame to fit inside its extents when rendered using the
font described by `family`, `bold`, and `italic`.... | _best_fit_font_size | python | scanny/python-pptx | src/pptx/text/text.py | https://github.com/scanny/python-pptx/blob/master/src/pptx/text/text.py | MIT |
def _extents(self) -> tuple[Length, Length]:
"""(cx, cy) 2-tuple representing the effective rendering area of this text-frame.
Margins are taken into account.
"""
parent = cast("ProvidesExtents", self._parent)
return (
Length(parent.width - self.margin_left - self.ma... | (cx, cy) 2-tuple representing the effective rendering area of this text-frame.
Margins are taken into account.
| _extents | python | scanny/python-pptx | src/pptx/text/text.py | https://github.com/scanny/python-pptx/blob/master/src/pptx/text/text.py | MIT |
def _set_font(self, family: str, size: int, bold: bool, italic: bool):
"""Set the font properties of all the text in this text frame."""
def iter_rPrs(txBody: CT_TextBody) -> Iterator[CT_TextCharacterProperties]:
for p in txBody.p_lst:
for elm in p.content_children:
... | Set the font properties of all the text in this text frame. | _set_font | python | scanny/python-pptx | src/pptx/text/text.py | https://github.com/scanny/python-pptx/blob/master/src/pptx/text/text.py | MIT |
def color(self) -> ColorFormat:
"""The |ColorFormat| instance that provides access to the color settings for this font."""
if self.fill.type != MSO_FILL.SOLID:
self.fill.solid()
return self.fill.fore_color | The |ColorFormat| instance that provides access to the color settings for this font. | color | python | scanny/python-pptx | src/pptx/text/text.py | https://github.com/scanny/python-pptx/blob/master/src/pptx/text/text.py | MIT |
def language_id(self) -> MSO_LANGUAGE_ID | None:
"""Get or set the language id of this |Font| instance.
The language id is a member of the :ref:`MsoLanguageId` enumeration. Assigning |None|
removes any language setting, the same behavior as assigning `MSO_LANGUAGE_ID.NONE`.
"""
... | Get or set the language id of this |Font| instance.
The language id is a member of the :ref:`MsoLanguageId` enumeration. Assigning |None|
removes any language setting, the same behavior as assigning `MSO_LANGUAGE_ID.NONE`.
| language_id | python | scanny/python-pptx | src/pptx/text/text.py | https://github.com/scanny/python-pptx/blob/master/src/pptx/text/text.py | MIT |
def name(self) -> str | None:
"""Get or set the typeface name for this |Font| instance.
Causes the text it controls to appear in the named font, if a matching font is found.
Returns |None| if the typeface is currently inherited from the theme. Setting it to |None|
removes any override o... | Get or set the typeface name for this |Font| instance.
Causes the text it controls to appear in the named font, if a matching font is found.
Returns |None| if the typeface is currently inherited from the theme. Setting it to |None|
removes any override of the theme typeface.
| name | python | scanny/python-pptx | src/pptx/text/text.py | https://github.com/scanny/python-pptx/blob/master/src/pptx/text/text.py | MIT |
def size(self) -> Length | None:
"""Indicates the font height in English Metric Units (EMU).
Read/write. |None| indicates the font size should be inherited from its style hierarchy,
such as a placeholder or document defaults (usually 18pt). |Length| is a subclass of |int|
having propert... | Indicates the font height in English Metric Units (EMU).
Read/write. |None| indicates the font size should be inherited from its style hierarchy,
such as a placeholder or document defaults (usually 18pt). |Length| is a subclass of |int|
having properties for convenient conversion into points or... | size | python | scanny/python-pptx | src/pptx/text/text.py | https://github.com/scanny/python-pptx/blob/master/src/pptx/text/text.py | MIT |
def underline(self) -> bool | MSO_TEXT_UNDERLINE_TYPE | None:
"""Indicaties the underline setting for this font.
Value is |True|, |False|, |None|, or a member of the :ref:`MsoTextUnderlineType`
enumeration. |None| is the default and indicates the underline setting should be inherited
fr... | Indicaties the underline setting for this font.
Value is |True|, |False|, |None|, or a member of the :ref:`MsoTextUnderlineType`
enumeration. |None| is the default and indicates the underline setting should be inherited
from the style hierarchy, such as from a placeholder. |True| indicates sing... | underline | python | scanny/python-pptx | src/pptx/text/text.py | https://github.com/scanny/python-pptx/blob/master/src/pptx/text/text.py | MIT |
def address(self) -> str | None:
"""The URL of the hyperlink.
Read/write. URL can be on http, https, mailto, or file scheme; others may work.
"""
if self._hlinkClick is None:
return None
return self.part.target_ref(self._hlinkClick.rId) | The URL of the hyperlink.
Read/write. URL can be on http, https, mailto, or file scheme; others may work.
| address | python | scanny/python-pptx | src/pptx/text/text.py | https://github.com/scanny/python-pptx/blob/master/src/pptx/text/text.py | MIT |
def add_run(self) -> _Run:
"""Return a new run appended to the runs in this paragraph."""
r = self._p.add_r()
return _Run(r, self) | Return a new run appended to the runs in this paragraph. | add_run | python | scanny/python-pptx | src/pptx/text/text.py | https://github.com/scanny/python-pptx/blob/master/src/pptx/text/text.py | MIT |
def clear(self):
"""Remove all content from this paragraph.
Paragraph properties are preserved. Content includes runs, line breaks, and fields.
"""
for elm in self._element.content_children:
self._element.remove(elm)
return self | Remove all content from this paragraph.
Paragraph properties are preserved. Content includes runs, line breaks, and fields.
| clear | python | scanny/python-pptx | src/pptx/text/text.py | https://github.com/scanny/python-pptx/blob/master/src/pptx/text/text.py | MIT |
def line_spacing(self) -> int | float | Length | None:
"""The space between baselines in successive lines of this paragraph.
A value of |None| indicates no explicit value is assigned and its effective value is
inherited from the paragraph's style hierarchy. A numeric value, e.g. `2` or `1.5`,
... | The space between baselines in successive lines of this paragraph.
A value of |None| indicates no explicit value is assigned and its effective value is
inherited from the paragraph's style hierarchy. A numeric value, e.g. `2` or `1.5`,
indicates spacing is applied in multiples of line heights. ... | line_spacing | python | scanny/python-pptx | src/pptx/text/text.py | https://github.com/scanny/python-pptx/blob/master/src/pptx/text/text.py | MIT |
def space_after(self) -> Length | None:
"""The spacing to appear between this paragraph and the subsequent paragraph.
A value of |None| indicates no explicit value is assigned and its effective value is
inherited from the paragraph's style hierarchy. |Length| objects provide convenience
... | The spacing to appear between this paragraph and the subsequent paragraph.
A value of |None| indicates no explicit value is assigned and its effective value is
inherited from the paragraph's style hierarchy. |Length| objects provide convenience
properties, such as `.pt` and `.inches`, that allo... | space_after | python | scanny/python-pptx | src/pptx/text/text.py | https://github.com/scanny/python-pptx/blob/master/src/pptx/text/text.py | MIT |
def space_before(self) -> Length | None:
"""The spacing to appear between this paragraph and the prior paragraph.
A value of |None| indicates no explicit value is assigned and its effective value is
inherited from the paragraph's style hierarchy. |Length| objects provide convenience
pro... | The spacing to appear between this paragraph and the prior paragraph.
A value of |None| indicates no explicit value is assigned and its effective value is
inherited from the paragraph's style hierarchy. |Length| objects provide convenience
properties, such as `.pt` and `.cm`, that allow easy co... | space_before | python | scanny/python-pptx | src/pptx/text/text.py | https://github.com/scanny/python-pptx/blob/master/src/pptx/text/text.py | MIT |
def hyperlink(self) -> _Hyperlink:
"""Proxy for any `a:hlinkClick` element under the run properties element.
Created on demand, the hyperlink object is available whether an `a:hlinkClick` element is
present or not, and creates or deletes that element as appropriate in response to actions
... | Proxy for any `a:hlinkClick` element under the run properties element.
Created on demand, the hyperlink object is available whether an `a:hlinkClick` element is
present or not, and creates or deletes that element as appropriate in response to actions
on its methods and attributes.
| hyperlink | python | scanny/python-pptx | src/pptx/text/text.py | https://github.com/scanny/python-pptx/blob/master/src/pptx/text/text.py | MIT |
def __getattr__(self, name):
"""
Intercept attribute access to generalize "with_{xmlattr_name}()"
methods.
"""
if name in self._xmlattr_method_map:
def with_xmlattr(value):
xmlattr_name = self._xmlattr_method_map[name]
self._set_xmlatt... |
Intercept attribute access to generalize "with_{xmlattr_name}()"
methods.
| __getattr__ | python | scanny/python-pptx | tests/unitdata.py | https://github.com/scanny/python-pptx/blob/master/tests/unitdata.py | MIT |
def with_nsdecls(self, *nspfxs):
"""
Cause the element to contain namespace declarations. By default, the
namespace prefixes defined in the Builder class are used. These can
be overridden by providing exlicit prefixes, e.g.
``with_nsdecls('a', 'r')``.
"""
if not n... |
Cause the element to contain namespace declarations. By default, the
namespace prefixes defined in the Builder class are used. These can
be overridden by providing exlicit prefixes, e.g.
``with_nsdecls('a', 'r')``.
| with_nsdecls | python | scanny/python-pptx | tests/unitdata.py | https://github.com/scanny/python-pptx/blob/master/tests/unitdata.py | MIT |
def xml(self, indent=0):
"""
Return element XML based on attribute settings
"""
indent_str = " " * indent
if self._is_empty:
xml = "%s%s\n" % (indent_str, self._empty_element_tag)
else:
xml = "%s\n" % self._non_empty_element_xml(indent)
ret... |
Return element XML based on attribute settings
| xml | python | scanny/python-pptx | tests/unitdata.py | https://github.com/scanny/python-pptx/blob/master/tests/unitdata.py | MIT |
def make_bubble_chart_data(ser_count, point_count):
"""
Return an |BubbleChartData| object populated with *ser_count* series,
each having *point_count* data points.
"""
points = (
(1.1, 11.1, 10.0),
(2.1, 12.1, 20.0),
(3.1, 13.1, 30.0),
(1.2, 11.2, 40.0),
(2.2... |
Return an |BubbleChartData| object populated with *ser_count* series,
each having *point_count* data points.
| make_bubble_chart_data | python | scanny/python-pptx | tests/chart/test_xmlwriter.py | https://github.com/scanny/python-pptx/blob/master/tests/chart/test_xmlwriter.py | MIT |
def make_category_chart_data(cat_count, cat_type, ser_count):
"""
Return a |CategoryChartData| instance populated with *cat_count*
categories of type *cat_type* and *ser_count* series. Values are
auto-generated.
"""
category_labels = {
date: (date(2016, 12, 27), date(2016, 12, 28), date(... |
Return a |CategoryChartData| instance populated with *cat_count*
categories of type *cat_type* and *ser_count* series. Values are
auto-generated.
| make_category_chart_data | python | scanny/python-pptx | tests/chart/test_xmlwriter.py | https://github.com/scanny/python-pptx/blob/master/tests/chart/test_xmlwriter.py | MIT |
def make_xy_chart_data(ser_count, point_count):
"""
Return an |XyChartData| object populated with *ser_count* series each
having *point_count* data points. Values are auto-generated.
"""
points = (
(1.1, 11.1),
(2.1, 12.1),
(3.1, 13.1),
(1.2, 11.2),
(2.2, 12.2... |
Return an |XyChartData| object populated with *ser_count* series each
having *point_count* data points. Values are auto-generated.
| make_xy_chart_data | python | scanny/python-pptx | tests/chart/test_xmlwriter.py | https://github.com/scanny/python-pptx/blob/master/tests/chart/test_xmlwriter.py | MIT |
def and_it_knows_the_relative_partname_for_an_internal_rel(self, request):
"""Internal relationships have a relative reference for `.target_ref`.
A relative reference looks like "../slideLayouts/slideLayout1.xml". This form
is suitable for writing to a .rels file.
"""
property_m... | Internal relationships have a relative reference for `.target_ref`.
A relative reference looks like "../slideLayouts/slideLayout1.xml". This form
is suitable for writing to a .rels file.
| and_it_knows_the_relative_partname_for_an_internal_rel | python | scanny/python-pptx | tests/opc/test_package.py | https://github.com/scanny/python-pptx/blob/master/tests/opc/test_package.py | MIT |
def it_can_create_a_new_tbl_element_tree(self):
"""
Indirectly tests that column widths are a proportional split of total
width and that row heights a proportional split of total height.
"""
expected_xml = (
'<a:tbl %s>\n <a:tblPr firstRow="1" bandRow="1">\n <a:ta... |
Indirectly tests that column widths are a proportional split of total
width and that row heights a proportional split of total height.
| it_can_create_a_new_tbl_element_tree | python | scanny/python-pptx | tests/oxml/test_table.py | https://github.com/scanny/python-pptx/blob/master/tests/oxml/test_table.py | MIT |
def it_can_create_a_new_pic_element(self, desc, xml_desc):
"""`desc` attr (often filename) is XML-escaped to handle special characters.
In particular, ampersand ('&'), less/greater-than ('</>') etc.
"""
pic = CT_Picture.new_pic(
shape_id=9, name="Picture 8", desc=desc, rId="... | `desc` attr (often filename) is XML-escaped to handle special characters.
In particular, ampersand ('&'), less/greater-than ('</>') etc.
| it_can_create_a_new_pic_element | python | scanny/python-pptx | tests/oxml/shapes/test_picture.py | https://github.com/scanny/python-pptx/blob/master/tests/oxml/shapes/test_picture.py | MIT |
def it_provides_access_to_an_existing_notes_master_part(
self, notes_master_part_, part_related_by_
):
"""This is the first of a two-part test to cover the existing notes master case.
The notes master not-present case follows.
"""
prs_part = PresentationPart(None, None, None... | This is the first of a two-part test to cover the existing notes master case.
The notes master not-present case follows.
| it_provides_access_to_an_existing_notes_master_part | python | scanny/python-pptx | tests/parts/test_presentation.py | https://github.com/scanny/python-pptx/blob/master/tests/parts/test_presentation.py | MIT |
def but_it_adds_a_notes_master_part_when_needed(
self, request, package_, notes_master_part_, part_related_by_, relate_to_
):
"""This is the second of a two-part test to cover notes-master-not-present case.
The notes master present case is just above.
"""
NotesMasterPart_ = ... | This is the second of a two-part test to cover notes-master-not-present case.
The notes master present case is just above.
| but_it_adds_a_notes_master_part_when_needed | python | scanny/python-pptx | tests/parts/test_presentation.py | https://github.com/scanny/python-pptx/blob/master/tests/parts/test_presentation.py | MIT |
def it_should_update_actual_value_on_indexed_assignment(self, indexed_assignment_fixture_):
"""
Assignment to AdjustmentCollection[n] updates nth actual
"""
adjs, idx, new_val, expected = indexed_assignment_fixture_
adjs[idx] = new_val
assert adjs._adjustments[idx].actual... |
Assignment to AdjustmentCollection[n] updates nth actual
| it_should_update_actual_value_on_indexed_assignment | python | scanny/python-pptx | tests/shapes/test_autoshape.py | https://github.com/scanny/python-pptx/blob/master/tests/shapes/test_autoshape.py | MIT |
def it_should_raise_on_assigned_bad_value(self, adjustments):
"""
AdjustmentCollection[n] = val raises on val is not number
"""
with pytest.raises(ValueError):
adjustments[0] = "1.0" |
AdjustmentCollection[n] = val raises on val is not number
| it_should_raise_on_assigned_bad_value | python | scanny/python-pptx | tests/shapes/test_autoshape.py | https://github.com/scanny/python-pptx/blob/master/tests/shapes/test_autoshape.py | MIT |
def in_order(node):
"""
Traverse the tree depth first to produce a list of its values,
in order.
"""
result = []
if node is None:
return result
result.extend(in_order(node._lesser))
result.append(node.value)
... |
Traverse the tree depth first to produce a list of its values,
in order.
| in_order | python | scanny/python-pptx | tests/text/test_layout.py | https://github.com/scanny/python-pptx/blob/master/tests/text/test_layout.py | MIT |
def part_(self, request, url, rId):
"""
Mock Part instance suitable for patching into _Hyperlink.part
property. It returns url for target_ref() and rId for relate_to().
"""
part_ = instance_mock(request, XmlPart)
part_.target_ref.return_value = url
part_.relate_to... |
Mock Part instance suitable for patching into _Hyperlink.part
property. It returns url for target_ref() and rId for relate_to().
| part_ | python | scanny/python-pptx | tests/text/test_text.py | https://github.com/scanny/python-pptx/blob/master/tests/text/test_text.py | MIT |
def nsdecls(*nspfxs):
"""
Return a string containing a namespace declaration for each of *nspfxs*,
in the order they are specified.
"""
nsdecls = ""
for nspfx in nspfxs:
nsdecls += ' xmlns:%s="%s"' % (nspfx, nsmap[nspfx])
return nsdecls |
Return a string containing a namespace declaration for each of *nspfxs*,
in the order they are specified.
| nsdecls | python | scanny/python-pptx | tests/unitutil/cxml.py | https://github.com/scanny/python-pptx/blob/master/tests/unitutil/cxml.py | MIT |
def connect_children(self, child_node_list):
"""
Make each of the elements appearing in *child_node_list* a child of
this element.
"""
for node in child_node_list:
child = node.element
self._children.append(child) |
Make each of the elements appearing in *child_node_list* a child of
this element.
| connect_children | python | scanny/python-pptx | tests/unitutil/cxml.py | https://github.com/scanny/python-pptx/blob/master/tests/unitutil/cxml.py | MIT |
def from_token(cls, token):
"""
Return an ``Element`` object constructed from a parser element token.
"""
tagname = token.tagname
attrs = [(name, value) for name, value in token.attr_list]
text = token.text
return cls(tagname, attrs, text) |
Return an ``Element`` object constructed from a parser element token.
| from_token | python | scanny/python-pptx | tests/unitutil/cxml.py | https://github.com/scanny/python-pptx/blob/master/tests/unitutil/cxml.py | MIT |
def local_nspfxs(self):
"""
The namespace prefixes local to this element, both on the tagname and
all of its attributes. An empty string (``''``) is used to represent
the default namespace for an element tag having no prefix.
"""
def nspfx(name, is_element=False):
... |
The namespace prefixes local to this element, both on the tagname and
all of its attributes. An empty string (``''``) is used to represent
the default namespace for an element tag having no prefix.
| local_nspfxs | python | scanny/python-pptx | tests/unitutil/cxml.py | https://github.com/scanny/python-pptx/blob/master/tests/unitutil/cxml.py | MIT |
def nspfxs(self):
"""
A sequence containing each of the namespace prefixes appearing in
this tree. Each prefix appears once and only once, and in document
order.
"""
def merge(seq, seq_2):
for item in seq_2:
if item in seq:
... |
A sequence containing each of the namespace prefixes appearing in
this tree. Each prefix appears once and only once, and in document
order.
| nspfxs | python | scanny/python-pptx | tests/unitutil/cxml.py | https://github.com/scanny/python-pptx/blob/master/tests/unitutil/cxml.py | MIT |
def _xml(self, indent):
"""
Return a string containing the XML of this element and all its
children with a starting indent of *indent* spaces.
"""
self._indent_str = " " * indent
xml = self._start_tag
for child in self._children:
xml += child._xml(inde... |
Return a string containing the XML of this element and all its
children with a starting indent of *indent* spaces.
| _xml | python | scanny/python-pptx | tests/unitutil/cxml.py | https://github.com/scanny/python-pptx/blob/master/tests/unitutil/cxml.py | MIT |
def _start_tag(self):
"""
The text of the opening tag of this element, including attributes. If
this is the root element, a namespace declaration for each of the
namespace prefixes that occur in this tree is added in front of any
attributes. If this element contains text, that te... |
The text of the opening tag of this element, including attributes. If
this is the root element, a namespace declaration for each of the
namespace prefixes that occur in this tree is added in front of any
attributes. If this element contains text, that text follows the
start tag.... | _start_tag | python | scanny/python-pptx | tests/unitutil/cxml.py | https://github.com/scanny/python-pptx/blob/master/tests/unitutil/cxml.py | MIT |
def _end_tag(self):
"""
The text of the closing tag of this element, if there is one. If the
element contains text, no leading indentation is included.
"""
if self._text:
tag = "</%s>\n" % self._tagname
elif self._children:
tag = "%s</%s>\n" % (sel... |
The text of the closing tag of this element, if there is one. If the
element contains text, no leading indentation is included.
| _end_tag | python | scanny/python-pptx | tests/unitutil/cxml.py | https://github.com/scanny/python-pptx/blob/master/tests/unitutil/cxml.py | MIT |
def snippet_bytes(snippet_file_name: str):
"""Return bytes read from snippet file having `snippet_file_name`."""
snippet_file_path = os.path.join(test_file_dir, "snippets", "%s.txt" % snippet_file_name)
with open(snippet_file_path, "rb") as f:
return f.read().strip() | Return bytes read from snippet file having `snippet_file_name`. | snippet_bytes | python | scanny/python-pptx | tests/unitutil/file.py | https://github.com/scanny/python-pptx/blob/master/tests/unitutil/file.py | MIT |
def snippet_text(snippet_file_name: str):
"""
Return the unicode text read from the test snippet file having
*snippet_file_name*.
"""
snippet_file_path = os.path.join(test_file_dir, "snippets", "%s.txt" % snippet_file_name)
with open(snippet_file_path, "rb") as f:
snippet_bytes = f.read(... |
Return the unicode text read from the test snippet file having
*snippet_file_name*.
| snippet_text | python | scanny/python-pptx | tests/unitutil/file.py | https://github.com/scanny/python-pptx/blob/master/tests/unitutil/file.py | MIT |
def testfile_bytes(*segments: str):
"""Return bytes of file at path formed by adding `segments` to test file dir."""
path = os.path.join(test_file_dir, *segments)
with open(path, "rb") as f:
return f.read() | Return bytes of file at path formed by adding `segments` to test file dir. | testfile_bytes | python | scanny/python-pptx | tests/unitutil/file.py | https://github.com/scanny/python-pptx/blob/master/tests/unitutil/file.py | MIT |
def class_mock(
request: FixtureRequest, q_class_name: str, autospec: bool = True, **kwargs: Any
) -> Mock:
"""Return a mock patching the class with qualified name *q_class_name*.
The mock is autospec'ed based on the patched class unless the optional argument
*autospec* is set to False. Any other keywo... | Return a mock patching the class with qualified name *q_class_name*.
The mock is autospec'ed based on the patched class unless the optional argument
*autospec* is set to False. Any other keyword arguments are passed through to
Mock(). Patch is reversed after calling test returns.
| class_mock | python | scanny/python-pptx | tests/unitutil/mock.py | https://github.com/scanny/python-pptx/blob/master/tests/unitutil/mock.py | MIT |
def cls_attr_mock(
request: FixtureRequest, cls: type, attr_name: str, name: str | None = None, **kwargs: Any
) -> Mock:
"""Return a mock for an attribute (class variable) `attr_name` on `cls`.
Patch is reversed after pytest uses it.
"""
name = request.fixturename if name is None else name
_pat... | Return a mock for an attribute (class variable) `attr_name` on `cls`.
Patch is reversed after pytest uses it.
| cls_attr_mock | python | scanny/python-pptx | tests/unitutil/mock.py | https://github.com/scanny/python-pptx/blob/master/tests/unitutil/mock.py | MIT |
def function_mock(
request: FixtureRequest, q_function_name: str, autospec: bool = True, **kwargs: Any
):
"""Return mock patching function with qualified name `q_function_name`.
Patch is reversed after calling test returns.
"""
_patch = patch(q_function_name, autospec=autospec, **kwargs)
reques... | Return mock patching function with qualified name `q_function_name`.
Patch is reversed after calling test returns.
| function_mock | python | scanny/python-pptx | tests/unitutil/mock.py | https://github.com/scanny/python-pptx/blob/master/tests/unitutil/mock.py | MIT |
def initializer_mock(request: FixtureRequest, cls: type, autospec: bool = True, **kwargs: Any):
"""Return mock for __init__() method on `cls`.
The patch is reversed after pytest uses it.
"""
_patch = patch.object(cls, "__init__", autospec=autospec, return_value=None, **kwargs)
request.addfinalizer(... | Return mock for __init__() method on `cls`.
The patch is reversed after pytest uses it.
| initializer_mock | python | scanny/python-pptx | tests/unitutil/mock.py | https://github.com/scanny/python-pptx/blob/master/tests/unitutil/mock.py | MIT |
def instance_mock(
request: FixtureRequest,
cls: type,
name: str | None = None,
spec_set: bool = True,
**kwargs: Any,
) -> Mock:
"""Return mock for instance of `cls` that draws its spec from that class.
The mock does not allow new attributes to be set on the instance. If `name` is
missi... | Return mock for instance of `cls` that draws its spec from that class.
The mock does not allow new attributes to be set on the instance. If `name` is
missing or |None|, the name of the returned |Mock| instance is set to
`request.fixturename`. Additional keyword arguments are passed through to the Mock()
... | instance_mock | python | scanny/python-pptx | tests/unitutil/mock.py | https://github.com/scanny/python-pptx/blob/master/tests/unitutil/mock.py | MIT |
def method_mock(
request: FixtureRequest, cls: type, method_name: str, autospec: bool = True, **kwargs: Any
):
"""Return mock for method `method_name` on `cls`.
The patch is reversed after pytest uses it.
"""
_patch = patch.object(cls, method_name, autospec=autospec, **kwargs)
request.addfinali... | Return mock for method `method_name` on `cls`.
The patch is reversed after pytest uses it.
| method_mock | python | scanny/python-pptx | tests/unitutil/mock.py | https://github.com/scanny/python-pptx/blob/master/tests/unitutil/mock.py | MIT |
def open_mock(request: FixtureRequest, module_name: str, **kwargs: Any):
"""Return a mock for the builtin `open()` method in `module_name`."""
target = "%s.open" % module_name
_patch = patch(target, mock_open(), create=True, **kwargs)
request.addfinalizer(_patch.stop)
return _patch.start() | Return a mock for the builtin `open()` method in `module_name`. | open_mock | python | scanny/python-pptx | tests/unitutil/mock.py | https://github.com/scanny/python-pptx/blob/master/tests/unitutil/mock.py | MIT |
def property_mock(request: FixtureRequest, cls: type, prop_name: str, **kwargs: Any):
"""Return a mock for property `prop_name` on class `cls`."""
_patch = patch.object(cls, prop_name, new_callable=PropertyMock, **kwargs)
request.addfinalizer(_patch.stop)
return _patch.start() | Return a mock for property `prop_name` on class `cls`. | property_mock | python | scanny/python-pptx | tests/unitutil/mock.py | https://github.com/scanny/python-pptx/blob/master/tests/unitutil/mock.py | MIT |
def var_mock(request: FixtureRequest, q_var_name: str, **kwargs: Any):
"""Return mock patching the variable with qualified name *q_var_name*."""
_patch = patch(q_var_name, **kwargs)
request.addfinalizer(_patch.stop)
return _patch.start() | Return mock patching the variable with qualified name *q_var_name*. | var_mock | python | scanny/python-pptx | tests/unitutil/mock.py | https://github.com/scanny/python-pptx/blob/master/tests/unitutil/mock.py | MIT |
def count(start=0, step=1):
"""
Local implementation of `itertools.count()` to allow v2.6 compatibility.
"""
n = start
while True:
yield n
n += step |
Local implementation of `itertools.count()` to allow v2.6 compatibility.
| count | python | scanny/python-pptx | tests/unitutil/__init__.py | https://github.com/scanny/python-pptx/blob/master/tests/unitutil/__init__.py | MIT |
def _open(filename=None, mode="r"):
"""Open a file or ``sys.stdout`` depending on the provided filename.
Args:
filename (str): The path to the file that should be opened. If
``None`` or ``'-'``, ``sys.stdout`` or ``sys.stdin`` is
returned depending on the desired mode. Defaults ... | Open a file or ``sys.stdout`` depending on the provided filename.
Args:
filename (str): The path to the file that should be opened. If
``None`` or ``'-'``, ``sys.stdout`` or ``sys.stdin`` is
returned depending on the desired mode. Defaults to ``None``.
mode (str): The mode t... | _open | python | bndr/pipreqs | pipreqs/pipreqs.py | https://github.com/bndr/pipreqs/blob/master/pipreqs/pipreqs.py | Apache-2.0 |
def ipynb_2_py(file_name, encoding="utf-8"):
"""
Args:
file_name (str): notebook file path to parse as python script
encoding (str): encoding of file
Returns:
str: parsed string
"""
exporter = PythonExporter()
(body, _) = exporter.from_filename(file_name)
return ... |
Args:
file_name (str): notebook file path to parse as python script
encoding (str): encoding of file
Returns:
str: parsed string
| ipynb_2_py | python | bndr/pipreqs | pipreqs/pipreqs.py | https://github.com/bndr/pipreqs/blob/master/pipreqs/pipreqs.py | Apache-2.0 |
def get_pkg_names(pkgs):
"""Get PyPI package names from a list of imports.
Args:
pkgs (List[str]): List of import names.
Returns:
List[str]: The corresponding PyPI package names.
"""
result = set()
with open(join("mapping"), "r") as f:
data = dict(x.strip().split(":") ... | Get PyPI package names from a list of imports.
Args:
pkgs (List[str]): List of import names.
Returns:
List[str]: The corresponding PyPI package names.
| get_pkg_names | python | bndr/pipreqs | pipreqs/pipreqs.py | https://github.com/bndr/pipreqs/blob/master/pipreqs/pipreqs.py | Apache-2.0 |
def compare_modules(file_, imports):
"""Compare modules in a file to imported modules in a project.
Args:
file_ (str): File to parse for modules to be compared.
imports (tuple): Modules being imported in the project.
Returns:
set: The modules not imported in the project, but do exi... | Compare modules in a file to imported modules in a project.
Args:
file_ (str): File to parse for modules to be compared.
imports (tuple): Modules being imported in the project.
Returns:
set: The modules not imported in the project, but do exist in the
specified file.
| compare_modules | python | bndr/pipreqs | pipreqs/pipreqs.py | https://github.com/bndr/pipreqs/blob/master/pipreqs/pipreqs.py | Apache-2.0 |
def diff(file_, imports):
"""Display the difference between modules in a file and imported modules.""" # NOQA
modules_not_imported = compare_modules(file_, imports)
logging.info(
"The following modules are in {} but do not seem to be imported: "
"{}".format(file_, ", ".join(x for x in modu... | Display the difference between modules in a file and imported modules. | diff | python | bndr/pipreqs | pipreqs/pipreqs.py | https://github.com/bndr/pipreqs/blob/master/pipreqs/pipreqs.py | Apache-2.0 |
def clean(file_, imports):
"""Remove modules that aren't imported in project from file."""
modules_not_imported = compare_modules(file_, imports)
if len(modules_not_imported) == 0:
logging.info("Nothing to clean in " + file_)
return
re_remove = re.compile("|".join(modules_not_imported)... | Remove modules that aren't imported in project from file. | clean | python | bndr/pipreqs | pipreqs/pipreqs.py | https://github.com/bndr/pipreqs/blob/master/pipreqs/pipreqs.py | Apache-2.0 |
def dynamic_versioning(scheme, imports):
"""Enables dynamic versioning with <compat>, <gt> or <non-pin> schemes."""
if scheme == "no-pin":
imports = [{"name": item["name"], "version": ""} for item in imports]
symbol = ""
elif scheme == "gt":
symbol = ">="
elif scheme == "compat":... | Enables dynamic versioning with <compat>, <gt> or <non-pin> schemes. | dynamic_versioning | python | bndr/pipreqs | pipreqs/pipreqs.py | https://github.com/bndr/pipreqs/blob/master/pipreqs/pipreqs.py | Apache-2.0 |
def test_get_imports_info(self):
"""
Test to see that the right number of packages were found on PyPI
"""
imports = pipreqs.get_all_imports(self.project)
with_info = pipreqs.get_imports_info(imports)
# Should contain 10 items without the "nonexistendmodule" and
# ... |
Test to see that the right number of packages were found on PyPI
| test_get_imports_info | python | bndr/pipreqs | tests/test_pipreqs.py | https://github.com/bndr/pipreqs/blob/master/tests/test_pipreqs.py | Apache-2.0 |
def test_get_use_local_only(self):
"""
Test without checking PyPI, check to see if names of local
imports matches what we expect
- Note even though pyflakes isn't in requirements.txt,
It's added to locals since it is a development dependency
for testing
"""
... |
Test without checking PyPI, check to see if names of local
imports matches what we expect
- Note even though pyflakes isn't in requirements.txt,
It's added to locals since it is a development dependency
for testing
| test_get_use_local_only | python | bndr/pipreqs | tests/test_pipreqs.py | https://github.com/bndr/pipreqs/blob/master/tests/test_pipreqs.py | Apache-2.0 |
def test_init(self):
"""
Test that all modules we will test upon are in requirements file
"""
pipreqs.init(
{
"<path>": self.project,
"--savepath": None,
"--print": False,
"--use-local": None,
"--... |
Test that all modules we will test upon are in requirements file
| test_init | python | bndr/pipreqs | tests/test_pipreqs.py | https://github.com/bndr/pipreqs/blob/master/tests/test_pipreqs.py | Apache-2.0 |
def test_init_local_only(self):
"""
Test that items listed in requirements.text are the same
as locals expected
"""
pipreqs.init(
{
"<path>": self.project,
"--savepath": None,
"--print": False,
"--use-loc... |
Test that items listed in requirements.text are the same
as locals expected
| test_init_local_only | python | bndr/pipreqs | tests/test_pipreqs.py | https://github.com/bndr/pipreqs/blob/master/tests/test_pipreqs.py | Apache-2.0 |
def test_init_savepath(self):
"""
Test that we can save requirements.txt correctly
to a different path
"""
pipreqs.init(
{
"<path>": self.project,
"--savepath": self.alt_requirement_path,
"--use-local": None,
... |
Test that we can save requirements.txt correctly
to a different path
| test_init_savepath | python | bndr/pipreqs | tests/test_pipreqs.py | https://github.com/bndr/pipreqs/blob/master/tests/test_pipreqs.py | Apache-2.0 |
def test_init_overwrite(self):
"""
Test that if requiremnts.txt exists, it will not be
automatically overwritten
"""
with open(self.requirements_path, "w") as f:
f.write("should_not_be_overwritten")
pipreqs.init(
{
"<path>": self.pr... |
Test that if requiremnts.txt exists, it will not be
automatically overwritten
| test_init_overwrite | python | bndr/pipreqs | tests/test_pipreqs.py | https://github.com/bndr/pipreqs/blob/master/tests/test_pipreqs.py | Apache-2.0 |
def test_get_import_name_without_alias(self):
"""
Test that function get_name_without_alias()
will work on a string.
- Note: This isn't truly needed when pipreqs is walking
the AST to find imports
"""
import_name_with_alias = "requests as R"
expected_imp... |
Test that function get_name_without_alias()
will work on a string.
- Note: This isn't truly needed when pipreqs is walking
the AST to find imports
| test_get_import_name_without_alias | python | bndr/pipreqs | tests/test_pipreqs.py | https://github.com/bndr/pipreqs/blob/master/tests/test_pipreqs.py | Apache-2.0 |
def test_custom_pypi_server(self):
"""
Test that trying to get a custom pypi sever fails correctly
"""
self.assertRaises(
requests.exceptions.MissingSchema,
pipreqs.init,
{
"<path>": self.project,
"--savepath": None,
... |
Test that trying to get a custom pypi sever fails correctly
| test_custom_pypi_server | python | bndr/pipreqs | tests/test_pipreqs.py | https://github.com/bndr/pipreqs/blob/master/tests/test_pipreqs.py | Apache-2.0 |
def test_clean_with_imports_to_clean(self):
"""
Test --clean parameter when there are imports to clean
"""
cleaned_module = "sqlalchemy"
pipreqs.init(
{
"<path>": self.project,
"--savepath": None,
"--print": False,
... |
Test --clean parameter when there are imports to clean
| test_clean_with_imports_to_clean | python | bndr/pipreqs | tests/test_pipreqs.py | https://github.com/bndr/pipreqs/blob/master/tests/test_pipreqs.py | Apache-2.0 |
def test_output_requirements(self):
"""
Test --print parameter
It should print to stdout the same content as requeriments.txt
"""
capturedOutput = StringIO()
sys.stdout = capturedOutput
pipreqs.init(
{
"<path>": self.project,
... |
Test --print parameter
It should print to stdout the same content as requeriments.txt
| test_output_requirements | python | bndr/pipreqs | tests/test_pipreqs.py | https://github.com/bndr/pipreqs/blob/master/tests/test_pipreqs.py | Apache-2.0 |
def test_import_notebooks(self):
"""
Test the function get_all_imports() using .ipynb file
"""
self.mock_scan_notebooks()
imports = pipreqs.get_all_imports(self.project_with_notebooks)
for item in imports:
self.assertTrue(item.lower() in self.modules, "Import ... |
Test the function get_all_imports() using .ipynb file
| test_import_notebooks | python | bndr/pipreqs | tests/test_pipreqs.py | https://github.com/bndr/pipreqs/blob/master/tests/test_pipreqs.py | Apache-2.0 |
def test_invalid_notebook(self):
"""
Test that invalid notebook files cannot be imported.
"""
self.mock_scan_notebooks()
self.assertRaises(SyntaxError, pipreqs.get_all_imports, self.project_with_invalid_notebooks) |
Test that invalid notebook files cannot be imported.
| test_invalid_notebook | python | bndr/pipreqs | tests/test_pipreqs.py | https://github.com/bndr/pipreqs/blob/master/tests/test_pipreqs.py | Apache-2.0 |
def test_ipynb_2_py(self):
"""
Test the function ipynb_2_py() which converts .ipynb file to .py format
"""
python_imports = pipreqs.get_all_imports(self.python_path_same_imports)
notebook_imports = pipreqs.get_all_imports(self.notebook_path_same_imports)
self.assertEqual(... |
Test the function ipynb_2_py() which converts .ipynb file to .py format
| test_ipynb_2_py | python | bndr/pipreqs | tests/test_pipreqs.py | https://github.com/bndr/pipreqs/blob/master/tests/test_pipreqs.py | Apache-2.0 |
def test_ignore_notebooks(self):
"""
Test if notebooks are ignored when the scan-notebooks parameter is False
"""
notebook_requirement_path = os.path.join(self.project_with_notebooks, "requirements.txt")
pipreqs.init(
{
"<path>": self.project_with_not... |
Test if notebooks are ignored when the scan-notebooks parameter is False
| test_ignore_notebooks | python | bndr/pipreqs | tests/test_pipreqs.py | https://github.com/bndr/pipreqs/blob/master/tests/test_pipreqs.py | Apache-2.0 |
def tearDown(self):
"""
Remove requiremnts.txt files that were written
"""
try:
os.remove(self.requirements_path)
except OSError:
pass
try:
os.remove(self.alt_requirement_path)
except OSError:
pass |
Remove requiremnts.txt files that were written
| tearDown | python | bndr/pipreqs | tests/test_pipreqs.py | https://github.com/bndr/pipreqs/blob/master/tests/test_pipreqs.py | Apache-2.0 |
def find_risky_files(path: str):
"""Searching for risky text in yml files for given path."""
return {
str(file)
for file in Path(path).rglob("*.yml")
if risky_text in file.read_text() and str(file) not in ignore_files
} | Searching for risky text in yml files for given path. | find_risky_files | python | mckinsey/vizro | tools/scan_yaml_for_risky_text.py | https://github.com/mckinsey/vizro/blob/master/tools/scan_yaml_for_risky_text.py | Apache-2.0 |
def post_comment(pr_object, config: PyCafeConfig, comparison_urls_dict: dict[str, dict[str, str]]):
"""Post a comment on the pull request with the PyCafe dashboard links."""
template = """## View the example dashboards of the current commit live on PyCafe :coffee: :rocket:\n
Updated on: {current_utc_time}
Commi... | Post a comment on the pull request with the PyCafe dashboard links. | post_comment | python | mckinsey/vizro | tools/pycafe/create_pycafe_links_comments.py | https://github.com/mckinsey/vizro/blob/master/tools/pycafe/create_pycafe_links_comments.py | Apache-2.0 |
def _get_vizro_requirement(config: PyCafeConfig, use_latest_release: bool = False) -> str:
"""Get the Vizro requirement string for PyCafe."""
if use_latest_release:
return "vizro"
return (
f"{config.pycafe_url}/gh/artifact/mckinsey/vizro/actions/runs/{config.run_id}/"
f"pip/vizro-{co... | Get the Vizro requirement string for PyCafe. | _get_vizro_requirement | python | mckinsey/vizro | tools/pycafe/pycafe_utils.py | https://github.com/mckinsey/vizro/blob/master/tools/pycafe/pycafe_utils.py | Apache-2.0 |
def _get_vizro_ai_requirement(config: PyCafeConfig, use_latest_release: bool = False) -> str:
"""Get the Vizro AI requirement string for PyCafe."""
if use_latest_release:
return "vizro-ai"
return (
f"{config.pycafe_url}/gh/artifact/mckinsey/vizro/actions/runs/{config.run_id}/"
f"pip2... | Get the Vizro AI requirement string for PyCafe. | _get_vizro_ai_requirement | python | mckinsey/vizro | tools/pycafe/pycafe_utils.py | https://github.com/mckinsey/vizro/blob/master/tools/pycafe/pycafe_utils.py | Apache-2.0 |
def _fetch_app_content(base_url: str) -> str:
"""Fetch and process app.py content from the repository."""
response = requests.get(f"{base_url}/app.py", timeout=10)
response.raise_for_status()
app_content = response.text
app_content_split = app_content.split('if __name__ == "__main__":')
if len(... | Fetch and process app.py content from the repository. | _fetch_app_content | python | mckinsey/vizro | tools/pycafe/pycafe_utils.py | https://github.com/mckinsey/vizro/blob/master/tools/pycafe/pycafe_utils.py | Apache-2.0 |
def _fetch_directory_files(config: PyCafeConfig, directory_path: str) -> list[dict]:
"""Fetch files in a directory from GitHub API."""
url = f"https://api.github.com/repos/{config.repo_name}/git/trees/{config.commit_sha}?recursive=1"
response = requests.get(url, timeout=20)
response.raise_for_status()
... | Fetch files in a directory from GitHub API. | _fetch_directory_files | python | mckinsey/vizro | tools/pycafe/pycafe_utils.py | https://github.com/mckinsey/vizro/blob/master/tools/pycafe/pycafe_utils.py | Apache-2.0 |
def generate_link(
config: PyCafeConfig,
directory_path: str,
extra_requirements: Optional[list[str]] = None,
use_latest_release: bool = False,
) -> str:
"""Generate a PyCafe link for the example dashboard."""
base_url = f"{config.vizro_raw_url}/{config.commit_sha}/{directory_path}"
# Requi... | Generate a PyCafe link for the example dashboard. | generate_link | python | mckinsey/vizro | tools/pycafe/pycafe_utils.py | https://github.com/mckinsey/vizro/blob/master/tools/pycafe/pycafe_utils.py | Apache-2.0 |
def create_status_check(
commit: Commit,
directory: str,
url: str,
state: str = "success",
description: str = "Test out the app live on PyCafe",
):
"""Create a GitHub status check for a PyCafe link."""
context = f"PyCafe Example ({directory})"
commit.create_status(state=state, target_url... | Create a GitHub status check for a PyCafe link. | create_status_check | python | mckinsey/vizro | tools/pycafe/pycafe_utils.py | https://github.com/mckinsey/vizro/blob/master/tools/pycafe/pycafe_utils.py | Apache-2.0 |
def get_example_directories() -> dict[str, Optional[list[str]]]:
"""Return a dictionary of example directories and their requirements."""
return {
"vizro-core/examples/scratch_dev": None,
"vizro-core/examples/dev/": ["openpyxl"],
"vizro-core/examples/visual-vocabulary/": [
"a... | Return a dictionary of example directories and their requirements. | get_example_directories | python | mckinsey/vizro | tools/pycafe/pycafe_utils.py | https://github.com/mckinsey/vizro/blob/master/tools/pycafe/pycafe_utils.py | Apache-2.0 |
def run_vizro_ai(user_prompt, n_clicks, data, model, api_key, api_base, vendor_input): # noqa: PLR0913
"""Gets the AI response and adds it to the text window."""
def create_response(ai_response, figure, ai_outputs):
return (ai_response, figure, {"ai_outputs": ai_outputs})
if not n_clicks:
... | Gets the AI response and adds it to the text window. | run_vizro_ai | python | mckinsey/vizro | vizro-ai/examples/dashboard_ui/actions.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/examples/dashboard_ui/actions.py | Apache-2.0 |
def display_filename(data):
"""Custom action to display uploaded filename."""
if data is None:
raise PreventUpdate
display_message = data.get("filename") or data.get("error_message")
return f"Uploaded file name: '{display_message}'" if "filename" in data else display_message | Custom action to display uploaded filename. | display_filename | python | mckinsey/vizro | vizro-ai/examples/dashboard_ui/actions.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/examples/dashboard_ui/actions.py | Apache-2.0 |
def toggle_code(value, data):
"""Callback for switching between vizro and plotly code."""
if not data:
return dash.no_update
ai_code = data["ai_outputs"]["vizro"]["code"] if value else data["ai_outputs"]["plotly"]["code"]
formatted_code = black.format_str(ai_code, mode=black.Mode(line_length=1... | Callback for switching between vizro and plotly code. | toggle_code | python | mckinsey/vizro | vizro-ai/examples/dashboard_ui/app.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/examples/dashboard_ui/app.py | Apache-2.0 |
def build(self):
"""Returns the text area component to display vizro-ai code output."""
return html.Div(
children=[
dcc.Textarea(
id=self.id,
placeholder="Describe the chart you want to create, e.g. "
"'Visualize the... | Returns the text area component to display vizro-ai code output. | build | python | mckinsey/vizro | vizro-ai/examples/dashboard_ui/components.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/examples/dashboard_ui/components.py | Apache-2.0 |
def build(self):
"""Returns the upload component for data upload."""
return html.Div(
[
dcc.Upload(
id=self.id,
children=html.Div(["Drag and Drop or ", html.A("Select Files")], id="data-upload"),
),
]
... | Returns the upload component for data upload. | build | python | mckinsey/vizro | vizro-ai/examples/dashboard_ui/components.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/examples/dashboard_ui/components.py | Apache-2.0 |
def build(self):
"""Returns the code clipboard component inside a output text area."""
code = black.format_str(self.code, mode=black.Mode(line_length=120))
code = code.strip("'\"")
markdown_code = "\n".join(["```python", code, "```"])
return dcc.Loading(
html.Div(
... | Returns the code clipboard component inside a output text area. | build | python | mckinsey/vizro | vizro-ai/examples/dashboard_ui/components.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/examples/dashboard_ui/components.py | Apache-2.0 |
def build(self):
"""Returns custom dropdown component that cannot be cleared."""
dropdown_build_obj = super().build()
dropdown_build_obj.id = f"{self.id}_outer_div"
dropdown_build_obj.children[1].clearable = False
return dropdown_build_obj | Returns custom dropdown component that cannot be cleared. | build | python | mckinsey/vizro | vizro-ai/examples/dashboard_ui/components.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/examples/dashboard_ui/components.py | Apache-2.0 |
def build(self):
"""Returns the off canvas component for settings."""
input_groups = html.Div(
[
dbc.InputGroup(
[
dbc.InputGroupText("API Key"),
dbc.Input(placeholder="API key", type="password", id=f"{self.i... | Returns the off canvas component for settings. | build | python | mckinsey/vizro | vizro-ai/examples/dashboard_ui/components.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/examples/dashboard_ui/components.py | Apache-2.0 |
def build(self):
"""Returns the icon for api settings."""
return html.Div(
children=[html.Span("settings", className="material-symbols-outlined", id=self.id)],
className="settings-div",
) | Returns the icon for api settings. | build | python | mckinsey/vizro | vizro-ai/examples/dashboard_ui/components.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/examples/dashboard_ui/components.py | Apache-2.0 |
def _get_llm_model(model: Optional[Union[BaseChatModel, str]] = None) -> BaseChatModel:
"""Fetches and initializes an instance of the LLM.
Args:
model: Model instance or model name.
Returns:
The initialized instance of the LLM.
Raises:
ValueError: If the provided model string ... | Fetches and initializes an instance of the LLM.
Args:
model: Model instance or model name.
Returns:
The initialized instance of the LLM.
Raises:
ValueError: If the provided model string does not match any pre-defined model
| _get_llm_model | python | mckinsey/vizro | vizro-ai/src/vizro_ai/_llm_models.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/_llm_models.py | Apache-2.0 |
def __init__(self, model: Optional[Union[BaseChatModel, str]] = None):
"""Initialization of VizroAI.
Args:
model: model instance or model name.
"""
self.model = _get_llm_model(model=model)
self.components_instances = {}
# TODO add pending URL link to docs
... | Initialization of VizroAI.
Args:
model: model instance or model name.
| __init__ | python | mckinsey/vizro | vizro-ai/src/vizro_ai/_vizro_ai.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/_vizro_ai.py | Apache-2.0 |
def plot(
self,
df: pd.DataFrame,
user_input: str,
max_debug_retry: int = 1,
return_elements: bool = False,
validate_code: bool = True,
_minimal_output: bool = False,
) -> Union[go.Figure, ChartPlan]:
"""Plot visuals using vizro via english description... | Plot visuals using vizro via english descriptions, english to chart translation.
Args:
df: The dataframe to be analyzed.
user_input: User questions or descriptions of the desired visual.
max_debug_retry: Maximum number of retries to debug errors. Defaults to `1`.
... | plot | python | mckinsey/vizro | vizro-ai/src/vizro_ai/_vizro_ai.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/_vizro_ai.py | Apache-2.0 |
def dashboard(
self,
dfs: list[pd.DataFrame],
user_input: str,
return_elements: bool = False,
) -> Union[DashboardOutputs, vm.Dashboard]:
"""Creates a Vizro dashboard using english descriptions.
Args:
dfs: The dataframes to be analyzed.
user_i... | Creates a Vizro dashboard using english descriptions.
Args:
dfs: The dataframes to be analyzed.
user_input: User questions or descriptions of the desired visual.
return_elements: Flag to return DashboardOutputs dataclass that includes all possible elements generated.
... | dashboard | python | mckinsey/vizro | vizro-ai/src/vizro_ai/_vizro_ai.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/_vizro_ai.py | Apache-2.0 |
def get_schemas_and_samples(self) -> dict[str, dict[str, str]]:
"""Retrieve only the df_schema and df_sample for all datasets."""
return {
name: {"df_schema": metadata.df_schema, "df_sample": metadata.df_sample}
for name, metadata in self.all_df_metadata.items()
} | Retrieve only the df_schema and df_sample for all datasets. | get_schemas_and_samples | python | mckinsey/vizro | vizro-ai/src/vizro_ai/dashboard/utils.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/dashboard/utils.py | Apache-2.0 |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.