Print out a table of nodes and the blocks they have at each block height
    starting with the common ancestor.
978489
def print_table(graph, tails, node_id_map):
    """"""
    node_count = len(tails)

    # Get the width of the table columns
    num_col_width = max(
        floor(log(max(get_heights(tails)), 10)) + 1,
        len("NUM"))
    node_col_width = max(
        floor(log(node_count, 10)) + 1,
        8)

    # Construct the output format string
    format_str = ''
    format_str += '{:<' + str(num_col_width) + '} '
    for _ in range(node_count):
        format_str += '{:<' + str(node_col_width) + '} '

    nodes_header = ["NODE " + str(node_id_map[i]) for i in range(node_count)]
    header = format_str.format("NUM", *nodes_header)
    print(header)
    print('-' * len(header))

    prev_block_num = -1
    node_list = [''] * node_count
    for block_num, _, siblings in graph.walk():
        if block_num != prev_block_num:
            # Need to skip the first one
            if prev_block_num != -1:
                print(format_str.format(prev_block_num, *node_list))

            node_list.clear()
            node_list.extend([''] * node_count)
            prev_block_num = block_num

        for block_id, node_ids in siblings.items():
            for node_id in node_ids:
                node_list[node_id] = block_id[:8]

    # Print the last one
    print(format_str.format(prev_block_num, *node_list))
1116239
def get_ancestors(self, limit: int, header: BlockHeader) -> Tuple[BaseBlock, ...]:
        
        ancestor_count = min(header.block_number, limit)

        # We construct a temporary block object
        vm_class = self.get_vm_class_for_block_number(header.block_number)
        block_class = vm_class.get_block_class()
        block = block_class(header=header, uncles=[])

        ancestor_generator = iterate(compose(
            self.get_block_by_hash,
            operator.attrgetter('parent_hash'),
            operator.attrgetter('header'),
        ), block)
        # we peel off the first element from the iterator which will be the
        # temporary block object we constructed.
        next(ancestor_generator)

        return tuple(take(ancestor_count, ancestor_generator))
952946
def ancestors(self):
        
        ancestors = []
        node = self.ancestor
        while node is not None:
            ancestors.append(node)
            node = node.ancestor
        return ancestors
198174
def _generate_dendro(self, current_section, spacing, offsets):
        '''
        '''
        max_dims = self._max_dims
        start_x = _spacingx(current_section, max_dims, offsets[0], spacing[0])

        for child in current_section.children:

            segments = child.points

            # number of leaves in child
            terminations = _n_terminations(child)

            # segement lengths
            seg_lengths = np.linalg.norm(np.subtract(segments[:-1, COLS.XYZ],
                                                     segments[1:, COLS.XYZ]), axis=1)

            # segment radii
            radii = np.vstack((segments[:-1, COLS.R], segments[1:, COLS.R])).T \
                if self._show_diameters else np.zeros((seg_lengths.shape[0], 2))

            y_offset = offsets[1]
            for i, slen in enumerate(seg_lengths):

                # offset update for the vertical segments
                new_offsets = _update_offsets(start_x, spacing, terminations,
                                              (offsets[0], y_offset), slen)

                # segments are drawn vertically, thus only y_offset changes from init offsets
                self._rectangles[self._n] = _vertical_segment((offsets[0], y_offset),
                                                              new_offsets, spacing, radii[i, :])
                self._n += 1
                y_offset = new_offsets[1]

            if y_offset + spacing[1] * 2 + sum(seg_lengths) > max_dims[1]:
                max_dims[1] = y_offset + spacing[1] * 2. + sum(seg_lengths)

            self._max_dims = max_dims
            # recursive call to self.
            self._generate_dendro(child, spacing, new_offsets)

            # update the starting position for the next child
            start_x += terminations * spacing[0]

            # write the horizontal lines only for bifurcations, where the are actual horizontal
            # lines and not zero ones
            if offsets[0] != new_offsets[0]:

                # horizontal segment. Thickness is either 0 if show_diameters is false
                # or 1. if show_diameters is true
                self._rectangles[self._n] = _horizontal_segment(offsets, new_offsets, spacing, 0.)
                self._n += 1
