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 as_params(self):
""" Returns the filters, orders, select, expands and search as query parameters
:rtype: dict
"""
params = {}
if self.has_filters:
params['$filter'] = self.get_filters()
if self.has_order:
params['$orderby'] = self.get_order()
... | Returns the filters, orders, select, expands and search as query parameters
:rtype: dict
| as_params | python | O365/python-o365 | O365/utils/utils.py | https://github.com/O365/python-o365/blob/master/O365/utils/utils.py | Apache-2.0 |
def get_filters(self):
""" Returns the result filters
:rtype: str or None
"""
if self._filters:
filters_list = self._filters
if isinstance(filters_list[-1], Enum):
filters_list = filters_list[:-1]
filters = ' '.join(
[f... | Returns the result filters
:rtype: str or None
| get_filters | python | O365/python-o365 | O365/utils/utils.py | https://github.com/O365/python-o365/blob/master/O365/utils/utils.py | Apache-2.0 |
def get_order(self):
""" Returns the result order by clauses
:rtype: str or None
"""
# first get the filtered attributes in order as they must appear
# in the order_by first
if not self.has_order:
return None
return ','.join(['{} {}'.format(attribute... | Returns the result order by clauses
:rtype: str or None
| get_order | python | O365/python-o365 | O365/utils/utils.py | https://github.com/O365/python-o365/blob/master/O365/utils/utils.py | Apache-2.0 |
def get_selects(self):
""" Returns the result select clause
:rtype: str or None
"""
if self._selects:
return ','.join(self._selects)
else:
return None | Returns the result select clause
:rtype: str or None
| get_selects | python | O365/python-o365 | O365/utils/utils.py | https://github.com/O365/python-o365/blob/master/O365/utils/utils.py | Apache-2.0 |
def get_expands(self):
""" Returns the result expand clause
:rtype: str or None
"""
if self._expands:
return ','.join(self._expands)
else:
return None | Returns the result expand clause
:rtype: str or None
| get_expands | python | O365/python-o365 | O365/utils/utils.py | https://github.com/O365/python-o365/blob/master/O365/utils/utils.py | Apache-2.0 |
def new(self, attribute, operation=ChainOperator.AND):
""" Combine with a new query
:param str attribute: attribute of new query
:param ChainOperator operation: operation to combine to new query
:rtype: Query
"""
if isinstance(operation, str):
operation = Cha... | Combine with a new query
:param str attribute: attribute of new query
:param ChainOperator operation: operation to combine to new query
:rtype: Query
| new | python | O365/python-o365 | O365/utils/utils.py | https://github.com/O365/python-o365/blob/master/O365/utils/utils.py | Apache-2.0 |
def chain(self, operation=ChainOperator.AND):
""" Start a chain operation
:param ChainOperator, str operation: how to combine with a new one
:rtype: Query
"""
if isinstance(operation, str):
operation = ChainOperator(operation)
self._chain = operation
... | Start a chain operation
:param ChainOperator, str operation: how to combine with a new one
:rtype: Query
| chain | python | O365/python-o365 | O365/utils/utils.py | https://github.com/O365/python-o365/blob/master/O365/utils/utils.py | Apache-2.0 |
def remove_filter(self, filter_attr):
""" Removes a filter given the attribute name """
filter_attr = self._get_mapping(filter_attr)
new_filters = []
remove_chain = False
for flt in self._filters:
if isinstance(flt, list):
if flt[0] == filter_attr:
... | Removes a filter given the attribute name | remove_filter | python | O365/python-o365 | O365/utils/utils.py | https://github.com/O365/python-o365/blob/master/O365/utils/utils.py | Apache-2.0 |
def _parse_filter_word(self, word):
""" Converts the word parameter into the correct format """
if isinstance(word, str):
word = "'{}'".format(word)
elif isinstance(word, dt.date):
if isinstance(word, dt.datetime):
if word.tzinfo is None:
... | Converts the word parameter into the correct format | _parse_filter_word | python | O365/python-o365 | O365/utils/utils.py | https://github.com/O365/python-o365/blob/master/O365/utils/utils.py | Apache-2.0 |
def logical_operator(self, operation, word):
""" Apply a logical operator
:param str operation: how to combine with a new one
:param word: other parameter for the operation
(a = b) would be like a.logical_operator('eq', 'b')
:rtype: Query
"""
word = self._parse_... | Apply a logical operator
:param str operation: how to combine with a new one
:param word: other parameter for the operation
(a = b) would be like a.logical_operator('eq', 'b')
:rtype: Query
| logical_operator | python | O365/python-o365 | O365/utils/utils.py | https://github.com/O365/python-o365/blob/master/O365/utils/utils.py | Apache-2.0 |
def function(self, function_name, word):
""" Apply a function on given word
:param str function_name: function to apply
:param str word: word to apply function on
:rtype: Query
"""
word = self._parse_filter_word(word)
# consume negation
negation = self._n... | Apply a function on given word
:param str function_name: function to apply
:param str word: word to apply function on
:rtype: Query
| function | python | O365/python-o365 | O365/utils/utils.py | https://github.com/O365/python-o365/blob/master/O365/utils/utils.py | Apache-2.0 |
def iterable(self, iterable_name, *, collection, word, attribute=None, func=None,
operation=None, negation=False):
""" Performs a filter with the OData 'iterable_name' keyword
on the collection
For example:
q.iterable('any', collection='email_addresses', attribute='addr... | Performs a filter with the OData 'iterable_name' keyword
on the collection
For example:
q.iterable('any', collection='email_addresses', attribute='address',
operation='eq', word='george@best.com')
will transform to a filter such as:
emailAddresses/any(a:a/address eq 'g... | iterable | python | O365/python-o365 | O365/utils/utils.py | https://github.com/O365/python-o365/blob/master/O365/utils/utils.py | Apache-2.0 |
def any(self, *, collection, word, attribute=None, func=None, operation=None, negation=False):
""" Performs a filter with the OData 'any' keyword on the collection
For example:
q.any(collection='email_addresses', attribute='address',
operation='eq', word='george@best.com')
will... | Performs a filter with the OData 'any' keyword on the collection
For example:
q.any(collection='email_addresses', attribute='address',
operation='eq', word='george@best.com')
will transform to a filter such as:
emailAddresses/any(a:a/address eq 'george@best.com')
:pa... | any | python | O365/python-o365 | O365/utils/utils.py | https://github.com/O365/python-o365/blob/master/O365/utils/utils.py | Apache-2.0 |
def all(self, *, collection, word, attribute=None, func=None, operation=None, negation=False):
""" Performs a filter with the OData 'all' keyword on the collection
For example:
q.any(collection='email_addresses', attribute='address',
operation='eq', word='george@best.com')
will... | Performs a filter with the OData 'all' keyword on the collection
For example:
q.any(collection='email_addresses', attribute='address',
operation='eq', word='george@best.com')
will transform to a filter such as:
emailAddresses/all(a:a/address eq 'george@best.com')
:pa... | all | python | O365/python-o365 | O365/utils/utils.py | https://github.com/O365/python-o365/blob/master/O365/utils/utils.py | Apache-2.0 |
def order_by(self, attribute=None, *, ascending=True):
""" Applies a order_by clause
:param str attribute: attribute to apply on
:param bool ascending: should it apply ascending order or descending
:rtype: Query
"""
attribute = self._get_mapping(attribute) or self._attri... | Applies a order_by clause
:param str attribute: attribute to apply on
:param bool ascending: should it apply ascending order or descending
:rtype: Query
| order_by | python | O365/python-o365 | O365/utils/utils.py | https://github.com/O365/python-o365/blob/master/O365/utils/utils.py | Apache-2.0 |
def open_group(self):
""" Applies a precedence grouping in the next filters """
# consume negation
if self._negation:
self._negation = False
self._open_group_flag.append(None) # flag a negated group open with None
else:
self._open_group_flag.append(Tr... | Applies a precedence grouping in the next filters | open_group | python | O365/python-o365 | O365/utils/utils.py | https://github.com/O365/python-o365/blob/master/O365/utils/utils.py | Apache-2.0 |
def get_iana_tz(windows_tz: str) -> ZoneInfo:
""" Returns a valid pytz TimeZone (Iana/Olson Timezones) from a given
windows TimeZone
:param windows_tz: windows format timezone usually returned by
microsoft api response
"""
timezone: str = WIN_TO_IANA.get(windows_tz)
if timezone is None:
... | Returns a valid pytz TimeZone (Iana/Olson Timezones) from a given
windows TimeZone
:param windows_tz: windows format timezone usually returned by
microsoft api response
| get_iana_tz | python | O365/python-o365 | O365/utils/windows_tz.py | https://github.com/O365/python-o365/blob/master/O365/utils/windows_tz.py | Apache-2.0 |
def get_windows_tz(iana_tz: ZoneInfo) -> str:
""" Returns a valid windows TimeZone from a given pytz TimeZone
(Iana/Olson Timezones)
Note: Windows Timezones are SHIT!... no ... really THEY ARE
HOLY FUCKING SHIT!.
"""
timezone = IANA_TO_WIN.get(
iana_tz.key if isinstance(iana_tz, tzinfo) ... | Returns a valid windows TimeZone from a given pytz TimeZone
(Iana/Olson Timezones)
Note: Windows Timezones are SHIT!... no ... really THEY ARE
HOLY FUCKING SHIT!.
| get_windows_tz | python | O365/python-o365 | O365/utils/windows_tz.py | https://github.com/O365/python-o365/blob/master/O365/utils/windows_tz.py | Apache-2.0 |
def test_authentication(self, pop, key_to_pop):
"""
Test the new auth flow type "password"
"""
kwargs = {
"scopes" : ["basic"],
"tenant_id" : Config.TENANT_ID,
"username" : Config.EMAIL,
"password" : Config.PASSWORD,
"auth_flow_... |
Test the new auth flow type "password"
| test_authentication | python | O365/python-o365 | tests/test_account.py | https://github.com/O365/python-o365/blob/master/tests/test_account.py | Apache-2.0 |
def test_auth_with_environment_variable_token_storage(self, token):
"""
Test the authentication with the new token storage system.
we will use EnvTokenBackend(BaseTokenBackend)
default environment variable name is "O365TOKEN", initialize the class with another token_env_name to change it... |
Test the authentication with the new token storage system.
we will use EnvTokenBackend(BaseTokenBackend)
default environment variable name is "O365TOKEN", initialize the class with another token_env_name to change it
| test_auth_with_environment_variable_token_storage | python | O365/python-o365 | tests/test_account.py | https://github.com/O365/python-o365/blob/master/tests/test_account.py | Apache-2.0 |
def link_callback(uri, _rel):
"""
Convert HTML URIs to absolute system paths so xhtml2pdf can access those
resources.
"""
result = finders.find(uri)
if result:
if not isinstance(result, (list, tuple)):
result = [result]
result = [os.path.realpath(path) for path in res... |
Convert HTML URIs to absolute system paths so xhtml2pdf can access those
resources.
| link_callback | python | xhtml2pdf/xhtml2pdf | demo/djangoproject/views.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/demo/djangoproject/views.py | Apache-2.0 |
def html2pdf(data, filename, *, open_file=False):
"""
Simple test showing how to create a PDF file from
PML Source String. Also shows errors and tries to start
the resulting PDF.
"""
with open(filename, "wb") as file:
pdf = pisa.CreatePDF(io.StringIO(data), file)
if open_file and (n... |
Simple test showing how to create a PDF file from
PML Source String. Also shows errors and tries to start
the resulting PDF.
| html2pdf | python | xhtml2pdf/xhtml2pdf | manual_test/cookbook.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/manual_test/cookbook.py | Apache-2.0 |
def __init__(self, **kw) -> None:
"""The self.kw could be used in getFileName if you like."""
self.kw = kw
self.tmpFileList: list[str] = [] | The self.kw could be used in getFileName if you like. | __init__ | python | xhtml2pdf/xhtml2pdf | manual_test/linkloading.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/manual_test/linkloading.py | Apache-2.0 |
def testCGI(data="Hello <b>World</b>"):
"""
This one shows, how to get the resulting PDF as a
file object and then send it to STDOUT.
"""
result = cStringIO.StringIO()
pdf = pisa.CreatePDF(cStringIO.StringIO(data), result)
if pdf.err:
print("Content-Type: text/plain")
dumpE... |
This one shows, how to get the resulting PDF as a
file object and then send it to STDOUT.
| testCGI | python | xhtml2pdf/xhtml2pdf | manual_test/simple.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/manual_test/simple.py | Apache-2.0 |
def testURL(url="http://www.htmltopdf.org", dest="test-website.pdf"):
"""
Loading from an URL. We open a file like object for the URL by
using 'urllib'. If there have to be loaded more data from the web,
the pisaLinkLoader helper is passed as 'link_callback'. The
pisaLinkLoader creates temporary fil... |
Loading from an URL. We open a file like object for the URL by
using 'urllib'. If there have to be loaded more data from the web,
the pisaLinkLoader helper is passed as 'link_callback'. The
pisaLinkLoader creates temporary files for everything it loads, because
the Reportlab Toolkit needs real file... | testURL | python | xhtml2pdf/xhtml2pdf | manual_test/simple.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/manual_test/simple.py | Apache-2.0 |
def test_asian_font_in_pdf(self):
"""
Tests if the asian fonts used in the CSS property "font-family"
are correctly embedded in the pdf result.
"""
# Read the embedded fonts from the finished pdf file
with io.BytesIO() as pdf_file:
pisa_doc = pisaDocument(src=... |
Tests if the asian fonts used in the CSS property "font-family"
are correctly embedded in the pdf result.
| test_asian_font_in_pdf | python | xhtml2pdf/xhtml2pdf | tests/test_asian_font_support.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/tests/test_asian_font_support.py | Apache-2.0 |
def test_get_default_asian_font(self):
"""Tests if we can successfully extract the default asian fonts"""
DEFAULT_ASIAN_FONT = get_default_asian_font()
# Test, if is dict
self.assertIsInstance(
DEFAULT_ASIAN_FONT, dict, "get_default_asian_font not returning a dict!"
... | Tests if we can successfully extract the default asian fonts | test_get_default_asian_font | python | xhtml2pdf/xhtml2pdf | tests/test_asian_font_support.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/tests/test_asian_font_support.py | Apache-2.0 |
def test_asian_reportlab_fonts(self):
"""
Tests the asian font list that we're getting from reportlab
If there is an Error here, ReportLab probably has changed/added new asian fonts
"""
reference = {
"HeiseiMin-W3": ("jpn", "UniJIS-UCS2-H"),
"HeiseiKakuGo-... |
Tests the asian font list that we're getting from reportlab
If there is an Error here, ReportLab probably has changed/added new asian fonts
| test_asian_reportlab_fonts | python | xhtml2pdf/xhtml2pdf | tests/test_asian_font_support.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/tests/test_asian_font_support.py | Apache-2.0 |
def test_media_all(self) -> None:
"""Test if the rule "@media all {" works"""
media_all = """
@media all {
p { color: yellow; }
}
"""
selector_media_all = self.parser.parse(media_all)[0]
css_media_all = self._get_first_dict_value(selector_... | Test if the rule "@media all {" works | test_media_all | python | xhtml2pdf/xhtml2pdf | tests/test_css_media_rule.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/tests/test_css_media_rule.py | Apache-2.0 |
def test_media_all_and(self) -> None:
"""Test if the rule "@media all and (...) {" works"""
media_all_and = """
@media all and (max-width: 500px) {
p { color: yellow; }
}
"""
selector_media_all_and = self.parser.parse(media_all_and)[0]
css... | Test if the rule "@media all and (...) {" works | test_media_all_and | python | xhtml2pdf/xhtml2pdf | tests/test_css_media_rule.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/tests/test_css_media_rule.py | Apache-2.0 |
def test_media_all_default(self) -> None:
"""Test if the rule "@media (...) {" works (no media type defaults to "all")"""
media_all_default = """
@media (max-width: 500px) {
p { color: yellow; }
}
"""
selector_media_all_default = self.parser.parse... | Test if the rule "@media (...) {" works (no media type defaults to "all") | test_media_all_default | python | xhtml2pdf/xhtml2pdf | tests/test_css_media_rule.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/tests/test_css_media_rule.py | Apache-2.0 |
def test_document_with_transparent_image(self) -> None:
"""Test that a transparent PNG image is rendered properly."""
tests_folder = os.path.dirname(os.path.realpath(__file__))
image_path = os.path.join(
tests_folder, "samples", "img", "denker-transparent.png"
)
extra... | Test that a transparent PNG image is rendered properly. | test_document_with_transparent_image | python | xhtml2pdf/xhtml2pdf | tests/test_document.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/tests/test_document.py | Apache-2.0 |
def test_document_background_image_not_on_all_pages(self) -> None:
"""Test that all pages are being rendered, when background is a pdf file and it's applied for the first page only."""
tests_folder = os.path.dirname(os.path.realpath(__file__))
background_path = os.path.join(tests_folder, "sample... | Test that all pages are being rendered, when background is a pdf file and it's applied for the first page only. | test_document_background_image_not_on_all_pages | python | xhtml2pdf/xhtml2pdf | tests/test_document.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/tests/test_document.py | Apache-2.0 |
def test_document_with_broken_image(self) -> None:
"""Test that broken images don't cause unhandled exception"""
# Although this is just html, it will be recognized as svg
image_path = "https://raw.githubusercontent.com/xhtml2pdf/xhtml2pdf/b01b1d8f9497dedd0f2454409d03408bdeea997c/tests/samples/i... | Test that broken images don't cause unhandled exception | test_document_with_broken_image | python | xhtml2pdf/xhtml2pdf | tests/test_document.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/tests/test_document.py | Apache-2.0 |
def test_document_cannot_identify_image(self) -> None:
"""Test that images which cannot be identified don't cause stack trace to be printed"""
image_path = "https://raw.githubusercontent.com/python-pillow/Pillow/7921da54a73dd4a30c23957369b79cda176005c6/Tests/images/zero_width.gif"
extra_html = f... | Test that images which cannot be identified don't cause stack trace to be printed | test_document_cannot_identify_image | python | xhtml2pdf/xhtml2pdf | tests/test_document.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/tests/test_document.py | Apache-2.0 |
def test_document_nested_table(self) -> None:
"""Test that nested tables are being rendered."""
tests_folder = os.path.dirname(os.path.realpath(__file__))
html_path = os.path.join(tests_folder, "samples", "nested_table.html")
with open(html_path, encoding="utf-8") as html_file:
... | Test that nested tables are being rendered. | test_document_nested_table | python | xhtml2pdf/xhtml2pdf | tests/test_document.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/tests/test_document.py | Apache-2.0 |
def test_timeout(self) -> None:
"""Test why some http request doesn't have a timeout"""
html = """<!DOCTYPE html>
<html lang="bs">
<head>
<meta charset="UTF-8" />
<title></title>
</head>
<body>
<h1>works</h1>
<img src="https://cars.usnews.com/static/images/Auto/custom/14737/2022_... | Test why some http request doesn't have a timeout | test_timeout | python | xhtml2pdf/xhtml2pdf | tests/test_http.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/tests/test_http.py | Apache-2.0 |
def test_height_as_list(self) -> None:
"""Asserts attributes like 'height: 10px !important" are parsed"""
c = pisaContext(".")
data = b"<p style='height: 10px !important;width: 10px !important'>test</p>"
r = pisaParser(data, c)
self.assertEqual(c, r)
self.assertEqual(r.er... | Asserts attributes like 'height: 10px !important" are parsed | test_height_as_list | python | xhtml2pdf/xhtml2pdf | tests/test_parser.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/tests/test_parser.py | Apache-2.0 |
def test_pdf_language_tag_in_html(self) -> None:
"""
this function is used to check if the "Custom Tag" <pdf:language/>
is located in the HTML file through assertNotEqual()
"""
text = ""
language_tag = '<pdf:language name=""/>'
html = self.HTML_CONTENT.format(
... |
this function is used to check if the "Custom Tag" <pdf:language/>
is located in the HTML file through assertNotEqual()
| test_pdf_language_tag_in_html | python | xhtml2pdf/xhtml2pdf | tests/test_right_to_left_font_support.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/tests/test_right_to_left_font_support.py | Apache-2.0 |
def test_language_attribute_in_pisaDocument(self) -> None:
"""Tests if the attribute 'language' is located in the pisaDocument."""
text = ""
language_tag = '<pdf:language name=""/>'
html = self.HTML_CONTENT.format(
ff_R=self.ff_R,
ff_M=self.ff_M,
ff_B... | Tests if the attribute 'language' is located in the pisaDocument. | test_language_attribute_in_pisaDocument | python | xhtml2pdf/xhtml2pdf | tests/test_right_to_left_font_support.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/tests/test_right_to_left_font_support.py | Apache-2.0 |
def test_empty_table(self) -> None:
"""
Test, if an empty table will return an empty story;
This will also raise a log.warning()
"""
html = """
<html>
<head>
</head>
<body>
<table>
</table>
</body>
</html>
... |
Test, if an empty table will return an empty story;
This will also raise a log.warning()
| test_empty_table | python | xhtml2pdf/xhtml2pdf | tests/test_table_css.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/tests/test_table_css.py | Apache-2.0 |
def test_tr_background_color(self) -> None:
"""
Test background on <tr> tag;
If it works, "darkgreen" will be returned as hexval "0x006400"
"""
html = """
<html>
<head>
<style>
tr { background-color: darkgreen }
</style>
... |
Test background on <tr> tag;
If it works, "darkgreen" will be returned as hexval "0x006400"
| test_tr_background_color | python | xhtml2pdf/xhtml2pdf | tests/test_table_css.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/tests/test_table_css.py | Apache-2.0 |
def test_td_colspan(self) -> None:
"""
Test colspan on <td> tag;
If it works, colspan="3" will be equal to (2, 0) in _spanCmds of the ReportLab table
"""
html = """
<html>
<head>
<style>
</style>
</head>
<body>
<... |
Test colspan on <td> tag;
If it works, colspan="3" will be equal to (2, 0) in _spanCmds of the ReportLab table
| test_td_colspan | python | xhtml2pdf/xhtml2pdf | tests/test_table_css.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/tests/test_table_css.py | Apache-2.0 |
def test_td_rowspan(self) -> None:
"""
Test rowspan on <td> tag;
If it works, rowspan="3" will be equal to (0, 2) in _spanCmds of the ReportLab table
"""
html = """
<html>
<head>
<style>
</style>
</head>
<body>
<... |
Test rowspan on <td> tag;
If it works, rowspan="3" will be equal to (0, 2) in _spanCmds of the ReportLab table
| test_td_rowspan | python | xhtml2pdf/xhtml2pdf | tests/test_table_css.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/tests/test_table_css.py | Apache-2.0 |
def test_td_width_and_height(self) -> None:
"""
Test width and height on <td> tag;
If it works, width: 2pt will be equal to 2.0 and height: 3pt will be equal to 3.0 in the ReportLab table
"""
html = """
<html>
<head>
<style>
td { width: 2pt... |
Test width and height on <td> tag;
If it works, width: 2pt will be equal to 2.0 and height: 3pt will be equal to 3.0 in the ReportLab table
| test_td_width_and_height | python | xhtml2pdf/xhtml2pdf | tests/test_table_css.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/tests/test_table_css.py | Apache-2.0 |
def test_check_updated_face_name(self) -> None:
"""
this function help us to check is the font-family value on the pdf and
the font-family from html element are same.
"""
# Create the pisaDocument in memory from the HTML
with io.BytesIO() as pdf_file:
pisa_doc... |
this function help us to check is the font-family value on the pdf and
the font-family from html element are same.
| test_check_updated_face_name | python | xhtml2pdf/xhtml2pdf | tests/test_update_face_name.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/tests/test_update_face_name.py | Apache-2.0 |
def test_unicode(self):
"""Asserts bytes generated by reportlab are returned"""
src = pisaTempFile()
value = (
b"%PDF-1.4\r\n%\x93\x8c\x8b\x9e ReportLab Generated PDF document"
b" http://www.reportlab.com"
)
try:
src.write(value)
except... | Asserts bytes generated by reportlab are returned | test_unicode | python | xhtml2pdf/xhtml2pdf | tests/test_utils.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/tests/test_utils.py | Apache-2.0 |
def __init__(self, buffer: str = "", capacity: int = CAPACITY) -> None:
"""
Creates a TempFile object containing the specified buffer.
If capacity is specified, we use a real temporary file once the
file gets larger than that size. Otherwise, the data is stored
in memory.
... |
Creates a TempFile object containing the specified buffer.
If capacity is specified, we use a real temporary file once the
file gets larger than that size. Otherwise, the data is stored
in memory.
| __init__ | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/files.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/files.py | Apache-2.0 |
def makeTempFile(self) -> None:
"""
Switch to next strategy. If an error occurred,
stay with the first strategy.
"""
if self.strategy == 0:
try:
new_delegate = self.STRATEGIES[1]()
new_delegate.write(self.getvalue())
sel... |
Switch to next strategy. If an error occurred,
stay with the first strategy.
| makeTempFile | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/files.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/files.py | Apache-2.0 |
def getvalue(self) -> bytes:
"""
Get value of file. Work around for second strategy.
Always returns bytes.
"""
if self.strategy == 0:
return self._delegate.getvalue()
self._delegate.flush()
self._delegate.seek(0)
value = self._delegate.read()
... |
Get value of file. Work around for second strategy.
Always returns bytes.
| getvalue | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/files.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/files.py | Apache-2.0 |
def write(self, value: bytes | str):
"""If capacity != -1 and length of file > capacity it is time to switch."""
if self.capacity > 0 and self.strategy == 0:
len_value = len(value)
if len_value >= self.capacity:
needs_new_strategy = True
else:
... | If capacity != -1 and length of file > capacity it is time to switch. | write | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/files.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/files.py | Apache-2.0 |
def splitIntoLines(
self, maxWidth: int, maxHeight: int, *, splitted: bool = False
) -> int | None:
"""
Split text into lines and calculate X positions. If we need more
space in height than available we return the rest of the text.
"""
self.lines = []
self.hei... |
Split text into lines and calculate X positions. If we need more
space in height than available we return the rest of the text.
| splitIntoLines | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/paragraph.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/paragraph.py | Apache-2.0 |
def dumpLines(self):
"""For debugging dump all line and their content."""
for i, line in enumerate(self.lines):
logger.debug("Line %d:", i)
logger.debug(line.dumpFragments()) | For debugging dump all line and their content. | dumpLines | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/paragraph.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/paragraph.py | Apache-2.0 |
def __getitem__(self, key):
"""Make sure slices return also Text object and not lists"""
if isinstance(key, slice):
return type(self)(super().__getitem__(key))
return super().__getitem__(key) | Make sure slices return also Text object and not lists | __getitem__ | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/paragraph.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/paragraph.py | Apache-2.0 |
def wrap(self, availWidth: int, availHeight: int) -> tuple[int, int]:
"""Determine the rectangle this paragraph really needs."""
# memorize available space
self.avWidth: int = availWidth
self.avHeight: int = availHeight
logger.debug("*** wrap (%f, %f)", availWidth, availHeight)
... | Determine the rectangle this paragraph really needs. | wrap | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/paragraph.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/paragraph.py | Apache-2.0 |
def draw(self) -> None:
"""Render the content of the paragraph."""
logger.debug("*** draw")
if not self.text:
return
canvas: Canvas = self.canv
style: Style = self.style
canvas.saveState()
# Draw box around paragraph for debugging
if self.d... | Render the content of the paragraph. | draw | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/paragraph.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/paragraph.py | Apache-2.0 |
def pisaParser(
src,
context,
default_css="",
xhtml=False, # noqa: FBT002
encoding="utf8",
xml_output=None,
):
"""
- Parse HTML and get miniDOM
- Extract CSS information, add default CSS, parse CSS
- Handle the document DOM itself and build reportlab story
- Return Context o... |
- Parse HTML and get miniDOM
- Extract CSS information, add default CSS, parse CSS
- Handle the document DOM itself and build reportlab story
- Return Context object.
| pisaParser | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/parser.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/parser.py | Apache-2.0 |
def imgVRange(h, va, fontSize):
"""Return bottom,top offsets relative to baseline(0)."""
if va == "baseline":
iyo = 0
elif va in {"text-top", "top"}:
iyo = fontSize - h
elif va == "middle":
iyo = fontSize - (1.2 * fontSize + h) * 0.5
elif va in {"text-bottom", "bottom"}:
... | Return bottom,top offsets relative to baseline(0). | imgVRange | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/reportlab_paragraph.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/reportlab_paragraph.py | Apache-2.0 |
def _sameFrag(f, g):
"""Returns 1 if two ParaFrags map out the same."""
if (
hasattr(f, "cbDefn")
or hasattr(g, "cbDefn")
or hasattr(f, "lineBreak")
or hasattr(g, "lineBreak")
):
return 0
for a in (
"fontName",
"fontSize",
"textColor",
... | Returns 1 if two ParaFrags map out the same. | _sameFrag | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/reportlab_paragraph.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/reportlab_paragraph.py | Apache-2.0 |
def _getFragWords(frags, *, reverse=False):
"""
Given a Parafrag list return a list of fragwords
[[size, (f00,w00), ..., (f0n,w0n)],....,[size, (fm0,wm0), ..., (f0n,wmn)]]
each pair f,w represents a style and some string
each sublist represents a word.
"""
R = []
W = []
n = 0
han... |
Given a Parafrag list return a list of fragwords
[[size, (f00,w00), ..., (f0n,w0n)],....,[size, (fm0,wm0), ..., (f0n,wmn)]]
each pair f,w represents a style and some string
each sublist represents a word.
| _getFragWords | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/reportlab_paragraph.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/reportlab_paragraph.py | Apache-2.0 |
def _drawBullet(canvas, offset, cur_y, bulletText, style):
"""Draw a bullet text could be a simple string or a frag list."""
tx2 = canvas.beginText(
style.bulletIndent, cur_y + getattr(style, "bulletOffsetY", 0)
)
tx2.setFont(style.bulletFontName, style.bulletFontSize)
tx2.setFillColor(
... | Draw a bullet text could be a simple string or a frag list. | _drawBullet | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/reportlab_paragraph.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/reportlab_paragraph.py | Apache-2.0 |
def _handleBulletWidth(bulletText, style, maxWidths):
"""Work out bullet width and adjust maxWidths[0] if neccessary."""
if bulletText:
if isinstance(bulletText, str):
bulletWidth = stringWidth(
bulletText, style.bulletFontName, style.bulletFontSize
)
else... | Work out bullet width and adjust maxWidths[0] if neccessary. | _handleBulletWidth | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/reportlab_paragraph.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/reportlab_paragraph.py | Apache-2.0 |
def _do_post_text(tx):
"""
Try to find out what the variables mean:
tx A structure containing more information about paragraph ???
leading Height of lines
ff 1/8 of the font size
y0 The "baseline" postion ???
y 1/8 below the baseline
"""
xs = tx.... |
Try to find out what the variables mean:
tx A structure containing more information about paragraph ???
leading Height of lines
ff 1/8 of the font size
y0 The "baseline" postion ???
y 1/8 below the baseline
| _do_post_text | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/reportlab_paragraph.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/reportlab_paragraph.py | Apache-2.0 |
def cjkFragSplit(frags, maxWidths, calcBounds, encoding="utf8"):
"""This attempts to be wordSplit for frags using the dumb algorithm."""
U = [] # get a list of single glyphs with their widths etc etc
for f in frags:
text = f.text
if not isinstance(text, str):
text = text.decode(... | This attempts to be wordSplit for frags using the dumb algorithm. | cjkFragSplit | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/reportlab_paragraph.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/reportlab_paragraph.py | Apache-2.0 |
def minWidth(self):
"""Attempt to determine a minimum sensible width."""
frags = self.frags
nFrags = len(frags)
if not nFrags:
return 0
if nFrags == 1:
f = frags[0]
fS = f.fontSize
fN = f.fontName
words = hasattr(f, "tex... | Attempt to determine a minimum sensible width. | minWidth | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/reportlab_paragraph.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/reportlab_paragraph.py | Apache-2.0 |
def breakLines(self, width):
"""
Returns a broken line structure. There are two cases.
A) For the simple case of a single formatting input fragment the output is
A fragment specifier with
- kind = 0
- fontName, fontSize, leading, textColor
... |
Returns a broken line structure. There are two cases.
A) For the simple case of a single formatting input fragment the output is
A fragment specifier with
- kind = 0
- fontName, fontSize, leading, textColor
- lines= A list of lines
... | breakLines | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/reportlab_paragraph.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/reportlab_paragraph.py | Apache-2.0 |
def breakLinesCJK(self, width):
"""
Initially, the dumbest possible wrapping algorithm.
Cannot handle font variations.
"""
if self.debug:
print(id(self), "breakLinesCJK")
maxWidths = width if isinstance(width, (list, tuple)) else [width]
style = self.... |
Initially, the dumbest possible wrapping algorithm.
Cannot handle font variations.
| breakLinesCJK | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/reportlab_paragraph.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/reportlab_paragraph.py | Apache-2.0 |
def drawPara(self, debug=0):
"""
Draws a paragraph according to the given style.
Returns the final y position at the bottom. Not safe for
paragraphs without spaces e.g. Japanese; wrapping
algorithm will go infinite.
"""
if self.debug:
print(id(self), "... |
Draws a paragraph according to the given style.
Returns the final y position at the bottom. Not safe for
paragraphs without spaces e.g. Japanese; wrapping
algorithm will go infinite.
| drawPara | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/reportlab_paragraph.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/reportlab_paragraph.py | Apache-2.0 |
def getPlainText(self, identify=None):
"""
Convenience function for templates which want access
to the raw text, without XML tags.
"""
frags = getattr(self, "frags", None)
if frags:
return "".join(frag.text for frag in frags if hasattr(frag, "text"))
i... |
Convenience function for templates which want access
to the raw text, without XML tags.
| getPlainText | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/reportlab_paragraph.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/reportlab_paragraph.py | Apache-2.0 |
def getActualLineWidths0(self):
"""
Convenience function; tells you how wide each line
actually is. For justified styles, this will be
the same as the wrap width; for others it might be
useful for seeing if paragraphs will fit in spaces.
"""
assert hasattr(self, ... |
Convenience function; tells you how wide each line
actually is. For justified styles, this will be
the same as the wrap width; for others it might be
useful for seeing if paragraphs will fit in spaces.
| getActualLineWidths0 | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/reportlab_paragraph.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/reportlab_paragraph.py | Apache-2.0 |
def transform_attrs(obj, keys, container, func, extras=None):
"""
Allows to apply one function to set of keys checking if key is in container,
also transform ccs key to report lab keys.
extras = Are extra params for func, it will be call like func(*[param1, param2])
obj = frag
keys = [(reportl... |
Allows to apply one function to set of keys checking if key is in container,
also transform ccs key to report lab keys.
extras = Are extra params for func, it will be call like func(*[param1, param2])
obj = frag
keys = [(reportlab, css), ... ]
container = cssAttr
| transform_attrs | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/util.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/util.py | Apache-2.0 |
def copy_attrs(obj1, obj2, attrs):
"""
Allows copy a list of attributes from object2 to object1.
Useful for copy ccs attributes to fragment.
"""
for attr in attrs:
value = getattr(obj2, attr) if hasattr(obj2, attr) else None
if value is None and isinstance(obj2, dict) and attr in obj... |
Allows copy a list of attributes from object2 to object1.
Useful for copy ccs attributes to fragment.
| copy_attrs | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/util.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/util.py | Apache-2.0 |
def set_value(obj, attrs, value, *, do_copy=False):
"""Allows set the same value to a list of attributes."""
for attr in attrs:
if do_copy:
value = copy(value)
setattr(obj, attr, value) | Allows set the same value to a list of attributes. | set_value | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/util.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/util.py | Apache-2.0 |
def getSize(
value: str | float | list | tuple,
relative=0,
base: int | None = None,
default: float = 0.0,
) -> float:
"""
Converts strings to standard sizes.
That is the function taking a string of CSS size ('12pt', '1cm' and so on)
and converts it into a float in a standard unit (in ou... |
Converts strings to standard sizes.
That is the function taking a string of CSS size ('12pt', '1cm' and so on)
and converts it into a float in a standard unit (in our case, points).
>>> getSize('12pt')
12.0
>>> getSize('1cm')
28.346456692913385
| getSize | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/util.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/util.py | Apache-2.0 |
def getCoords(x, y, w, h, pagesize):
"""
As a stupid programmer I like to use the upper left
corner of the document as the 0,0 coords therefore
we need to do some fancy calculations.
"""
# ~ print pagesize
ax, ay = pagesize
if x < 0:
x = ax + x
if y < 0:
y = ay + y
... |
As a stupid programmer I like to use the upper left
corner of the document as the 0,0 coords therefore
we need to do some fancy calculations.
| getCoords | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/util.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/util.py | Apache-2.0 |
def getBox(box, pagesize):
"""
Parse sizes by corners in the form:
<X-Left> <Y-Upper> <Width> <Height>
The last to values with negative values are interpreted as offsets form
the right and lower border.
"""
box = str(box).split()
if len(box) != 4:
msg = "box not defined right way... |
Parse sizes by corners in the form:
<X-Left> <Y-Upper> <Width> <Height>
The last to values with negative values are interpreted as offsets form
the right and lower border.
| getBox | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/util.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/util.py | Apache-2.0 |
def getFrameDimensions(
data, page_width: float, page_height: float
) -> tuple[float, float, float, float]:
"""
Calculate dimensions of a frame.
Returns left, top, width and height of the frame in points.
"""
box = data.get("-pdf-frame-box", [])
if len(box) == 4:
return (getSize(box... |
Calculate dimensions of a frame.
Returns left, top, width and height of the frame in points.
| getFrameDimensions | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/util.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/util.py | Apache-2.0 |
def handle_nextPageTemplate(self, pt: str | int | list | tuple) -> None:
"""If pt has also templates for even and odd page convert it to list."""
has_left_template: bool = self._has_template_for_name(f"{pt}_left")
has_right_template: bool = self._has_template_for_name(f"{pt}_right")
if ... | If pt has also templates for even and odd page convert it to list. | handle_nextPageTemplate | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/xhtml2pdf_reportlab.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/xhtml2pdf_reportlab.py | Apache-2.0 |
def getRGBData(self) -> bytes | str:
"""Return byte array of RGB data as string."""
if self._data is None:
self._dataA = None
if sys.platform[:4] == "java":
import jarray # TODO: Move to top.
from java.awt.image import PixelGrabber
... | Return byte array of RGB data as string. | getRGBData | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/xhtml2pdf_reportlab.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/xhtml2pdf_reportlab.py | Apache-2.0 |
def wrap(self, availWidth, availHeight):
"""
Resize the image if necessary.
This can be called more than once! Do not overwrite important data like drawWidth.
"""
availHeight = self.setMaxHeight(availHeight)
# print "image wrap", id(self), availWidth, availHeight, self.d... |
Resize the image if necessary.
This can be called more than once! Do not overwrite important data like drawWidth.
| wrap | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/xhtml2pdf_reportlab.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/xhtml2pdf_reportlab.py | Apache-2.0 |
def getDrawing(
self, width: float | None = None, height: float | None = None
) -> Drawing | None:
"""If this image is a vector image and the library is available, returns a ReportLab Drawing."""
if svg2rlg:
try:
drawing = svg2rlg(BytesIO(self._imgdata))
... | If this image is a vector image and the library is available, returns a ReportLab Drawing. | getDrawing | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/xhtml2pdf_reportlab.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/xhtml2pdf_reportlab.py | Apache-2.0 |
def getDrawingRaster(self) -> BytesIO | None:
"""If this image is a vector image and the libraries are available, returns a PNG raster."""
if svg2rlg and renderPM:
svg: Drawing = self.getDrawing()
if svg:
imgdata = BytesIO()
renderPM.drawToFile(svg... | If this image is a vector image and the libraries are available, returns a PNG raster. | getDrawingRaster | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/xhtml2pdf_reportlab.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/xhtml2pdf_reportlab.py | Apache-2.0 |
def wrap(self, availWidth, availHeight):
"""All table properties should be known by now."""
widths = (availWidth - self.rightColumnWidth, self.rightColumnWidth)
# makes an internal table which does all the work.
# we draw the LAST RUN's entries! If there are
# none, we make som... | All table properties should be known by now. | wrap | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/xhtml2pdf_reportlab.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/xhtml2pdf_reportlab.py | Apache-2.0 |
def generate_pdf_background(
pisafile: pisaFileObject,
pagesize: tuple[int, int],
*,
is_portrait: bool,
context: dict | None = None,
) -> pisaFileObject:
"""
Pypdf requires pdf as background so convert image to pdf in temporary file with same page dimensions
... |
Pypdf requires pdf as background so convert image to pdf in temporary file with same page dimensions
:param pisafile: Image File
:param pagesize: Page size for the new pdf
| generate_pdf_background | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/builders/watermarks.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/builders/watermarks.py | Apache-2.0 |
def findStyleFor(self, element, attrName, default=NotImplemented):
"""
Attempts to find the style setting for attrName in the CSSRulesets.
Note: This method does not attempt to resolve rules that return
"inherited", "default", or values that have units (including "%").
This is l... |
Attempts to find the style setting for attrName in the CSSRulesets.
Note: This method does not attempt to resolve rules that return
"inherited", "default", or values that have units (including "%").
This is left up to the client app to re-query the CSS in order to
implement the... | findStyleFor | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/w3c/css.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/w3c/css.py | Apache-2.0 |
def _calcSpecificity(self):
"""From http://www.w3.org/TR/CSS21/cascade.html#specificity."""
hashCount = 0
qualifierCount = 0
elementCount = int(self.name != "*")
for qualifier in self.qualifiers:
if qualifier.isHash():
hashCount += 1
elif q... | From http://www.w3.org/TR/CSS21/cascade.html#specificity. | _calcSpecificity | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/w3c/css.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/w3c/css.py | Apache-2.0 |
def mergeStyles(self, styles):
"""XXX Bugfix for use in PISA."""
for k, v in styles.items():
if k in self and self[k]:
self[k] = copy.copy(self[k])
self[k].update(v)
else:
self[k] = v | XXX Bugfix for use in PISA. | mergeStyles | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/w3c/css.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/w3c/css.py | Apache-2.0 |
def atPage(
self,
name: str,
pseudopage: str | None,
data: dict,
*,
isLandscape: bool,
pageBorder,
):
"""This is overridden by xhtml2pdf.context.pisaCSSBuilder."""
raise NotImplementedError | This is overridden by xhtml2pdf.context.pisaCSSBuilder. | atPage | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/w3c/css.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/w3c/css.py | Apache-2.0 |
def parseFile(self, srcFile):
"""
Parses CSS file-like objects using the current cssBuilder.
Use for external stylesheets.
"""
with open(srcFile, encoding="utf-8") as file_handler:
file_content = file_handler.read()
return self.parse(file_content) |
Parses CSS file-like objects using the current cssBuilder.
Use for external stylesheets.
| parseFile | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/w3c/cssParser.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/w3c/cssParser.py | Apache-2.0 |
def parse(self, src):
"""
Parses CSS string source using the current cssBuilder.
Use for embedded stylesheets.
"""
self.cssBuilder.beginStylesheet()
try:
# XXX Some simple preprocessing
src = cssSpecial.cleanupCSS(src)
try:
... |
Parses CSS string source using the current cssBuilder.
Use for embedded stylesheets.
| parse | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/w3c/cssParser.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/w3c/cssParser.py | Apache-2.0 |
def parseInline(self, src):
"""
Parses CSS inline source string using the current cssBuilder.
Use to parse a tag's 'style'-like attribute.
"""
self.cssBuilder.beginInline()
try:
try:
src, properties = self._parseDeclarationGroup(src.strip(), br... |
Parses CSS inline source string using the current cssBuilder.
Use to parse a tag's 'style'-like attribute.
| parseInline | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/w3c/cssParser.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/w3c/cssParser.py | Apache-2.0 |
def parseAttributes(self, attributes=None, **kwAttributes):
"""
Parses CSS attribute source strings, and return as an inline stylesheet.
Use to parse a tag's highly CSS-based attributes like 'font'.
See also: parseSingleAttr
"""
attributes = attributes if attributes is n... |
Parses CSS attribute source strings, and return as an inline stylesheet.
Use to parse a tag's highly CSS-based attributes like 'font'.
See also: parseSingleAttr
| parseAttributes | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/w3c/cssParser.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/w3c/cssParser.py | Apache-2.0 |
def parseSingleAttr(self, attr_value):
"""
Parse a single CSS attribute source string, and returns the built CSS expression.
Use to parse a tag's highly CSS-based attributes like 'font'.
See also: parseAttributes
"""
results = self.parseAttributes(temp=attr_value)
... |
Parse a single CSS attribute source string, and returns the built CSS expression.
Use to parse a tag's highly CSS-based attributes like 'font'.
See also: parseAttributes
| parseSingleAttr | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/w3c/cssParser.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/w3c/cssParser.py | Apache-2.0 |
def _parseStylesheet(self, src):
"""
stylesheet
: [ CHARSET_SYM S* STRING S* ';' ]?
[S|CDO|CDC]* [ import [S|CDO|CDC]* ]*
[ [ ruleset | media | page | font_face ] [S|CDO|CDC]* ]*
;
"""
# FIXME: BYTES to STR
if isinstance(src, bytes):
... |
stylesheet
: [ CHARSET_SYM S* STRING S* ';' ]?
[S|CDO|CDC]* [ import [S|CDO|CDC]* ]*
[ [ ruleset | media | page | font_face ] [S|CDO|CDC]* ]*
;
| _parseStylesheet | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/w3c/cssParser.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/w3c/cssParser.py | Apache-2.0 |
def _parseSelectorAttribute(self, src, selector):
"""
attrib
: '[' S* [ namespace_selector ]? IDENT S* [ [ '=' | INCLUDES | DASHMATCH ] S*
[ IDENT | STRING ] S* ]? ']'
;
"""
ctxsrc = src
if not src.startswith("["):
msg = "Selector Attribute... |
attrib
: '[' S* [ namespace_selector ]? IDENT S* [ [ '=' | INCLUDES | DASHMATCH ] S*
[ IDENT | STRING ] S* ]? ']'
;
| _parseSelectorAttribute | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/w3c/cssParser.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/w3c/cssParser.py | Apache-2.0 |
def _parseExpressionTerm(self, src):
"""
term
: unary_operator?
[ NUMBER S* | PERCENTAGE S* | LENGTH S* | EMS S* | EXS S* | ANGLE S* |
TIME S* | FREQ S* | function ]
| STRING S* | IDENT S* | URI S* | RGB S* | UNICODERANGE S* | hexcolor
;
"""
... |
term
: unary_operator?
[ NUMBER S* | PERCENTAGE S* | LENGTH S* | EMS S* | EXS S* | ANGLE S* |
TIME S* | FREQ S* | function ]
| STRING S* | IDENT S* | URI S* | RGB S* | UNICODERANGE S* | hexcolor
;
| _parseExpressionTerm | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/w3c/cssParser.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/w3c/cssParser.py | Apache-2.0 |
def splitBorder(parts):
"""
The order of the elements seems to be of no importance:
http://www.w3.org/TR/CSS21/box.html#border-shorthand-properties
"""
width = style = color = None
if len(parts) > 3:
log.warning("To many elements for border style %r", parts)
for part in parts:
... |
The order of the elements seems to be of no importance:
http://www.w3.org/TR/CSS21/box.html#border-shorthand-properties
| splitBorder | python | xhtml2pdf/xhtml2pdf | xhtml2pdf/w3c/cssSpecial.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/master/xhtml2pdf/w3c/cssSpecial.py | Apache-2.0 |
def softmax(y):
""" simple helper function here that takes unnormalized logprobs """
maxy = np.amax(y)
e = np.exp(y - maxy)
return e / np.sum(e) | simple helper function here that takes unnormalized logprobs | softmax | python | yukezhu/tensorflow-reinforce | rl/pg_actor_critic.py | https://github.com/yukezhu/tensorflow-reinforce/blob/master/rl/pg_actor_critic.py | MIT |
def parse_url(url, warning=True):
"""Parse URLs especially for Google Drive links.
file_id: ID of file on Google Drive.
is_download_link: Flag if it is download link of Google Drive.
"""
# test=url.split('drive')
# print(test)
# if len(test)>1:
# url='https://drive.{}'.format(test[1])
# print(url)
parsed ... | Parse URLs especially for Google Drive links.
file_id: ID of file on Google Drive.
is_download_link: Flag if it is download link of Google Drive.
| parse_url | python | julesontheroad/NSC_BUILDER | py/ztools/Drive/Public.py | https://github.com/julesontheroad/NSC_BUILDER/blob/master/py/ztools/Drive/Public.py | MIT |
def encrypt(self, data, iv=None):
'''Encrypts some data in CBC mode.'''
if iv is None:
iv = self.iv
out = b''
while data:
encb = self.aes.encrypt_block_ecb(sxor(data[:0x10], iv))
out += encb
iv = encb
data = data[0x10:]
return out | Encrypts some data in CBC mode. | encrypt | python | julesontheroad/NSC_BUILDER | py/ztools/lib/aes128.py | https://github.com/julesontheroad/NSC_BUILDER/blob/master/py/ztools/lib/aes128.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.