Recursively parse COLLADA scene nodes.
769475
def _parse_node(node,
                parent_matrix,
                material_map,
                meshes,
                graph,
                resolver=None):
    

    # Parse mesh node
    if isinstance(node, collada.scene.GeometryNode):
        geometry = node.geometry

        # Create local material map from material symbol to actual material
        local_material_map = {}
        for mn in node.materials:
            symbol = mn.symbol
            m = mn.target
            if m.id in material_map:
                local_material_map[symbol] = material_map[m.id]
            else:
                local_material_map[symbol] = _parse_material(m, resolver)

        # Iterate over primitives of geometry
        for i, primitive in enumerate(geometry.primitives):
            if isinstance(primitive, collada.polylist.Polylist):
                primitive = primitive.triangleset()
            if isinstance(primitive, collada.triangleset.TriangleSet):
                vertex = primitive.vertex
                vertex_index = primitive.vertex_index
                vertices = vertex[vertex_index].reshape(
                    len(vertex_index) * 3, 3)

                # Get normals if present
                normals = None
                if primitive.normal is not None:
                    normal = primitive.normal
                    normal_index = primitive.normal_index
                    normals = normal[normal_index].reshape(
                        len(normal_index) * 3, 3)

                # Get colors if present
                colors = None
                s = primitive.sources
                if ('COLOR' in s and len(s['COLOR'])
                        > 0 and len(primitive.index) > 0):
                    color = s['COLOR'][0][4].data
                    color_index = primitive.index[:, :, s['COLOR'][0][0]]
                    colors = color[color_index].reshape(
                        len(color_index) * 3, 3)

                faces = np.arange(
                    vertices.shape[0]).reshape(
                    vertices.shape[0] // 3, 3)

                # Get UV coordinates if possible
                vis = None
                if primitive.material in local_material_map:
                    material = copy.copy(
                        local_material_map[primitive.material])
                    uv = None
                    if len(primitive.texcoordset) > 0:
                        texcoord = primitive.texcoordset[0]
                        texcoord_index = primitive.texcoord_indexset[0]
                        uv = texcoord[texcoord_index].reshape(
                            (len(texcoord_index) * 3, 2))
                    vis = visual.texture.TextureVisuals(
                        uv=uv, material=material)

                primid = '{}.{}'.format(geometry.id, i)
                meshes[primid] = {
                    'vertices': vertices,
                    'faces': faces,
                    'vertex_normals': normals,
                    'vertex_colors': colors,
                    'visual': vis}

                graph.append({'frame_to': primid,
                              'matrix': parent_matrix,
                              'geometry': primid})

    # recurse down tree for nodes with children
    elif isinstance(node, collada.scene.Node):
        if node.children is not None:
            for child in node.children:
                # create the new matrix
                matrix = np.dot(parent_matrix, node.matrix)
                # parse the child node
                _parse_node(
                    node=child,
                    parent_matrix=matrix,
                    material_map=material_map,
                    meshes=meshes,
                    graph=graph,
                    resolver=resolver)

    elif isinstance(node, collada.scene.CameraNode):
        # TODO: convert collada cameras to trimesh cameras
        pass
    elif isinstance(node, collada.scene.LightNode):
        # TODO: convert collada lights to trimesh lights
        pass
948300
def _parse(s, g):
    """"""
    # The CYK table. Indexed with a 2-tuple: (start pos, end pos)
    table = defaultdict(set)
    # Top-level structure is similar to the CYK table. Each cell is a dict from
    # rule name to the best (lightest) tree for that rule.
    trees = defaultdict(dict)
    # Populate base case with existing terminal production rules
    for i, w in enumerate(s):
        for terminal, rules in g.terminal_rules.items():
            if match(terminal, w):
                for rule in rules:
                    table[(i, i)].add(rule)
                    if (rule.lhs not in trees[(i, i)] or
                        rule.weight < trees[(i, i)][rule.lhs].weight):
                        trees[(i, i)][rule.lhs] = RuleNode(rule, [T(w)], weight=rule.weight)

    # Iterate over lengths of sub-sentences
    for l in xrange(2, len(s) + 1):
        # Iterate over sub-sentences with the given length
        for i in xrange(len(s) - l + 1):
            # Choose partition of the sub-sentence in [1, l)
            for p in xrange(i + 1, i + l):
                span1 = (i, p - 1)
                span2 = (p, i + l - 1)
                for r1, r2 in itertools.product(table[span1], table[span2]):
                    for rule in g.nonterminal_rules.get((r1.lhs, r2.lhs), []):
                        table[(i, i + l - 1)].add(rule)
                        r1_tree = trees[span1][r1.lhs]
                        r2_tree = trees[span2][r2.lhs]
                        rule_total_weight = rule.weight + r1_tree.weight + r2_tree.weight
                        if (rule.lhs not in trees[(i, i + l - 1)]
                            or rule_total_weight < trees[(i, i + l - 1)][rule.lhs].weight):
                            trees[(i, i + l - 1)][rule.lhs] = RuleNode(rule, [r1_tree, r2_tree], weight=rule_total_weight)
    return table, trees
1313069
def _parse_tree(self, node):
        
        if 'filename' in node.attrib:
            self.filename = node.attrib['filename']
        if 'type' in node.attrib:
            self.kind = node.attrib['type']
        if 'target' in node.attrib:
            self.target = node.attrib['target']
        self.value = node.text
402409
def get_trees(self, data, showerrors = False): # -> list:
        
        if not all(check(self._productionset.alphabet, [x]) for x in data):
            raise ValueError("Unknown element in {}, alphabet:{}".format(str(data), self.productionset.alphabet))
        result = self.__recursive_parser(self._productionset.initialsymbol, data, self._productionset.main_production, showerrors)
        finalresult = []
        for eresult in result:
            if eresult.left == 0 and eresult.right == len(data) and eresult not in finalresult:
                finalresult.append(eresult)        
        return finalresult
111891
def parse(node)
      node.xpath('*').each do |node_child|
        case node_child.name
        when 'blip'
          @file_reference = FileReference.new(parent: self).parse(node_child)
        when 'tile'
          @tile = Tile.new(OOXMLCoordinates.parse(node_child, x_attr: 'tx', y_attr: 'ty'),
                           OOXMLCoordinates.parse(node_child, x_attr: 'sx', y_attr: 'sy'),
                           parent: self).parse(node_child)
        end
      end
      self
    end
623461
function processScene(scene) {
      if (!outputJSON.scenes) {
        outputJSON.scenes = [];
        outputJSON.scene = 0;
      }

      var gltfScene = {
        nodes: []
      };

      if (scene.name !== '') {
        gltfScene.name = scene.name;
      }

      outputJSON.scenes.push(gltfScene);

      var nodes = [];

      for (var i = 0, l = scene.children.length; i < l; i++) {
        var child = scene.children[i];

        if (child.visible || options.onlyVisible === false) {
          var node = processNode(child);

          if (node !== null) {
            nodes.push(node);
          }
        }
      }

      if (nodes.length > 0) {
        gltfScene.nodes = nodes;
      }
    }
905906
def _parse_tree(self, node):
        
        if 'type' in node.attrib:
            self.kind = node.attrib['type']
        for c3 in node:
            if c3.tag == 'caption':
                self.caption = _parse_desc(c3)
            elif c3.tag == 'image':
                im = Image()
                im._parse_tree(c3)
                self.add_image(im)
1274584
def parse_nodes(nodes)
      output = ''

      # Short-circuit if it's empty
      return output if !nodes || nodes.empty?

      # Loop through nodes
      nodes.each do |node|
        case node.name
        when 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'
          level = node.name.match(/\Ah(\d)\Z/)[1].to_i
          if @options[:underline_headers] && level < 3
            content = parse_content(node)
            output << content + "\n"
            character = level == 1 ? '=' : '-'
            content.length.times { output << character}
          else
            hashes = ''
            level.times { hashes << '#' }
            output << "#{hashes} #{parse_content(node)}"
          end
        when 'blockquote'
          parse_content(node).split("\n").each do |line|
            output << "> #{line}\n"
          end
        when 'ul', 'ol'
          output << "\n\n" if @list.count > 0

          if unordered = node.name == 'ul'
            @list << :unordered
          else
            @list << :ordered
            @list_position << 0
          end

          output << parse_nodes(node.children)

          @list.pop
          @list_position.pop unless unordered
        when 'li'
          (@list.count - 1).times { output << '    ' }
          if @list.last == :unordered
            output << "* #{parse_content(node)}"
          else
            num = (@list_position[@list_position.count - 1] += 1)
            output << "#{num}. #{parse_content(node)}"
          end
        when 'pre'
          content = parse_content(node)

          if @options[:fenced_code_blocks]
            output << "```\n#{content}\n```"
          else
            content.split("\n").each do |line|
              output << "    #{line}\n"
            end
          end
        when 'hr'
          output << "---\n\n"
        when 'a'
          output << "[#{parse_content(node)}](#{node['href']}#{build_title(node)})"
        when 'i', 'em'
          output << "*#{parse_content(node)}*"
        when 'b', 'strong'
          output << "**#{parse_content(node)}**"
        when 'u'
          output << "_#{parse_content(node)}_"
        when 'mark'
          output << "==#{parse_content(node)}=="
        when 'code'
          output << "`#{parse_content(node)}`"
        when 'img'
          output << "![#{node['alt']}](#{node['src']}#{build_title(node)})"
        when 'text'
          content = parse_content(node)

          # Optionally look for links
          content.gsub!(AUTOLINK_URL_REGEX, '<\1>') if @options[:autolink]
          content.gsub!(AUTOLINK_EMAIL_REGEX, '<\1>') if @options[:autolink]

          output << content
        when 'script'
          next unless @options[:allow_scripts]
          output << node.to_html
        else
          # If it's an supported node or a node that just contains text, just get
          # its content
          output << parse_content(node)
        end

        output << "\n\n" if BLOCK_ELEMENT_NAMES.include?(node.name)
      end

      output
    end
1293926
def get_scene(self):
        """"""
        if self._scene is None:
            parent = getattr(self, "parent", None)
            if parent:
                self._scene = parent.get_scene()
        return self._scene
518603
def _handle_nodes(nodes: MaybeNodeList) -> List[BaseEntity]:
    """"""
    if isinstance(nodes, BaseEntity):
        return [nodes]

    return [
        (
            parse_result_to_dsl(node)
            if not isinstance(node, BaseEntity) else
            node
        )
        for node in nodes
    ]
512157
function extractMetaNodes(profile) {
        const topLevelNodes = profile.resultRoot.children;
        for (let i = 0; i < topLevelNodes.length && !(profile.gcNode && profile.programNode && profile.idleNode); i++) {
            const node = topLevelNodes[i];
            if (node.functionName === '(garbage collector)')
                profile.gcNode = node;
            else if (node.functionName === '(program)')
                profile.programNode = node;
            else if (node.functionName === '(idle)')
                profile.idleNode = node;
        }
    }
1339312
def get_children(self, depth=1):
        """"""
        yield self
        if depth == 0: return
        for child in self.children.values():
            for node in child.get_children(depth-1): yield node
928732
function parseHierarchy(nodes) {
  let prev = nodes[0], // the previous node
      heads = [[]],    // the set of inserton heads, at each level
      set = heads[0];  // the current insertion set

  nodes.forEach(node => {
    node.children = node.children || [];

    // indented -->
    if (node.level > prev.level) {
      node.level = prev.level + 1; // ensures consistent nesting.
      set = heads[node.level] = prev.children;
    }
    
    // outdented <--
    if (node.level < prev.level) {
      set = heads[node.level] = heads[node.level] || [];
    }

    set.push(node);
    prev = node;
  });

  return heads[0]; // root node set
}
116449
def _parse_figure(self, node, state):
        
        if node.tag not in ["img", "figure"]:
            return state

        # Process the Figure
        stable_id = (
            f"{state['document'].name}"
            f"::"
            f"{'figure'}"
            f":"
            f"{state['figure']['idx']}"
        )

        # Set name for Figure
        name = node.attrib["name"] if "name" in node.attrib else None

        # img within a Figure get's processed in the parent Figure
        if node.tag == "img" and isinstance(state["parent"][node], Figure):
            return state

        # NOTE: We currently do NOT support nested figures.
        parts = {}
        parent = state["parent"][node]
        if isinstance(parent, Section):
            parts["section"] = parent
        elif isinstance(parent, Cell):
            parts["section"] = parent.table.section
            parts["cell"] = parent
        else:
            logger.warning(f"Figure is nested within {state['parent'][node]}")
            return state

        parts["document"] = state["document"]
        parts["stable_id"] = stable_id
        parts["name"] = name
        parts["position"] = state["figure"]["idx"]

        # If processing a raw img
        if node.tag == "img":
            # Create the Figure entry in the DB
            parts["url"] = node.get("src")
            state["context"][node] = Figure(**parts)
        elif node.tag == "figure":
            # Pull the image from a child img node, if one exists
            imgs = [child for child in node if child.tag == "img"]

            if len(imgs) > 1:
                logger.warning("Figure contains multiple images.")
                # Right now we don't support multiple URLs in the Figure context
                # As a workaround, just ignore the outer Figure and allow processing
                # of the individual images. We ignore the accompanying figcaption
                # by marking it as visited.
                captions = [child for child in node if child.tag == "figcaption"]
                state["visited"].update(captions)
                return state

            img = imgs[0]
            state["visited"].add(img)

            # Create the Figure entry in the DB
            parts["url"] = img.get("src")
            state["context"][node] = Figure(**parts)

        state["figure"]["idx"] += 1
        return state
974277
def _elem_from_descendants(children_nodes, **options):
    
    for child in children_nodes:  # child should be a dict-like object.
        for ckey, cval in anyconfig.compat.iteritems(child):
            celem = ET.Element(ckey)
            container_to_etree(cval, parent=celem, **options)
            yield celem
848832
def get_children_treepos(self, treepos):
        """"""
        children_treepos = []
        for i, child in enumerate(self.dgtree[treepos]):
            if isinstance(child, nltk.Tree):
                children_treepos.append(child.treeposition())
            elif is_leaf(child):
                # we can't call .treeposition() on a leaf node
                treepos_list = list(treepos)
                treepos_list.append(i)
                leaf_treepos = tuple(treepos_list)
                children_treepos.append(leaf_treepos)
        return children_treepos
695945
public function parse_recursive(DOMElement $context = null, $depth = 0) {
		$mfs = array();
		$mfElements = $this->getRootMF($context);

		foreach ($mfElements as $node) {
			$is_backcompat = !$this->hasRootMf2($node);

			if ($this->convertClassic && $is_backcompat) {
				$this->backcompat($node);
			}

			$recurse = $this->parse_recursive($node, $depth + 1);

			// set bool flag for nested mf
			$has_nested_mf = ($recurse);

			// parse for root mf
			$result = $this->parseH($node, $is_backcompat, $has_nested_mf);

			// TODO: Determine if clearing this is required?
			$this->elementPrefixParsed($node, 'h');
			$this->elementPrefixParsed($node, 'p');
			$this->elementPrefixParsed($node, 'u');
			$this->elementPrefixParsed($node, 'dt');
			$this->elementPrefixParsed($node, 'e');

			// parseH returned a parsed result
			if ($result) {

				// merge recursive results into current results
				if ($recurse) {
					$result = array_merge_recursive($result, $recurse);
				}

				// currently a nested mf; check if node is an mf property of parent
				if ($depth > 0) {
					$temp_properties = nestedMfPropertyNamesFromElement($node);

					// properties found; set up parsed result in 'properties'
					if (!empty($temp_properties)) {

						foreach ($temp_properties as $property => $prefixes) {
							// Note: handling microformat nesting under multiple conflicting prefixes is not currently specified by the mf2 parsing spec.
							$prefixSpecificResult = $result;
							if (in_array('p-', $prefixes)) {
								$prefixSpecificResult['value'] = (!is_array($prefixSpecificResult['properties']) || empty($prefixSpecificResult['properties']['name'][0])) ? $this->parseP($node) : $prefixSpecificResult['properties']['name'][0];
							} elseif (in_array('e-', $prefixes)) {
								$eParsedResult = $this->parseE($node);
								$prefixSpecificResult['html'] = $eParsedResult['html'];
								$prefixSpecificResult['value'] = $eParsedResult['value'];
							} elseif (in_array('u-', $prefixes)) {
								$prefixSpecificResult['value'] = (!is_array($result['properties']) || empty($result['properties']['url'])) ? $this->parseU($node) : reset($result['properties']['url']);
							} elseif (in_array('dt-', $prefixes)) {
								$parsed_property = $this->parseDT($node);
								$prefixSpecificResult['value'] = ($parsed_property) ? $parsed_property : '';
							}

							$mfs['properties'][$property][] = $prefixSpecificResult;
						}

					// otherwise, set up in 'children'
					} else {
						$mfs['children'][] = $result;
					}
				// otherwise, top-level mf
				} else {
					$mfs[] = $result;
				}
			}
		}

		return $mfs;
	}