Adapts the AST sub-tree that is rooted at the given background node.
191988
def adapt_background!(parsed_background, gathered_comments)
      # Saving off the original data
      parsed_background['cuke_modeler_parsing_data'] = Marshal::load(Marshal.dump(parsed_background))

      # Removing parsed data for child elements in order to avoid duplicating data
      parsed_background['cuke_modeler_parsing_data']['steps'] = nil

      if parsed_background['comments']
        parsed_background['cuke_modeler_parsing_data']['comments'] = nil
        gathered_comments.concat(parsed_background['comments'])
      end

      if parsed_background['steps']
        parsed_background['steps'].each do |step|
          adapt_step!(step, gathered_comments)
        end
      end
    end
784061
public static void apply(Program program, TreeGP manager)
   {
      int iMaxProgramDepth = manager.getMaxProgramDepth();
      TGPMutationStrategy method = manager.getMutationStrategy();
      RandEngine randEngine = manager.getRandEngine();
      
      if (method == TGPMutationStrategy.MUTATION_SUBTREE || method == TGPMutationStrategy.MUTATION_SUBTREE_KINNEAR)
      {
         TreeNode node = program.anyNode(randEngine)._1();
         int depth = program.calcDepth();

         TreeNode root = program.getRoot();

         if (method == TGPMutationStrategy.MUTATION_SUBTREE)
         {
            int node_depth = root.depth2Node(node);
            node.getChildren().clear();

            node.setPrimitive(program.anyPrimitive(randEngine));

            if (!node.getPrimitive().isTerminal())
            {
               int max_depth = iMaxProgramDepth - node_depth;
               TreeGenerator.createWithDepth(program, node, max_depth, TGPInitializationStrategy.INITIALIZATION_METHOD_GROW, randEngine);
            }
         }
         else
         {
            int subtree_depth = root.depth2Node(node);
            int current_depth = depth - subtree_depth;
            int max_depth = (int)(depth * 1.15) - current_depth;

            node.getChildren().clear();
            node.setPrimitive(program.anyPrimitive(randEngine));

            if (!node.getPrimitive().isTerminal())
            {
               TreeGenerator.createWithDepth(program, node, max_depth, TGPInitializationStrategy.INITIALIZATION_METHOD_GROW, randEngine);
            }
         }
      }
      else if (method == TGPMutationStrategy.MUTATION_HOIST)
      {
         TreeNode node = program.anyNode(randEngine)._1();

         if (node != program.getRoot())
         {
            program.setRoot(node);
         }
      }
      else if (method == TGPMutationStrategy.MUTATION_SHRINK)
      {
         TreeNode node = program.anyNode(randEngine)._1();
         node.getChildren().clear();
         node.setPrimitive(program.anyTerminal(randEngine));
      }

      program.calcDepth();
      program.calcLength();
   }
