convert an RST tree (DGParentedTree -> lxml etree)
559371
def gen_etree(self):
        """"""
        relations_elem = self.gen_relations()
        header = E('header')
        header.append(relations_elem)

        self.gen_body()

        tree = E('rst')
        tree.append(header)

        # The <body> contains both <segment>, as well as <group> elements.
        # While the order of the elements should theoretically be irrelevant,
        # rs3 files usually list the segments before the groups.
        body = E('body')
        for segment in self.body['segments']:
            body.append(segment)
        for group in self.body['groups']:
            body.append(group)

        tree.append(body)
        return tree
1337792
def xmllint_format(xml):
    
    parser = ET.XMLParser(resolve_entities=False, strip_cdata=False, remove_blank_text=True)
    document = ET.fromstring(xml, parser)
    return ('%s\n%s' % ('<?xml version="1.0" encoding="UTF-8"?>', ET.tostring(document, pretty_print=True).decode('utf-8'))).encode('utf-8')
1198905
def pattern_convert(grammar, raw_node_info):
    """"""
    type, value, context, children = raw_node_info
    if children or type in grammar.number2symbol:
        return pytree.Node(type, children, context=context)
    else:
        return pytree.Leaf(type, value, context=context)
469799
def __convert_node(node, default_value='', default_flags=vsflags()):
    """"""
    name = __get_attribute(node, 'Name')
    logging.debug('Found %s named %s', node.tagName, name)

    converted = {}
    converted['name'] = name
    converted['switch'] = __get_attribute(node, 'Switch')
    converted['comment'] = __get_attribute(node, 'DisplayName')
    converted['value'] = default_value

    # Check for the Flags attribute in case it was created during preprocessing
    flags = __get_attribute(node, 'Flags')

    if flags:
        flags = flags.split(',')
    else:
        flags = default_flags

    converted['flags'] = flags

    return converted
1073706
def dict_to_xml(xml_dict):
    
    import lxml.etree as etree
    root_tag = list(xml_dict.keys())[0]
    root = etree.Element(root_tag)
    _dict_to_xml_recurse(root, xml_dict[root_tag])
    return root
20623
def convert(gr, raw_node):
    
    type, value, context, children = raw_node
    if children or type in gr.number2symbol:
        # If there's exactly one child, return that child instead of
        # creating a new node.
        if len(children) == 1:
            return children[0]
        return Node(type, children, context=context)
    else:
        return Leaf(type, value, context=context)
517552
def rst(filename):
    '''
    
    '''
    content = open(filename).read()
    return re.sub(r'\.\.\s? code-block::\s*(\w|\+)+', '::', content)
600924
def node_to_truncated_gr(node, bin_width=0.1):
    
    # Parse to float dictionary
    if not all([node.attrib[key]
                for key in ["minMag", "maxMag", "aValue", "bValue"]]):
        return None
    tgr = dict((key, float_(node.attrib[key])) for key in node.attrib)
    return mfd.truncated_gr.TruncatedGRMFD(min_mag=tgr["minMag"],
                                           max_mag=tgr["maxMag"],
                                           bin_width=bin_width,
                                           a_val=tgr["aValue"],
                                           b_val=tgr["bValue"])
587597
def etree_to_string(tree):
        
        buff = BytesIO()
        tree.write(buff, xml_declaration=True, encoding='UTF-8')
        return buff.getvalue()
754848
def reverse_toctree(app, doctree, docname):
    """"""
    if docname == "changes":
        for node in doctree.traverse():
            if node.tagname == "toctree" and node.get("glob"):
                node["entries"].reverse()
                break
320453
def notebook_object_to_rst(ntbk, rpth, cr=None):
    

    # Parent directory of file rpth
    rdir = os.path.dirname(rpth)
    # File basename
    rb = os.path.basename(os.path.splitext(rpth)[0])

    # Pre-process notebook prior to conversion to rst
    if cr is not None:
        preprocess_notebook(ntbk, cr)
    # Convert notebook to rst
    rex = RSTExporter()
    rsttxt, rstres = rex.from_notebook_node(ntbk)
    # Replace `` with ` in sphinx cross-references
    rsttxt = re.sub(r':([^:]+):``(.*?)``', r':\1:`\2`', rsttxt)
    # Insert a cross-reference target at top of file
    reflbl = '.. _examples_' + os.path.basename(rdir) + '_' + \
             rb.replace('-', '_') + ':\n'
    rsttxt = reflbl + rsttxt
    # Write the converted rst to disk
    write_notebook_rst(rsttxt, rstres, rb, rdir)
