Recursively construct HTML nested list version of book tree.
    The original caller should not call this function with the
    `parent_id` defined.
199445
def html_listify(tree, root_ul_element, parent_id=None):
    
    request = get_current_request()
    is_first_node = parent_id is None
    if is_first_node:
        parent_id = tree[0]['id']
    for node in tree:
        li_elm = etree.SubElement(root_ul_element, 'li')
        a_elm = etree.SubElement(li_elm, 'a')
        a_elm.text = node['title']
        if node['id'] != 'subcol':
            if is_first_node:
                a_elm.set('href', request.route_path(
                    'content', ident_hash=node['id'], ext='.html'))
            else:
                a_elm.set('href', request.route_path(
                    'content',
                    separator=':',
                    ident_hash=parent_id,
                    page_ident_hash=node['id'],
                    ext='.html'))
        if 'contents' in node:
            elm = etree.SubElement(li_elm, 'ul')
            html_listify(node['contents'], elm, parent_id)
226469
function detree(items, children, parent_id) {

		var item,
		    i;

		for (i = 0; i < children.length; i++) {

			item = children[i];

			if (parent_id) {
				item.parent = parent_id;
			}

			items.push(item);

			if (item.children) {
				detree(items, item.children, item.id);
			}

			delete item.children;
		}
	}
945016
def nested
      @page = Page.find_by(id: params[:page_id]) || Language.current_root_page

      render json: PageTreeSerializer.new(@page,
        ability: current_ability,
        user: current_alchemy_user,
        elements: params[:elements],
        full: true)
    end
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;
}
23807
def is_parent_of(page1, page2):
    

    try:
        return page1.tree_id == page2.tree_id and page1.lft < page2.lft and page1.rght > page2.rght
    except AttributeError:
        return False
669057
private function buildTree($rows, $parent_id = 0)
    {
        $containerAttributes = '';

        if (!$this->containerOptionsIsSet) {
            $containerAttributes = Html::renderTagAttributes($this->containerOptions);
            $this->containerOptionsIsSet = true;
        }

        $result = "<ul$containerAttributes>";

        foreach ($rows as $row) {
            if ($row['parent_id'] == $parent_id) {

                $value = call_user_func_array($this->value, ['model' => $row['model']]);
                $result .= "<li>$value";

                if ($this->hasChild($rows, $row['id'])) {
                    $result.= $this->buildTree($rows, $row['id']);
                }

                $result .= '</li>';
            }
        }

        $result .= '</ul>';

        return $result;
    }
1108759
def _build_gadgets_rec(self, gadget_tree_root):
        
        root = gadget_tree_root.get_root()
        children = gadget_tree_root.get_children()

        node_list = []

        root_gadget_ins = root

        if not children:
            node_list += [[root_gadget_ins]]
        else:
            for child in children:
                node_list_rec = self._build_gadgets_rec(child)

                node_list += [n + [root_gadget_ins] for n in node_list_rec]

        return node_list
296432
function processList(ul) {
	if ( ul.getAttribute( "data-xdh-mktree" ) == "handled" )
		return;
	
	if (!ul.childNodes || ul.childNodes.length==0) { return; }
	// Iterate LIs
	var childNodesLength = ul.childNodes.length;
	for (var itemi=0;itemi<childNodesLength;itemi++) {
		var item = ul.childNodes[itemi];
		if (item.nodeName == "LI") {
			// Iterate things in this LI
			var subLists = false;
			var itemChildNodesLength = item.childNodes.length;
			for (var sitemi=0;sitemi<itemChildNodesLength;sitemi++) {
				var sitem = item.childNodes[sitemi];
				if (sitem.nodeName=="UL") {
					subLists = true;
					processList(sitem);
				}
			}
			var s= document.createElement("SPAN");
			var t= '\u00A0'; // &nbsp;
			s.className = nodeLinkClass;
			if (subLists) {
				// This LI has UL's in it, so it's a +/- node
				if (item.className==null || item.className=="") {
					item.className = nodeClosedClass;
				}
				// If it's just text, make the text work as the link also
				if (item.firstChild.nodeName=="#text") {
					t = t+item.firstChild.nodeValue;
					item.removeChild(item.firstChild);
				}
				s.onclick = treeNodeOnclick;
			}
			else {
				// No sublists, so it's just a bullet node
				item.className = nodeBulletClass;
				s.onclick = retFalse;
			}
			s.appendChild(document.createTextNode(t));
			item.insertBefore(s,item.firstChild);
		}
	}
}
1156417
function parentise(tree, height) {
	if (height == tree.height) {
		return tree;
	} else {
		var list = [parentise(tree, height - 1)];
		list.height = height;
		list.sizes = [length(tree)];
		return list;
	}
}
267336
private static String nestedListToHtml( NestedList nl ){
		if( nl == null ) {
			return "null";
		}

		StringBuilder result = new StringBuilder();

		if( nl.getClass()==NestedListElement.class ){
			result.append( "<li>\n"+ contentElementToHtml( (NestedListElement)nl ) +"</li>\n" );
		}
		else{
			result.append("<table class=\"NestedList\">\n" +
					"<tr><th class=\"NestedList\">NestedList</th></tr>\n"+
					"<tr><td class=\"NestedList\">" );

			result.append((((NestedListContainer)nl).isNumbered()?"<ol>":"<ul>")+"\n" );
			for( NestedList nl2 : ((NestedListContainer)nl).getNestedLists() ) {
				result.append( nestedListToHtml( nl2 ) );
			}
			result.append((((NestedListContainer)nl).isNumbered()?"</ol>":"</ul>")+"\n");

			result.append("</td></tr>\n" );
			result.append("</table>\n");
		}

		return result.toString();
	}