167250
def reduce_tree(node, parent=None):
    

    new_node = None
    #switch on the node type
    if node.type == syms.Matcher:
        #skip
        node = node.children[0]

    if node.type == syms.Alternatives  :
        #2 cases
        if len(node.children) <= 2:
            #just a single 'Alternative', skip this node
            new_node = reduce_tree(node.children[0], parent)
        else:
            #real alternatives
            new_node = MinNode(type=TYPE_ALTERNATIVES)
            #skip odd children('|' tokens)
            for child in node.children:
                if node.children.index(child)%2:
                    continue
                reduced = reduce_tree(child, new_node)
                if reduced is not None:
                    new_node.children.append(reduced)
    elif node.type == syms.Alternative:
        if len(node.children) > 1:

            new_node = MinNode(type=TYPE_GROUP)
            for child in node.children:
                reduced = reduce_tree(child, new_node)
                if reduced:
                    new_node.children.append(reduced)
            if not new_node.children:
                # delete the group if all of the children were reduced to None
                new_node = None

        else:
            new_node = reduce_tree(node.children[0], parent)

    elif node.type == syms.Unit:
        if (isinstance(node.children[0], pytree.Leaf) and
            node.children[0].value == '('):
            #skip parentheses
            return reduce_tree(node.children[1], parent)
        if ((isinstance(node.children[0], pytree.Leaf) and
               node.children[0].value == '[')
               or
               (len(node.children)>1 and
               hasattr(node.children[1], "value") and
               node.children[1].value == '[')):
            #skip whole unit if its optional
            return None

        leaf = True
        details_node = None
        alternatives_node = None
        has_repeater = False
        repeater_node = None
        has_variable_name = False

        for child in node.children:
            if child.type == syms.Details:
                leaf = False
                details_node = child
            elif child.type == syms.Repeater:
                has_repeater = True
                repeater_node = child
            elif child.type == syms.Alternatives:
                alternatives_node = child
            if hasattr(child, 'value') and child.value == '=': # variable name
                has_variable_name = True

        #skip variable name
        if has_variable_name:
            #skip variable name, '='
            name_leaf = node.children[2]
            if hasattr(name_leaf, 'value') and name_leaf.value == '(':
                # skip parenthesis
                name_leaf = node.children[3]
        else:
            name_leaf = node.children[0]

        #set node type
        if name_leaf.type == token_labels.NAME:
            #(python) non-name or wildcard
            if name_leaf.value == 'any':
                new_node = MinNode(type=TYPE_ANY)
            else:
                if hasattr(token_labels, name_leaf.value):
                    new_node = MinNode(type=getattr(token_labels, name_leaf.value))
                else:
                    new_node = MinNode(type=getattr(pysyms, name_leaf.value))

        elif name_leaf.type == token_labels.STRING:
            #(python) name or character; remove the apostrophes from
            #the string value
            name = name_leaf.value.strip("'")
            if name in tokens:
                new_node = MinNode(type=tokens[name])
            else:
                new_node = MinNode(type=token_labels.NAME, name=name)
        elif name_leaf.type == syms.Alternatives:
            new_node = reduce_tree(alternatives_node, parent)

        #handle repeaters
        if has_repeater:
            if repeater_node.children[0].value == '*':
                #reduce to None
                new_node = None
            elif repeater_node.children[0].value == '+':
                #reduce to a single occurence i.e. do nothing
                pass
            else:
                #TODO: handle {min, max} repeaters
                raise NotImplementedError
                pass

        #add children
        if details_node and new_node is not None:
            for child in details_node.children[1:-1]:
                #skip '<', '>' markers
                reduced = reduce_tree(child, new_node)
                if reduced is not None:
                    new_node.children.append(reduced)
    if new_node:
        new_node.parent = parent
    return new_node
728557
function loadSubTree(root, own) {
            var loadSubTrees = function (nodes) {
                    for (var i = 0; i < nodes.length; i++) {
                        nodes[i] = self.loadSubTree(nodes[i], own);
                    }
                    return TASYNC.lift(nodes);

                },
                childLoading = own === true ? self.loadOwnChildren : self.loadChildren;
            return TASYNC.call(function (children) {
                if (children.length < 1) {
                    return [root];
                } else {
                    return TASYNC.call(function (subArrays) {
                        var nodes = [],
                            i;
                        for (i = 0; i < subArrays.length; i++) {
                            nodes = nodes.concat(subArrays[i]);
                        }
                        nodes.unshift(root);
                        return nodes;
                    }, loadSubTrees(children));
                }
            }, childLoading(root));
        }