790475
def indx_table(node_dict, tbl_mode=False):
    """"""
    nt = PrettyTable()
    nt.header = False
    nt.padding_width = 2
    nt.border = False
    clr_num = C_TI + "NUM"
    clr_name = C_TI + "NAME"
    clr_state = "STATE" + C_NORM
    t_lu = {True: [clr_num, "NAME", "REGION", "CLOUD",
                   "SIZE", "PUBLIC IP", clr_state],
            False: [clr_name, "REGION", "CLOUD", "SIZE",
                    "PUBLIC IP", clr_state]}
    nt.add_row(t_lu[tbl_mode])
    for i, node in node_dict.items():
        state = C_STAT[node.state] + node.state + C_NORM
        inum = C_WARN + str(i) + C_NORM
        if node.public_ips:
            n_ip = node.public_ips
        else:
            n_ip = "-"
        r_lu = {True: [inum, node.name, node.zone, node.cloud,
                       node.size, n_ip, state],
                False: [node.name, node.zone, node.cloud,
                        node.size, n_ip, state]}
        nt.add_row(r_lu[tbl_mode])
    if not tbl_mode:
        print(nt)
    else:
        idx_tbl = nt.get_string()
        return idx_tbl
180379
def print_tree(current_node, childattr='children', nameattr='name', indent='', last='updown'):

    if hasattr(current_node, nameattr):
        name = lambda node: getattr(node, nameattr)
    else:
        name = lambda node: str(node)

    children = lambda node: getattr(node, childattr)
    nb_children = lambda node: sum(nb_children(child) for child in children(node)) + 1
    size_branch = {child: nb_children(child) for child in children(current_node)}

    
    up = sorted(children(current_node), key=lambda node: nb_children(node))
    down = []
    while up and sum(size_branch[node] for node in down) < sum(size_branch[node] for node in up):
        down.append(up.pop())

    """ Printing of "up" branch. """
    for child in up:     
        next_last = 'up' if up.index(child) is 0 else ''
        next_indent = '{0}{1}{2}'.format(indent, ' ' if 'up' in last else '│', ' ' * len(name(current_node)))
        print_tree(child, childattr, nameattr, next_indent, next_last)

    """ Printing of current node. """
    if last == 'up': start_shape = '┌'
    elif last == 'down': start_shape = '└'
    elif last == 'updown': start_shape = ' '
    else: start_shape = '├'

    if up: end_shape = '┤'
    elif down: end_shape = '┐'
    else: end_shape = ''

    print('{0}{1}{2}{3}'.format(indent, start_shape, name(current_node), end_shape))

    """ Printing of "down" branch. """
    for child in down:
        next_last = 'down' if down.index(child) is len(down) - 1 else ''
        next_indent = '{0}{1}{2}'.format(indent, ' ' if 'down' in last else '│', ' ' * len(name(current_node)))
        print_tree(child, childattr, nameattr, next_indent, next_last)
175075
def visit_print(self, node):
        """"""
        nodes = ", ".join(n.accept(self) for n in node.values)
        if not node.nl:
            nodes = "%s," % nodes
        if node.dest:
            return "print >> %s, %s" % (node.dest.accept(self), nodes)
        return "print %s" % nodes
1342159
private void printDocument(Node node, Hashtable properties) {

        // if node is empty do nothing... (Recursion)
        if (node == null) {
            return;
        }
        // initialise local variables
        int type = node.getNodeType();
        String name = node.getNodeName();

        // detect node type
        switch (type) {
            case Node.DOCUMENT_NODE:

                printDocument(((Document)node).getDocumentElement(), properties);
                break;
            case Node.ELEMENT_NODE:

                // check if its the <head> node. Nothing inside the <head> node
                // must be
                // part of the output, but we must scan the content of this
                // node to get all
                // <meta> tags
                if (name.equals(NODE_HEAD)) {
                    m_write = false;
                }
                // scan element node; if a block has to be removed or replaced,
                // break and discard child nodes
                transformStartElement(node, properties);

                // test if node has children
                NodeList children = node.getChildNodes();
                if (children != null) {
                    int len = children.getLength();
                    for (int i = 0; i < len; i++) {
                        // recursively call printDocument with all child nodes
                        printDocument(children.item(i), properties);
                    }
                }
                break;
            case Node.TEXT_NODE:

                // replace subStrings in text nodes
                transformTextNode(node);
                break;
            default:

                break;
        }
        // end of recursion, add eventual endtags and suffixes
        switch (type) {
            case Node.ELEMENT_NODE:
                // analyse endtags and add them to output
                transformEndElement(node);
                if (node.getNodeName().equals(NODE_HEAD)) {
                    m_write = true;
                }
                break;
            case Node.DOCUMENT_NODE:
                break;
            default:
                break;
        }
    }
