Adapts the AST sub-tree that is rooted at the given cell node.
344611
def adapt_table_cell!(parsed_cell)
      # Saving off the original data
      parsed_cell['cuke_modeler_parsing_data'] = Marshal::load(Marshal.dump(parsed_cell))

      parsed_cell['value'] = parsed_cell.delete(:value)
      parsed_cell['line'] = parsed_cell.delete(:location)[:line]
    end
924105
protected void rebuildTree() {
    final int dim = root.getDimensionality();
    double t = estimateThreshold(root) / leaves;
    t *= t;
    // Never decrease the threshold.
    thresholdsq = t > thresholdsq ? t : thresholdsq;
    LOG.debug("New squared threshold: " + thresholdsq);

    LeafIterator iter = new LeafIterator(root); // Will keep the old root.
    assert (iter.valid());
    ClusteringFeature first = iter.get();

    leaves = 0;
    // Make a new root node:
    root = new TreeNode(dim, capacity);
    root.children[0] = first;
    root.addToStatistics(first);
    ++leaves;
    for(iter.advance(); iter.valid(); iter.advance()) {
      TreeNode other = insert(root, iter.get());
      // Handle root overflow:
      if(other != null) {
        TreeNode newnode = new TreeNode(dim, capacity);
        newnode.addToStatistics(newnode.children[0] = root);
        newnode.addToStatistics(newnode.children[1] = other);
        root = newnode;
      }
    }
  }
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
810196
def build_ast(self):
        """"""
        n = self.root_node
        if n.type == syms.file_input:
            stmts = []
            for i in range(len(n.children) - 1):
                stmt = n.children[i]
                if stmt.type == tokens.NEWLINE:
                    continue
                sub_stmts_count = self.number_of_statements(stmt)
                if sub_stmts_count == 1:
                    stmts.append(self.handle_stmt(stmt))
                else:
                    stmt = stmt.children[0]
                    for j in range(sub_stmts_count):
                        small_stmt = stmt.children[j * 2]
                        stmts.append(self.handle_stmt(small_stmt))
            return ast.Module(stmts)
        elif n.type == syms.eval_input:
            body = self.handle_testlist(n.children[0])
            return ast.Expression(body)
        elif n.type == syms.single_input:
            first_child = n.children[0]
            if first_child.type == tokens.NEWLINE:
                # An empty line.
                return ast.Interactive([])
            else:
                num_stmts = self.number_of_statements(first_child)
                if num_stmts == 1:
                    stmts = [self.handle_stmt(first_child)]
                else:
                    stmts = []
                    for i in range(0, len(first_child.children), 2):
                        stmt = first_child.children[i]
                        if stmt.type == tokens.NEWLINE:
                            break
                        stmts.append(self.handle_stmt(stmt))
                return ast.Interactive(stmts)
        else:
            raise AssertionError("unknown root node")
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
762837
def aux_moveTree(offset, tree):
	""""""
	if tree.x1 != None and tree.x2 != None :
		tree.x1, tree.x2 = tree.x1+offset, tree.x2+offset
		
	for c in tree.children:
		aux_moveTree(offset, c)
592734
public static void mergeNodeChildren(TreeNode node) {
        DefaultMutableTreeNode masterNode = (DefaultMutableTreeNode) node;

        // The rules are there are no rules. Nothing else needs to be done
        // except for merging through the children
        for (int i = 0; i < masterNode.getChildCount(); i++) {
            DefaultMutableTreeNode child = (DefaultMutableTreeNode) masterNode.getChildAt(i);

            if (!child.isLeaf()) {
                MergeHelpUtilities.mergeNodeChildren(DEFAULT_MERGE_TYPE, child);
            }
        }
    }
1271761
public static void expandNodes(@NonNull JTree tree)
	{
		for (int i = 0; i < tree.getRowCount(); i++)
		{
			tree.expandRow(i);
		}
	}
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();
   }
