Translate a select node into a latex qtree node.
        :param node: a treebrd node
        :return: a qtree subtree rooted at the node
341837
def select(self, node):
        
        child = self.translate(node.child)
        return '[.${op}_{{{conditions}}}$ {child} ]'\
            .format(op=latex_operator[node.operator],
                    conditions=node.conditions, child=child)
503193
def node_to_elem(root):
    
    def generate_elem(append, node, level):
        var = "e" + str(level)
        arg = repr(node.tag)
        if node.attrib:
            arg += ", **%r" % node.attrib
        if level == 1:
            append("e1 = Element(%s)" % arg)
        else:
            append("%s = SubElement(e%d, %s)" % (var, level - 1, arg))
        if not node.nodes:
            append("%s.text = %r" % (var, node.text))
        for x in node:
            generate_elem(append, x, level + 1)
    # generate code to create a tree
    output = []
    generate_elem(output.append, root, 1)  # print "\n".join(output)
    namespace = {"Element": ElementTree.Element,
                 "SubElement": ElementTree.SubElement}
    exec("\n".join(output), globals(), namespace)
    return namespace["e1"]
439574
def extract_subtree(self, node):
        '''
        '''
        if not isinstance(node, Node):
            raise TypeError("node must be a Node")
        r = self.root; self.root = node; o = copy(self); self.root = r; return o
1046214
def get_node_type(tree):
    
    node_type = tree[0].label()
    assert node_type in NODE_TYPES, "node_type: {}".format(node_type)
    return node_type
564862
function transform(node) {
  /**
   * Combine adjacent text and inline nodes before processing so they can
   * share marks.
   */
  const combinedChildren = node.nodes && combineTextAndInline(node.nodes);

  /**
   * Call `transform` recursively on child nodes, and flatten the resulting
   * array.
   */
  const children = !isEmpty(combinedChildren) && flatMap(combinedChildren, transform);

  /**
   * Run individual nodes through conversion factories.
   */
  return ['text'].includes(node.object) ? convertTextNode(node) : convertNode(node, children);
}
123639
def convert_to_latex(node)
      latex_code = nil
      Open3.popen3("pandoc -f json -t latex --wrap=none") {|stdin, stdout, stderr, wait_thr|
        stdin.write(node.to_json)
        stdin.close  # stdin, stdout and stderr should be closed explicitly in this form.
        latex_code = stdout.read

        pid = wait_thr.pid # pid of the started process.
        exit_status = wait_thr.value # Process::Status object returned.
      }
      latex_code
    end
793026
def _transform(self, node):
        
        cls = node.__class__
        if cls not in self.transforms:
            # no transform registered for this class of node
            return node

        transforms = self.transforms[cls]
        for transform_func, predicate in transforms:
            if predicate is None or predicate(node):
                ret = transform_func(node)
                # if the transformation function returns something, it's
                # expected to be a replacement for the node
                if ret is not None:
                    node = ret
                if ret.__class__ != cls:
                    # Can no longer apply the rest of the transforms.
                    break
        return node
853975
function _doc_to_tree_node(doc, parent_id){

    var retnode = {};

    // ID.
    var raw_id = doc['id'];
    var safe_id = raw_id; // need to process?
    retnode['attr'] = { "id" : safe_id }; 

    // Label (with fallback).
    var label = doc['label'];
    if( ! label || label == '' ){
	label = raw_id;
    }else{
	label = label + ' (' + raw_id + ')';
    }

    // Set anchor title and href.
    var detlink = linker.url(raw_id, 'term');
    retnode['data'] = {"title" : label,
		       "attr": {"href": detlink}};

    // Turn to graph, get kids.
    var graph = new bbop.model.graph();
    graph.load_json(jQuery.parseJSON(doc['topology_graph']));
    var kids = graph.get_child_nodes(doc['id']);

    // Add state and kid_query.
    if( ! kids || kids.length == 0 ){
	// No kids...
    }else{
	// No kids, make sure the node is closed.
    	retnode['state'] = 'closed';

	// Collect kid info for the query to get them later.
	var qbuff = [];
	bbop.core.each(kids,
		       function(kid){
			   qbuff.push('id:"' + kid.id() + '"');
		       });
	retnode['attr']['kid_query'] = qbuff.join(' OR ');
    }

    // If the parent_id is defined, use that to pull the relationship
    // out of the graph and get a more appropriate icon.
    if( parent_id ){

	// Try and dig out the rel to display.
	var edges = graph.get_edges(raw_id, parent_id);
	if( edges && edges.length ){
	    var weight = {
		'is_a': 3,
		'part_of': 2
	    };
	    var unknown_rel_weight = 1;
	    edges.sort(
		function(a, b){
		    var aw = weight[a.predicate_id()];
		    if( ! aw ){ aw = unknown_rel_weight; }
		    var bw = weight[b.predicate_id()];
		    if( ! bw ){ bw = unknown_rel_weight; }
		    return bw - aw;
		});

	    // Add it in a brittle way.
	    var prime_rel = edges[0].predicate_id();
	    retnode['data']['icon'] = 
	    	server_meta.image_base() + '/' + prime_rel + '.gif';
	}
    }

    return retnode;
}
1303238
def _ensure_node(node: Union[str, AbstractNode]) -> AbstractNode:
    
    if isinstance(node, str):
        return Text(node)
    elif isinstance(node, Node):
        return node
    else:
        raise TypeError('Invalid type to append: {}'.format(node))