377332
def _print(self, tree, prefix, carryon):
        
        level = prefix.count(self.cross) + prefix.count(self.vline)
        len_children = 0
        if isinstance(tree , _Node):
            len_children = len(tree.children)

        # add vertex
        prefix += str(tree)
        # and as many spaces as the vertex is long
        carryon += self.space * len(str(tree))
        if (level == self.maxdepth) or (not isinstance(tree, _Node)) or\
           (len_children == 0):
            self.stream.write(prefix+'\n')
            return
        else:
            # add in between connections
            prefix += self.hline
            carryon += self.space
            # if there is more than one branch, add a cross
            if len(tree.children) > 1:
                prefix += self.cross
                carryon += self.vline
            prefix += self.hline
            carryon += self.space

            if len_children > 0:
                # print the first branch (on the same line)
                self._print(tree.children[0], prefix, carryon)
                for b in range(1, len_children):
                    # the caryon becomes the prefix for all following children
                    prefix = carryon[:-2] + self.cross + self.hline
                    # remove the vlines for any children of last branch
                    if b == (len_children-1):
                        carryon = carryon[:-2] + 2*self.space
                    self._print(tree.children[b], prefix, carryon)
                    # leave a free line before the next branch
                    if b == (len_children-1):
                        if len(carryon.strip(' ')) == 0:
                            return
                        self.stream.write(carryon[:-2].rstrip()+'\n')
814404
def pretty_print(node):
        
        for pre, _, node in RenderTree(node):
            print('{}{}'.format(pre, node.name))
596783
def _get_ancestors_of(self, obs_nodes_list):
        
        if not obs_nodes_list:
            return set()
        return set(obs_nodes_list) | set(self.parent_node)
62497
def print_tree(graph, tails, node_id_map):
    """"""
    # Example:
    # |
    # | 5
    # *  a {0, 1, 2, 3, 4}
    # |
    # | 6
    # |\
    # * |  b {0, 1, 2, 3}
    # | *  n {4}
    # | |
    # | | 7
    # * |  c {0, 1, 2, 3}
    # | *  o {4}
    # | |
    # | | 8
    # |\ \
    # * | |  i {2, 3}
    # | * |  d {0, 1}
    # | | *  p {4}
    # | | |
    # | | | 9
    # * | |  j {2, 3}
    # | * |  e {0, 1}
    # | | *  q {4}
    # | | |
    # | | | 10
    # * | |  k {2, 3}
    # | * |  f {0, 1}
    # | | *  r {4}
    # | | |
    # | | | 11
    # |\ \ \
    # | | |\ \
    # * | | | |    g {0}
    # | * | | |    h {1}
    # |   * | |    l {2}
    # |   | * |    m {3}
    # |   |   *    s {4}
    # |  /   /
    # | |  /
    # | | | 12
    # * | |   t {0}
    # | * |   u {2}
    # | | *   v {4}
    # | |
    # | | 13
    # * |   w {0}
    # | *   x {2}
    # |
    # | 14
    # *   y {0}
    # | 15
    # *   z {0}

    walker = graph.walk()
    next_block_num, next_parent, next_siblings = next(walker)
    prev_cliques = []

    done = False
    while not done:
        cliques = {}
        block_num = next_block_num

        # Read all the cliques for this block number
        try:
            while block_num == next_block_num:
                cliques[next_parent] = next_siblings
                next_block_num, next_parent, next_siblings = next(walker)
        except StopIteration:
            # Do one last iteration after we've consumed the entire graph
            done = True

        print_cliques(prev_cliques, cliques, node_id_map)

        print_block_num_row(block_num, prev_cliques, cliques)

        print_splits(prev_cliques, cliques)

        print_folds(prev_cliques, cliques)

        prev_cliques = build_ordered_cliques(prev_cliques, cliques)

    print_cliques(prev_cliques, [], node_id_map)
