Convert an internal dictionary (not JSON!) into an Element.

    Whatever Element implementation we could import will be
    used by default; if you want to use something else, pass the
    Element class as the factory parameter.
555120
def internal_to_elem(pfsh, factory=ET.Element):

    

    attribs = {}
    text = None
    tail = None
    sublist = []
    tag = list(pfsh.keys())
    if len(tag) != 1:
        raise ValueError("Illegal structure with multiple tags: %s" % tag)
    tag = tag[0]
    value = pfsh[tag]
    if isinstance(value, dict):
        for k, v in list(value.items()):
            if k[:1] == "@":
                attribs[k[1:]] = v
            elif k == "#text":
                text = v
            elif k == "#tail":
                tail = v
            elif isinstance(v, list):
                for v2 in v:
                    sublist.append(internal_to_elem({k: v2}, factory=factory))
            else:
                sublist.append(internal_to_elem({k: v}, factory=factory))
    else:
        text = value
    e = factory(tag, attribs)
    for sub in sublist:
        e.append(sub)
    e.text = text
    e.tail = tail
    return e
617043
def element_as_json(name):
    
    if name:
        element = fetch_json_by_name(name)
        if element.json:
            return element.json
88601
def _xml_to_dict(self, element):
        
        return_dict = {}
        for el in element:
            return_dict[el.tag] = None
            children = el.getchildren()
            if children:
                return_dict[el.tag] = self._xml_to_dict(children)
            else:
                return_dict[el.tag] = el.text
        return return_dict
62154
def insert_element_to_dict_of_dicts(dict_of_dicts: Dict[str, Dict[str, str]], first_key: str, second_key: str, contents):
    

    if first_key not in dict_of_dicts.keys():
        dict_of_dicts[first_key] = {second_key: contents}
    else:
        if second_key not in dict_of_dicts[first_key].keys():
            dict_of_dicts[first_key][second_key] = contents
        else:
            warn('Overriding contents for ' + first_key + '/' + second_key)
            dict_of_dicts[first_key][second_key] = contents
649644
def create_element(tag: str, name: str = None, base: type = None,
                   attr: dict = None) -> Node:
    
    from wdom.web_node import WdomElement
    from wdom.tag import Tag
    from wdom.window import customElements
    if attr is None:
        attr = {}
    if name:
        base_class = customElements.get((name, tag))
    else:
        base_class = customElements.get((tag, None))
    if base_class is None:
        attr['_registered'] = False
        base_class = base or WdomElement
    if issubclass(base_class, Tag):
        return base_class(**attr)
    return base_class(tag, **attr)
513666
def append(self, element):
        
        if is_valid_type(element, Element):
            self._class_collection_map[element.__class__].setdefault(element.id, element)
966316
def instantiate_from_dict(self, values):
        

        name = values['ENGINE']
        options = values.get('OPTIONS', {})

        # Parse the name
        parts = name.split('.')
        module_name = '.'.join(parts[:-1])
        class_name = parts[-1]

        # Get the class
        try:
            module = import_module(module_name)
            cls = getattr(module, class_name)
        except (ValueError, AttributeError, TypeError, ImportError):
            raise ValueError('Cannot find class %s' % name)

        options = self.instantiate_objects(options)

        return cls(**options)
1195160
def from_dict(cls, tag=None):
        

        if tag is None:
            tag = {}

        l = Tag()
        l.name = tag['name']
        return l
502689
def to_internal_value(self, data):
        
        if html.is_html_input(data):
            data = html.parse_html_list(data)
        if isinstance(data, type('')) or isinstance(data, collections.Mapping) or not hasattr(data, '__iter__'):
            self.fail('not_a_list', input_type=type(data).__name__)
        if not self.allow_empty and len(data) == 0:
            self.fail('empty')
        return [self.child.run_validation(item) for item in data]
1330658
def _from_dict(cls, _dict):
        """"""
        args = {}
        if 'model_id' in _dict:
            args['model_id'] = _dict.get('model_id')
        if 'model_version' in _dict:
            args['model_version'] = _dict.get('model_version')
        if 'documents' in _dict:
            args['documents'] = [
                Document._from_dict(x) for x in (_dict.get('documents'))
            ]
        if 'aligned_elements' in _dict:
            args['aligned_elements'] = [
                AlignedElement._from_dict(x)
                for x in (_dict.get('aligned_elements'))
            ]
        if 'unaligned_elements' in _dict:
            args['unaligned_elements'] = [
                UnalignedElement._from_dict(x)
                for x in (_dict.get('unaligned_elements'))
            ]
        return cls(**args)
978349
def _elementtree_to_dict(self, element):
        
        node = {}
        text = getattr(element, 'text')
        if text is not None:
            text = text.strip()
            if len(text) != 0:
                node['text'] = text
        node.update(element.items())  # element's attributes
        child_nodes = {}
        for child in element:  # element's children
            child_nodes.setdefault(child.tag, []).append(
                self._elementtree_to_dict(child))
        # convert all single-element lists into non-lists
        for key, value in child_nodes.items():
            if len(value) == 1:
                child_nodes[key] = value[0]
        node.update(child_nodes.items())
        return node
742640
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))
635590
def from_dict(cls, D, is_json=False):
        '''

        '''
        instance = cls()
        instance.set_data(D, is_json=is_json)
        return instance
256701
def parse_data_to_internal(self, include_custom=False):
        
        for element in self.data:
            self.data[element].parse_data_to_internal()
        if include_custom:
            for element in self.custom_data:
                self.custom_data[element].parse_data_to_internal()
337093
def insert_element_to_dict_of_dicts_of_list(dict_of_dict_of_list, first_key, second_key, parser):
    
    list_to_insert = parser if isinstance(parser, list) else [parser]

    if first_key not in dict_of_dict_of_list.keys():
        dict_of_dict_of_list[first_key] = {second_key: list_to_insert}
    else:
        if second_key not in dict_of_dict_of_list[first_key].keys():
            dict_of_dict_of_list[first_key][second_key] = list_to_insert
        else:
            dict_of_dict_of_list[first_key][second_key] += list_to_insert
570181
def create_elements(self, method, args=[]):
        
        args = encode_args(args)

        js = """
            create_elements(ELEMENTS, %(method)s(%(args)s))
        """ % {
            'method': method,
            'args': args,
        }

        indexes = self.json(js)
        return map(Element, indexes)
409038
def create_from_dict(self, dictionary):
        
        # Defaults
        args = []
        kwargs = {}
        factory_method = None
        factory_args = []
        factory_kwargs = {}
        static = False
        calls = None

        # Check dictionary for arguments
        if 'args' in dictionary:
            args = dictionary['args']

        if 'kwargs' in dictionary:
            kwargs = dictionary['kwargs']

        if 'factory-method' in dictionary:
            factory_method = dictionary['factory-method']

        if 'factory-args' in dictionary:
            factory_args = dictionary['factory-args']

        if 'factory-kwargs' in dictionary:
            factory_kwargs = dictionary['factory-kwargs']

        if 'static' in dictionary:
            static = dictionary['static']

        if 'calls' in dictionary:
            calls = dictionary['calls']

        return self.create(
            dictionary['module'],
            dictionary['class'],
            args=args,
            kwargs=kwargs,
            factory_method=factory_method,
            factory_args=factory_args,
            factory_kwargs=factory_kwargs,
            static=static,
            calls=calls
        )