984591
private void adaptForInsert(final ITreeData paramNewNode, final boolean addAsFirstChild) throws TTException {
        assert paramNewNode != null;

        if (paramNewNode instanceof ITreeStructData) {
            final ITreeStructData strucNode = (ITreeStructData)paramNewNode;
            final ITreeStructData parent = (ITreeStructData)getPtx().getData(paramNewNode.getParentKey());
            parent.incrementChildCount();
            if (addAsFirstChild) {
                parent.setFirstChildKey(paramNewNode.getDataKey());
            }
            getPtx().setData(parent);

            if (strucNode.hasRightSibling()) {
                final ITreeStructData rightSiblingNode =
                    (ITreeStructData)getPtx().getData(strucNode.getRightSiblingKey());
                rightSiblingNode.setLeftSiblingKey(paramNewNode.getDataKey());
                getPtx().setData(rightSiblingNode);
            }
            if (strucNode.hasLeftSibling()) {
                final ITreeStructData leftSiblingNode =
                    (ITreeStructData)getPtx().getData(strucNode.getLeftSiblingKey());
                leftSiblingNode.setRightSiblingKey(paramNewNode.getDataKey());
                getPtx().setData(leftSiblingNode);
            }
        }

    }
938858
protected AbstractNode adopt(AbstractNode child) throws IllegalStateException {
		child.ensureParentless();
		child.parent = this;
		return child;
	}
71949
private void trainOnInstanceImpl(Instance inst) {
		if(this.treeRoot == null){
			this.treeRoot = newLearningNode(this.parallelismHint);
			this.activeLeafNodeCount = 1;
                        
		}
		FoundNode foundNode = this.treeRoot.filterInstanceToLeaf(inst, null, -1);
                trainOnInstanceImpl(foundNode, inst);
        }
866757
private static List<JoinNode> generateInnerJoinOrdersForTree(JoinNode subTree) {
        // Get a list of the leaf nodes(tables) to permute them
        List<JoinNode> tableNodes = subTree.generateLeafNodesJoinOrder();
        List<List<JoinNode>> joinOrders = PermutationGenerator.generatePurmutations(tableNodes);
        List<JoinNode> newTrees = new ArrayList<>();
        for (List<JoinNode> joinOrder: joinOrders) {
            newTrees.add(JoinNode.reconstructJoinTreeFromTableNodes(joinOrder, JoinType.INNER));
        }
        //Collect all the join/where conditions to reassign them later
        AbstractExpression combinedWhereExpr = subTree.getAllFilters();
        List<JoinNode> treePermutations = new ArrayList<>();
        for (JoinNode newTree : newTrees) {
            if (combinedWhereExpr != null) {
                newTree.setWhereExpression(combinedWhereExpr.clone());
            }
            // The new tree root node id must match the original one to be able to reconnect the
            // subtrees
            newTree.setId(subTree.getId());
            treePermutations.add(newTree);
        }
        return treePermutations;
    }
413087
public void replaceScript(JsAst ast) {
    CompilerInput input = this.getInput(ast.getInputId());
    if (!replaceIncrementalSourceAst(ast)) {
      return;
    }
    Node originalRoot = checkNotNull(input.getAstRoot(this));

    processNewScript(ast, originalRoot);
  }
1334753
void flattenSets() {
        Assert.assrt(fType != setRef);

        if (fLeftChild != null) {
            if (fLeftChild.fType == setRef) {
                RBBINode setRefNode = fLeftChild;
                RBBINode usetNode = setRefNode.fLeftChild;
                RBBINode replTree = usetNode.fLeftChild;
                fLeftChild = replTree.cloneTree();
                fLeftChild.fParent = this;
            } else {
                fLeftChild.flattenSets();
            }
        }

        if (fRightChild != null) {
            if (fRightChild.fType == setRef) {
                RBBINode setRefNode = fRightChild;
                RBBINode usetNode = setRefNode.fLeftChild;
                RBBINode replTree = usetNode.fLeftChild;
                fRightChild = replTree.cloneTree();
                fRightChild.fParent = this;
                // delete setRefNode;
            } else {
                fRightChild.flattenSets();
            }
        }
    }
48110
def add_subtree(cls, for_node, node, options):
        
        if cls.is_loop_safe(for_node, node):
            options.append(
                (node.pk,
                 mark_safe(cls.mk_indent(node.get_depth()) + escape(node))))
            for subnode in node.get_children():
                cls.add_subtree(for_node, subnode, options)
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