378355
def add_compare_chains_parser(subparsers, parent_parser):
    
    parser = subparsers.add_parser(
        'compare-chains',
        help='Compare chains from different nodes.',
        description=(
            'Compute and display information about how the chains at '
            'different nodes differ.'
        ),
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog='''
By default, prints a table of summary data and a table of per-node data with
the following fields. Pass --tree for a fork graph.

COMMON ANCESTOR
    The most recent block that all chains have in common.

COMMON HEIGHT
    Let min_height := the minimum height of any chain across all nodes passed
    in. COMMON HEIGHT = min_height.

HEAD
    The block id of the most recent block on a given chain.

HEIGHT
    The block number of the most recent block on a given chain.

LAG
    Let max_height := the maximum height of any chain across all nodes passed
    in. LAG = max_height - HEIGHT for a given chain.

DIVERG
    Let common_ancestor_height := the height of the COMMON ANCESTOR.
    DIVERG = HEIGHT - common_ancestor_height

''',
        parents=[parent_parser, base_multinode_parser()])

    parser.add_argument(
        '-l',
        '--limit',
        default=25,
        type=int,
        help='the number of blocks to request at a time',
    )

    parser.add_argument(
        '--table',
        action='store_true',
        help='Print out a fork table for all nodes since the common ancestor.')

    parser.add_argument(
        '--tree',
        action='store_true',
        help='Print out a fork tree for all nodes since the common ancestor.')
120791
def iter_ancestors(self):
        
        node = self
        while node.up is not None:
            yield node.up
            node = node.up
164856
function printNodes(node, indent) {
    indent = indent || 0;

    // This is hacky, but this is just a debugging function anyway
    function print(str, indent, inline) {
        var lines = str.split('\n');

        for(var i=0; i<lines.length; i++) {
            if(lines[i]) {
                if((inline && i > 0) || !inline) {
                    for(var j=0; j<indent; j++) {
                        process.stdout.write(' ');
                    }
                }
            }

            if(i === lines.length-1) {
                process.stdout.write(lines[i]);
            }
            else {
                process.stdout.write(lines[i] + '\n');
            }
        }
    }

    print(node.typename + ': ', indent);

    if(node instanceof NodeList) {
        print('\n');
        lib.each(node.children, function(n) {
            printNodes(n, indent + 2);
        });
    }
    else if(node instanceof CallExtension) {
        print(node.extName + '.' + node.prop);
        print('\n');

        if(node.args) {
            printNodes(node.args, indent + 2);
        }

        if(node.contentArgs) {
            lib.each(node.contentArgs, function(n) {
                printNodes(n, indent + 2);
            });
        }
    }
    else {
        var nodes = null;
        var props = null;

        node.iterFields(function(val, field) {
            if(val instanceof Node) {
                nodes = nodes || {};
                nodes[field] = val;
            }
            else {
                props = props || {};
                props[field] = val;
            }
        });

        if(props) {
            print(JSON.stringify(props, null, 2) + '\n', null, true);
        }
        else {
            print('\n');
        }

        if(nodes) {
            for(var k in nodes) {
                printNodes(nodes[k], indent + 2);
            }
        }

    }
}
900189
def printStats(self):
        
        printDebug("----------------")
        printDebug("Parents......: %d" % len(self.parents()))
        printDebug("Children.....: %d" % len(self.children()))
        printDebug("Ancestors....: %d" % len(self.ancestors()))
        printDebug("Descendants..: %d" % len(self.descendants()))
        printDebug("Domain of....: %d" % len(self.domain_of))
        printDebug("Range of.....: %d" % len(self.range_of))
        printDebug("Instances....: %d" % self.count())
        printDebug("----------------")
1097588
def print_children_recursively(all_items, for_item, level):
    
    children = [child for child in all_items if child.parentid == for_item.id]
    for child in children:
        #message = f"{for_item.name}({for_item.id}) is a parent to {child.name}({child.id})"
        indent = " " * level * 2
        id_col = f"{indent} {child.id}"
        print_row(id_col, child.name, f"{child.allocation:,.2f}", level)

        # Process children.
        print_children_recursively(all_items, child, level+1)