index
int64 0
731k
| package
stringlengths 2
98
⌀ | name
stringlengths 1
76
| docstring
stringlengths 0
281k
⌀ | code
stringlengths 4
1.07M
⌀ | signature
stringlengths 2
42.8k
⌀ |
---|---|---|---|---|---|
46,597 |
easul.visual.visual
|
Visual
|
Wrap visual elements and optionally an algorithm related metadata.
Also includes rendering of the HTML and automatic loading/calculation of metadata.
|
class Visual:
"""
Wrap visual elements and optionally an algorithm related metadata.
Also includes rendering of the HTML and automatic loading/calculation of metadata.
"""
elements = field()
title = field(default=None)
metadata = field(default=None, init=False)
metadata_filename = field(default=None)
algorithm = field(default=None)
metadata_dataset = field(default=None)
def describe(self):
return {
"title": self.title,
"type": self.__class__.__name__
}
def __attrs_post_init__(self):
self.metadata = self._create_metadata()
def _create_metadata(self):
if self.metadata_filename:
filename = self.metadata_filename
metadata = FileMetadata(filename=filename, algorithm=self.algorithm, visual=self)
try:
metadata.load()
except FileNotFoundError:
LOG.warning("Unable to load metadata - not calculating")
else:
metadata = Metadata(algorithm=self.algorithm, visual = self)
return metadata
def calculate_metadata(self):
if self.algorithm:
if not self.metadata_dataset:
LOG.warning("Could not calculate algorithm metadata as no 'metadata_dataset' was provided to visual")
self.metadata.calculate(util.string_to_function(self.metadata_dataset))
def generate_context(self, input_data, **kwargs):
result = {}
for element in self.flattened_elements:
if not hasattr(element,"generate_context"):
continue
ctx = element.generate_context(algorithm=self.algorithm, input_data=input_data, visual=self, **kwargs)
if not ctx:
continue
result.update(ctx)
return result
def render(self, driver=None, step=None, steps=None, result=None, context=None, renderer=None, **kwargs):
if not renderer:
renderer = PlainRenderer()
if step and hasattr(step,"run_logic"):
try:
cl_step = driver._client.get_step(step.name, journey_id=driver.journey_id)
except ValueError:
raise StepDataError(driver.journey, step.name)
# if not cl_step:
# raise SystemError(f"Outcome for reference '{driver.journey['reference']}' and step '{step.name}' does not exist")
result = None
context = None
if cl_step:
outcome = cl_step.get("outcome",{})
if outcome:
result = outcome.get("result")
context = outcome.get("context")
if self.metadata.algorithm:
algorithm = self.metadata.algorithm
else:
algorithm = step.algorithm if hasattr(step,"algorithm") else None
if "algorithm" not in kwargs:
kwargs["algorithm"] = algorithm
return renderer.create(visual=self, driver=driver, steps=steps, step=step, result=result, context=context,
**kwargs)
@property
def flattened_elements(self):
return Visual._get_nested_elements(self)
@classmethod
def _get_nested_elements(cls, element):
if hasattr(element, "elements") is False:
return [element]
elements = []
for sub_element in element.elements:
elements.extend(cls._get_nested_elements(sub_element))
return elements
|
(*, elements, title=None, metadata_filename=None, algorithm=None, metadata_dataset=None) -> None
|
46,598 |
easul.visual.visual
|
__attrs_post_init__
| null |
def __attrs_post_init__(self):
self.metadata = self._create_metadata()
|
(self)
|
46,599 |
easul.visual.visual
|
__eq__
|
Method generated by attrs for class Visual.
|
from collections import UserDict
from attrs import define, field
import logging
from easul.error import StepDataError
from easul.step import ActionEvent
from easul.visual.render import PlainRenderer
from easul import util
LOG = logging.getLogger(__name__)
class Metadata(UserDict):
def __init__(self, algorithm=None, visual=None):
super().__init__({})
self.visual = visual
self.algorithm = algorithm
self.init = False
def calculate(self, dataset):
if not self.visual:
raise AttributeError("Cannot calculate metadata as instance has not been called with Visual object")
metadata = {}
for element in self.visual.elements:
element_metadata = element.generate_metadata(algorithm=self.algorithm, dataset=dataset)
if element_metadata:
metadata.update(element_metadata)
metadata["algorithm_digest"] = self.algorithm.unique_digest
self.init = True
self.data.update(metadata)
|
(self, other)
|
46,602 |
easul.visual.visual
|
__ne__
|
Method generated by attrs for class Visual.
| null |
(self, other)
|
46,605 |
easul.visual.visual
|
_create_metadata
| null |
def _create_metadata(self):
if self.metadata_filename:
filename = self.metadata_filename
metadata = FileMetadata(filename=filename, algorithm=self.algorithm, visual=self)
try:
metadata.load()
except FileNotFoundError:
LOG.warning("Unable to load metadata - not calculating")
else:
metadata = Metadata(algorithm=self.algorithm, visual = self)
return metadata
|
(self)
|
46,606 |
easul.visual.visual
|
calculate_metadata
| null |
def calculate_metadata(self):
if self.algorithm:
if not self.metadata_dataset:
LOG.warning("Could not calculate algorithm metadata as no 'metadata_dataset' was provided to visual")
self.metadata.calculate(util.string_to_function(self.metadata_dataset))
|
(self)
|
46,607 |
easul.visual.visual
|
describe
| null |
def describe(self):
return {
"title": self.title,
"type": self.__class__.__name__
}
|
(self)
|
46,608 |
easul.visual.visual
|
generate_context
| null |
def generate_context(self, input_data, **kwargs):
result = {}
for element in self.flattened_elements:
if not hasattr(element,"generate_context"):
continue
ctx = element.generate_context(algorithm=self.algorithm, input_data=input_data, visual=self, **kwargs)
if not ctx:
continue
result.update(ctx)
return result
|
(self, input_data, **kwargs)
|
46,609 |
easul.visual.visual
|
render
| null |
def render(self, driver=None, step=None, steps=None, result=None, context=None, renderer=None, **kwargs):
if not renderer:
renderer = PlainRenderer()
if step and hasattr(step,"run_logic"):
try:
cl_step = driver._client.get_step(step.name, journey_id=driver.journey_id)
except ValueError:
raise StepDataError(driver.journey, step.name)
# if not cl_step:
# raise SystemError(f"Outcome for reference '{driver.journey['reference']}' and step '{step.name}' does not exist")
result = None
context = None
if cl_step:
outcome = cl_step.get("outcome",{})
if outcome:
result = outcome.get("result")
context = outcome.get("context")
if self.metadata.algorithm:
algorithm = self.metadata.algorithm
else:
algorithm = step.algorithm if hasattr(step,"algorithm") else None
if "algorithm" not in kwargs:
kwargs["algorithm"] = algorithm
return renderer.create(visual=self, driver=driver, steps=steps, step=step, result=result, context=context,
**kwargs)
|
(self, driver=None, step=None, steps=None, result=None, context=None, renderer=None, **kwargs)
|
46,610 |
easul.error
|
VisualDataMissing
|
Error thrown when there are problems with data used to generate visuals.
The scope determine which message is used.
|
class VisualDataMissing(Exception):
"""
Error thrown when there are problems with data used to generate visuals.
The scope determine which message is used.
"""
def __init__(self, element, scope):
if scope == "result":
msg = NO_VISUAL_RESULT_MESSAGE
elif scope == "metadata":
msg = NO_VISUAL_METADATA_MESSAGE
else:
msg = NO_VISUAL_CONTEXT_MESSAGE
self.element = element
super().__init__(msg)
|
(element, scope)
|
46,611 |
easul.error
|
__init__
| null |
def __init__(self, element, scope):
if scope == "result":
msg = NO_VISUAL_RESULT_MESSAGE
elif scope == "metadata":
msg = NO_VISUAL_METADATA_MESSAGE
else:
msg = NO_VISUAL_CONTEXT_MESSAGE
self.element = element
super().__init__(msg)
|
(self, element, scope)
|
46,612 |
easul.step
|
VisualStep
|
Visual focussed step.
|
class VisualStep(Step):
"""
Visual focussed step.
"""
exclude_from_chart = True
requires_journey = field(default=True)
|
(*, title, visual=None, exclude_from_chart=False, name=None, actions=NOTHING, requires_journey=True) -> None
|
46,613 |
easul.step
|
__eq__
|
Method generated by attrs for class VisualStep.
|
from attrs import define, field
import logging
from easul.decision import BinaryDecision
LOG = logging.getLogger(__name__)
from easul.error import StepDataNotAvailable, ConversionError, InvalidStepData, VisualDataMissing, ValidationError
from enum import Enum, auto
from easul.outcome import Outcome, EndOutcome, PauseOutcome, InvalidDataOutcome, MissingDataOutcome
from abc import abstractmethod
NO_VISUAL_IN_STEP_MESSAGE = "Sorry no visual for this step"
@define(kw_only=True)
class Step:
"""
Base Step class. Steps are the driving force of plans, they bring the different components together.
The key things are 'visual' components which provide graphical views associated with steps and 'actions' which
define action classes that occur during the lifecycle of a step run.
"""
title = field()
visual = field(default=None)
exclude_from_chart = field(default=False)
name = field(default=None)
actions = field(factory=list)
def layout_kwargs(self, driver, steps, **kwargs):
return {"steps":steps, "driver":driver, "step":self, **kwargs}
def render_visual(self, driver: "easul.driver.Driver", steps, result=None, context=None, renderer=None, **kwargs):
"""
Render visual to HTML utilising the data in the broker (if not supplied) and the supplied renderer
Args:
driver:
steps:
result:
context:
renderer:
**kwargs:
Returns:
"""
if not self.visual:
return NO_VISUAL_IN_STEP_MESSAGE
if not result and not context:
b_data = driver.get_broker_data("outcome:" + self.name)
if b_data:
result = b_data.get("result")
context = b_data.get("context")
try:
return self.visual.render(driver=driver, steps=steps, step=self, result=result, context=context, renderer=renderer)
except VisualDataMissing as ex:
return str(ex)
@property
def possible_links(self):
return {}
@property
def data_sources(self):
return []
def _trigger_actions(self, trigger_type, event):
for action in self.actions:
getattr(action, trigger_type)(event)
def _generate_visual_context(self, data):
return self.visual.generate_context(data) if self.visual else None
def __repr__(self):
return self.name
def describe(self):
"""
Describe step as Python data structures (lists and dicts)
Returns:
"""
return {
"name": self.name,
"title": self.title,
"actions": [a.describe() for a in self.actions],
"visual":self.visual.describe() if self.visual else "N/A"
}
|
(self, other)
|
46,616 |
easul.step
|
__ne__
|
Method generated by attrs for class VisualStep.
| null |
(self, other)
|
46,624 |
dominate.tags
|
a
|
If the a element has an href attribute, then it represents a hyperlink (a
hypertext anchor).
If the a element has no href attribute, then the element represents a
placeholder for where a link might otherwise have been placed, if it had been
relevant.
|
class a(html_tag):
'''
If the a element has an href attribute, then it represents a hyperlink (a
hypertext anchor).
If the a element has no href attribute, then the element represents a
placeholder for where a link might otherwise have been placed, if it had been
relevant.
'''
pass
|
(*args, **kwargs)
|
46,625 |
dominate.dom_tag
|
__bool__
|
Hack for "if x" and __len__
|
def __bool__(self):
'''
Hack for "if x" and __len__
'''
return True
|
(self)
|
46,626 |
dominate.dom_tag
|
__call__
|
tag instance is being used as a decorator.
wrap func to make a copy of this tag
|
def __call__(self, func):
'''
tag instance is being used as a decorator.
wrap func to make a copy of this tag
'''
# remove decorator from its context so it doesn't
# get added in where it was defined
if self._ctx:
self._ctx.used.add(self)
@wraps(func)
def f(*args, **kwargs):
tag = copy.deepcopy(self)
tag._add_to_ctx()
with tag:
return func(*args, **kwargs) or tag
return f
|
(self, func)
|
46,627 |
dominate.dom_tag
|
__contains__
|
Checks recursively if item is in children tree.
Accepts both a string and a class.
|
def __contains__(self, item):
'''
Checks recursively if item is in children tree.
Accepts both a string and a class.
'''
return bool(self.get(item))
|
(self, item)
|
46,628 |
dominate.dom_tag
|
delete_attribute
| null |
def delete_attribute(self, key):
if isinstance(key, int):
del self.children[key:key+1]
else:
del self.attributes[key]
|
(self, key)
|
46,629 |
dominate.dom_tag
|
__enter__
| null |
def __enter__(self):
stack = dom_tag._with_contexts[_get_thread_context()]
stack.append(dom_tag.frame(self, [], set()))
return self
|
(self)
|
46,630 |
dominate.dom_tag
|
__exit__
| null |
def __exit__(self, type, value, traceback):
thread_id = _get_thread_context()
stack = dom_tag._with_contexts[thread_id]
frame = stack.pop()
for item in frame.items:
if item in frame.used: continue
self.add(item)
if not stack:
del dom_tag._with_contexts[thread_id]
|
(self, type, value, traceback)
|
46,631 |
dominate.dom_tag
|
__getitem__
|
Returns the stored value of the specified attribute or child
(if it exists).
|
def __getitem__(self, key):
'''
Returns the stored value of the specified attribute or child
(if it exists).
'''
if isinstance(key, int):
# Children are accessed using integers
try:
return object.__getattribute__(self, 'children')[key]
except IndexError:
raise IndexError('Child with index "%s" does not exist.' % key)
elif isinstance(key, basestring):
# Attributes are accessed using strings
try:
return object.__getattribute__(self, 'attributes')[key]
except KeyError:
raise AttributeError('Attribute "%s" does not exist.' % key)
else:
raise TypeError('Only integer and string types are valid for accessing '
'child tags and attributes, respectively.')
|
(self, key)
|
46,633 |
dominate.dom_tag
|
__iadd__
|
Reflexive binary addition simply adds tag as a child.
|
def __iadd__(self, obj):
'''
Reflexive binary addition simply adds tag as a child.
'''
self.add(obj)
return self
|
(self, obj)
|
46,634 |
dominate.tags
|
__init__
|
Creates a new html tag instance.
|
def __init__(self, *args, **kwargs):
'''
Creates a new html tag instance.
'''
super(html_tag, self).__init__(*args, **kwargs)
|
(self, *args, **kwargs)
|
46,635 |
dominate.dom_tag
|
__iter__
|
Iterates over child elements.
|
def __iter__(self):
'''
Iterates over child elements.
'''
return self.children.__iter__()
|
(self)
|
46,636 |
dominate.dom_tag
|
__len__
|
Number of child elements.
|
def __len__(self):
'''
Number of child elements.
'''
return len(self.children)
|
(self)
|
46,637 |
dominate.dom_tag
|
__new__
|
Check if bare tag is being used a a decorator
(called with a single function arg).
decorate the function and return
|
def __new__(_cls, *args, **kwargs):
'''
Check if bare tag is being used a a decorator
(called with a single function arg).
decorate the function and return
'''
if len(args) == 1 and isinstance(args[0], Callable) \
and not isinstance(args[0], dom_tag) and not kwargs:
wrapped = args[0]
@wraps(wrapped)
def f(*args, **kwargs):
with _cls() as _tag:
return wrapped(*args, **kwargs) or _tag
return f
return object.__new__(_cls)
|
(_cls, *args, **kwargs)
|
46,639 |
dominate.dom_tag
|
__repr__
| null |
def __repr__(self):
name = '%s.%s' % (self.__module__, type(self).__name__)
attributes_len = len(self.attributes)
attributes = '%s attribute' % attributes_len
if attributes_len != 1: attributes += 's'
children_len = len(self.children)
children = '%s child' % children_len
if children_len != 1: children += 'ren'
return '<%s at %x: %s, %s>' % (name, id(self), attributes, children)
|
(self)
|
46,640 |
dominate.dom_tag
|
set_attribute
|
Add or update the value of an attribute.
|
def set_attribute(self, key, value):
'''
Add or update the value of an attribute.
'''
if isinstance(key, int):
self.children[key] = value
elif isinstance(key, basestring):
self.attributes[key] = value
else:
raise TypeError('Only integer and string types are valid for assigning '
'child tags and attributes, respectively.')
|
(self, key, value)
|
46,641 |
dominate.dom_tag
|
__unicode__
| null |
def __unicode__(self):
return self.render()
|
(self)
|
46,643 |
dominate.dom_tag
|
_add_to_ctx
| null |
def _add_to_ctx(self):
stack = dom_tag._with_contexts.get(_get_thread_context())
if stack:
self._ctx = stack[-1]
stack[-1].items.append(self)
|
(self)
|
46,644 |
dominate.dom_tag
|
_render
| null |
def _render(self, sb, indent_level, indent_str, pretty, xhtml):
pretty = pretty and self.is_pretty
name = getattr(self, 'tagname', type(self).__name__)
# Workaround for python keywords and standard classes/methods
# (del, object, input)
if name[-1] == '_':
name = name[:-1]
# open tag
sb.append('<')
sb.append(name)
for attribute, value in sorted(self.attributes.items()):
if value in (False, None):
continue
val = unicode(value) if isinstance(value, util.text) and not value.escape else util.escape(unicode(value), True)
sb.append(' %s="%s"' % (attribute, val))
sb.append(' />' if self.is_single and xhtml else '>')
if self.is_single:
return sb
inline = self._render_children(sb, indent_level + 1, indent_str, pretty, xhtml)
if pretty and not inline:
sb.append('\n')
sb.append(indent_str * indent_level)
# close tag
sb.append('</')
sb.append(name)
sb.append('>')
return sb
|
(self, sb, indent_level, indent_str, pretty, xhtml)
|
46,645 |
dominate.dom_tag
|
_render_children
| null |
def _render_children(self, sb, indent_level, indent_str, pretty, xhtml):
inline = True
for child in self.children:
if isinstance(child, dom_tag):
if pretty and not child.is_inline:
inline = False
sb.append('\n')
sb.append(indent_str * indent_level)
child._render(sb, indent_level, indent_str, pretty, xhtml)
else:
sb.append(unicode(child))
return inline
|
(self, sb, indent_level, indent_str, pretty, xhtml)
|
46,646 |
dominate.dom_tag
|
add
|
Add new child tags.
|
def add(self, *args):
'''
Add new child tags.
'''
for obj in args:
if isinstance(obj, numbers.Number):
# Convert to string so we fall into next if block
obj = str(obj)
if isinstance(obj, basestring):
obj = util.escape(obj)
self.children.append(obj)
elif isinstance(obj, dom_tag):
stack = dom_tag._with_contexts.get(_get_thread_context(), [])
for s in stack:
s.used.add(obj)
self.children.append(obj)
obj.parent = self
elif isinstance(obj, dict):
for attr, value in obj.items():
self.set_attribute(*dom_tag.clean_pair(attr, value))
elif hasattr(obj, '__iter__'):
for subobj in obj:
self.add(subobj)
else: # wtf is it?
raise ValueError('%r not a tag or string.' % obj)
if len(args) == 1:
return args[0]
return args
|
(self, *args)
|
46,647 |
dominate.dom_tag
|
add_raw_string
| null |
def add_raw_string(self, s):
self.children.append(s)
|
(self, s)
|
46,648 |
dominate.dom1core
|
appendChild
|
DOM API: Add an item to the end of the children list.
|
def appendChild(self, obj):
'''
DOM API: Add an item to the end of the children list.
'''
self.add(obj)
return self
|
(self, obj)
|
46,649 |
dominate.dom_tag
|
clean_attribute
|
Normalize attribute names for shorthand and work arounds for limitations
in Python's syntax
|
@staticmethod
def clean_attribute(attribute):
'''
Normalize attribute names for shorthand and work arounds for limitations
in Python's syntax
'''
# Shorthand
attribute = {
'cls': 'class',
'className': 'class',
'class_name': 'class',
'klass': 'class',
'fr': 'for',
'html_for': 'for',
'htmlFor': 'for',
'phor': 'for',
}.get(attribute, attribute)
# Workaround for Python's reserved words
if attribute[0] == '_':
attribute = attribute[1:]
# Workaround for dash
special_prefix = any([attribute.startswith(x) for x in ('data_', 'aria_')])
if attribute in set(['http_equiv']) or special_prefix:
attribute = attribute.replace('_', '-').lower()
# Workaround for colon
if attribute.split('_')[0] in ('xlink', 'xml', 'xmlns'):
attribute = attribute.replace('_', ':', 1).lower()
return attribute
|
(attribute)
|
46,650 |
dominate.dom_tag
|
clear
| null |
def clear(self):
for i in self.children:
if isinstance(i, dom_tag) and i.parent is self:
i.parent = None
self.children = []
|
(self)
|
46,652 |
dominate.dom_tag
|
get
|
Recursively searches children for tags of a certain
type with matching attributes.
|
def get(self, tag=None, **kwargs):
'''
Recursively searches children for tags of a certain
type with matching attributes.
'''
# Stupid workaround since we can not use dom_tag in the method declaration
if tag is None: tag = dom_tag
attrs = [(dom_tag.clean_attribute(attr), value)
for attr, value in kwargs.items()]
results = []
for child in self.children:
if (isinstance(tag, basestring) and type(child).__name__ == tag) or \
(not isinstance(tag, basestring) and isinstance(child, tag)):
if all(child.attributes.get(attribute) == value
for attribute, value in attrs):
# If the child is of correct type and has all attributes and values
# in kwargs add as a result
results.append(child)
if isinstance(child, dom_tag):
# If the child is a dom_tag extend the search down through its children
results.extend(child.get(tag, **kwargs))
return results
|
(self, tag=None, **kwargs)
|
46,653 |
dominate.dom1core
|
getElementById
|
DOM API: Returns single element with matching id value.
|
def getElementById(self, id):
'''
DOM API: Returns single element with matching id value.
'''
results = self.get(id=id)
if len(results) > 1:
raise ValueError('Multiple tags with id "%s".' % id)
elif results:
return results[0]
return None
|
(self, id)
|
46,654 |
dominate.dom1core
|
getElementsByTagName
|
DOM API: Returns all tags that match name.
|
def getElementsByTagName(self, name):
'''
DOM API: Returns all tags that match name.
'''
if isinstance(name, basestring):
return self.get(name.lower())
return None
|
(self, name)
|
46,655 |
dominate.dom_tag
|
remove
| null |
def remove(self, obj):
self.children.remove(obj)
|
(self, obj)
|
46,656 |
dominate.dom_tag
|
render
| null |
def render(self, indent=' ', pretty=True, xhtml=False):
data = self._render([], 0, indent, pretty, xhtml)
return u''.join(data)
|
(self, indent=' ', pretty=True, xhtml=False)
|
46,658 |
dominate.tags
|
abbr
|
The abbr element represents an abbreviation or acronym, optionally with its
expansion. The title attribute may be used to provide an expansion of the
abbreviation. The attribute, if specified, must contain an expansion of the
abbreviation, and nothing else.
|
class abbr(html_tag):
'''
The abbr element represents an abbreviation or acronym, optionally with its
expansion. The title attribute may be used to provide an expansion of the
abbreviation. The attribute, if specified, must contain an expansion of the
abbreviation, and nothing else.
'''
pass
|
(*args, **kwargs)
|
46,694 |
dominate.tags
|
address
|
The address element represents the contact information for its nearest
article or body element ancestor. If that is the body element, then the
contact information applies to the document as a whole.
|
class address(html_tag):
'''
The address element represents the contact information for its nearest
article or body element ancestor. If that is the body element, then the
contact information applies to the document as a whole.
'''
pass
|
(*args, **kwargs)
|
46,729 |
dominate.tags
|
area
|
The area element represents either a hyperlink with some text and a
corresponding area on an image map, or a dead area on an image map.
|
class area(html_tag):
'''
The area element represents either a hyperlink with some text and a
corresponding area on an image map, or a dead area on an image map.
'''
is_single = True
|
(*args, **kwargs)
|
46,763 |
dominate.tags
|
article
|
The article element represents a self-contained composition in a document,
page, application, or site and that is, in principle, independently
distributable or reusable, e.g. in syndication. This could be a forum post, a
magazine or newspaper article, a blog entry, a user-submitted comment, an
interactive widget or gadget, or any other independent item of content.
|
class article(html_tag):
'''
The article element represents a self-contained composition in a document,
page, application, or site and that is, in principle, independently
distributable or reusable, e.g. in syndication. This could be a forum post, a
magazine or newspaper article, a blog entry, a user-submitted comment, an
interactive widget or gadget, or any other independent item of content.
'''
pass
|
(*args, **kwargs)
|
46,797 |
dominate.tags
|
aside
|
The aside element represents a section of a page that consists of content
that is tangentially related to the content around the aside element, and
which could be considered separate from that content. Such sections are
often represented as sidebars in printed typography.
|
class aside(html_tag):
'''
The aside element represents a section of a page that consists of content
that is tangentially related to the content around the aside element, and
which could be considered separate from that content. Such sections are
often represented as sidebars in printed typography.
'''
pass
|
(*args, **kwargs)
|
46,831 |
dominate.dom_tag
|
attr
|
Set attributes on the current active tag context
|
def attr(*args, **kwargs):
'''
Set attributes on the current active tag context
'''
c = get_current()
dicts = args + (kwargs,)
for d in dicts:
for attr, value in d.items():
c.set_attribute(*dom_tag.clean_pair(attr, value))
|
(*args, **kwargs)
|
46,832 |
dominate.tags
|
audio
|
An audio element represents a sound or audio stream.
|
class audio(html_tag):
'''
An audio element represents a sound or audio stream.
'''
pass
|
(*args, **kwargs)
|
46,866 |
enum
|
auto
|
Instances are replaced with an appropriate value in Enum class suites.
|
class auto:
"""
Instances are replaced with an appropriate value in Enum class suites.
"""
value = _auto_null
|
()
|
46,867 |
dominate.tags
|
b
|
The b element represents a span of text to which attention is being drawn for
utilitarian purposes without conveying any extra importance and with no
implication of an alternate voice or mood, such as key words in a document
abstract, product names in a review, actionable words in interactive
text-driven software, or an article lede.
|
class b(html_tag):
'''
The b element represents a span of text to which attention is being drawn for
utilitarian purposes without conveying any extra importance and with no
implication of an alternate voice or mood, such as key words in a document
abstract, product names in a review, actionable words in interactive
text-driven software, or an article lede.
'''
pass
|
(*args, **kwargs)
|
46,901 |
dominate.tags
|
base
|
The base element allows authors to specify the document base URL for the
purposes of resolving relative URLs, and the name of the default browsing
context for the purposes of following hyperlinks. The element does not
represent any content beyond this information.
|
class base(html_tag):
'''
The base element allows authors to specify the document base URL for the
purposes of resolving relative URLs, and the name of the default browsing
context for the purposes of following hyperlinks. The element does not
represent any content beyond this information.
'''
is_single = True
|
(*args, **kwargs)
|
46,936 |
dominate.tags
|
bdi
|
The bdi element represents a span of text that is to be isolated from its
surroundings for the purposes of bidirectional text formatting.
|
class bdi(html_tag):
'''
The bdi element represents a span of text that is to be isolated from its
surroundings for the purposes of bidirectional text formatting.
'''
pass
|
(*args, **kwargs)
|
46,970 |
dominate.tags
|
bdo
|
The bdo element represents explicit text directionality formatting control
for its children. It allows authors to override the Unicode bidirectional
algorithm by explicitly specifying a direction override.
|
class bdo(html_tag):
'''
The bdo element represents explicit text directionality formatting control
for its children. It allows authors to override the Unicode bidirectional
algorithm by explicitly specifying a direction override.
'''
pass
|
(*args, **kwargs)
|
47,004 |
dominate.tags
|
blockquote
|
The blockquote element represents a section that is quoted from another
source.
|
class blockquote(html_tag):
'''
The blockquote element represents a section that is quoted from another
source.
'''
pass
|
(*args, **kwargs)
|
47,038 |
dominate.tags
|
body
|
The body element represents the main content of the document.
|
class body(html_tag):
'''
The body element represents the main content of the document.
'''
pass
|
(*args, **kwargs)
|
47,072 |
dominate.tags
|
br
|
The br element represents a line break.
|
class br(html_tag):
'''
The br element represents a line break.
'''
is_single = True
is_inline = True
|
(*args, **kwargs)
|
47,106 |
dominate.tags
|
button
|
The button element represents a button. If the element is not disabled, then
the user agent should allow the user to activate the button.
|
class button(html_tag):
'''
The button element represents a button. If the element is not disabled, then
the user agent should allow the user to activate the button.
'''
pass
|
(*args, **kwargs)
|
47,140 |
easul.process
|
calculate_age
| null |
def calculate_age(start_date:datetime.date, end_date:datetime.date):
if start_date is None or end_date is None:
return None
try:
birthday = start_date.replace(year=end_date.year)
# raised when birth date is February 29
# and the current year is not a leap year
except ValueError:
birthday = start_date.replace(year=start_date.year,
month=start_date.month + 1, day=1)
if birthday > end_date:
return end_date.year - start_date.year - 1
else:
return end_date.year - start_date.year
|
(start_date: <method 'date' of 'datetime.datetime' objects>, end_date: <method 'date' of 'datetime.datetime' objects>)
|
47,141 |
dominate.tags
|
canvas
|
The canvas element provides scripts with a resolution-dependent bitmap
canvas, which can be used for rendering graphs, game graphics, or other
visual images on the fly.
|
class canvas(html_tag):
'''
The canvas element provides scripts with a resolution-dependent bitmap
canvas, which can be used for rendering graphs, game graphics, or other
visual images on the fly.
'''
pass
|
(*args, **kwargs)
|
47,175 |
dominate.tags
|
caption
|
The caption element represents the title of the table that is its parent, if
it has a parent and that is a table element.
|
class caption(html_tag):
'''
The caption element represents the title of the table that is its parent, if
it has a parent and that is a table element.
'''
pass
|
(*args, **kwargs)
|
47,209 |
easul.data
|
check_and_encode_data
|
Check and encode data if it has not already been encoded. If data has already been encoded but is different
throws a SystemError.
Args:
data:
encoder:
Returns:
|
def check_and_encode_data(data, encoder):
"""
Check and encode data if it has not already been encoded. If data has already been encoded but is different
throws a SystemError.
Args:
data:
encoder:
Returns:
"""
if data.encoded_with is None and encoder is None:
return data
if data.is_encoded:
if data.is_matching_encoder(encoder) is False:
raise SystemError(
f"Data was not encoded in the same way as the supplied encoder (data set encoded_with:{data.encoded_with}, supplied encoder:{encoder})")
else:
return data
encoder.encode_dataset(data)
return data
|
(data, encoder)
|
47,210 |
dominate.tags
|
cite
|
The cite element represents the title of a work (e.g. a book, a paper, an
essay, a poem, a score, a song, a script, a film, a TV show, a game, a
sculpture, a painting, a theatre production, a play, an opera, a musical, an
exhibition, a legal case report, etc). This can be a work that is being
quoted or referenced in detail (i.e. a citation), or it can just be a work
that is mentioned in passing.
|
class cite(html_tag):
'''
The cite element represents the title of a work (e.g. a book, a paper, an
essay, a poem, a score, a song, a script, a film, a TV show, a game, a
sculpture, a painting, a theatre production, a play, an opera, a musical, an
exhibition, a legal case report, etc). This can be a work that is being
quoted or referenced in detail (i.e. a citation), or it can just be a work
that is mentioned in passing.
'''
pass
|
(*args, **kwargs)
|
47,244 |
dominate.tags
|
code
|
The code element represents a fragment of computer code. This could be an XML
element name, a filename, a computer program, or any other string that a
computer would recognize.
|
class code(html_tag):
'''
The code element represents a fragment of computer code. This could be an XML
element name, a filename, a computer program, or any other string that a
computer would recognize.
'''
pass
|
(*args, **kwargs)
|
47,278 |
dominate.tags
|
col
|
If a col element has a parent and that is a colgroup element that itself has
a parent that is a table element, then the col element represents one or more
columns in the column group represented by that colgroup.
|
class col(html_tag):
'''
If a col element has a parent and that is a colgroup element that itself has
a parent that is a table element, then the col element represents one or more
columns in the column group represented by that colgroup.
'''
is_single = True
|
(*args, **kwargs)
|
47,312 |
dominate.tags
|
colgroup
|
The colgroup element represents a group of one or more columns in the table
that is its parent, if it has a parent and that is a table element.
|
class colgroup(html_tag):
'''
The colgroup element represents a group of one or more columns in the table
that is its parent, if it has a parent and that is a table element.
'''
pass
|
(*args, **kwargs)
|
47,346 |
dominate.tags
|
command
|
The command element represents a command that the user can invoke.
|
class command(html_tag):
'''
The command element represents a command that the user can invoke.
'''
is_single = True
|
(*args, **kwargs)
|
47,380 |
dominate.tags
|
comment
|
Normal, one-line comment:
>>> print comment("Hello, comments!")
<!--Hello, comments!-->
For IE's "if" statement comments:
>>> print comment(p("Upgrade your browser."), condition='lt IE6')
<!--[if lt IE6]><p>Upgrade your browser.</p><![endif]-->
Downlevel conditional comments:
>>> print comment(p("You are using a ", em("downlevel"), " browser."),
condition='false', downlevel='revealed')
<![if false]><p>You are using a <em>downlevel</em> browser.</p><![endif]>
For more on conditional comments see:
http://msdn.microsoft.com/en-us/library/ms537512(VS.85).aspx
|
class comment(html_tag):
'''
Normal, one-line comment:
>>> print comment("Hello, comments!")
<!--Hello, comments!-->
For IE's "if" statement comments:
>>> print comment(p("Upgrade your browser."), condition='lt IE6')
<!--[if lt IE6]><p>Upgrade your browser.</p><![endif]-->
Downlevel conditional comments:
>>> print comment(p("You are using a ", em("downlevel"), " browser."),
condition='false', downlevel='revealed')
<![if false]><p>You are using a <em>downlevel</em> browser.</p><![endif]>
For more on conditional comments see:
http://msdn.microsoft.com/en-us/library/ms537512(VS.85).aspx
'''
ATTRIBUTE_CONDITION = 'condition'
# Valid values are 'hidden', 'downlevel' or 'revealed'
ATTRIBUTE_DOWNLEVEL = 'downlevel'
def _render(self, sb, indent_level=1, indent_str=' ', pretty=True, xhtml=False):
has_condition = comment.ATTRIBUTE_CONDITION in self.attributes
is_revealed = comment.ATTRIBUTE_DOWNLEVEL in self.attributes and \
self.attributes[comment.ATTRIBUTE_DOWNLEVEL] == 'revealed'
sb.append('<!')
if not is_revealed:
sb.append('--')
if has_condition:
sb.append('[if %s]>' % self.attributes[comment.ATTRIBUTE_CONDITION])
pretty = self._render_children(sb, indent_level - 1, indent_str, pretty, xhtml)
# if len(self.children) > 1:
if any(isinstance(child, dom_tag) for child in self):
sb.append('\n')
sb.append(indent_str * (indent_level - 1))
if has_condition:
sb.append('<![endif]')
if not is_revealed:
sb.append('--')
sb.append('>')
return sb
|
(*args, **kwargs)
|
47,400 |
dominate.tags
|
_render
| null |
def _render(self, sb, indent_level=1, indent_str=' ', pretty=True, xhtml=False):
has_condition = comment.ATTRIBUTE_CONDITION in self.attributes
is_revealed = comment.ATTRIBUTE_DOWNLEVEL in self.attributes and \
self.attributes[comment.ATTRIBUTE_DOWNLEVEL] == 'revealed'
sb.append('<!')
if not is_revealed:
sb.append('--')
if has_condition:
sb.append('[if %s]>' % self.attributes[comment.ATTRIBUTE_CONDITION])
pretty = self._render_children(sb, indent_level - 1, indent_str, pretty, xhtml)
# if len(self.children) > 1:
if any(isinstance(child, dom_tag) for child in self):
sb.append('\n')
sb.append(indent_str * (indent_level - 1))
if has_condition:
sb.append('<![endif]')
if not is_revealed:
sb.append('--')
sb.append('>')
return sb
|
(self, sb, indent_level=1, indent_str=' ', pretty=True, xhtml=False)
|
47,414 |
easul.data
|
create_input_dataset
|
Create input dataset according to input data. If it already a DataInput class. And if a dictionary then returns a
SingleDataInput, or if a list it returns a MultiDataInput. If no schema is provided raises and exception.
Args:
data:
schema:
allow_multiple:
encoder:
Returns:
|
def create_input_dataset(data, schema=None, allow_multiple=False, encoder=None):
"""
Create input dataset according to input data. If it already a DataInput class. And if a dictionary then returns a
SingleDataInput, or if a list it returns a MultiDataInput. If no schema is provided raises and exception.
Args:
data:
schema:
allow_multiple:
encoder:
Returns:
"""
from easul import data as dat
if allow_multiple is False and (isinstance(data, dat.MultiDataInput) or isinstance(data, list)):
raise AttributeError("data must represent a single row (e.g. a SingleInputDataSet or a dictionary)")
if issubclass(data.__class__, DataInput):
return check_and_encode_data(data, encoder)
if not schema:
raise AttributeError("schema is required if data is not already a DataSet")
elif type(data) is list:
return check_and_encode_data(dat.MultiDataInput(data, schema, convert=True), encoder)
return check_and_encode_data(dat.SingleDataInput(data, schema, convert=True), encoder)
|
(data, schema=None, allow_multiple=False, encoder=None)
|
47,416 |
dominate.tags
|
datalist
|
The datalist element represents a set of option elements that represent
predefined options for other controls. The contents of the element represents
fallback content for legacy user agents, intermixed with option elements that
represent the predefined options. In the rendering, the datalist element
represents nothing and it, along with its children, should be hidden.
|
class datalist(html_tag):
'''
The datalist element represents a set of option elements that represent
predefined options for other controls. The contents of the element represents
fallback content for legacy user agents, intermixed with option elements that
represent the predefined options. In the rendering, the datalist element
represents nothing and it, along with its children, should be hidden.
'''
pass
|
(*args, **kwargs)
|
47,452 |
dominate.tags
|
dd
|
The dd element represents the description, definition, or value, part of a
term-description group in a description list (dl element).
|
class dd(html_tag):
'''
The dd element represents the description, definition, or value, part of a
term-description group in a description list (dl element).
'''
pass
|
(*args, **kwargs)
|
47,487 |
attr._next_gen
|
define
|
Define an *attrs* class.
Differences to the classic `attr.s` that it uses underneath:
- Automatically detect whether or not *auto_attribs* should be `True` (c.f.
*auto_attribs* parameter).
- Converters and validators run when attributes are set by default -- if
*frozen* is `False`.
- *slots=True*
.. caution::
Usually this has only upsides and few visible effects in everyday
programming. But it *can* lead to some surprising behaviors, so please
make sure to read :term:`slotted classes`.
- *auto_exc=True*
- *auto_detect=True*
- *order=False*
- Some options that were only relevant on Python 2 or were kept around for
backwards-compatibility have been removed.
Please note that these are all defaults and you can change them as you
wish.
:param Optional[bool] auto_attribs: If set to `True` or `False`, it behaves
exactly like `attr.s`. If left `None`, `attr.s` will try to guess:
1. If any attributes are annotated and no unannotated `attrs.fields`\ s
are found, it assumes *auto_attribs=True*.
2. Otherwise it assumes *auto_attribs=False* and tries to collect
`attrs.fields`\ s.
For now, please refer to `attr.s` for the rest of the parameters.
.. versionadded:: 20.1.0
.. versionchanged:: 21.3.0 Converters are also run ``on_setattr``.
.. versionadded:: 22.2.0
*unsafe_hash* as an alias for *hash* (for :pep:`681` compliance).
|
def define(
maybe_cls=None,
*,
these=None,
repr=None,
unsafe_hash=None,
hash=None,
init=None,
slots=True,
frozen=False,
weakref_slot=True,
str=False,
auto_attribs=None,
kw_only=False,
cache_hash=False,
auto_exc=True,
eq=None,
order=False,
auto_detect=True,
getstate_setstate=None,
on_setattr=None,
field_transformer=None,
match_args=True,
):
r"""
Define an *attrs* class.
Differences to the classic `attr.s` that it uses underneath:
- Automatically detect whether or not *auto_attribs* should be `True` (c.f.
*auto_attribs* parameter).
- Converters and validators run when attributes are set by default -- if
*frozen* is `False`.
- *slots=True*
.. caution::
Usually this has only upsides and few visible effects in everyday
programming. But it *can* lead to some surprising behaviors, so please
make sure to read :term:`slotted classes`.
- *auto_exc=True*
- *auto_detect=True*
- *order=False*
- Some options that were only relevant on Python 2 or were kept around for
backwards-compatibility have been removed.
Please note that these are all defaults and you can change them as you
wish.
:param Optional[bool] auto_attribs: If set to `True` or `False`, it behaves
exactly like `attr.s`. If left `None`, `attr.s` will try to guess:
1. If any attributes are annotated and no unannotated `attrs.fields`\ s
are found, it assumes *auto_attribs=True*.
2. Otherwise it assumes *auto_attribs=False* and tries to collect
`attrs.fields`\ s.
For now, please refer to `attr.s` for the rest of the parameters.
.. versionadded:: 20.1.0
.. versionchanged:: 21.3.0 Converters are also run ``on_setattr``.
.. versionadded:: 22.2.0
*unsafe_hash* as an alias for *hash* (for :pep:`681` compliance).
"""
def do_it(cls, auto_attribs):
return attrs(
maybe_cls=cls,
these=these,
repr=repr,
hash=hash,
unsafe_hash=unsafe_hash,
init=init,
slots=slots,
frozen=frozen,
weakref_slot=weakref_slot,
str=str,
auto_attribs=auto_attribs,
kw_only=kw_only,
cache_hash=cache_hash,
auto_exc=auto_exc,
eq=eq,
order=order,
auto_detect=auto_detect,
collect_by_mro=True,
getstate_setstate=getstate_setstate,
on_setattr=on_setattr,
field_transformer=field_transformer,
match_args=match_args,
)
def wrap(cls):
"""
Making this a wrapper ensures this code runs during class creation.
We also ensure that frozen-ness of classes is inherited.
"""
nonlocal frozen, on_setattr
had_on_setattr = on_setattr not in (None, setters.NO_OP)
# By default, mutable classes convert & validate on setattr.
if frozen is False and on_setattr is None:
on_setattr = _ng_default_on_setattr
# However, if we subclass a frozen class, we inherit the immutability
# and disable on_setattr.
for base_cls in cls.__bases__:
if base_cls.__setattr__ is _frozen_setattrs:
if had_on_setattr:
msg = "Frozen classes can't use on_setattr (frozen-ness was inherited)."
raise ValueError(msg)
on_setattr = setters.NO_OP
break
if auto_attribs is not None:
return do_it(cls, auto_attribs)
try:
return do_it(cls, True)
except UnannotatedAttributeError:
return do_it(cls, False)
# maybe_cls's type depends on the usage of the decorator. It's a class
# if it's used as `@attrs` but ``None`` if used as `@attrs()`.
if maybe_cls is None:
return wrap
return wrap(maybe_cls)
|
(maybe_cls=None, *, these=None, repr=None, unsafe_hash=None, hash=None, init=None, slots=True, frozen=False, weakref_slot=True, str=False, auto_attribs=None, kw_only=False, cache_hash=False, auto_exc=True, eq=None, order=False, auto_detect=True, getstate_setstate=None, on_setattr=None, field_transformer=None, match_args=True)
|
47,488 |
dominate.tags
|
del_
|
The del element represents a removal from the document.
|
class del_(html_tag):
'''
The del element represents a removal from the document.
'''
pass
|
(*args, **kwargs)
|
47,522 |
dominate.tags
|
details
|
The details element represents a disclosure widget from which the user can
obtain additional information or controls.
|
class details(html_tag):
'''
The details element represents a disclosure widget from which the user can
obtain additional information or controls.
'''
pass
|
(*args, **kwargs)
|
47,556 |
dominate.tags
|
dfn
|
The dfn element represents the defining instance of a term. The paragraph,
description list group, or section that is the nearest ancestor of the dfn
element must also contain the definition(s) for the term given by the dfn
element.
|
class dfn(html_tag):
'''
The dfn element represents the defining instance of a term. The paragraph,
description list group, or section that is the nearest ancestor of the dfn
element must also contain the definition(s) for the term given by the dfn
element.
'''
pass
|
(*args, **kwargs)
|
47,591 |
dominate.tags
|
div
|
The div element has no special meaning at all. It represents its children. It
can be used with the class, lang, and title attributes to mark up semantics
common to a group of consecutive elements.
|
class div(html_tag):
'''
The div element has no special meaning at all. It represents its children. It
can be used with the class, lang, and title attributes to mark up semantics
common to a group of consecutive elements.
'''
pass
|
(*args, **kwargs)
|
47,625 |
dominate.tags
|
dl
|
The dl element represents an association list consisting of zero or more
name-value groups (a description list). Each group must consist of one or
more names (dt elements) followed by one or more values (dd elements).
Within a single dl element, there should not be more than one dt element for
each name.
|
class dl(html_tag):
'''
The dl element represents an association list consisting of zero or more
name-value groups (a description list). Each group must consist of one or
more names (dt elements) followed by one or more values (dd elements).
Within a single dl element, there should not be more than one dt element for
each name.
'''
pass
|
(*args, **kwargs)
|
47,659 |
dominate.dom1core
|
dom1core
|
Implements the Document Object Model (Core) Level 1
http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/
http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core.html
|
class dom1core(object):
'''
Implements the Document Object Model (Core) Level 1
http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/
http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core.html
'''
@property
def parentNode(self):
'''
DOM API: Returns the parent tag of the current element.
'''
return self.parent
def getElementById(self, id):
'''
DOM API: Returns single element with matching id value.
'''
results = self.get(id=id)
if len(results) > 1:
raise ValueError('Multiple tags with id "%s".' % id)
elif results:
return results[0]
return None
def getElementsByTagName(self, name):
'''
DOM API: Returns all tags that match name.
'''
if isinstance(name, basestring):
return self.get(name.lower())
return None
def appendChild(self, obj):
'''
DOM API: Add an item to the end of the children list.
'''
self.add(obj)
return self
|
()
|
47,663 |
dominate.dom_tag
|
dom_tag
| null |
class dom_tag(object):
is_single = False # Tag does not require matching end tag (ex. <hr/>)
is_pretty = True # Text inside the tag should be left as-is (ex. <pre>)
# otherwise, text will be escaped() and whitespace may be
# modified
is_inline = False
def __new__(_cls, *args, **kwargs):
'''
Check if bare tag is being used a a decorator
(called with a single function arg).
decorate the function and return
'''
if len(args) == 1 and isinstance(args[0], Callable) \
and not isinstance(args[0], dom_tag) and not kwargs:
wrapped = args[0]
@wraps(wrapped)
def f(*args, **kwargs):
with _cls() as _tag:
return wrapped(*args, **kwargs) or _tag
return f
return object.__new__(_cls)
def __init__(self, *args, **kwargs):
'''
Creates a new tag. Child tags should be passed as arguments and attributes
should be passed as keyword arguments.
There is a non-rendering attribute which controls how the tag renders:
* `__inline` - Boolean value. If True renders all children tags on the same
line.
'''
self.attributes = {}
self.children = []
self.parent = None
# Does not insert newlines on all children if True (recursive attribute)
self.is_inline = kwargs.pop('__inline', self.is_inline)
self.is_pretty = kwargs.pop('__pretty', self.is_pretty)
#Add child elements
if args:
self.add(*args)
for attr, value in kwargs.items():
self.set_attribute(*type(self).clean_pair(attr, value))
self._ctx = None
self._add_to_ctx()
# context manager
frame = namedtuple('frame', ['tag', 'items', 'used'])
# stack of frames
_with_contexts = defaultdict(list)
def _add_to_ctx(self):
stack = dom_tag._with_contexts.get(_get_thread_context())
if stack:
self._ctx = stack[-1]
stack[-1].items.append(self)
def __enter__(self):
stack = dom_tag._with_contexts[_get_thread_context()]
stack.append(dom_tag.frame(self, [], set()))
return self
def __exit__(self, type, value, traceback):
thread_id = _get_thread_context()
stack = dom_tag._with_contexts[thread_id]
frame = stack.pop()
for item in frame.items:
if item in frame.used: continue
self.add(item)
if not stack:
del dom_tag._with_contexts[thread_id]
def __call__(self, func):
'''
tag instance is being used as a decorator.
wrap func to make a copy of this tag
'''
# remove decorator from its context so it doesn't
# get added in where it was defined
if self._ctx:
self._ctx.used.add(self)
@wraps(func)
def f(*args, **kwargs):
tag = copy.deepcopy(self)
tag._add_to_ctx()
with tag:
return func(*args, **kwargs) or tag
return f
def set_attribute(self, key, value):
'''
Add or update the value of an attribute.
'''
if isinstance(key, int):
self.children[key] = value
elif isinstance(key, basestring):
self.attributes[key] = value
else:
raise TypeError('Only integer and string types are valid for assigning '
'child tags and attributes, respectively.')
__setitem__ = set_attribute
def delete_attribute(self, key):
if isinstance(key, int):
del self.children[key:key+1]
else:
del self.attributes[key]
__delitem__ = delete_attribute
def add(self, *args):
'''
Add new child tags.
'''
for obj in args:
if isinstance(obj, numbers.Number):
# Convert to string so we fall into next if block
obj = str(obj)
if isinstance(obj, basestring):
obj = util.escape(obj)
self.children.append(obj)
elif isinstance(obj, dom_tag):
stack = dom_tag._with_contexts.get(_get_thread_context(), [])
for s in stack:
s.used.add(obj)
self.children.append(obj)
obj.parent = self
elif isinstance(obj, dict):
for attr, value in obj.items():
self.set_attribute(*dom_tag.clean_pair(attr, value))
elif hasattr(obj, '__iter__'):
for subobj in obj:
self.add(subobj)
else: # wtf is it?
raise ValueError('%r not a tag or string.' % obj)
if len(args) == 1:
return args[0]
return args
def add_raw_string(self, s):
self.children.append(s)
def remove(self, obj):
self.children.remove(obj)
def clear(self):
for i in self.children:
if isinstance(i, dom_tag) and i.parent is self:
i.parent = None
self.children = []
def get(self, tag=None, **kwargs):
'''
Recursively searches children for tags of a certain
type with matching attributes.
'''
# Stupid workaround since we can not use dom_tag in the method declaration
if tag is None: tag = dom_tag
attrs = [(dom_tag.clean_attribute(attr), value)
for attr, value in kwargs.items()]
results = []
for child in self.children:
if (isinstance(tag, basestring) and type(child).__name__ == tag) or \
(not isinstance(tag, basestring) and isinstance(child, tag)):
if all(child.attributes.get(attribute) == value
for attribute, value in attrs):
# If the child is of correct type and has all attributes and values
# in kwargs add as a result
results.append(child)
if isinstance(child, dom_tag):
# If the child is a dom_tag extend the search down through its children
results.extend(child.get(tag, **kwargs))
return results
def __getitem__(self, key):
'''
Returns the stored value of the specified attribute or child
(if it exists).
'''
if isinstance(key, int):
# Children are accessed using integers
try:
return object.__getattribute__(self, 'children')[key]
except IndexError:
raise IndexError('Child with index "%s" does not exist.' % key)
elif isinstance(key, basestring):
# Attributes are accessed using strings
try:
return object.__getattribute__(self, 'attributes')[key]
except KeyError:
raise AttributeError('Attribute "%s" does not exist.' % key)
else:
raise TypeError('Only integer and string types are valid for accessing '
'child tags and attributes, respectively.')
__getattr__ = __getitem__
def __len__(self):
'''
Number of child elements.
'''
return len(self.children)
def __bool__(self):
'''
Hack for "if x" and __len__
'''
return True
__nonzero__ = __bool__
def __iter__(self):
'''
Iterates over child elements.
'''
return self.children.__iter__()
def __contains__(self, item):
'''
Checks recursively if item is in children tree.
Accepts both a string and a class.
'''
return bool(self.get(item))
def __iadd__(self, obj):
'''
Reflexive binary addition simply adds tag as a child.
'''
self.add(obj)
return self
# String and unicode representations are the same as render()
def __unicode__(self):
return self.render()
__str__ = __unicode__
def render(self, indent=' ', pretty=True, xhtml=False):
data = self._render([], 0, indent, pretty, xhtml)
return u''.join(data)
def _render(self, sb, indent_level, indent_str, pretty, xhtml):
pretty = pretty and self.is_pretty
name = getattr(self, 'tagname', type(self).__name__)
# Workaround for python keywords and standard classes/methods
# (del, object, input)
if name[-1] == '_':
name = name[:-1]
# open tag
sb.append('<')
sb.append(name)
for attribute, value in sorted(self.attributes.items()):
if value in (False, None):
continue
val = unicode(value) if isinstance(value, util.text) and not value.escape else util.escape(unicode(value), True)
sb.append(' %s="%s"' % (attribute, val))
sb.append(' />' if self.is_single and xhtml else '>')
if self.is_single:
return sb
inline = self._render_children(sb, indent_level + 1, indent_str, pretty, xhtml)
if pretty and not inline:
sb.append('\n')
sb.append(indent_str * indent_level)
# close tag
sb.append('</')
sb.append(name)
sb.append('>')
return sb
def _render_children(self, sb, indent_level, indent_str, pretty, xhtml):
inline = True
for child in self.children:
if isinstance(child, dom_tag):
if pretty and not child.is_inline:
inline = False
sb.append('\n')
sb.append(indent_str * indent_level)
child._render(sb, indent_level, indent_str, pretty, xhtml)
else:
sb.append(unicode(child))
return inline
def __repr__(self):
name = '%s.%s' % (self.__module__, type(self).__name__)
attributes_len = len(self.attributes)
attributes = '%s attribute' % attributes_len
if attributes_len != 1: attributes += 's'
children_len = len(self.children)
children = '%s child' % children_len
if children_len != 1: children += 'ren'
return '<%s at %x: %s, %s>' % (name, id(self), attributes, children)
@staticmethod
def clean_attribute(attribute):
'''
Normalize attribute names for shorthand and work arounds for limitations
in Python's syntax
'''
# Shorthand
attribute = {
'cls': 'class',
'className': 'class',
'class_name': 'class',
'klass': 'class',
'fr': 'for',
'html_for': 'for',
'htmlFor': 'for',
'phor': 'for',
}.get(attribute, attribute)
# Workaround for Python's reserved words
if attribute[0] == '_':
attribute = attribute[1:]
# Workaround for dash
special_prefix = any([attribute.startswith(x) for x in ('data_', 'aria_')])
if attribute in set(['http_equiv']) or special_prefix:
attribute = attribute.replace('_', '-').lower()
# Workaround for colon
if attribute.split('_')[0] in ('xlink', 'xml', 'xmlns'):
attribute = attribute.replace('_', ':', 1).lower()
return attribute
@classmethod
def clean_pair(cls, attribute, value):
'''
This will call `clean_attribute` on the attribute and also allows for the
creation of boolean attributes.
Ex. input(selected=True) is equivalent to input(selected="selected")
'''
attribute = cls.clean_attribute(attribute)
# Check for boolean attributes
# (i.e. selected=True becomes selected="selected")
if value is True:
value = attribute
# Ignore `if value is False`: this is filtered out in render()
return (attribute, value)
|
(*args, **kwargs)
|
47,673 |
dominate.dom_tag
|
__init__
|
Creates a new tag. Child tags should be passed as arguments and attributes
should be passed as keyword arguments.
There is a non-rendering attribute which controls how the tag renders:
* `__inline` - Boolean value. If True renders all children tags on the same
line.
|
def __init__(self, *args, **kwargs):
'''
Creates a new tag. Child tags should be passed as arguments and attributes
should be passed as keyword arguments.
There is a non-rendering attribute which controls how the tag renders:
* `__inline` - Boolean value. If True renders all children tags on the same
line.
'''
self.attributes = {}
self.children = []
self.parent = None
# Does not insert newlines on all children if True (recursive attribute)
self.is_inline = kwargs.pop('__inline', self.is_inline)
self.is_pretty = kwargs.pop('__pretty', self.is_pretty)
#Add child elements
if args:
self.add(*args)
for attr, value in kwargs.items():
self.set_attribute(*type(self).clean_pair(attr, value))
self._ctx = None
self._add_to_ctx()
|
(self, *args, **kwargs)
|
47,698 |
dominate.tags
|
em
|
The em element represents stress emphasis of its contents.
|
class em(html_tag):
'''
The em element represents stress emphasis of its contents.
'''
pass
|
(*args, **kwargs)
|
47,732 |
dominate.tags
|
embed
|
The embed element represents an integration point for an external (typically
non-HTML) application or interactive content.
|
class embed(html_tag):
'''
The embed element represents an integration point for an external (typically
non-HTML) application or interactive content.
'''
is_single = True
|
(*args, **kwargs)
|
47,769 |
attr._next_gen
|
field
|
Identical to `attr.ib`, except keyword-only and with some arguments
removed.
.. versionadded:: 23.1.0
The *type* parameter has been re-added; mostly for `attrs.make_class`.
Please note that type checkers ignore this metadata.
.. versionadded:: 20.1.0
|
def field(
*,
default=NOTHING,
validator=None,
repr=True,
hash=None,
init=True,
metadata=None,
type=None,
converter=None,
factory=None,
kw_only=False,
eq=None,
order=None,
on_setattr=None,
alias=None,
):
"""
Identical to `attr.ib`, except keyword-only and with some arguments
removed.
.. versionadded:: 23.1.0
The *type* parameter has been re-added; mostly for `attrs.make_class`.
Please note that type checkers ignore this metadata.
.. versionadded:: 20.1.0
"""
return attrib(
default=default,
validator=validator,
repr=repr,
hash=hash,
init=init,
metadata=metadata,
type=type,
converter=converter,
factory=factory,
kw_only=kw_only,
eq=eq,
order=order,
on_setattr=on_setattr,
alias=alias,
)
|
(*, default=NOTHING, validator=None, repr=True, hash=None, init=True, metadata=None, type=None, converter=None, factory=None, kw_only=False, eq=None, order=None, on_setattr=None, alias=None)
|
47,770 |
dominate.tags
|
fieldset
|
The fieldset element represents a set of form controls optionally grouped
under a common name.
|
class fieldset(html_tag):
'''
The fieldset element represents a set of form controls optionally grouped
under a common name.
'''
pass
|
(*args, **kwargs)
|
47,804 |
dominate.tags
|
figcaption
|
The figcaption element represents a caption or legend for the rest of the
contents of the figcaption element's parent figure element, if any.
|
class figcaption(html_tag):
'''
The figcaption element represents a caption or legend for the rest of the
contents of the figcaption element's parent figure element, if any.
'''
pass
|
(*args, **kwargs)
|
47,838 |
dominate.tags
|
figure
|
The figure element represents some flow content, optionally with a caption,
that is self-contained and is typically referenced as a single unit from the
main flow of the document.
|
class figure(html_tag):
'''
The figure element represents some flow content, optionally with a caption,
that is self-contained and is typically referenced as a single unit from the
main flow of the document.
'''
pass
|
(*args, **kwargs)
|
47,872 |
dominate.tags
|
font
|
The font element represents the font in a html .
|
class font(html_tag):
'''
The font element represents the font in a html .
'''
pass
|
(*args, **kwargs)
|
47,906 |
dominate.tags
|
footer
|
The footer element represents a footer for its nearest ancestor sectioning
content or sectioning root element. A footer typically contains information
about its section such as who wrote it, links to related documents,
copyright data, and the like.
|
class footer(html_tag):
'''
The footer element represents a footer for its nearest ancestor sectioning
content or sectioning root element. A footer typically contains information
about its section such as who wrote it, links to related documents,
copyright data, and the like.
'''
pass
|
(*args, **kwargs)
|
47,940 |
dominate.tags
|
form
|
The form element represents a collection of form-associated elements, some of
which can represent editable values that can be submitted to a server for
processing.
|
class form(html_tag):
'''
The form element represents a collection of form-associated elements, some of
which can represent editable values that can be submitted to a server for
processing.
'''
pass
|
(*args, **kwargs)
|
47,974 |
easul.visual.render
|
from_html_template
| null |
def from_html_template(template_file, context):
return env.get_template(template_file).render(**context)
|
(template_file, context)
|
47,975 |
dominate.dom_tag
|
get_current
|
get the current tag being used as a with context or decorated function.
if no context is active, raises ValueError, or returns the default, if provided
|
def get_current(default=_get_current_none):
'''
get the current tag being used as a with context or decorated function.
if no context is active, raises ValueError, or returns the default, if provided
'''
h = _get_thread_context()
ctx = dom_tag._with_contexts.get(h, None)
if ctx:
return ctx[-1].tag
if default is _get_current_none:
raise ValueError('no current context')
return default
|
(default=<object object at 0x7f4a1a2bff60>)
|
47,976 |
easul.util
|
get_current_result
| null |
def get_current_result(results, current_time, ts_key, sort_field=None, reverse_sort=None):
sorted_results = sorted(results, key=lambda x:x[ts_key], reverse=True)
results = list(filter(lambda x: x[ts_key]<=current_time, sorted_results))
results_in_hour = list(filter(lambda x: x[ts_key]>=current_time - timedelta(hours=1), results))
if len(results_in_hour)>0 and sort_field:
results = sorted(results_in_hour, key=lambda x: x[sort_field], reverse=reverse_sort)
return results[0] if len(results)>0 else None
|
(results, current_time, ts_key, sort_field=None, reverse_sort=None)
|
47,977 |
easul.data
|
get_field_options_from_schema
|
Extract field options from the DataSchema as a dictionary.
Args:
field_name:
schema:
Returns:
|
def get_field_options_from_schema(field_name, schema):
"""
Extract field options from the DataSchema as a dictionary.
Args:
field_name:
schema:
Returns:
"""
options = schema[field_name]["options"]
return dict(sorted(options.items(), key=operator.itemgetter(0)))
|
(field_name, schema)
|
47,978 |
easul.decision
|
get_result_value
|
Extract value from result object or result dictionary.
Args:
result:
field:
Returns:
|
def get_result_value(result, field):
"""
Extract value from result object or result dictionary.
Args:
result:
field:
Returns:
"""
if issubclass(result.__class__, Result):
return getattr(result, field)
return result[field]
|
(result, field)
|
47,979 |
easul.util
|
get_start_step
|
Get a start step from a set of steps. If there are multiple start steps it returns the first.
Args:
steps:
Returns:
|
def get_start_step(steps):
"""
Get a start step from a set of steps. If there are multiple start steps it returns the first.
Args:
steps:
Returns:
"""
from easul.step import StartStep
start_steps = list(filter(lambda x: isinstance(x, StartStep), steps.values()))
if len(start_steps) == 0:
raise SystemError("No 'StartStep' is defined in the plan")
return start_steps[0]
|
(steps)
|
47,980 |
dominate.tags
|
h1
|
Represents the highest ranking heading.
|
class h1(html_tag):
'''
Represents the highest ranking heading.
'''
pass
|
(*args, **kwargs)
|
48,014 |
dominate.tags
|
h2
|
Represents the second-highest ranking heading.
|
class h2(html_tag):
'''
Represents the second-highest ranking heading.
'''
pass
|
(*args, **kwargs)
|
48,048 |
dominate.tags
|
h3
|
Represents the third-highest ranking heading.
|
class h3(html_tag):
'''
Represents the third-highest ranking heading.
'''
pass
|
(*args, **kwargs)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.