1029594
def adapt(parsed_ast)
      # Saving off the original data
      parsed_ast['cuke_modeler_parsing_data'] = Marshal::load(Marshal.dump(parsed_ast))

      # Removing parsed data for child elements in order to avoid duplicating data
      parsed_ast['cuke_modeler_parsing_data'][:feature] = nil
      parsed_ast['cuke_modeler_parsing_data'][:comments] = nil

      # Comments are stored on the feature file in gherkin 4.x
      parsed_ast['comments'] = []
      parsed_ast[:comments].each do |comment|
        adapt_comment!(comment)
      end
      parsed_ast['comments'].concat(parsed_ast.delete(:comments))

      adapt_feature!(parsed_ast[:feature]) if parsed_ast[:feature]
      parsed_ast['feature'] = parsed_ast.delete(:feature)

      [parsed_ast]
    end
1134174
def from_ast(
        pyast_node, node=None, node_cls=None, Node=Node,
        iter_fields=ast.iter_fields, AST=ast.AST):
    '''
    '''
    node_cls = node_cls or Node
    node = node or node_cls()
    name = pyast_node.__class__.__name__

    attrs = []
    for field, value in iter_fields(pyast_node):
        if name == 'Dict':
            for key, value in zip(pyast_node.keys, pyast_node.values):
                if isinstance(value, list):
                    for item in value:
                        if isinstance(item, AST):
                            value = from_ast(item)
                elif isinstance(value, AST):
                    value = from_ast(value)
                attrs.append((key.s, value))
        else:
            if isinstance(value, list):
                for item in value:
                    if isinstance(item, AST):
                        value = from_ast(item)
            elif isinstance(value, AST):
                value = from_ast(value)
            attrs.append((field, value))
    node.update(attrs, type=name)
    return node
549996
private void tryReplaceSuper(Node superNode) {
    checkState(!superclasses.isEmpty(), "`super` cannot appear outside a function");
    Optional<Node> currentSuperclass = superclasses.peek();
    if (!currentSuperclass.isPresent() || !currentSuperclass.get().isQualifiedName()) {
      // either if a) we're in a static class fn without an 'extends' clause or b) we're not in
      // a static class function
      return;
    }

    Node fullyQualifiedSuperRef = currentSuperclass.get().cloneTree();
    superNode.replaceWith(fullyQualifiedSuperRef);
    compiler.reportChangeToEnclosingScope(fullyQualifiedSuperRef);
  }
518905
private static <P extends GISPrimitive, N extends AbstractGISTreeSetNode<P, N>>
		N rearrangeTree(AbstractGISTreeSet<P, N> tree, N node, Rectangle2afp<?, ?, ?, ?, ?, ?> desiredBounds,
				GISTreeSetNodeFactory<P, N> builder) {
		// Search for the node that completely contains the desired area
		N topNode = node.getParentNode();
		while (topNode != null && isOutsideNodeBuildingBounds(topNode, desiredBounds)) {
			topNode = topNode.getParentNode();
		}

		final Rectangle2afp<?, ?, ?, ?, ?, ?> dr;
		if (topNode == null) {
			// Node node found, the entire tree should be rebuilt
			topNode = tree.getTree().getRoot();
			if (topNode == null) {
				throw new IllegalStateException();
			}
			dr = union(topNode, desiredBounds);
		} else {
			dr = getNormalizedNodeBuildingBounds(topNode, desiredBounds);
		}

		// Build a new subtree
		final N parent = topNode.getParentNode();
		final Iterator<P> dataIterator = new PrefixDataDepthFirstTreeIterator<>(topNode);
		final N newTopNode = builder.newNode(
				topNode.getZone(),
				dr.getMinX(), dr.getMinY(), dr.getWidth(), dr.getHeight());
		while (dataIterator.hasNext()) {
			if (!addInside(tree, newTopNode, dataIterator.next(), builder, false)) {
				throw new IllegalStateException();
			}
		}

		// Replace rearranged subtree by the new one
		if (parent != null) {
			parent.setChildAt(topNode.getZone().ordinal(), newTopNode);
			return parent;
		}
		tree.getTree().setRoot(newTopNode);
		return newTopNode;
	}