412021
def get_parent_gradebook_nodes(self):
        
        parent_gradebook_nodes = []
        for node in self._my_map['parentNodes']:
            parent_gradebook_nodes.append(GradebookNode(
                node._my_map,
                runtime=self._runtime,
                proxy=self._proxy,
                lookup_session=self._lookup_session))
        return GradebookNodeList(parent_gradebook_nodes)
1349109
def validate_nesting(self):
        '''
        
        '''
        error_dict = {}
        story_root = self.story_tree_root
        story_nodes = story_root.get_descendants().prefetch_related('arcelementnode_set').filter(depth=2)

        def parse_children(node_object, seq=0):
            '''
            Recursive method to check all generations of a node for arc
            elements.
            '''
            returnable_ae_dict = {}
            if node_object.get_children_count():
                for node in node_object.get_children().prefetch_related('arcelementnode_set'):
                    if node.get_children_count():
                        local_ae_dict, newseq = parse_children(node, seq)
                        for arc in local_ae_dict.keys():
                            if arc not in returnable_ae_dict.keys():
                                returnable_ae_dict[arc] = []
                            returnable_ae_dict[arc] = returnable_ae_dict[arc] + (local_ae_dict[arc])
                        seq = newseq
                    else:
                        local_arc_elements = node.arcelementnode_set.all()
                        for ae in local_arc_elements:
                            if ae.is_milestone:
                                logger.debug('Found a milestone to sequence.')
                                if ae.arc not in returnable_ae_dict.keys():
                                    returnable_ae_dict[ae.arc] = []
                                returnable_ae_dict[ae.arc].append({
                                    ae.arc_element_type: seq,
                                })
                                logger.debug('Appended an element of type %s  from arc %s at sequence %d' % (
                                    ae.arc_element_type,
                                    ae.arc.name,
                                    seq))
                        seq += 1
            return returnable_ae_dict, seq

        arcs_out_of_sequence = []
        arc_milestone_elements = {}
        x = 0
        arcs_with_nest_conflicts = []
        for node in story_nodes:
            arc_elements_found, x = parse_children(node, x)
            for arc in arc_elements_found.keys():
                if arc not in arc_milestone_elements.keys():
                    arc_milestone_elements[arc] = []
                arc_milestone_elements[arc] = arc_milestone_elements[arc] + arc_elements_found[arc]
        arc_entry_exit = {}
        for arc, elements in arc_milestone_elements.items():
            z = {}
            last_local_seq = 0
            logger.debug("There are %d elements to parse" % len(elements))
            for ae_elements in elements:
                logger.debug('Parsing %s' % ae_elements)
                for k, v in ae_elements.items():
                    z[k] = v
            logger.debug('%s' % OrderedDict(sorted(z.items(), key=lambda t: t[1])))
            for key, value in OrderedDict(sorted(z.items(), key=lambda t: t[1])).items():
                if last_local_seq > ARC_NODE_ELEMENT_DEFINITIONS[key]['milestone_seq']:
                    arcs_out_of_sequence.append(arc)
                    break
                last_local_seq = ARC_NODE_ELEMENT_DEFINITIONS[key]['milestone_seq']
                if 'mile_hook' in z.keys() and 'mile_reso' in z.keys():
                    arc_entry_exit[arc] = {
                        'entry': z['mile_hook'],
                        'exit': z['mile_reso'],
                    }
        if arc_entry_exit:
            temp_ent = {}
            temp_ex = {}
            for en_arc, enter in arc_entry_exit.items():
                temp_ent[en_arc] = enter['entry']
            for ex_arc, leave in arc_entry_exit.items():
                temp_ex[ex_arc] = leave['exit']
            arc_entries = OrderedDict(sorted(temp_ent.items(), key=lambda t: t[1]))
            arc_exits = OrderedDict(sorted(temp_ex.items(), key=lambda t: t[1], reverse=True))
            logger.debug("Evaluating entries vs exits: %s vs %s" % (arc_entries, arc_exits))
            index_num = 0
            for entrance in arc_entries.keys():
                test_exit = list(arc_exits.keys())[index_num]
                logger.debug('Checking %s vs %s arcs' % (entrance, test_exit))
                if entrance != test_exit:
                    logger.debug("Different arcs.. making sure they don't share an entry/exist point")
                    if (arc_entry_exit[entrance]['entry'] != arc_entry_exit[test_exit]['entry'] and
                        arc_entry_exit[entrance]['exit'] != arc_entry_exit[test_exit]['exit']):
                        if ((arc_entry_exit[entrance]['entry'] < arc_entry_exit[test_exit]['entry'] and
                                arc_entry_exit[entrance]['exit'] > arc_entry_exit[test_exit]['exit']) or
                            (arc_entry_exit[entrance]['entry'] > arc_entry_exit[test_exit]['entry'] and
                             arc_entry_exit[entrance]['exit'] < arc_entry_exit[test_exit]['exit'])):
                            logger.debug("No same entry point, but the nest is still valid.")
                        else:
                            logger.debug("nesting error found: %s should resole before %s" % (entrance, test_exit))
                            if entrance not in arcs_with_nest_conflicts:
                                arcs_with_nest_conflicts.append(entrance)
                            if test_exit not in arcs_with_nest_conflicts:
                                arcs_with_nest_conflicts.append(test_exit)
                    else:
                        logger.debug('Arcs share an entry/exit point so nesting error is ignored.')
                index_num += 1
        unique_nest_errors = list(set(arcs_with_nest_conflicts))
        logger.debug("%d arcs with nesting errors found" % len(unique_nest_errors))
        logger.debug('Arcs with nesting errors: %s' % unique_nest_errors)
        story_tree = story_root.get_descendants().prefetch_related('arcelementnode_set')
        if arcs_out_of_sequence:
            error_dict['nest_arc_seq'] = {
                'error_message': "Arc element milestones are out of sequence",
                'offending_arcs': []
            }
            logger.debug('There are %d arcs out of internal sequence' % len(arcs_out_of_sequence))
            arc_sequence_error_dict = {}
            story_root.refresh_from_db()
            for arc in arcs_out_of_sequence:
                arc_sequence_error_dict['offending_nodes'] = story_tree.filter(arcelementnode__arc=arc)
            error_dict['nest_arc_seq']['offending_arcs'].append(arc_sequence_error_dict)
        if unique_nest_errors:
            error_dict['nest_reso_error'] = {
                'error_message': "Arcs should resolve in the opposite order that they were introduced",
                'offending_nodes': story_tree.filter(
                    arcelementnode__arc__in=unique_nest_errors,
                    arcelementnode__arc_element_type='mile_reso'
                )
            }
        return error_dict
