Processes the {Haml::Parser::ParseNode} tree and returns a tree composed
 of friendlier {HamlLint::Tree::Node}s.

 @param original_tree [Haml::Parser::ParseNode]
 @return [Haml::Tree::Node]
15426
def process_tree(original_tree)
      # Remove the trailing empty HAML comment that the parser creates to signal
      # the end of the HAML document
      if Gem::Requirement.new('~> 4.0.0').satisfied_by?(Gem.loaded_specs['haml'].version)
        original_tree.children.pop
      end

      @node_transformer = HamlLint::NodeTransformer.new(self)
      convert_tree(original_tree)
    end
727780
def from_etree(
    el, node=None, node_cls=None,
    tagsub=functools.partial(re.sub, r'\{.+?\}', ''),
    Node=Node):
    '''
    '''
    node_cls = node_cls or Node
    if node is None:
        node = node_cls()
    tag = tagsub(el.tag)
    attrib = dict((tagsub(k), v) for (k, v) in el.attrib.items())
    node.update(attrib, tag=tag)

    if el.text:
        node['text'] = el.text
    for child in el:
        child = from_etree(child, node_cls=node_cls)
        node.append(child)
    if el.tail:
        node['tail'] = el.tail
    return node
1125200
def deep_clone!(options = {})
      processed_options = Para::Cloneable::IncludeTreeBuilder.new(self, cloneable_options).build
      options = options.reverse_merge(processed_options)
      callback = build_clone_callback(options.delete(:prepare))
      
      deep_clone(options) do |original, clone|
        Para::Cloneable::AttachmentsCloner.new(original, clone).clone!
        callback&.call(original, clone)
      end
    end
715808
def merge_reference_trees(roots)
      roots.inject(empty_forest) do |forest, root|
        root.keys do |full_key, node|
          if full_key == node.value.to_s
            log_warn(
              "Self-referencing key #{node.full_key(root: false).inspect} in #{node.data[:locale].inspect}"
            )
          end
        end
        forest.merge!(
          root.children,
          on_leaves_merge: lambda do |node, other|
            if node.value != other.value
              log_warn(
                'Conflicting references: '\
            "#{node.full_key(root: false)} ⮕ #{node.value} in #{node.data[:locale]},"\
            " but ⮕ #{other.value} in #{other.data[:locale]}"
              )
            end
          end
        )
      end
    end
1208294
def replace_parent(self, parent_simples):
        
        assert parent_simples

        ancestors = parent_simples[:-1]
        parent = parent_simples[-1]

        did_replace = False
        new_tokens = []
        for token in self.tokens:
            if not did_replace and token in ('&', 'self'):
                did_replace = True
                new_tokens.extend(parent.tokens)
                if token == 'self':
                    warn(FutureWarning(
                        "The xCSS 'self' selector is deprecated and will be "
                        "removed in 2.0.  Use & instead.  ({0!r})"
                        .format(self)
                    ))
            else:
                new_tokens.append(token)

        if not did_replace:
            # This simple selector doesn't contain a parent reference so just
            # stick it on the end
            return parent_simples + (self,)

        # This simple selector was merged into the direct parent.
        merged_self = type(self)(parent.combinator, new_tokens)
        selector = ancestors + (merged_self,)
        # Our combinator goes on the first ancestor, i.e., substituting "foo
        # bar baz" into "+ &.quux" produces "+ foo bar baz.quux".  This means a
        # potential conflict with the first ancestor's combinator!
        root = selector[0]
        if not _is_combinator_subset_of(self.combinator, root.combinator):
            raise ValueError(
                "Can't sub parent {0!r} into {1!r}: "
                "combinators {2!r} and {3!r} conflict!"
                .format(
                    parent_simples, self, self.combinator, root.combinator))

        root = type(self)(self.combinator, root.tokens)
        selector = (root,) + selector[1:]
        return tuple(selector)
