text stringlengths 18 773k |
|---|
def _listitemify(self, item):
'''Creates an xbmcswift2.ListItem if the provided value for item is a
dict. If item is already a valid xbmcswift2.ListItem, the item is
returned unmodified.
'''
info_type = self.info_type if hasattr(self, 'info_type') else 'video'
# Create L... |
def _add_subtitles(self, subtitles):
'''Adds subtitles to playing video.
:param subtitles: A URL to a remote subtitles file or a local filename
for a subtitles file.
.. warning:: You must start playing a video before calling this method
or it will... |
def set_resolved_url(self, item=None, subtitles=None):
'''Takes a url or a listitem to be played. Used in conjunction with a
playable list item with a path that calls back into your addon.
:param item: A playable list item or url. Pass None to alert XBMC of a
failure to res... |
def add_items(self, items):
'''Adds ListItems to the XBMC interface. Each item in the
provided list should either be instances of xbmcswift2.ListItem,
or regular dictionaries that will be passed to
xbmcswift2.ListItem.from_dict. Returns the list of ListItems.
:param items: An it... |
def end_of_directory(self, succeeded=True, update_listing=False,
cache_to_disc=True):
'''Wrapper for xbmcplugin.endOfDirectory. Records state in
self._end_of_directory.
Typically it is not necessary to call this method directly, as
calling :meth:`~xbmcswift2.Plu... |
def add_sort_method(self, sort_method, label2_mask=None):
'''A wrapper for `xbmcplugin.addSortMethod()
<http://mirrors.xbmc.org/docs/python-docs/xbmcplugin.html#-addSortMethod>`_.
You can use ``dir(xbmcswift2.SortMethod)`` to list all available sort
methods.
:param sort_method: ... |
def finish(self, items=None, sort_methods=None, succeeded=True,
update_listing=False, cache_to_disc=True, view_mode=None):
'''Adds the provided items to the XBMC interface.
:param items: an iterable of items where each item is either a
dictionary with keys/values suitable for... |
def register_cleanup(cleanup):
"""Register a cleanup function to be called at the end of every validation
task. Takes either a callable (including a class with a __call_ method),
or a class with a `cleanup` class method."""
if not callable(cleanup):
# Allow decorating a class with a `cleanup` c... |
def version_range(guid, version, before=None, app_versions=None):
"""Returns all values after (and including) `version` for the app `guid`"""
if app_versions is None:
app_versions = validator.constants.APPROVED_APPLICATIONS
app_key = None
# Support for shorthand instead of full GUIDs.
for ... |
def match(self, path):
'''Attempts to match a url to the given path. If successful, a tuple is
returned. The first item is the matchd function and the second item is
a dictionary containing items to be passed to the function parsed from
the provided path.
If the provided path do... |
def _make_path(self, items):
'''Returns a relative path for the given dictionary of items.
Uses this url rule's url pattern and replaces instances of <var_name>
with the appropriate value from the items dict.
'''
for key, val in items.items():
if not isinstance(val, ... |
def make_path_qs(self, items):
'''Returns a relative path complete with query string for the given
dictionary of items.
Any items with keys matching this rule's url pattern will be inserted
into the path. Any remaining items will be appended as query string
parameters.
... |
def sync(self):
'''Write the dict to disk'''
if self.flag == 'r':
return
filename = self.filename
tempname = filename + '.tmp'
fileobj = open(tempname, 'wb' if self.file_format == 'pickle' else 'w')
try:
self.dump(fileobj)
except Exception:... |
def dump(self, fileobj):
'''Handles the writing of the dict to the file object'''
if self.file_format == 'csv':
csv.writer(fileobj).writerows(self.raw_dict().items())
elif self.file_format == 'json':
json.dump(self.raw_dict(), fileobj, separators=(',', ':'))
elif ... |
def load(self, fileobj):
'''Load the dict from the file object'''
# try formats from most restrictive to least restrictive
for loader in (pickle.load, json.load, csv.reader):
fileobj.seek(0)
try:
return self.initial_update(loader(fileobj))
exce... |
def initial_update(self, mapping):
'''Initially fills the underlying dictionary with keys, values and
timestamps.
'''
for key, val in mapping.items():
_, timestamp = val
if not self.TTL or (datetime.utcnow() -
datetime.utcfromtimestamp(timestamp) <... |
def setup_log(name):
'''Returns a logging instance for the provided name. The returned
object is an instance of logging.Logger. Logged messages will be
printed to stderr when running in the CLI, or forwarded to XBMC's
log when running in XBMC mode.
'''
_log = logging.getLogger(name)
_log.set... |
def filter(self, record):
'''Returns True for all records if running in the CLI, else returns
True.
When running inside XBMC it calls the xbmc.log() method and prevents
the message from being double printed to STDOUT.
'''
# When running in XBMC, any logged statements wi... |
def validate_name(err, value, source):
'Tests a manifest name value for trademarks.'
ff_pattern = re.compile('(mozilla|firefox)', re.I)
err.metadata['name'] = value
if ff_pattern.search(value):
err.warning(
('metadata_helpers', '_test_name', 'trademark'),
'Add-on has p... |
def validate_id(err, value, source):
'Tests a manifest UUID value'
field_name = '<em:id>' if source == 'install.rdf' else 'id'
id_pattern = re.compile(
'('
# UUID format.
'\{[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}\}'
'|'
# "email" format.
'[a-z0-9-\.\+_]*\... |
def validate_version(err, value, source):
'Tests a manifest version number'
field_name = '<em:version>' if source == 'install.rdf' else 'version'
err.metadata['version'] = value
# May not be longer than 32 characters
if len(value) > 32:
err.error(
('metadata_helpers', '_test_... |
def get_device(self, pin=None):
""" Query the status of a specific pin (or all configured pins if pin is ommitted) """
url = self.base_url + '/device'
try:
r = requests.get(url, params={'pin': pin}, timeout=10)
return r.json()
except RequestException as err:
... |
def get_status(self):
""" Query the device status. Returns JSON of the device internal state """
url = self.base_url + '/status'
try:
r = requests.get(url, timeout=10)
return r.json()
except RequestException as err:
raise Client.ClientError(err) |
def put_device(self, pin, state, momentary=None, times=None, pause=None):
""" Actuate a device pin """
url = self.base_url + '/device'
payload = {
"pin": pin,
"state": state
}
if momentary is not None:
payload["momentary"] = momentary
... |
def put_settings(self, sensors=[], actuators=[], auth_token=None,
endpoint=None, blink=None, discovery=None,
dht_sensors=[], ds18b20_sensors=[]):
""" Sync settings to the Konnected device """
url = self.base_url + '/settings'
payload = {
"se... |
def parse_mime_type(mime_type):
"""Parses a mime-type into its component parts.
Carves up a mime-type and returns a tuple of the (type, subtype, params)
where 'params' is a dictionary of all the parameters for the media range.
For example, the media range 'application/xhtml;q=0.5' would get parsed
... |
def parse_media_range(range):
"""Parse a media-range into its component parts.
Carves up a media range and returns a tuple of the (type, subtype,
params) where 'params' is a dictionary of all the parameters for the media
range. For example, the media range 'application/*;q=0.5' would get parsed
in... |
def quality_and_fitness_parsed(mime_type, parsed_ranges):
"""Find the best match for a mime-type amongst parsed media-ranges.
Find the best match for a given mime-type against a list of media_ranges
that have already been parsed by parse_media_range(). Returns a tuple of
the fitness value and the value... |
def quality(mime_type, ranges):
"""Return the quality ('q') of a mime-type against a list of media-ranges.
Returns the quality 'q' of a mime-type when compared against the
media-ranges in ranges. For example:
>>> quality('text/html','text/*;q=0.3, text/html;q=0.7,
text/html;level=1, ... |
def best_match(supported, header):
"""Return mime-type with the highest quality ('q') from list of candidates.
Takes a list of supported mime-types and finds the best match for all the
media-ranges listed in header. The value of header must be a string that
conforms to the format of the HTTP Accept: he... |
def makeXsl(filename):
""" Helper that creates a XSLT stylesheet """
pkg = 'cnxml2html'
package = ''.join(['.' + x for x in __name__.split('.')[:-1]])[1:]
if package != '':
pkg = package + '.' + pkg
path = pkg_resources.resource_filename(pkg, filename)
xml = etree.parse(path)
return etree.XSLT(xml) |
def transform_collxml(collxml_file):
""" Given a collxml file (collection.xml) this returns an HTML version of it
(including "include" anchor links to the modules) """
xml = etree.parse(collxml_file)
xslt = makeXsl('collxml2xhtml.xsl')
xml = xslt(xml)
return xml |
def transform_cnxml(cnxml_file):
""" Given a module cnxml file (index.cnxml) this returns an HTML version of it """
xml = etree.parse(cnxml_file)
xslt = makeXsl('cnxml2xhtml.xsl')
xml = xslt(xml)
return xml |
def transform_collection(collection_dir):
""" Given an unzipped collection generate a giant HTML file representing
the entire collection (including loading and converting individual modules) """
collxml_file = open(os.path.join(collection_dir, 'collection.xml'))
collxml_html = transform_collxml(col... |
def from_dict(cls, d: dict, force_snake_case: bool=True, force_cast: bool=False, restrict: bool=True) -> T:
"""From dict to instance
:param d: Dict
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
... |
def from_optional_dict(cls, d: Optional[dict],
force_snake_case: bool=True,force_cast: bool=False, restrict: bool=True) -> TOption[T]:
"""From dict to optional instance.
:param d: Dict
:param force_snake_case: Keys are transformed to snake case in order to compliant P... |
def from_dicts(cls, ds: List[dict],
force_snake_case: bool=True, force_cast: bool=False, restrict: bool=True) -> TList[T]:
"""From list of dict to list of instance
:param ds: List of dict
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 i... |
def from_optional_dicts(cls, ds: Optional[List[dict]],
force_snake_case: bool=True, force_cast: bool=False, restrict: bool=True) -> TOption[TList[T]]:
"""From list of dict to optional list of instance.
:param ds: List of dict
:param force_snake_case: Keys are transfo... |
def from_dicts_by_key(cls, ds: dict,
force_snake_case: bool=True, force_cast: bool=False, restrict: bool=True) -> TDict[T]:
"""From dict of dict to dict of instance
:param ds: Dict of dict
:param force_snake_case: Keys are transformed to snake case in order to complian... |
def from_optional_dicts_by_key(cls, ds: Optional[dict],
force_snake_case=True, force_cast: bool=False, restrict: bool=True) -> TOption[TDict[T]]:
"""From dict of dict to optional dict of instance.
:param ds: Dict of dict
:param force_snake_case: Keys are trans... |
def from_json(cls, data: str, force_snake_case=True, force_cast: bool=False, restrict: bool=False) -> T:
"""From json string to instance
:param data: Json string
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcib... |
def from_jsonf(cls, fpath: str, encoding: str='utf8',
force_snake_case=True, force_cast: bool=False, restrict: bool=False) -> T:
"""From json file path to instance
:param fpath: Json file path
:param encoding: Json file encoding
:param force_snake_case: Keys are trans... |
def from_json_to_list(cls, data: str,
force_snake_case=True, force_cast: bool=False, restrict: bool=False) -> TList[T]:
"""From json string to list of instance
:param data: Json string
:param force_snake_case: Keys are transformed to snake case in order to compliant PE... |
def from_jsonf_to_list(cls, fpath: str, encoding: str='utf8',
force_snake_case=True, force_cast: bool=False, restrict: bool=False) -> TList[T]:
"""From json file path to list of instance
:param fpath: Json file path
:param encoding: Json file encoding
:param f... |
def from_yaml(cls, data: str, force_snake_case=True, force_cast: bool=False, restrict: bool=True) -> T:
"""From yaml string to instance
:param data: Yaml string
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibl... |
def from_yamlf(cls, fpath: str, encoding: str='utf8',
force_snake_case=True, force_cast: bool=False, restrict: bool=True) -> T:
"""From yaml file path to instance
:param fpath: Yaml file path
:param encoding: Yaml file encoding
:param force_snake_case: Keys are transf... |
def from_yaml_to_list(cls, data: str,
force_snake_case=True, force_cast: bool=False, restrict: bool=True) -> TList[T]:
"""From yaml string to list of instance
:param data: Yaml string
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP... |
def from_yamlf_to_list(cls, fpath: str, encoding: str='utf8',
force_snake_case=True, force_cast: bool=False, restrict: bool=True) -> TList[T]:
"""From yaml file path to list of instance
:param fpath: Yaml file path
:param encoding: Yaml file encoding
:param fo... |
def from_csvf(cls, fpath: str, fieldnames: Optional[Sequence[str]]=None, encoding: str='utf8',
force_snake_case: bool=True, restrict: bool=True) -> TList[T]:
"""From csv file path to list of instance
:param fpath: Csv file path
:param fieldnames: Specify csv header names if no... |
def from_json_url(cls, url: str, force_snake_case=True, force_cast: bool=False, restrict: bool=False) -> T:
"""From url which returns json to instance
:param url: Url which returns json
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param... |
def get(self, index: int) -> TOption[T]:
"""
:param index:
Usage:
>>> TList([1, 2, 3, 4, 5]).get(3)
Option --> 4
>>> TList([1, 2, 3, 4, 5]).get(5)
Option --> None
"""
return TOption(self[index]) if len(self) > index else TOption(N... |
def emap(self, func):
"""
:param func:
:type func: T, int -> U
:rtype: TList[U]
Usage:
>>> TList([10, 20, 30, 40, 50]).emap(lambda x, i: (x+1, i))
[(11, 0), (21, 1), (31, 2), (41, 3), (51, 4)]
"""
return TList([func(x, i) for i, x in enum... |
def head_while(self, func: Callable[[T], bool]) -> 'TList[T]':
"""
:param func:
:type func: T -> bool
Usage:
>>> TList([1, 2, 30, 4, 50]).head_while(lambda x: x < 10)
[1, 2]
"""
r = TList()
for x in self:
if not func(x):
... |
def uniq(self) -> 'TList[T]':
"""
Usage:
>>> TList([1, 2, 3, 2, 1]).uniq()
[1, 2, 3]
"""
rs = TList()
for e in self:
if e not in rs:
rs.append(e)
return rs |
def uniq_by(self, func: Callable[[T], Any]) -> 'TList[T]':
"""
Usage:
>>> TList([1, 2, 3, -2, -1]).uniq_by(lambda x: x**2)
[1, 2, 3]
"""
rs = TList()
for e in self:
if func(e) not in rs.map(func):
rs.append(e)
return rs |
def group_by(self, to_key):
"""
:param to_key:
:type to_key: T -> unicode
:rtype: TDict[TList[T]]
Usage:
>>> TList([1, 2, 3, 4, 5]).group_by(lambda x: x % 2).to_json()
'{"0": [2,4],"1": [1,3,5]}'
"""
ret = TDict()
for v in self:
... |
def key_by(self, to_key: Callable[[T], str]) -> 'TDict[T]':
"""
:param to_key: value -> key
Usage:
>>> TList(['a1', 'b2', 'c3']).key_by(lambda x: x[0]).to_json()
'{"a": "a1","b": "b2","c": "c3"}'
>>> TList([1, 2, 3, 4, 5]).key_by(lambda x: x % 2).to_json()
... |
def order_by(self, func, reverse=False):
"""
:param func:
:type func: T -> any
:param reverse: Sort by descend order if True, else by ascend
:type reverse: bool
:rtype: TList[T]
Usage:
>>> TList([12, 25, 31, 40, 57]).order_by(lambda x: x % 10)
... |
def concat(self, values, first=False):
"""
:param values:
:type values: TList[T]
:param first:
:type first: bool
:rtype: TList[T]
Usage:
>>> TList([1, 2]).concat(TList([3, 4]))
[1, 2, 3, 4]
>>> TList([1, 2]).concat(TList([3, 4... |
def find(self, func: Callable[[T], bool]) -> TOption[T]:
"""
Usage:
>>> TList([1, 2, 3, 4, 5]).find(lambda x: x > 3)
Option --> 4
>>> TList([1, 2, 3, 4, 5]).find(lambda x: x > 6)
Option --> None
"""
for x in self:
if func(x):
... |
def get(self, key: K) -> TOption[T]:
"""
:param key:
Usage:
>>> TDict(k1=1, k2=2, k3=3).get("k2")
Option --> 2
>>> TDict(k1=1, k2=2, k3=3).get("unknown")
Option --> None
"""
return TOption(self[key]) if key in self else TOption(No... |
def map(self, func):
"""
:param func:
:type func: (K, T) -> U
:rtype: TList[U]
Usage:
>>> sorted(TDict(k1=1, k2=2, k3=3).map(lambda k, v: v*2))
[2, 4, 6]
"""
return TList([func(k, v) for k, v in self.items()]) |
def map_values(self, func):
"""
:param func:
:type func: T -> U
:rtype: TDict[U]
Usage:
>>> TDict(k1=1, k2=2, k3=3).map_values(lambda x: x*2) == {
... "k1": 2,
... "k2": 4,
... "k3": 6
... }
Tru... |
def map_values2(self, func):
"""
:param func:
:type func: (K, T) -> U
:rtype: TDict[U]
Usage:
>>> TDict(k1=1, k2=2, k3=3).map_values2(lambda k, v: f'{k} -> {v*2}') == {
... "k1": "k1 -> 2",
... "k2": "k2 -> 4",
... "k3... |
def filter(self, func):
"""
:param func:
:type func: (K, T) -> bool
:rtype: TList[T]
Usage:
>>> TDict(k1=1, k2=2, k3=3).filter(lambda k, v: v < 2)
[1]
"""
return TList([v for k, v in self.items() if func(k, v)]) |
def reject(self, func):
"""
:param func:
:type func: (K, T) -> bool
:rtype: TList[T]
Usage:
>>> TDict(k1=1, k2=2, k3=3).reject(lambda k, v: v < 3)
[3]
"""
return TList([v for k, v in self.items() if not func(k, v)]) |
def find(self, func: Callable[[K, T], bool]) -> TOption[T]:
"""
Usage:
>>> TDict(k1=1, k2=2, k3=3).find(lambda k, v: v == 2)
Option --> 2
>>> TDict(k1=1, k2=2, k3=3).find(lambda k, v: v == 4)
Option --> None
"""
for k, v in self.items():
... |
def all(self, func):
"""
:param func:
:type func: (K, T) -> bool
:rtype: bool
Usage:
>>> TDict(k1=1, k2=2, k3=3).all(lambda k, v: v > 0)
True
>>> TDict(k1=1, k2=2, k3=3).all(lambda k, v: v > 1)
False
"""
return all... |
def any(self, func):
"""
:param func:
:type func: (K, T) -> bool
:rtype: bool
Usage:
>>> TDict(k1=1, k2=2, k3=3).any(lambda k, v: v > 2)
True
>>> TDict(k1=1, k2=2, k3=3).any(lambda k, v: v > 3)
False
"""
return any... |
def pick_by(self, func: Callable[[K, T], bool]) -> 'TDict[T]':
"""
Usage:
>>> TDict(k1=1, k2=2, k3=3).pick_by(lambda k, v: v > 2)
{'k3': 3}
"""
return TDict({k: v for k, v in self.items() if func(k, v)}) |
def storeSectionState(self, level):
"""
Takes a header tagname (e.g. 'h1') and adjusts the
stack that remembers the headers seen.
"""
# self.document.append("<!-- storeSectionState(): " + str(len(self.header_stack)) + " open section tags. " + str(self.header_stack) + "-->\n")
... |
def endSections(self, level=u'0'):
"""Closes all sections of level >= sectnum. Defaults to closing all open sections"""
iSectionsClosed = self.storeSectionState(level)
self.document.append("</section>\n" * iSectionsClosed) |
def to_dict(self, ignore_none: bool=True, force_value: bool=True, ignore_empty: bool=False) -> dict:
"""From instance to dict
:param ignore_none: Properties which is None are excluded if True
:param force_value: Transform to value using to_value (default: str()) of ValueTransformer which inheri... |
def to_dicts(self, ignore_none: bool=True, force_value: bool=True, ignore_empty: bool=False) -> List[dict]:
"""From instance to dict
:param ignore_none: Properties which is None are excluded if True
:param force_value: Transform to value using to_value (default: str()) of ValueTransformer which... |
def to_json(self, indent: int=None, ignore_none: bool=True, ignore_empty: bool=False) -> str:
"""From instance to json string
:param indent: Number of indentation
:param ignore_none: Properties which is None are excluded if True
:param ignore_empty: Properties which is empty are exclude... |
def to_jsonf(self, fpath: str, encoding: str='utf8', indent: int=None, ignore_none: bool=True, ignore_empty: bool=False) -> str:
"""From instance to json file
:param fpath: Json file path
:param encoding: Json file encoding
:param indent: Number of indentation
:param ignore_none... |
def to_pretty_json(self, ignore_none: bool=True, ignore_empty: bool=False) -> str:
"""From instance to pretty json string
:param ignore_none: Properties which is None are excluded if True
:param ignore_empty: Properties which is empty are excluded if True
:return: Json string
U... |
def to_yaml(self, ignore_none: bool=True, ignore_empty: bool=False) -> str:
"""From instance to yaml string
:param ignore_none: Properties which is None are excluded if True
:param ignore_empty: Properties which is empty are excluded if True
:return: Yaml string
Usage:
... |
def to_yamlf(self, fpath: str, encoding: str='utf8', ignore_none: bool=True, ignore_empty: bool=False) -> str:
"""From instance to yaml file
:param ignore_none: Properties which is None are excluded if True
:param fpath: Yaml file path
:param encoding: Yaml file encoding
:return... |
def to_csv(self, fieldnames: Sequence[str], with_header: bool=False, crlf: bool=False, tsv: bool=False) -> str:
"""From sequence of text to csv string
:param fieldnames: Order of columns by property name
:param with_header: Add headers at the first line if True
:param crlf: Add CRLF lin... |
def to_csvf(self, fpath: str, fieldnames: Sequence[str], encoding: str='utf8',
with_header: bool=False, crlf: bool=False, tsv: bool=False) -> str:
"""From instance to yaml file
:param fpath: Csv file path
:param fieldnames: Order of columns by property name
:param encodi... |
def to_table(self, fieldnames: Sequence[str]) -> str:
"""From sequence of text to csv string
:param fieldnames: Order of columns by property name
:return: Table string
Usage:
>>> from owlmixin.samples import Human
>>> humans = Human.from_dicts([
...... |
def _pre_tidy(html):
""" This method transforms a few things before tidy runs. When we get rid
of tidy, this can go away. """
tree = etree.fromstring(html, etree.HTMLParser())
for el in tree.xpath('//u'):
el.tag = 'em'
c = el.attrib.get('class', '').split()
if 'underline' not... |
def _post_tidy(html):
""" This method transforms post tidy. Will go away when tidy goes away. """
tree = etree.fromstring(html)
ems = tree.xpath(
"//xh:em[@class='underline']|//xh:em[contains(@class, ' underline ')]",
namespaces={'xh': 'http://www.w3.org/1999/xhtml'})
for el in ems:
... |
def _tidy2xhtml5(html):
"""Tidy up a html4/5 soup to a parsable valid XHTML5.
Requires tidy-html5 from https://github.com/w3c/tidy-html5
Installation: http://goo.gl/FG27n
"""
html = _io2string(html)
html = _pre_tidy(html) # Pre-process
xhtml5, errors =\
tidy_document(html,
... |
def _make_xsl(filename):
"""Helper that creates a XSLT stylesheet """
path = pkg_resources.resource_filename('rhaptos.cnxmlutils.xsl', filename)
xml = etree.parse(path)
return etree.XSLT(xml) |
def _transform(xsl_filename, xml, **kwargs):
"""Transforms the xml using the specifiec xsl file."""
xslt = _make_xsl(xsl_filename)
xml = xslt(xml, **kwargs)
return xml |
def _unescape_math(xml):
"""Unescapes Math from Mathjax to MathML."""
xpath_math_script = etree.XPath(
'//x:script[@type="math/mml"]',
namespaces={'x': 'http://www.w3.org/1999/xhtml'})
math_script_list = xpath_math_script(xml)
for mathscript in math_script_list:
math = ma... |
def cnxml_to_html(cnxml_source):
"""Transform the CNXML source to HTML"""
source = _string2io(cnxml_source)
xml = etree.parse(source)
# Run the CNXML to HTML transform
xml = _transform('cnxml-to-html5.xsl', xml,
version='"{}"'.format(version))
xml = XHTML_MODULE_BODY_XPATH(x... |
def aloha_to_etree(html_source):
""" Converts HTML5 from Aloha editor output to a lxml etree. """
xml = _tidy2xhtml5(html_source)
for i, transform in enumerate(ALOHA2HTML_TRANSFORM_PIPELINE):
xml = transform(xml)
return xml |
def aloha_to_html(html_source):
"""Converts HTML5 from Aloha to a more structured HTML5"""
xml = aloha_to_etree(html_source)
return etree.tostring(xml, pretty_print=True) |
def html_to_cnxml(html_source, cnxml_source):
"""Transform the HTML to CNXML. We need the original CNXML content in
order to preserve the metadata in the CNXML document.
"""
source = _string2io(html_source)
xml = etree.parse(source)
cnxml = etree.parse(_string2io(cnxml_source))
# Run the HTM... |
def html_to_valid_cnxml(html_source):
"""Transform the HTML to valid CNXML (used for OERPUB).
No original CNXML is needed. If HTML is from Aloha please use
aloha_to_html before using this method
"""
source = _string2io(html_source)
xml = etree.parse(source)
return etree_to_valid_cnxml(xml, ... |
def get_or(self, default: T) -> T:
"""
Usage:
>>> TOption(3).get_or(999)
3
>>> TOption(0).get_or(999)
0
>>> TOption(None).get_or(999)
999
"""
return default if self.value is None else self.value |
def map(self, func: Callable[[T], U]) -> 'TOption[T]':
"""
Usage:
>>> TOption(3).map(lambda x: x+1).get()
4
>>> TOption(None).map(lambda x: x+1).get_or(999)
999
"""
return self if self.is_none() else TOption(func(self.value)) |
def flat_map(self, func: Callable[[T], 'TOption[T]']) -> 'TOption[T]':
"""
Usage:
>>> TOption(3).flat_map(lambda x: TOption(x+1)).get()
4
>>> TOption(3).flat_map(lambda x: TOption(None)).get_or(999)
999
>>> TOption(None).flat_map(lambda x: TOp... |
def replace(text):
"""Replace both the hex and decimal versions of symbols in an XML string"""
for hex, value in UNICODE_DICTIONARY.items():
num = int(hex[3:-1], 16)
#uni = unichr(num)
decimal = '&#' + str(num) + ';'
for key in [ hex, decimal ]: #uni
text = text.replace(key, value)
return te... |
def replace_keys(d, keymap, force_snake_case):
"""
:param dict d:
:param Dict[unicode, unicode] keymap:
:param bool force_snake_case:
:rtype: Dict[unicode, unicode]
"""
return {
to_snake(keymap.get(k, k)) if force_snake_case else keymap.get(k, k):
v for k, v in d.items()
... |
def load_jsonf(fpath, encoding):
"""
:param unicode fpath:
:param unicode encoding:
:rtype: dict | list
"""
with codecs.open(fpath, encoding=encoding) as f:
return json.load(f) |
def load_yamlf(fpath, encoding):
"""
:param unicode fpath:
:param unicode encoding:
:rtype: dict | list
"""
with codecs.open(fpath, encoding=encoding) as f:
return yaml.safe_load(f) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.