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) return data
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 bool :param str state_id: ID of state to delete. (required) :return: None If the method is called asynchronously, returns the request thread.
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 data
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 :param str state_id: ID of state to return (required) :return: State If the method is called asynchronously, returns the request thread.
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: page number :param int size: page size :param str sort: page order :return: page[State] If the method is called asynchronously, returns the request thread.
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, state, **kwargs) return data
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 bool :param str state_id: ID of state to replace (required) :param State state: Attributes of state to replace (required) :return: State If the method is called asynchronously, returns the request thread.
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, **kwargs) return data
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 :param str state_id: ID of state to update. (required) :param State state: Attributes of state to update. (required) :return: State If the method is called asynchronously, returns the request thread.
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( key, self.parser.default[key]) if _compat.PY2: value = raw_input(prompt.encode('utf-8')).decode('utf-8') else: value = input(prompt.encode('utf-8')) value = value.strip() if value: self.parser.default[key] = value self.parser.default['templates'] = tt = ','.join( t.name for t in templates) logging.warning("Paste templates: {0}".format(tt)) self.make_directory(self.params.TARGET) logging.debug("\nDefault context:\n----------------") logging.debug( ''.join('{0:<15} {1}\n'.format(*v) for v in self.parser.default.items()) ) return [t.paste( **dict(self.parser.default.items())) for t in templates]
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: f.write(body) f.close() j += 1 except Exception, e: log.error( "could not write downloaded file to local drive - failed with this error %s: " % (str(e),)) return -1 return
*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.video_source_process.pid) self.video_source_process = Nonf 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.video_source_process.pid) self.video_source_process = None
.. 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.execute(self.plugin.hub_name, 'ping', timeout_s=1, silent=True) except IOError: self.on_heartbeat_error() else: self.heartbeat_alive_timestamp = datetime.now() logger.debug('Hub connection alive as of %s', self.heartbeat_alive_timestamp) return Truf 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.execute(self.plugin.hub_name, 'ping', timeout_s=1, silent=True) except IOError: self.on_heartbeat_error() else: self.heartbeat_alive_timestamp = datetime.now() logger.debug('Hub connection alive as of %s', self.heartbeat_alive_timestamp) return True
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 .electrode_states) self.on_electrode_states_set(statesf 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 .electrode_states) self.on_electrode_states_set(states)
.. 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 = states['electrode_states'] surface = self.canvas_slave.render_static_electrode_state_shapes() self.canvas_slave.set_surface('static_electrode_state_shapes', surface) self.canvas_slave.cairo_surface = flatten_surfaces(self.canvas_slave .df_surfaces) gobject.idle_add(self.canvas_slave.drawf 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 = states['electrode_states'] surface = self.canvas_slave.render_static_electrode_state_shapes() self.canvas_slave.set_surface('static_electrode_state_shapes', surface) self.canvas_slave.cairo_surface = flatten_surfaces(self.canvas_slave .df_surfaces) gobject.idle_add(self.canvas_slave.draw)
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_shapes() self.canvas_slave.set_surface('dynamic_electrode_state_shapes', surface) self.canvas_slave.cairo_surface = flatten_surfaces(self.canvas_slave .df_surfaces) gobject.idle_add(self.canvas_slave.drawf 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_shapes() self.canvas_slave.set_surface('dynamic_electrode_state_shapes', surface) self.canvas_slave.cairo_surface = flatten_surfaces(self.canvas_slave .df_surfaces) gobject.idle_add(self.canvas_slave.draw)
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 .df_surfaces) gtk.idle_add(self.canvas_slave.drawf 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 .df_surfaces) gtk.idle_add(self.canvas_slave.draw)
.. 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) # Decode content to raise error, if necessary. try: decode_content_data(reply) except Exception: _L().error('Global command error.', exc_info=True) self.plugin.execute_async(group, command, callback=command_callbackf 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) # Decode content to raise error, if necessary. try: decode_content_data(reply) except Exception: _L().error('Global command error.', exc_info=True) self.plugin.execute_async(group, command, callback=command_callback)
.. 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 file callar = inspect.getouterframes(inspect.currentframe())[-1][1] # get version info from distribution try: di = get_distribution(name) installed_directory = os.path.join(di.location, name) if not callar.startswith(installed_directory) and not allow_ambiguous: # not installed, but there is another version that *is* raise DistributionNotFound except DistributionNotFound: return default else: return di.version
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 named application is not installed yet allow_ambiguous : boolean ``True`` for allowing ambiguous version information. Turn this argument to ``False`` if ``get_string_version`` report wrong version. Returns -------- string A version string or not found message (:attr:`default`) Examples -------- >>> import re >>> v = get_string_version('app_version', allow_ambiguous=True) >>> re.match('^\d+.\d+\.\d+', v) is not None True >>> get_string_version('distribution_which_is_not_installed') 'Please install this application with setup.py'
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, allow_ambiguous=allow_ambiguous) # convert string version to tuple version # prefer integer for easy handling if isinstance(version, tuple): # not found return version return tuple(map(_prefer_int, version.split('.')))
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 value used when the named application is not installed yet allow_ambiguous : boolean ``True`` for allowing ambiguous version information. Returns -------- string A version tuple Examples -------- >>> v = get_tuple_version('app_version', allow_ambiguous=True) >>> len(v) >= 3 True >>> isinstance(v[0], int) True >>> isinstance(v[1], int) True >>> isinstance(v[2], int) True >>> get_tuple_version('distribution_which_is_not_installed') (0, 0, 0)
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, allow_ambiguous) return version_string, version_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 A default returning value used when the named application is not installed yet default_tuple : tuple A default returning value used when the named application is not installed yet allow_ambiguous : boolean ``True`` for allowing ambiguous version information. Returns -------- tuple A version string and version tuple Examples -------- >>> import re >>> v1, v2 = get_versions('app_version', allow_ambiguous=True) >>> isinstance(v1, str) True >>> isinstance(v2, tuple) True >>> get_versions('distribution_which_is_not_installed') ('Please install this application with setup.py', (0, 0, 0))
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 NotASingleSymbolException(right) return right[0]
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 NotASingleSymbolException: If number of symbols on the left is more.
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 NotASingleSymbolException(left) return left[0]
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 NotASingleSymbolException: If number of symbols on the right is more.
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 NotASingleSymbolException: If number of symbols on the left is more.
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 NotASingleSymbolException: If number of symbols on the left is more.
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 number of symbols on the left is more.
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: If number of symbols on the left is more.
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 rule is not define', side) if EPS in side and len(side) > 1: raise UselessEpsilonException(cls) for symb in side: if isclass(symb) and issubclass(symb, Nonterminal): if symb not in grammar.nonterminals: raise NonterminalDoesNotExistsException(cls, symb, grammar) elif symb is EPS: continue elif symb not in grammar.terminals: raise TerminalDoesNotExistsException(cls, symb, grammar)
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 terminal does not exists in the grammar. :raise NonterminalDoesNotExistsException: If nonterminal does not exists in the grammar.
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 len(defined & {'left', 'right', 'toSymbol', 'fromSymbol'}) > 0 or \ 'left' in defined and 'fromSymbol' in defined or \ 'right' in defined and 'toSymbol' in defined: raise MultipleDefinitionException(cls, 'Rule is defined multiple times') # check if the rule is defined properly all = cls.rules if not isinstance(all, list): raise RuleSyntaxException(cls, 'Rules property is not enclose in list') for rule in all: if not isinstance(rule, tuple): raise RuleSyntaxException(cls, 'One of the rules is not enclose in tuple', rule) if len(rule) != 2: raise RuleSyntaxException(cls, 'One of the rules does not have define left and right part', rule) left = rule[0] right = rule[1] cls._controlSide(left, grammar) cls._controlSide(right, grammar) if left == [EPS] and right == [EPS]: raise UselessEpsilonException(cls)
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 grammar. :raise NonterminalDoesNotExistsException: If nonterminal does not exists in the grammar.
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): for k, v in dc.iteritems(): # do not add Comment instance to the key if k is not etree.Comment: dd[k].append(v) d[t.tag] = {k: v[0] if len(v) == 1 else v for k, v in dd.iteritems()} if t.attrib: d[t.tag].update(('@' + k, v) for k, v in t.attrib.iteritems()) if trim and t.text: t.text = t.text.strip() if t.text: if t.tag is etree.Comment and not kw.get('without_comments'): # adds a comments node d['#comments'] = t.text elif children or t.attrib: d[t.tag]['#text'] = t.text else: d[t.tag] = t.text return d
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: memo = set() iterator = None if isinstance(obj, Mapping): iterator = iteritems elif isinstance(obj, (Sequence, Set)) and not isinstance(obj, string_types): iterator = enumerate if iterator: if id(obj) not in memo: memo.add(id(obj)) for path_component, value in iterator(obj): for result in self.objwalk(value, path + (path_component,), memo): yield result memo.remove(id(obj)) else: yield path, obj
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 element.attrib.update(attribute_kwargs) return ElementTree(element)
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_kwargs: optional attributes to add to the root element :return: a new ElementTree with the specified root and attributes
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 element.attrib = elem_atr return element
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_element = Element(from_element.tag) else: dest_element = insert_element(Element(from_element.tag), 0, path_to_copy) dest_element.tag = from_element.tag dest_element.text = from_element.text dest_element.tail = from_element.tail dest_element.attrib = from_element.attrib copied_children = [] for elem in from_element: copied_children.append(copy_element(elem)) for idx, child in enumerate(copied_children): dest_element.insert(idx, child) return dest_element
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.read()) elif isinstance(parent_to_parse, STRING_TYPES): parent_to_parse = string_to_element(parent_to_parse) elif isinstance(parent_to_parse, dict): parent_to_parse = dict_to_element(parent_to_parse) if parent_to_parse is None: return None elif not isinstance(parent_to_parse, ElementType): element_type = type(parent_to_parse).__name__ raise TypeError('Invalid element type: {0}'.format(element_type)) return parent_to_parse.find(element_path) if element_path else parent_to_parse
: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 = urllib.request.urlopen(url) content = remote.read() finally: # For Python 2 compliance: fails in `with` block (no `__exit__`) remote.close() return get_element(strip_namespaces(content), element_path)
: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 element_path in element_paths: exists = element_exists(element, element_path) if all_exist and not exists: return False if exists and not all_exist: return True return exists
: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 (element.attrib is None or not len(element.attrib)) and (not len(element.getchildren())) ) return is_empty
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(XPATH_DELIM) if element_exists(element, elem_path): # Get the next to last element in the XPATH parent = get_element(element, XPATH_DELIM.join(tags[:-1])) # Insert the new element as sibling to the last one return insert_element(parent, elem_idx, tags[-1], elem_txt, **attrib_kwargs) else: this_elem = element last_idx = len(tags) - 1 # Iterate over tags from root to leaf for idx, tag in enumerate(tags): next_elem = get_element(this_elem, tag) # Insert missing elements in the path or continue if next_elem is None: # Apply text and index to last element only if idx == last_idx: next_elem = insert_element(this_elem, elem_idx, tag, elem_txt, **attrib_kwargs) else: next_elem = insert_element(this_elem, 0, tag, u'', **attrib_kwargs) this_elem = next_elem return this_elem subelem = Element(elem_path, attrib_kwargs) subelem.text = elem_txt element.insert(elem_idx, subelem) return subelem
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 elem_path is an XPATH pointing to an existing element, the new element is inserted as a sibling of the last one in the path at the index specified.
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 get_elements(element, element_path): removed.append(subelem) element.remove(subelem) else: xpath_segments = element_path.split(XPATH_DELIM) parent_segment = XPATH_DELIM.join(xpath_segments[:-1]) last_segment = xpath_segments[-1] for parent in get_elements(element, parent_segment): rem = remove_element(parent, last_segment) removed.extend(rem if isinstance(rem, list) else [rem]) if clear_empty: removed.extend(remove_empty_element(element, parent_segment)) return removed[0] if len(removed) == 1 else (removed or None)
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_element(parent_to_parse, element_path)
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) removed.extend(rem if isinstance(rem, list) else [rem]) else: for xpath in element_paths: rem = remove_element(element, xpath, clear_empty) removed.extend(rem if isinstance(rem, list) else [rem]) return removed
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.endswith(target_element): element_path = XPATH_DELIM.join([element_path, target_element]) target_element = None if XPATH_DELIM not in element_path: # Loop over and remove empty sub-elements directly for subelem in get_elements(element, element_path): if element_is_empty(subelem): removed.append(subelem) element.remove(subelem) else: # Parse target element from last node in element path xpath_segments = element_path.split(XPATH_DELIM) element_path = XPATH_DELIM.join(xpath_segments[:-1]) target_element = xpath_segments[-1] # Loop over children and remove empty ones directly for parent in get_elements(element, element_path): for child in get_elements(parent, target_element): if element_is_empty(child): removed.append(child) parent.remove(child) # Parent may be empty now: recursively remove empty elements in XPATH if element_is_empty(parent): if len(xpath_segments) == 2: removed.extend(remove_empty_element(element, xpath_segments[0])) else: next_element_path = XPATH_DELIM.join(xpath_segments[:-2]) next_target_element = parent.tag removed.extend(remove_empty_element(element, next_element_path, next_target_element)) return removed
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_value
: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_value
: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(parent_element, prop_name) texts = texts.strip() if isinstance(texts, string_types) else texts texts = [texts] if texts else [] else: texts = [t for t in ( prop.strip() if isinstance(prop, string_types) else prop for prop in (getattr(node, prop_name) for node in parent_element.findall(element_path)) if prop ) if t] return texts
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(value, string_types): value = u'' setattr(element, prop_name, value) return element
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 values.
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 values.
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(element, None, prop_name, values[0])] elements = get_elements(element, element_path) affected = [] for idx, val in enumerate(values): if idx < len(elements): next_elem = elements[idx] else: next_elem = insert_element(element, idx, element_path) affected.append( _set_element_property(next_elem, None, prop_name, val) ) return affected
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): raise TypeError('Invalid element dict: {0}'.format(element_as_dict)) if len(element_as_dict) == 0: return None try: converted = Element( element_as_dict[_ELEM_NAME], element_as_dict.get(_ELEM_ATTRIBS, {}) ) converted.tail = element_as_dict.get(_ELEM_TAIL, u'') converted.text = element_as_dict.get(_ELEM_TEXT, u'') for child in element_as_dict.get(_ELEM_CHILDREN, []): converted.append(dict_to_element(child)) except KeyError: raise SyntaxError('Invalid element dict: {0}'.format(element_as_dict)) return converted
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 containing element attributes - children: a List of converted child elements
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: element.attrib, _ELEM_CHILDREN: [] } if recurse is True: for child in element: converted[_ELEM_CHILDREN].append(element_to_dict(child, recurse=recurse)) return converted return {}
: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 immediately following the element - attributes: a Dictionary containing element attributes - children: a List of converted child elements
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_element(elem_to_parse, element_path) element_tree = get_element_tree(elem_to_parse) element_root = element_tree.getroot() root_tag = u'' if element_root is None else element_root.tag return root_tag, {root_tag: _element_to_object(element_root)}
: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'nested dict text', u'nested dict tail']}, u'attribute' ] }}
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'' element_as_string = tostring(element, encoding, method).decode(encoding=encoding) if include_declaration: return element_as_string else: return strip_xml_declaration(element_as_string)
: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: element_as_string = _xml_content_to_string(element_as_string) if not isinstance(element_as_string, string_types): # Let cElementTree handle the error return fromstring(element_as_string) elif not strip_xml_declaration(element_as_string): # Same as ElementTree().getroot() return None elif include_namespaces: return fromstring(element_as_string) else: return fromstring(strip_namespaces(element_as_string))
: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 # Start event loads child; by the End event it's ready for processing for event, child in context: if root is None: root = child if event == 'end': # Ensures the element has been fully read element_function(child, **kwargs) root.clear()
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 pattern, which is efficient for reading in a file, making changes and writing it again.
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: xml_content = _NAMESPACES_FROM_DEC_REGEX.sub(r'\1', xml_content) # Remove namespaces at the tag level xml_content = _NAMESPACES_FROM_TAG_REGEX.sub(r'\1', xml_content) # Remove namespaces at the attribute level xml_content = _NAMESPACES_FROM_ATTR_REGEX.sub(r'\1\3', xml_content) return xml_content
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', size=4, width=1) rc('ytick.minor', size=2, width=1)
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_http_info(zip_codes_geo_zone, **kwargs) return data
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() :param async bool :param ZipCodesGeoZone zip_codes_geo_zone: Attributes of zipCodesGeoZone to create (required) :return: ZipCodesGeoZone If the method is called asynchronously, returns the request thread.
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_codes_geo_zone_by_id_with_http_info(zip_codes_geo_zone_id, **kwargs) return data
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) >>> result = thread.get() :param async bool :param str zip_codes_geo_zone_id: ID of zipCodesGeoZone to delete. (required) :return: None If the method is called asynchronously, returns the request thread.
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_zone_by_id_with_http_info(zip_codes_geo_zone_id, **kwargs) return data
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) >>> result = thread.get() :param async bool :param str zip_codes_geo_zone_id: ID of zipCodesGeoZone to return (required) :return: ZipCodesGeoZone If the method is called asynchronously, returns the request thread.
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) return data
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 bool :param int page: page number :param int size: page size :param str sort: page order :return: page[ZipCodesGeoZone] If the method is called asynchronously, returns the request thread.
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) else: (data) = cls._replace_zip_codes_geo_zone_by_id_with_http_info(zip_codes_geo_zone_id, zip_codes_geo_zone, **kwargs) return data
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) >>> result = thread.get() :param async bool :param str zip_codes_geo_zone_id: ID of zipCodesGeoZone to replace (required) :param ZipCodesGeoZone zip_codes_geo_zone: Attributes of zipCodesGeoZone to replace (required) :return: ZipCodesGeoZone If the method is called asynchronously, returns the request thread.
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: (data) = cls._update_zip_codes_geo_zone_by_id_with_http_info(zip_codes_geo_zone_id, zip_codes_geo_zone, **kwargs) return data
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) >>> result = thread.get() :param async bool :param str zip_codes_geo_zone_id: ID of zipCodesGeoZone to update. (required) :param ZipCodesGeoZone zip_codes_geo_zone: Attributes of zipCodesGeoZone to update. (required) :return: ZipCodesGeoZone If the method is called asynchronously, returns the request thread.
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 base in bases[::-1]: if hasattr(base, 'base_fields'): fields = base.base_fields.items() + fields return dict(fields)
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.messages except AttributeError, e: raise ValidationError('data should be of type dict but is %s' % (type(data),)) # check for extra fields extras = set(data.keys()) - set(self.fields.keys()) if extras: errors[', '.join(extras)] = ['field(s) not allowed'] # if errors, raise ValidationError if errors: raise ValidationError(errors)
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 :return: the data to be validated
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 your request." return {'success': False, 'message': msg} user_role = event.get('user_role', None) if not user_role: msg = "Missing user role: `admin`, `analyst`" return {'success': False, 'message': msg} user_name = event.get('user_name', '') seed = random.randint(100000000, 999999999) hash_key = "{}{}".format(user_email, seed) api_key = hashlib.sha256(hash_key).hexdigest() if auth.get('init', False): user_role = 'admin' else: user_role = user_role obj = {'email': user_email, 'name': user_name, 'api_key': api_key, 'role': user_role} response = users.put_item(Item=obj) return obj
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_string.strip('redis://') host, port = connect_string.split(':') # Build and return the redis client. return redis.StrictRedis(host=host, port=port, password=self._password)
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: tmp = json.load(fp) return self.make_response(tmp["data"], tmp["meta"]) else: cache_file = None meta, data = self._get(path, **kwargs) if cache_file: with open(cache_file, "w") as fp: json.dump({"meta": meta, "data": data}, fp, indent=2) return self.make_response(data, meta)
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( text = text, parsers = [ megaparsex.parse, parse_networking ], help_message = "Does not compute. I can report my IP address and I " "can restart my script." ) if type(response) is megaparsex.confirmation: while response.confirmed() is None: response.test( text = megaparsex.get_input( prompt = response.prompt() + " " ) ) if response.confirmed(): print(response.feedback()) response.run() else: print(response.feedback()) elif type(response) is megaparsex.command: output = response.engage_command( command = megaparsex.get_input( prompt = response.prompt() + " " ), background = False ) if output: print("output:\n{output}".format(output = output)) else: print(response)
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') for t in sorted(starter.iterate_templates()): logging.warn("%s -- %s", t.name, t.params.get( 'description', 'no description')) return True try: starter.copy() except Exception as e: # noqa logging.error(e) sys.exit(1)
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 + seconds # iterate over the pipeline for i in generator: # if there is still time if ts() < end: # yield the next item yield i # otherwise else: # stop breaf 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 + seconds # iterate over the pipeline for i in generator: # if there is still time if ts() < end: # yield the next item yield i # otherwise else: # stop break
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.channelL!=None: sub.call(["gpio","-g","mode", "{}".format(self.channelL), self.PIN_MODE_AUDIO ]) except: isOK = False print("Open audio left channel failed.") return isOK
! \~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.channelL!=None: sub.call(["gpio","-g","mode", "{}".format(self.channelL), self.PIN_MODE_OUTPUT ]) except: isOK = False print("Close audio left channel failed.") return isOK
! \~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': ':memory:' } # note: no other settings are required for sqlite # otherwise parse the url as normal config = {} url = urlparse.urlparse(url) # Remove query strings. path = url.path[1:] path = path.split('?', 2)[0] # if we are using sqlite and we have no path, then assume we # want an in-memory database (this is the behaviour of sqlalchemy) if url.scheme == 'sqlite' and path == '': path = ':memory:' # Update with environment configuration. config.update({ 'NAME': path or '', 'USER': url.username or '', 'PASSWORD': url.password or '', 'HOST': url.hostname or '', 'PORT': url.port or '', }) if url.scheme in DATABASE_SCHEMES: config['ENGINE'] = DATABASE_SCHEMES[url.scheme] return config
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 isinstance(data, list): return [json_unicode_to_utf8(elem) for elem in data] else: return data
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