749602
final TreeNode<K,V> findTreeNode(int h, Object k, Class<?> kc) {
            if (k != null) {
                TreeNode<K,V> p = this;
                do {
                    int ph, dir; K pk; TreeNode<K,V> q;
                    TreeNode<K,V> pl = p.left, pr = p.right;
                    if ((ph = p.hash) > h)
                        p = pl;
                    else if (ph < h)
                        p = pr;
                    else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
                        return p;
                    else if (pl == null)
                        p = pr;
                    else if (pr == null)
                        p = pl;
                    else if ((kc != null ||
                              (kc = comparableClassFor(k)) != null) &&
                             (dir = compareComparables(kc, k, pk)) != 0)
                        p = (dir < 0) ? pl : pr;
                    else if ((q = pr.findTreeNode(h, k, kc)) != null)
                        return q;
                    else
                        p = pl;
                } while (p != null);
            }
            return null;
        }
1068910
def from_etree(cls, etree_element):
        
        ins = SaltEdge.from_etree(etree_element)
        # TODO: this looks dangerous, ask Stackoverflow about it!
        # convert SaltEdge into DominanceRelation
        ins.__class__ = DominanceRelation.mro()[0]
        ins.features = get_annotations(etree_element)
        return ins
1133048
def flattenTrees(root, nodeSelector: Callable[[LNode], bool]):
    
    for ch in root.children:
        if ch.children:
            flattenTrees(ch, nodeSelector)

    # collect all nodes which can be potentialy reduced
    reducibleChildren = set()
    for ch in root.children:
        if nodeSelector(ch):
            reducibleChildren.add(ch)

    while reducibleChildren:
        # try to pick a node from random tree and search it's root
        _treeRoot = reducibleChildren.pop()
        reducibleChildren.add(_treeRoot)
        # we need to keep order of inputs, use preorder
        treeRoot = searchRootOfTree(reducibleChildren, _treeRoot)

        reducedNodes, inputEdges = collectNodesInTree(treeRoot, reducibleChildren)
        # if tree is big enoguh for reduction, reduce it to single node
        if len(reducedNodes) > 1:
            newName = reducedNodes[0].name
            newNode = root.addNode(newName)

            o = newNode.addPort("", PortType.OUTPUT, PortSide.EAST)

            oEdges = treeRoot.east[0].outgoingEdges
            for outputedge in list(oEdges):
                dsts = list(outputedge.dsts)
                assert len(dsts) > 0
                outputedge.remove()
                root.addHyperEdge([o, ], dsts, originObj=outputedge.originObj)

            for i, (iN, iP, iE) in enumerate(inputEdges):
                name = None
                index = len(inputEdges) - i - 1
                if hasattr(iE.originObj, "_dtype"):
                    w = iE.originObj._dtype.bit_length()
                    if w > 1:
                        name = "[%d:%d]" % ((index + 1) * w, index * w)
                    else:
                        name = None

                if name is None:
                    name = "[%d]" % (index)

                inp = newNode.addPort(name,
                                      PortType.INPUT, PortSide.WEST)
                iE.removeTarget(iP)
                iE.addTarget(inp)

            for n in reducedNodes:
                root.children.remove(n)
                reducibleChildren.remove(n)
        else:
            reducibleChildren.remove(reducedNodes[0])
1264107
private Grammar cloneGrammarIntoNewResourceSet(final Grammar original) {
    final Resource originalResource = original.eResource();
    XtextResourceSet _xtextResourceSet = new XtextResourceSet();
    final XtextResourceSet clonedResourceSet = EcoreUtil2.<XtextResourceSet>clone(_xtextResourceSet, originalResource.getResourceSet());
    final Resource clonedResource = clonedResourceSet.getResource(originalResource.getURI(), false);
    EObject _head = IterableExtensions.<EObject>head(clonedResource.getContents());
    return ((Grammar) _head);
  }
