code stringlengths 52 7.75k | docs stringlengths 1 5.85k |
|---|---|
def delete_state_by_id(cls, state_id, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._delete_state_by_id_with_http_info(state_id, **kwargs)
else:
(data) = cls._delete_state_by_id_with_http_info(state_id, **kwargs)
... | Delete State
Delete an instance of State by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_state_by_id(state_id, async=True)
>>> result = thread.get()
:param async boo... |
def get_state_by_id(cls, state_id, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._get_state_by_id_with_http_info(state_id, **kwargs)
else:
(data) = cls._get_state_by_id_with_http_info(state_id, **kwargs)
return ... | Find State
Return single instance of State by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_state_by_id(state_id, async=True)
>>> result = thread.get()
:param async bool... |
def list_all_states(cls, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._list_all_states_with_http_info(**kwargs)
else:
(data) = cls._list_all_states_with_http_info(**kwargs)
return data | List States
Return a list of States
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_states(async=True)
>>> result = thread.get()
:param async bool
:param int page: pa... |
def replace_state_by_id(cls, state_id, state, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._replace_state_by_id_with_http_info(state_id, state, **kwargs)
else:
(data) = cls._replace_state_by_id_with_http_info(state_id, sta... | Replace State
Replace all attributes of State
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.replace_state_by_id(state_id, state, async=True)
>>> result = thread.get()
:param async b... |
def update_state_by_id(cls, state_id, state, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._update_state_by_id_with_http_info(state_id, state, **kwargs)
else:
(data) = cls._update_state_by_id_with_http_info(state_id, state,... | Update State
Update attributes of State
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_state_by_id(state_id, state, async=True)
>>> result = thread.get()
:param async bool
... |
def make_directory(path):
try:
makedirs(path)
logging.debug('Directory created: {0}'.format(path))
except OSError as e:
if e.errno != errno.EEXIST:
raise | Create directory if that not exists. |
def copy_file(self, from_path, to_path):
if not op.exists(op.dirname(to_path)):
self.make_directory(op.dirname(to_path))
shutil.copy(from_path, to_path)
logging.debug('File copied: {0}'.format(to_path)) | Copy file. |
def params(self):
parser = JinjaInterpolationNamespace()
parser.read(self.configuration)
return dict(parser['params'] or {}) | Read self params from configuration. |
def scan(cls, path):
result = []
try:
for _p in listdir(path):
try:
result.append(Template(_p, op.join(path, _p)))
except ValueError:
continue
except OSError:
pass
return result | Scan directory for templates. |
def copy(self):
templates = self.prepare_templates()
if self.params.interactive:
keys = list(self.parser.default)
for key in keys:
if key.startswith('_'):
continue
prompt = "{0} (default is \"{1}\")? ".format(
... | Prepare and paste self templates. |
def iterate_templates(self):
return [t for dd in self.dirs for t in Template.scan(dd)] | Iterate self starter templates.
:returns: A templates generator |
def _dump_files_to_local_drive(bodies, theseUrls, log):
j = 0
log.debug("attempting to write file data to local drive")
log.debug('%s URLS = %s' % (len(theseUrls), str(theseUrls),))
for body in bodies:
try:
if theseUrls[j]:
with open(theseUrls[j], 'w') as f:
... | *takes the files stored in memory and dumps them to the local drive*
****Key Arguments:****
- ``bodies`` -- array of file data (currently stored in memory)
- ``theseUrls`` -- array of local files paths to dump the file data into
- ``log`` -- the logger
**Return:**
- ``None`` |
def cleanup_video(self):
'''
.. versionchanged:: 0.6.1
Log terminated video source process ID.
'''
if self.video_source_process is not None:
self.video_source_process.terminate()
logger.info('Terminated video process: %s',
self.... | .. versionchanged:: 0.6.1
Log terminated video source process ID. |
def ping_hub(self):
'''
Attempt to ping the ZeroMQ plugin hub to verify connection is alive.
If ping is successful, record timestamp.
If ping is unsuccessful, call `on_heartbeat_error` method.
'''
if self.plugin is not None:
try:
self.plugin.e... | Attempt to ping the ZeroMQ plugin hub to verify connection is alive.
If ping is successful, record timestamp.
If ping is unsuccessful, call `on_heartbeat_error` method. |
def on_electrode_states_updated(self, states):
'''
.. versionchanged:: 0.12
Refactor to use :meth:`on_electrode_states_set`.
'''
states['electrode_states'] = \
states['electrode_states'].combine_first(self.canvas_slave
... | .. versionchanged:: 0.12
Refactor to use :meth:`on_electrode_states_set`. |
def on_electrode_states_set(self, states):
'''
Render and draw updated **static** electrode actuations layer on
canvas.
'''
if (self.canvas_slave.electrode_states
.equals(states['electrode_states'])):
return
self.canvas_slave.electrode_states ... | Render and draw updated **static** electrode actuations layer on
canvas. |
def on_dynamic_electrode_states_set(self, states):
'''
Render and draw updated **dynamic** electrode actuations layer on
canvas.
.. versionadded:: 0.12
'''
self.canvas_slave._dynamic_electrodes = states
surface = self.canvas_slave.render_dynamic_electrode_state... | Render and draw updated **dynamic** electrode actuations layer on
canvas.
.. versionadded:: 0.12 |
def on_canvas_slave__routes_set(self, slave, df_routes):
'''
.. versionadded:: 0.11.3
'''
self.canvas_slave.set_surface('routes',
self.canvas_slave.render_routes())
self.canvas_slave.cairo_surface = flatten_surfaces(self.canvas_slave
... | .. versionadded:: 0.11.3 |
def on_canvas_slave__global_command(self, slave, group, command, data):
'''
.. versionadded:: 0.13
Execute global command (i.e., command not tied to a specific
electrode or route).
'''
def command_callback(reply):
_L().debug('%s.%s()', group, command)... | .. versionadded:: 0.13
Execute global command (i.e., command not tied to a specific
electrode or route). |
def get_string_version(name,
default=DEFAULT_STRING_NOT_FOUND,
allow_ambiguous=True):
# get filename of callar
callar = inspect.getouterframes(inspect.currentframe())[1][1]
if callar.startswith('<doctest'):
# called from doctest, find written script... | Get string version from installed package information.
It will return :attr:`default` value when the named package is not
installed.
Parameters
-----------
name : string
An application name used to install via setuptools.
default : string
A default returning value used when the... |
def get_tuple_version(name,
default=DEFAULT_TUPLE_NOT_FOUND,
allow_ambiguous=True):
def _prefer_int(x):
try:
return int(x)
except ValueError:
return x
version = get_string_version(name, default=default,
... | Get tuple version from installed package information for easy handling.
It will return :attr:`default` value when the named package is not
installed.
Parameters
-----------
name : string
An application name used to install via setuptools.
default : tuple
A default returning val... |
def get_versions(name,
default_string=DEFAULT_STRING_NOT_FOUND,
default_tuple=DEFAULT_TUPLE_NOT_FOUND,
allow_ambiguous=True):
version_string = get_string_version(name, default_string, allow_ambiguous)
version_tuple = get_tuple_version(name, default_tuple, ... | Get string and tuple versions from installed package information
It will return :attr:`default_string` and :attr:`default_tuple` values when
the named package is not installed.
Parameters
-----------
name : string
An application name used to install via setuptools.
default : string
... |
def _get_toSymbol(cls):
# type: (_MetaRule) -> object
if cls._traverse:
raise RuleNotDefinedException(cls)
if len(cls.rules) > 1:
raise CantCreateSingleRuleException(cls)
right = cls.rules[0][1]
if len(right) > 1:
raise NotASingleSymbo... | Get symbol from which the rule is rewrote.
:param cls: Rule for which return the symbol.
:return: Symbol from which the rule is rewrote.
:raise RuleNotDefinedException: If the rule is not defined.
:raise CantCreateSingleRuleException: If the rule consists of more rules.
:raise No... |
def _get_fromSymbol(cls):
# type: (_MetaRule) -> object
if cls._traverse:
raise RuleNotDefinedException(cls)
if len(cls.rules) > 1:
raise CantCreateSingleRuleException(cls)
left = cls.rules[0][0]
if len(left) > 1:
raise NotASingleSymbo... | Get symbol to which the rule is rewrote.
:param cls: Rule for which return the symbol.
:return: Symbol to which the rule is rewrote.
:raise RuleNotDefinedException: If the rule is not defined.
:raise CantCreateSingleRuleException: If the rule consists of more rules.
:raise NotASi... |
def _get_right(cls):
# type: (_MetaRule) -> List[object]
if cls._traverse:
return [cls.toSymbol]
if len(cls.rules) > 1:
raise CantCreateSingleRuleException(cls)
return cls.rules[0][1] | Get right part of the rule.
:param cls: Rule for which return the right side.
:return: Symbols on the right side of the array.
:raise RuleNotDefinedException: If the rule is not defined.
:raise CantCreateSingleRuleException: If the rule consists of more rules.
:raise NotASingleSy... |
def _get_left(cls):
# type: (_MetaRule) -> List[object]
if cls._traverse:
return [cls.fromSymbol]
if len(cls.rules) > 1:
raise CantCreateSingleRuleException(cls)
return cls.rules[0][0] | Get left part of the rule.
:param cls: Rule for which return the left side.
:return: Symbols on the left side of the array.
:raise RuleNotDefinedException: If the rule is not defined.
:raise CantCreateSingleRuleException: If the rule consists of more rules.
:raise NotASingleSymbo... |
def _get_rule(cls):
# type: (_MetaRule) -> (List[object], List[object])
if cls._traverse:
return (cls.left, cls.right)
if len(cls.rules) > 1:
raise CantCreateSingleRuleException(cls)
return cls.rules[0] | Get rule on the Rule class.
:param cls: Rule for which return the rule.
:return: Rule inside the Rule class.
:raise RuleNotDefinedException: If the rule is not defined.
:raise CantCreateSingleRuleException: If the rule consists of more rules.
:raise NotASingleSymbolException: If ... |
def _get_rules(cls):
# type: (_MetaRule) -> List[(List[object], List[object])]
cls._traverse = True
r = cls.rule
cls._traverse = False
return [r] | Get rules on the Rule class.
:param cls: Rule for which return the rules.
:return: Rules inside the Rule class.
:raise RuleNotDefinedException: If the rule is not defined.
:raise CantCreateSingleRuleException: If the rule consists of more rules.
:raise NotASingleSymbolException: ... |
def _controlSide(cls, side, grammar):
# type: (_MetaRule, List[object], Grammar) -> None
if not isinstance(side, list):
raise RuleSyntaxException(cls, 'One side of rule is not enclose by list', side)
if len(side) == 0:
raise RuleSyntaxException(cls, 'One side of ... | Validate one side of the rule.
:param side: Iterable side of the rule.
:param grammar: Grammar on which to validate.
:raise RuleSyntaxException: If invalid syntax is use.
:raise UselessEpsilonException: If useless epsilon is used.
:raise TerminalDoesNotExistsException: If termina... |
def validate(cls, grammar):
# type: (_MetaRule, Grammar) -> None
# check if the rule is not defined multiple times
defined = set(dir(cls))
if 'rules' in defined and len(defined & {'rule', 'left', 'right', 'toSymbol', 'fromSymbol'}) > 0 or \
'rule' in defined and ... | Perform rules validation of the class.
:param grammar: Grammar on which to validate.
:raise RuleSyntaxException: If invalid syntax is used.
:raise UselessEpsilonException: If epsilon used in rules in useless.
:raise TerminalDoesNotExistsException: If terminal does not exists in the gramm... |
def no_empty_value(func):
@wraps(func)
def wrapper(value):
if not value:
raise Exception("Empty value not allowed")
return func(value)
return wrapper | Raises an exception if function argument is empty. |
def to_bool(value):
cases = {
'0': False,
'false': False,
'no': False,
'1': True,
'true': True,
'yes': True,
}
value = value.lower() if isinstance(value, basestring) else value
return cases.get(value, bool(value)) | Converts human boolean-like values to Python boolean.
Falls back to :class:`bool` when ``value`` is not recognized.
:param value: the value to convert
:returns: ``True`` if value is truthy, ``False`` otherwise
:rtype: bool |
def etree_to_dict(t, trim=True, **kw):
u
d = {t.tag: {} if t.attrib else None}
children = list(t)
etree_to_dict_w_args = partial(etree_to_dict, trim=trim, **kw)
if children:
dd = defaultdict(list)
d = {t.tag: {}}
for dc in map(etree_to_dict_w_args, children):
fo... | u"""Converts an lxml.etree object to Python dict.
>>> etree_to_dict(etree.Element('root'))
{'root': None}
:param etree.Element t: lxml tree to convert
:returns d: a dict representing the lxml tree ``t``
:rtype: dict |
def objwalk(self, obj, path=(), memo=None):
# dual python 2/3 compatability, inspired by the "six" library
string_types = (str, unicode) if str is bytes else (str, bytes)
iteritems = lambda mapping: getattr(mapping, 'iteritems', mapping.items)()
if memo is None:
me... | Traverse a dictionary recursively and save path
Taken from:
http://code.activestate.com/recipes/577982-recursively-walk-python-objects/ |
def set_cache_dir(directory):
global cache_dir
if directory is None:
cache_dir = None
return
if not os.path.exists(directory):
os.makedirs(directory)
if not os.path.isdir(directory):
raise ValueError("not a directory")
cache_dir = directory | Set the directory to cache JSON responses from most API endpoints. |
def create_element_tree(elem_or_name=None, text=None, **attribute_kwargs):
if elem_or_name is None:
return ElementTree()
is_elem = isinstance(elem_or_name, ElementType)
element = elem_or_name if is_elem else Element(elem_or_name)
if text is not None:
element.text = text
elem... | Creates an ElementTree from elem_or_name, updated it with text and attributes.
If elem_or_name is None, a permanently empty ElementTree is returned.
:param elem_or_name: an Element or the name of the root element tag
:param text: optional text with which to update the root element
:param attribute_kwarg... |
def clear_children(parent_to_parse, element_path=None):
element = get_element(parent_to_parse, element_path)
if element is None:
return parent_to_parse
else:
elem_txt = element.text
elem_atr = element.attrib
element.clear()
element.text = elem_txt
ele... | Clears only children (not text or attributes) from the parsed parent
or named element. |
def clear_element(parent_to_parse, element_path=None):
element = get_element(parent_to_parse, element_path)
if element is None:
return parent_to_parse
else:
element.clear()
return element | Clears everything (text, attributes and children) from the parsed parent
or named element. |
def copy_element(from_element, to_element=None, path_to_copy=None):
from_element = get_element(from_element, path_to_copy)
dest_element = get_element(to_element, path_to_copy)
if from_element is None:
return None
if dest_element is None:
if path_to_copy is None:
dest_... | Copies the element at path_to_copy in from_element and uses it to create or update
the first element found at the same location (path_to_copy) in to_element.
If path_to_copy is not provided, from_element is copied to the root of to_element. |
def get_element_tree(parent_to_parse):
if isinstance(parent_to_parse, ElementTree):
return parent_to_parse
element = get_element(parent_to_parse)
return ElementTree() if element is None else ElementTree(element) | :return: an ElementTree initialized with the parsed element.
:see: get_element(parent_to_parse, element_path) |
def get_element(parent_to_parse, element_path=None):
if parent_to_parse is None:
return None
elif isinstance(parent_to_parse, ElementTree):
parent_to_parse = parent_to_parse.getroot()
elif hasattr(parent_to_parse, 'read'):
parent_to_parse = string_to_element(parent_to_parse.r... | :return: an element from the parent or parsed from a Dictionary, XML string
or file. If element_path is not provided the root element is returned. |
def get_remote_element(url, element_path=None):
content = None
if url is None:
return content
elif _FILE_LOCATION_REGEX.match(url):
with open(url, 'rb') as xml:
content = xml.read()
else:
try:
urllib = getattr(six_moves, 'urllib')
remote... | :return: an element initialized with the content at the specified file or URL
:see: get_element(parent_to_parse, element_path) |
def elements_exist(elem_to_parse, element_paths=None, all_exist=False):
element = get_element(elem_to_parse)
if element is None:
return False
if not element_paths or isinstance(element_paths, string_types):
return element_exists(element, element_paths)
exists = False
for el... | :return: true if any of the named elements exist in the parent by default,
unless all_exist is true, in which case all the named elements must exist |
def element_is_empty(elem_to_parse, element_path=None):
element = get_element(elem_to_parse, element_path)
if element is None:
return True
is_empty = (
(element.text is None or not element.text.strip()) and
(element.tail is None or not element.tail.strip()) and
(eleme... | Returns true if the element is None, or has no text, tail, children or attributes.
Whitespace in the element is stripped from text and tail before making the determination. |
def insert_element(elem_to_parse, elem_idx, elem_path, elem_txt=u'', **attrib_kwargs):
element = get_element(elem_to_parse)
if element is None or not elem_path:
return None
if not elem_idx:
elem_idx = 0
if elem_path and XPATH_DELIM in elem_path:
tags = elem_path.split(XP... | Creates an element named after elem_path, containing elem_txt, with kwargs
as attributes, inserts it into elem_to_parse at elem_idx and returns it.
If elem_path is an XPATH pointing to a non-existent element, elements not
in the path are inserted and the text and index are applied to the last one.
If ... |
def remove_element(parent_to_parse, element_path, clear_empty=False):
element = get_element(parent_to_parse)
removed = []
if element is None or not element_path:
return None
if element_exists(element, element_path):
if XPATH_DELIM not in element_path:
for subelem in g... | Searches for a sub-element named after element_name in the parsed element,
and if it exists, removes them all and returns them as a list.
If clear_empty is True, removes empty parents if all children are removed.
:see: remove_empty_element(parent_to_parse, element_path, target_element=None)
:see: get_el... |
def remove_elements(parent_to_parse, element_paths, clear_empty=False):
element = get_element(parent_to_parse)
removed = []
if element is None or not element_paths:
return removed
if isinstance(element_paths, string_types):
rem = remove_element(element, element_paths, clear_empty... | Removes all elements named after each elements_or_paths. If clear_empty is True,
for each XPATH, empty parents are removed if all their children are removed.
:see: remove_element(parent_to_parse, element_path) |
def remove_empty_element(parent_to_parse, element_path, target_element=None):
element = get_element(parent_to_parse)
removed = []
if element is None or not element_path:
return removed
if target_element:
# Always deal with just the element path
if not element_path.endswi... | Searches for all empty sub-elements named after element_name in the parsed element,
and if it exists, removes them all and returns them as a list. |
def get_elements(parent_to_parse, element_path):
element = get_element(parent_to_parse)
if element is None or not element_path:
return []
return element.findall(element_path) | :return: all elements by name from the parsed parent element.
:see: get_element(parent_to_parse, element_path) |
def get_element_attribute(elem_to_parse, attrib_name, default_value=u''):
element = get_element(elem_to_parse)
if element is None:
return default_value
return element.attrib.get(attrib_name, default_value) | :return: an attribute from the parsed element if it has the attribute,
otherwise the default value |
def get_element_attributes(parent_to_parse, element_path=None):
element = get_element(parent_to_parse, element_path)
return {} if element is None else element.attrib | :return: all the attributes for the parsed element if it has any, or an empty dict |
def set_element_attributes(elem_to_parse, **attrib_kwargs):
element = get_element(elem_to_parse)
if element is None:
return element
if len(attrib_kwargs):
element.attrib.update(attrib_kwargs)
return element.attrib | Adds the specified key/value pairs to the element's attributes, and
returns the updated set of attributes.
If the element already contains any of the attributes specified in
attrib_kwargs, they are updated accordingly. |
def remove_element_attributes(elem_to_parse, *args):
element = get_element(elem_to_parse)
if element is None:
return element
if len(args):
attribs = element.attrib
return {key: attribs.pop(key) for key in args if key in attribs}
return {} | Removes the specified keys from the element's attributes, and
returns a dict containing the attributes that have been removed. |
def get_element_tail(parent_to_parse, element_path=None, default_value=u''):
parent_element = get_element(parent_to_parse, element_path)
if parent_element is None:
return default_value
if parent_element.tail:
return parent_element.tail.strip() or default_value
return default_val... | :return: text following the parsed parent element if it exists,
otherwise the default value.
:see: get_element(parent_to_parse, element_path) |
def get_element_text(parent_to_parse, element_path=None, default_value=u''):
parent_element = get_element(parent_to_parse, element_path)
if parent_element is None:
return default_value
if parent_element.text:
return parent_element.text.strip() or default_value
return default_val... | :return: text from the parsed parent element if it has a text value,
otherwise the default value.
:see: get_element(parent_to_parse, element_path) |
def get_elements_attributes(parent_to_parse, element_path=None, attrib_name=None):
attrs = _get_elements_property(parent_to_parse, element_path, 'attrib')
if not attrib_name:
return attrs
return [attr[attrib_name] for attr in attrs if attrib_name in attr] | :return: list of text representing an attribute of parent or each element at element path,
or a list of dicts representing all the attributes parsed from each element |
def _get_elements_property(parent_to_parse, element_path, prop_name):
parent_element = get_element(parent_to_parse)
if parent_element is None:
return []
if element_path and not element_exists(parent_element, element_path):
return []
if not element_path:
texts = getattr(p... | A helper to construct a list of values from |
def set_element_tail(parent_to_parse, element_path=None, element_tail=u''):
return _set_element_property(parent_to_parse, element_path, _ELEM_TAIL, element_tail) | Assigns the text following the parsed parent element and then returns it.
If element_path is provided and doesn't exist, it is inserted with element_tail.
:see: get_element(parent_to_parse, element_path) |
def set_element_text(parent_to_parse, element_path=None, element_text=u''):
return _set_element_property(parent_to_parse, element_path, _ELEM_TEXT, element_text) | Assigns a string value to the parsed parent element and then returns it.
If element_path is provided and doesn't exist, it is inserted with element_text.
:see: get_element(parent_to_parse, element_path) |
def _set_element_property(parent_to_parse, element_path, prop_name, value):
element = get_element(parent_to_parse)
if element is None:
return None
if element_path and not element_exists(element, element_path):
element = insert_element(element, 0, element_path)
if not isinstance(... | Assigns the value to the parsed parent element and then returns it |
def set_elements_tail(parent_to_parse, element_path=None, tail_values=None):
if tail_values is None:
tail_values = []
return _set_elements_property(parent_to_parse, element_path, _ELEM_TAIL, tail_values) | Assigns an array of tail values to each of the elements parsed from the parent. The
tail values are assigned in the same order they are provided.
If there are less values then elements, the remaining elements are skipped; but if
there are more, new elements will be inserted for each with the remaining tail ... |
def set_elements_text(parent_to_parse, element_path=None, text_values=None):
if text_values is None:
text_values = []
return _set_elements_property(parent_to_parse, element_path, _ELEM_TEXT, text_values) | Assigns an array of text values to each of the elements parsed from the parent. The
text values are assigned in the same order they are provided.
If there are less values then elements, the remaining elements are skipped; but if
there are more, new elements will be inserted for each with the remaining text ... |
def _set_elements_property(parent_to_parse, element_path, prop_name, values):
element = get_element(parent_to_parse)
if element is None or not values:
return []
if isinstance(values, string_types):
values = [values]
if not element_path:
return [_set_element_property(elem... | Assigns an array of string values to each of the elements parsed from the parent.
The values must be strings, and they are assigned in the same order they are provided.
The operation stops when values run out; extra values will be inserted as new elements.
:see: get_element(parent_to_parse, element_path) |
def dict_to_element(element_as_dict):
if element_as_dict is None:
return None
elif isinstance(element_as_dict, ElementTree):
return element_as_dict.getroot()
elif isinstance(element_as_dict, ElementType):
return element_as_dict
elif not isinstance(element_as_dict, dict):
... | Converts a Dictionary object to an element. The Dictionary can
include any of the following tags, only name is required:
- name (required): the name of the element tag
- text: the text contained by element
- tail: text immediately following the element
- attributes: a Dictionary cont... |
def element_to_dict(elem_to_parse, element_path=None, recurse=True):
element = get_element(elem_to_parse, element_path)
if element is not None:
converted = {
_ELEM_NAME: element.tag,
_ELEM_TEXT: element.text,
_ELEM_TAIL: element.tail,
_ELEM_ATTRIBS:... | :return: an element losslessly as a dictionary. If recurse is True,
the element's children are included, otherwise they are omitted.
The resulting Dictionary will have the following attributes:
- name: the name of the element tag
- text: the text contained by element
- tail: text immedi... |
def element_to_object(elem_to_parse, element_path=None):
if isinstance(elem_to_parse, STRING_TYPES) or hasattr(elem_to_parse, 'read'):
# Always strip namespaces if not already parsed
elem_to_parse = strip_namespaces(elem_to_parse)
if element_path is not None:
elem_to_parse = get_e... | :return: the root key, and a dict with all the XML data, but without preserving structure, for instance:
<elem val="attribute"><val>nested text</val><val prop="attr">nested dict text</val>nested dict tail</elem>
{'elem': {
'val': [
u'nested text',
{'prop': u'attr', 'value': [u'n... |
def element_to_string(element, include_declaration=True, encoding=DEFAULT_ENCODING, method='xml'):
if isinstance(element, ElementTree):
element = element.getroot()
elif not isinstance(element, ElementType):
element = get_element(element)
if element is None:
return u''
ele... | :return: the string value of the element or element tree |
def string_to_element(element_as_string, include_namespaces=False):
if element_as_string is None:
return None
elif isinstance(element_as_string, ElementTree):
return element_as_string.getroot()
elif isinstance(element_as_string, ElementType):
return element_as_string
else:
... | :return: an element parsed from a string value, or the element as is if already parsed |
def iter_elements(element_function, parent_to_parse, **kwargs):
parent = get_element(parent_to_parse)
if not hasattr(element_function, '__call__'):
return parent
for child in ([] if parent is None else parent):
element_function(child, **kwargs)
return parent | Applies element_function to each of the sub-elements in parent_to_parse.
The passed in function must take at least one element, and an optional
list of kwargs which are relevant to each of the elements in the list:
def elem_func(each_elem, **kwargs) |
def iterparse_elements(element_function, file_or_path, **kwargs):
if not hasattr(element_function, '__call__'):
return
file_path = getattr(file_or_path, 'name', file_or_path)
context = iter(iterparse(file_path, events=('start', 'end')))
root = None # Capture root for Memory management
... | Applies element_function to each of the sub-elements in the XML file.
The passed in function must take at least one element, and an optional
list of **kwarg which are relevant to each of the elements in the list:
def elem_func(each_elem, **kwargs)
Implements the recommended cElementTree iterparse p... |
def strip_namespaces(file_or_xml):
xml_content = _xml_content_to_string(file_or_xml)
if not isinstance(xml_content, string_types):
return xml_content
# This pattern can have overlapping matches, necessitating the loop
while _NAMESPACES_FROM_DEC_REGEX.search(xml_content) is not None:
... | Removes all namespaces from the XML file or string passed in.
If file_or_xml is not a file or string, it is returned as is. |
def strip_xml_declaration(file_or_xml):
xml_content = _xml_content_to_string(file_or_xml)
if not isinstance(xml_content, string_types):
return xml_content
# For Python 2 compliance: replacement string must not specify unicode u''
return _XML_DECLARATION_REGEX.sub(r'', xml_content, 1) | Removes XML declaration line from file or string passed in.
If file_or_xml is not a file or string, it is returned as is. |
def write_element(elem_to_parse, file_or_path, encoding=DEFAULT_ENCODING):
xml_header = '<?xml version="1.0" encoding="{0}"?>'.format(encoding)
get_element_tree(elem_to_parse).write(file_or_path, encoding, xml_header) | Writes the contents of the parsed element to file_or_path
:see: get_element(parent_to_parse, element_path) |
def floating_point_to_datetime(day, fp_time):
result = datetime(year=day.year, month=day.month, day=day.day)
result += timedelta(minutes=math.ceil(60 * fp_time))
return result | Convert a floating point time to a datetime. |
def _make_fn_text(self):
if not self._f:
text = "(not loaded)"
elif self._f.filename:
text = os.path.relpath(self._f.filename, ".")
else:
text = "(filename not set)"
return text | Makes filename text |
def format_BLB():
rc("figure", facecolor="white")
rc('font', family = 'serif', size=10) #, serif = 'cmr10')
rc('xtick', labelsize=10)
rc('ytick', labelsize=10)
rc('axes', linewidth=1)
rc('xtick.major', size=4, width=1)
rc('xtick.minor', size=2, width=1)
rc('ytick.major', si... | Sets some formatting options in Matplotlib. |
def set_figure_size(fig, width, height):
dpi = float(fig.get_dpi())
fig.set_size_inches(float(width) / dpi, float(height) / dpi) | Sets MatPlotLib figure width and height in pixels
Reference: https://github.com/matplotlib/matplotlib/issues/2305/ |
def create_zip_codes_geo_zone(cls, zip_codes_geo_zone, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._create_zip_codes_geo_zone_with_http_info(zip_codes_geo_zone, **kwargs)
else:
(data) = cls._create_zip_codes_geo_zone_with... | Create ZipCodesGeoZone
Create a new ZipCodesGeoZone
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_zip_codes_geo_zone(zip_codes_geo_zone, async=True)
>>> result = thread.get()
... |
def delete_zip_codes_geo_zone_by_id(cls, zip_codes_geo_zone_id, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._delete_zip_codes_geo_zone_by_id_with_http_info(zip_codes_geo_zone_id, **kwargs)
else:
(data) = cls._delete_zip_c... | Delete ZipCodesGeoZone
Delete an instance of ZipCodesGeoZone by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_zip_codes_geo_zone_by_id(zip_codes_geo_zone_id, async=True)
>>> r... |
def get_zip_codes_geo_zone_by_id(cls, zip_codes_geo_zone_id, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._get_zip_codes_geo_zone_by_id_with_http_info(zip_codes_geo_zone_id, **kwargs)
else:
(data) = cls._get_zip_codes_geo_... | Find ZipCodesGeoZone
Return single instance of ZipCodesGeoZone by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_zip_codes_geo_zone_by_id(zip_codes_geo_zone_id, async=True)
>>> re... |
def list_all_zip_codes_geo_zones(cls, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._list_all_zip_codes_geo_zones_with_http_info(**kwargs)
else:
(data) = cls._list_all_zip_codes_geo_zones_with_http_info(**kwargs)
... | List ZipCodesGeoZones
Return a list of ZipCodesGeoZones
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_zip_codes_geo_zones(async=True)
>>> result = thread.get()
:param async... |
def replace_zip_codes_geo_zone_by_id(cls, zip_codes_geo_zone_id, zip_codes_geo_zone, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._replace_zip_codes_geo_zone_by_id_with_http_info(zip_codes_geo_zone_id, zip_codes_geo_zone, **kwargs)
el... | Replace ZipCodesGeoZone
Replace all attributes of ZipCodesGeoZone
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.replace_zip_codes_geo_zone_by_id(zip_codes_geo_zone_id, zip_codes_geo_zone, async=True... |
def update_zip_codes_geo_zone_by_id(cls, zip_codes_geo_zone_id, zip_codes_geo_zone, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._update_zip_codes_geo_zone_by_id_with_http_info(zip_codes_geo_zone_id, zip_codes_geo_zone, **kwargs)
else... | Update ZipCodesGeoZone
Update attributes of ZipCodesGeoZone
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_zip_codes_geo_zone_by_id(zip_codes_geo_zone_id, zip_codes_geo_zone, async=True)
... |
def get_declared_fields(bases, attrs):
def is_field(prop):
return isinstance(prop, forms.Field) or \
isinstance(prop, BaseRepresentation)
fields = [(field_name, attrs.pop(field_name)) for field_name, obj in attrs.items() if is_field(obj)]
# add fields from base classes:
for ba... | Find all fields and return them as a dictionary.
note:: this function is copied and modified
from django.forms.get_declared_fields |
def validate(self, data=None):
errors = {}
data = self._getData(data)
# validate each field, one by one
for name, field in self.fields.items():
try:
field.clean(data.get(name))
except ValidationError, e:
errors[name] = e... | Validate the data
Check also that no extra properties are present.
:raises: ValidationError if the data is not valid. |
def _getData(self, data):
if not isinstance(data, dict):
raise ValidationError(
'data is not a valid dictionary: %s' % (str(type(data)),))
return data | Check that data is acceptable and return it.
Default behavior is that the data has to be of type `dict`. In derived
classes this method could for example allow `None` or empty strings and
just return empty dictionary.
:raises: ``ValidationError`` if data is missing or wrong type
... |
def lambda_handler(event, context):
users = boto3.resource("dynamodb").Table(os.environ['people'])
auth = check_auth(event, role=["admin"])
if not auth['success']:
return auth
user_email = event.get('user_email', None)
if not user_email:
msg = "Missing user_email parameter in yo... | Main handler. |
def get_connection(self, internal=False):
# Determine the connection string to use.
connect_string = self.connect_string
if internal:
connect_string = self.internal_connect_string
# Stripe Redis protocol prefix coming from the API.
connect_string = connect_s... | Get a live connection to this instance.
:param bool internal: Whether or not to use a DC internal network connection.
:rtype: :py:class:`redis.client.StrictRedis` |
def get_cached(self, path, cache_name, **kwargs):
if gw2api.cache_dir and gw2api.cache_time and cache_name:
cache_file = os.path.join(gw2api.cache_dir, cache_name)
if mtime(cache_file) >= time.time() - gw2api.cache_time:
with open(cache_file, "r") as fp:
... | Request a resource form the API, first checking if there is a cached
response available. Returns the parsed JSON data. |
def main():
for text in [
"how are you",
"ip address",
"restart",
"run command",
"rain EGPF",
"reverse SSH"
]:
print("\nparse text: " + text + "\nWait 3 seconds, then parse.")
time.sleep(3)
response = megaparsex.multiparse(
... | Loop over a list of input text strings. Parse each string using a list of
parsers, one included in megaparsex and one defined in this script. If a
confirmation is requested, seek confirmation, otherwise display any response
text and engage any triggered functions. |
def get_packet_id(self, packet):
for p in self._packets:
if isinstance(packet, p['cls']):
return p['id']
return None | Returns the ID of a protocol buffer packet. Returns None
if no ID was found. |
def main(*args):
args = args or sys.argv[1:]
params = PARSER.parse_args(args)
from .log import setup_logging
setup_logging(params.level.upper())
from .core import Starter
starter = Starter(params)
if not starter.params.TEMPLATES or starter.params.list:
setup_logging('WARN')
... | Enter point. |
def timed_pipe(generator, seconds=3):
''' This is a time limited pipeline. If you have a infinite pipeline and
want it to stop yielding after a certain amount of time, use this! '''
# grab the highest precision timer
# when it started
start = ts()
# when it will stop
end = start + second... | This is a time limited pipeline. If you have a infinite pipeline and
want it to stop yielding after a certain amount of time, use this! |
def destruct(particles, index):
mat = np.zeros((2**particles, 2**particles))
flipper = 2**index
for i in range(2**particles):
ispin = btest(i, index)
if ispin == 1:
mat[i ^ flipper, i] = phase(i, index)
return csr_matrix(mat) | Fermion annihilation operator in matrix representation for a indexed
particle in a bounded N-particles fermion fock space |
def on(self):
isOK = True
try:
if self.channelR!=None:
sub.call(["gpio", "-g", "mode", "{}".format(self.channelR), self.PIN_MODE_AUDIO ])
except:
isOK = False
print("Open audio right channel failed.")
try:
if self.... | !
\~english
Open Audio output. set pin mode to ALT0
@return a boolean value. if True means open audio output is OK otherwise failed to open.
\~chinese
打开音频输出。 将引脚模式设置为ALT0
@return 布尔值。 如果 True 表示打开音频输出成功,否则不成功。 |
def off(self):
isOK = True
try:
if self.channelR!=None:
sub.call(["gpio","-g","mode", "{}".format(self.channelR), self.PIN_MODE_OUTPUT ])
except:
isOK = False
print("Close audio right channel failed.")
try:
if self... | !
\~english
Close Audio output. set pin mode to output
@return a boolean value. if True means close audio output is OK otherwise failed to close.
\~chinese
关闭音频输出。 将引脚模式设置为输出
@return 布尔值。 如果为 True 关闭音频输出成功,否则关闭不成功。 |
def parse_database_url(url):
if url == 'sqlite://:memory:':
# this is a special case, because if we pass this URL into
# urlparse, urlparse will choke trying to interpret "memory"
# as a port number
return {
'ENGINE': DATABASE_SCHEMES['sqlite'],
'NAME': ... | Parses a database URL. |
def config(name='DATABASE_URL', default='sqlite://:memory:'):
config = {}
s = env(name, default)
if s:
config = parse_database_url(s)
return config | Returns configured DATABASE dictionary from DATABASE_URL. |
def json_unicode_to_utf8(data):
if isinstance(data, unicode):
return data.encode('utf-8')
elif isinstance(data, dict):
newdict = {}
for key in data:
newdict[json_unicode_to_utf8(
key)] = json_unicode_to_utf8(data[key])
return newdict
elif isin... | Change all strings in a JSON structure to UTF-8. |
def json_decode_file(filename):
seq = open(filename).read()
# The JSON standard has no comments syntax. We have to remove them
# before feeding python's JSON parser
seq = json_remove_comments(seq)
# Parse all the unicode stuff to utf-8
return json_unicode_to_utf8(json.loads(seq)) | Parses a textfile using json to build a python object representation |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.