1214084
def nested_list_from_xml_string(xml, container_element_name, list_element_name = default_list_element_name)
        xml_doc = Nokogiri::XML(xml)
        nested_list_from_xml_doc(xml_doc.at_xpath("./#{container_element_name}"), list_element_name)
      end
529294
function (nodeList, newNodes) {
			// Unregister all childNodeLists.
			var oldNodes = nodeLists.unregisterChildren(nodeList);

			newNodes = makeArray(newNodes);

			var oldListLength = nodeList.length;

			// Replace oldNodeLists's contents.
			splice.apply(nodeList, [
				0,
				oldListLength
			].concat(newNodes));

			// Replacements are nodes that have replaced the original element this is on.
			// We can't simply insert elements because stache does children before parents.
			if(nodeList.replacements){
				nodeLists.nestReplacements(nodeList);
				nodeList.deepChildren = nodeList.newDeepChildren;
				nodeList.newDeepChildren = [];
			} else {
				nodeLists.nestList(nodeList);
			}

			return oldNodes;
		}
56254
def nested(self, format_callback=None):
        
        seen = set()
        roots = []
        for root in self.edges.get(None, ()):
            roots.extend(self._nested(root, seen, format_callback))
        return roots
1279929
def tree_list(ref)
      if (sha = @access.ref_to_sha(ref))
        commit = @access.commit(sha)
        tree_map_for(sha).inject([]) do |list, entry|
          next list unless @page_class.valid_page_name?(entry.name)
          list << entry.page(self, commit)
        end
      else
        []
      end
    end
417133
def _open_list(self, list_type):
        
        if list_type in LIST_TYPES.keys():
            tag = LIST_TYPES[list_type]
        else:
            raise Exception('CustomSlackdownHTMLParser:_open_list: Not a valid list type.')

        html = '<{t} class="list-container-{c}">'.format(
            t=tag,
            c=list_type
        )
        self.cleaned_html += html
        self.current_parent_element['tag'] = LIST_TYPES[list_type]
        self.current_parent_element['attrs'] = {'class': list_type}