124340
protected void adopt(final CmsTreeItem item) {

        item.setParentItem(this);
        item.setTree(m_tree);
        onChangeChildren();
        if ((m_tree != null) && m_tree.isAnimationEnabled()) {
            // could be null if not yet attached
            item.getElement().getStyle().setOpacity(0);
            // animate
            (new Animation() {

                /**
                 * @see com.google.gwt.animation.client.Animation#onUpdate(double)
                 */
                @Override
                protected void onUpdate(double progress) {

                    item.getElement().getStyle().setOpacity(progress);
                }
            }).run(ANIMATION_DURATION);
        }
    }
1258864
def add_node_parents(root: ast.AST) -> None:
    
    for node in ast.walk(root):
        for child in ast.iter_child_nodes(node):
            child.parent = node
1311398
private void fillNodesInContext(SiteNode rootNode, List<SiteNode> nodesList) {
		@SuppressWarnings("unchecked")
		Enumeration<TreeNode> en = rootNode.children();
		while (en.hasMoreElements()) {
			SiteNode sn = (SiteNode) en.nextElement();
			if (isInContext(sn)) {
				nodesList.add(sn);
			}
			fillNodesInContext(sn, nodesList);
		}
	}
1098550
private void mapTreeHierarchy(final WComponent currentComponent,
			final StringTreeNode currentNode, final WText selectedMenuText) {
		if (currentNode.isLeaf()) {
			WMenuItem menuItem = new WMenuItem(currentNode.getData(), new ExampleMenuAction(
					selectedMenuText));
			menuItem.setActionObject(currentNode.getData());
			if (currentComponent instanceof WMenu) {
				((WMenu) currentComponent).add(menuItem);
			} else {
				((WSubMenu) currentComponent).add(menuItem);
			}
		} else {
			WSubMenu subMenu = new WSubMenu(currentNode.getData());
			subMenu.setSelectMode(SelectMode.SINGLE);

			if (currentComponent instanceof WMenu) {
				((WMenu) currentComponent).add(subMenu);
			} else {
				((WSubMenu) currentComponent).add(subMenu);
			}

			// Expand the first couple of levels in the tree by default.
			if (currentNode.getLevel() < 2) {
				subMenu.setOpen(true);
			}

			for (Iterator<TreeNode> i = currentNode.children(); i.hasNext();) {
				mapTreeHierarchy(subMenu, (StringTreeNode) i.next(), selectedMenuText);
			}
		}
	}
453093
def node_branch(self, astr_node, abranch):
            
            self.dict_branch[astr_node].node_dictBranch(abranch.dict_branch)
544315
def _handle_file_ast(self, node, scope, ctxt, stream):
        
        self._root = ctxt = fields.Dom(stream)
        ctxt._pfp__scope = scope
        self._root._pfp__name = "__root"
        self._root._pfp__interp = self
        self._dlog("handling file AST with {} children".format(len(node.children())))

        for child in node.children():
            self._handle_node(child, scope, ctxt, stream)

        ctxt._pfp__process_fields_metadata()

        return ctxt
494491
private void adjustNodeCount(final int delta) {
		for (TableTreeNode parent = this; parent != null; parent = (TableTreeNode) parent.
				getParent()) {
			parent.nodeCount += delta;
		}
	}
887328
def update_tree(root, executed_acts, total_rew):
    
    root.value = max(total_rew, root.value)
    root.visits += 1
    new_nodes = 0

    node = root
    for step, act in enumerate(executed_acts):
        if act not in node.children:
            node.children[act] = Node()
            new_nodes += 1
        node = node.children[act]
        node.value = max(total_rew, node.value)
        node.visits += 1

    return new_nodes
479275
def visit_setcomp(self, node, parent):
        """"""
        newnode = nodes.SetComp(node.lineno, node.col_offset, parent)
        newnode.postinit(
            self.visit(node.elt, newnode),
            [self.visit(child, newnode) for child in node.generators],
        )
        return newnode