354547
def qbe_tree(graph, nodes, root=None):
    
    if root:
        start = root
    else:
        index = random.randint(0, len(nodes) - 1)
        start = nodes[index]
    # A queue to BFS instead DFS
    to_visit = deque()
    cnodes = copy(nodes)
    visited = set()
    # Format is (parent, parent_edge, neighbor, neighbor_field)
    to_visit.append((None, None, start, None))
    tree = {}
    while len(to_visit) != 0 and nodes:
        parent, parent_edge, v, v_edge = to_visit.pop()
        # Prune
        if v in nodes:
            nodes.remove(v)
        node = graph[v]
        if v not in visited and len(node) > 1:
            visited.add(v)
            # Preorder process
            if all((parent, parent_edge, v, v_edge)):
                if parent not in tree:
                    tree[parent] = []
                if (parent_edge, v, v_edge) not in tree[parent]:
                    tree[parent].append((parent_edge, v, v_edge))
                if v not in tree:
                    tree[v] = []
                if (v_edge, parent, parent_edge) not in tree[v]:
                    tree[v].append((v_edge, parent, parent_edge))
            # Iteration
            for node_edge, neighbor, neighbor_edge in node:
                value = (v, node_edge, neighbor, neighbor_edge)
                to_visit.append(value)
    remove_leafs(tree, cnodes)
    return tree, (len(nodes) == 0)
387002
def get_tree(cls, parent=None):
        
        cls = get_result_class(cls)

        if parent is None:
            # return the entire tree
            return cls.objects.all()
        if parent.is_leaf():
            return cls.objects.filter(pk=parent.pk)
        return cls.objects.filter(
            tree_id=parent.tree_id,
            lft__range=(parent.lft, parent.rgt - 1))
909156
def and_after_calling_original
      self.and_wrap_original do |m, *args, &block|
        result = m.call(*args, &block)
        yield result
        result
      end
    end
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)
793919
def dplptree2dgparentedtree(self):
        
        def transform(dplp_tree):
            """Transform a DPLP parse tree into a more conventional parse tree."""
            if isinstance(dplp_tree, basestring) or not hasattr(dplp_tree, 'label'):
                return dplp_tree
            assert len(dplp_tree) == 2, "We can only handle binary trees."

            match = DPLP_REL_RE.match(dplp_tree.label())
            assert match, "Relation '{}' does not match regex '{}'".format(dplp_tree.label(), DPLP_REL_RE)
            left_child_nuc, right_child_nuc, relname = match.groups()
            dplp_tree._label = relname

            for i, child_nuclearity in enumerate([left_child_nuc, right_child_nuc]):
                child = dplp_tree[i]
                dplp_tree[i] = Tree(child_nuclearity, [transform(child)])
            return dplp_tree

        tree = transform(self.parsetree)
        return DGParentedTree.convert(tree)
1303086
static LeafNodeDupMutable convert(@NotNull ILeafNode ln, @NotNull BTreeMutable mainTree) {

        final boolean isLeafNodeDup = ln.isDup();
        if (isLeafNodeDup && ln instanceof LeafNodeDupMutable) {
            return (LeafNodeDupMutable) ln;
        }

        // wrapper tree that doesn't allow duplicates
        final BTreeDupMutable dupTree = isLeafNodeDup ?
                ((LeafNodeDup) ln).getTreeCopyMutable() :
                new BTreeDupMutable(
                        new BTreeEmpty(mainTree.getLog(), mainTree.getBalancePolicy(), false, mainTree.getStructureId()),
                        ln.getKey()
                );
        dupTree.mainTree = mainTree;
        return convert(ln, mainTree, dupTree);
    }
269739
function factory(original) {
  replacement.locator = original.locator

  return replacement

  /* Replacer for tokeniser or visitor. */
  function replacement(node) {
    var self = this
    var result = original.apply(self, arguments)
    var marker = result && result.type ? result : node
    var data

    try {
      data = jsYAML.safeLoad(marker.value)
      data = data && data.remark

      if (data) {
        self.setOptions(data)
      }
    } catch (error) {
      self.file.fail(error.message, marker)
    }

    return result
  }
}
544201
def parsesingle(s, strictmode=True, expansionlimit=None, convertpos=False):
    ''''''
    p = _parser(s, strictmode=strictmode, expansionlimit=expansionlimit)
    tree = p.parse()
    if convertpos:
        ast.posconverter(s).visit(tree)
    return tree