1238212
def dom_lt(graph):
    """"""

    def _dfs(v, n):
        semi[v] = n = n + 1
        vertex[n] = label[v] = v
        ancestor[v] = 0
        for w in graph.all_sucs(v):
            if not semi[w]:
                parent[w] = v
                n = _dfs(w, n)
            pred[w].add(v)
        return n

    def _compress(v):
        u = ancestor[v]
        if ancestor[u]:
            _compress(u)
            if semi[label[u]] < semi[label[v]]:
                label[v] = label[u]
            ancestor[v] = ancestor[u]

    def _eval(v):
        if ancestor[v]:
            _compress(v)
            return label[v]
        return v

    def _link(v, w):
        ancestor[w] = v

    parent, ancestor, vertex = {}, {}, {}
    label, dom = {}, {}
    pred, bucket = defaultdict(set), defaultdict(set)

    # Step 1:
    semi = {v: 0 for v in graph.nodes}
    n = _dfs(graph.entry, 0)
    for i in range(n, 1, -1):
        w = vertex[i]
        # Step 2:
        for v in pred[w]:
            u = _eval(v)
            y = semi[w] = min(semi[w], semi[u])
        bucket[vertex[y]].add(w)
        pw = parent[w]
        _link(pw, w)
        # Step 3:
        bpw = bucket[pw]
        while bpw:
            v = bpw.pop()
            u = _eval(v)
            dom[v] = u if semi[u] < semi[v] else pw
    # Step 4:
    for i in range(2, n + 1):
        w = vertex[i]
        dw = dom[w]
        if dw != vertex[semi[w]]:
            dom[w] = dom[dw]
    dom[graph.entry] = None
    return dom
199291
def pformat_xml(xml):
    """"""
    try:
        from lxml import etree  # delayed import
        if not isinstance(xml, bytes):
            xml = xml.encode('utf-8')
        xml = etree.parse(io.BytesIO(xml))
        xml = etree.tostring(xml, pretty_print=True, xml_declaration=True,
                             encoding=xml.docinfo.encoding)
        xml = bytes2str(xml)
    except Exception:
        if isinstance(xml, bytes):
            xml = bytes2str(xml)
        xml = xml.replace('><', '>\n<')
    return xml.replace('  ', ' ').replace('\t', ' ')
549169
def get_node_type(dgtree):
    """"""
    if is_leaf(dgtree):
        return TreeNodeTypes.leaf_node

    root_label = dgtree.label()
    if root_label == '':
        assert dgtree == DGParentedTree('', []), \
            "The tree has no root label, but isn't empty: {}".format(dgtree)
        return TreeNodeTypes.empty_tree
    elif root_label in NUCLEARITY_LABELS:
        return TreeNodeTypes.nuclearity_node
    else:
        assert isinstance(dgtree, (RSTTree, DGParentedTree)), type(dgtree)
        return TreeNodeTypes.relation_node
1212594
def convert(self, obj):
        
        if self.pristine_if_invalid:
            raise NotImplementedError('pristine_if_invalid option is not supported yet')

        nex = get_nexml_el(obj)
        assert nex
        # Create the new objects as locals. This section should not
        #   mutate obj, so that if there is an exception the object
        #   is unchanged on the error exit
        otus = _index_list_of_values(nex, 'otus')
        o_t = self.convert_otus(otus)
        otusById, otusElementOrder = o_t
        trees = _get_index_list_of_values(nex, 'trees')
        treesById = dict((i['@id'], i) for i in trees)
        treesElementOrder = [i['@id'] for i in trees]
        if len(treesById) != len(treesElementOrder):
            trees_id_set = set()
            for tgid in treesElementOrder:
                if tgid in trees_id_set:
                    raise NexsonError('Repeated trees element id "{}"'.format(tgid))
                trees_id_set.add(tgid)
        tree_id_set = set()
        treeContainingObjByTreesId = {}
        for tree_group in trees:
            # _LOG.debug('converting tree group {} to by_id'.format(tree_group['@id']))
            treeById = {}
            treeElementOrder = []
            tree_array = _get_index_list_of_values(tree_group, 'tree')
            for tree in tree_array:
                # _LOG.debug('# pre-convert keys = {}'.format(tree.keys()))
                t_t = self.convert_tree(tree)
                if t_t is None:
                    continue
                tid, tree_alias = t_t  # pylint: disable=W0633
                if tid in tree_id_set:
                    raise NexsonError('Repeated tree element id "{}"'.format(tid))
                tree_id_set.add(tid)

                # _LOG.debug('converting tree {} to by_id'.format(tid))
                # _LOG.debug('# post-convert keys = {}'.format(tree.keys()))
                assert tree_alias is tree
                treeById[tid] = tree
                treeElementOrder.append(tid)
            treeContainingObjByTreesId[tree_group['@id']] = treeById
            tree_group['^ot:treeElementOrder'] = treeElementOrder

        # If all that succeeds, add the new object to the dict, creating a fat structure
        nex['otusById'] = otusById
        nex['^ot:otusElementOrder'] = otusElementOrder
        nex['treesById'] = treesById
        nex['^ot:treesElementOrder'] = treesElementOrder
        for k, v in treeContainingObjByTreesId.items():
            treesById[k]['treeById'] = v
        nex['@nexml2json'] = str(BY_ID_HONEY_BADGERFISH)
        # Make the struct leaner
        if self.remove_old_structs:
            del nex['otus']
            del nex['trees']
            for k, v in treesById.items():
                if 'tree' in v:
                    del v['tree']
                del v['@id']
        return obj
1022355
def _format_subtree(self, subtree):
        """"""
        subtree['children'] = list(subtree['children'].values())
        for child in subtree['children']:
            self._format_subtree(child)
        return subtree
837588
def to_etree(self):
        
        attribs = {
            '{{{pre}}}type'.format(pre=NAMESPACES['xsi']): self.xsi_type,
            'namespace': self.namespace, 'name': self.name,
            'value': self.hexvalue, 'valueString': self.value}
        non_empty_attribs = {key: val for (key, val) in attribs.items()
                             if val is not None}
        E = ElementMaker()
        return E('labels', non_empty_attribs)