739424
def assign(self, node):
        
        child = self.translate(node.child)
        attributes = ''
        if node.attributes:
            attributes = '({})'.format(','.join(node.attributes.names))
        return '[.${name}{attributes}$ {child} ]'\
            .format(name=node.name, attributes=attributes, child=child)
646746
def make_node(clss, node, *params):
        ''' 
        '''
        if node is None:
            node = clss()

        if node.token != 'PARAMLIST':
            return clss.make_node(None, node, *params)

        for i in params:
            if i is not None:
                node.appendChild(i)

        return node
116902
def node(self, parent=None, tag='g', attrib=None, **extras):
        """"""
        if parent is None:
            parent = self.root
        attrib = attrib or {}
        attrib.update(extras)

        def in_attrib_and_number(key):
            return key in attrib and isinstance(attrib[key], Number)

        for pos, dim in (('x', 'width'), ('y', 'height')):
            if in_attrib_and_number(dim) and attrib[dim] < 0:
                attrib[dim] = -attrib[dim]
                if in_attrib_and_number(pos):
                    attrib[pos] = attrib[pos] - attrib[dim]

        for key, value in dict(attrib).items():
            if value is None:
                del attrib[key]

            attrib[key] = to_str(value)
            if key.endswith('_'):
                attrib[key.rstrip('_')] = attrib[key]
                del attrib[key]
            elif key == 'href':
                attrib[etree.QName('http://www.w3.org/1999/xlink',
                                   key)] = attrib[key]
                del attrib[key]
        return etree.SubElement(parent, tag, attrib)
852865
def get_node_text(self, node):
        
        text_children = [n.nodeValue for n in self.get_node_children(node)
                         if n.nodeType == xml.dom.Node.TEXT_NODE]
        if text_children:
            return u''.join(text_children)
        else:
            return None
1033024
def tree_text(node):
    
    text = []
    for descendant in walk_dom(node):
        if is_text(descendant):
            text.append(descendant.nodeValue)
    return ' '.join(text)
293042
def _translate_nodes(root, *nodes):
    
    #name2node = {[n, None] for n in nodes if type(n) is str}
    name2node = dict([[n, None] for n in nodes if type(n) is str])
    for n in root.traverse():
        if n.name in name2node:
            if name2node[n.name] is not None:
                raise TreeError("Ambiguous node name: {}".format(str(n.name)))
            else:
                name2node[n.name] = n

    if None in list(name2node.values()):
        notfound = [key for key, value in six.iteritems(name2node) if value is None]
        raise ValueError("Node names not found: "+str(notfound))

    valid_nodes = []
    for n in nodes:
        if type(n) is not str:
            if type(n) is not root.__class__:
                raise TreeError("Invalid target node: "+str(n))
            else:
                valid_nodes.append(n)

    valid_nodes.extend(list(name2node.values()))
    if len(valid_nodes) == 1:
        return valid_nodes[0]
    else:
        return valid_nodes
653660
def make_node(cls, node, *args):
        ''' 
        '''
        if node is None:
            return cls.make_node(SymbolBOUNDLIST(), *args)

        if node.token != 'BOUNDLIST':
            return cls.make_node(None, node, *args)

        for arg in args:
            if arg is None:
                continue
            node.appendChild(arg)

        return node
446851
def node_to_dict(node):
    
    dic = dict(tag=striptag(node.tag))
    if node.attrib:
        dic['attrib'] = node.attrib
    if node.text is not None:
        dic['text'] = node.text
    if node.nodes:
        dic['nodes'] = [node_to_dict(n) for n in node]
    return dic