Print the AST in a nicely formatted tree format for debuggin
977874
function printNodes(node, indent) {
  indent = indent || 0;

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

  if (node instanceof NodeList) {
    print('\n');
    node.children.forEach((n) => {
      printNodes(n, indent + 2);
    });
  } else if (node instanceof CallExtension) {
    print(`${node.extName}.${node.prop}\n`);

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

    if (node.contentArgs) {
      node.contentArgs.forEach((n) => {
        printNodes(n, indent + 2);
      });
    }
  } else {
    let nodes = [];
    let props = null;

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

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

    nodes.forEach(([fieldName, n]) => {
      print(`[${fieldName}] =>`, indent + 2);
      printNodes(n, indent + 4);
    });
  }
}
861636
def ast_to_code(ast, indent=0):
    # type: (Any, int) -> str
    
    code = []

    def append(line):
        # type: (str) -> None
        code.append(("    " * indent) + line)

    if isinstance(ast, Node):
        append("ast.{}(".format(ast.__class__.__name__))
        indent += 1
        for i, k in enumerate(ast._fields, 1):
            v = getattr(ast, k)
            append("{}={},".format(k, ast_to_code(v, indent)))
        if ast.loc:
            append("loc={}".format(ast_to_code(ast.loc, indent)))

        indent -= 1
        append(")")

    elif isinstance(ast, Loc):
        append("loc({}, {})".format(ast.start, ast.end))

    elif isinstance(ast, list):
        if ast:
            append("[")
            indent += 1

            for i, it in enumerate(ast, 1):
                is_last = i == len(ast)
                append(ast_to_code(it, indent) + ("," if not is_last else ""))

            indent -= 1
            append("]")
        else:
            append("[]")

    else:
        append(repr(ast))

    return "\n".join(code).strip()
1202244
def pretty_print(source, dest):
    
    parser = etree.XMLParser(remove_blank_text=True)
    if not isinstance(source, str):
        source = str(source)
    tree = etree.parse(source, parser)
    docinfo = tree.docinfo
    with open(dest, 'wb') as fp:
        fp.write(etree.tostring(tree, pretty_print=True,
                                encoding=docinfo.encoding, standalone=docinfo.standalone))
915001
protected static void printFeatureTree(String cs, float[] tempW) {
        String name = "*";
        if (tempW.length == 4) {
            name = "U";
        }
        name += "*" + (cs.charAt(cs.length() - 1) - Config.FEATURE_BEGIN + 1) + ":" + cs.substring(0, cs.length() - 1);
        for (int i = 0; i < tempW.length; i++) {
            if (tempW[i] != 0) {
                System.out.println(name + "\t" + Config.getTagName(i / 4 - 1) + "\t" + Config.getTagName(i % 4) + "\t"
                                + tempW[i]);
            }

        }
    }
893440
def dump(self):
        
        for seg in self.seglist:
            print("==== %08x-%08x" % (seg.startea, seg.endea))
            if seg.endea - seg.startea < 30:
                for ea in range(seg.startea, seg.endea):
                    print("    %08x: %08x" % (ea, self.getFlags(ea)))
            else:
                for ea in range(seg.startea, seg.startea + 10):
                    print("    %08x: %08x" % (ea, self.getFlags(ea)))
                print("...")
                for ea in range(seg.endea - 10, seg.endea):
                    print("    %08x: %08x" % (ea, self.getFlags(ea)))
678830
def print_stack(pid, include_greenlet=False, debugger=None, verbose=False):
    """"""
    # TextIOWrapper of Python 3 is so strange.
    sys_stdout = getattr(sys.stdout, 'buffer', sys.stdout)
    sys_stderr = getattr(sys.stderr, 'buffer', sys.stderr)

    make_args = make_gdb_args
    environ = dict(os.environ)
    if (
        debugger == 'lldb' or
        (debugger is None and platform.system().lower() == 'darwin')
    ):
        make_args = make_lldb_args
        # fix the PATH environment variable for using built-in Python with lldb
        environ['PATH'] = '/usr/bin:%s' % environ.get('PATH', '')

    tmp_fd, tmp_path = tempfile.mkstemp()
    os.chmod(tmp_path, 0o777)
    commands = []
    commands.append(FILE_OPEN_COMMAND)
    commands.extend(UTILITY_COMMANDS)
    commands.extend(THREAD_STACK_COMMANDS)
    if include_greenlet:
        commands.extend(GREENLET_STACK_COMMANDS)
    commands.append(FILE_CLOSE_COMMAND)
    command = r';'.join(commands)

    args = make_args(pid, command % tmp_path)
    process = subprocess.Popen(
        args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, err = process.communicate()
    if verbose:
        sys_stderr.write(b'Standard Output:\n%s\n' % out)
        sys_stderr.write(b'Standard Error:\n%s\n' % err)
        sys_stderr.flush()

    for chunk in iter(functools.partial(os.read, tmp_fd, 1024), b''):
        sys_stdout.write(chunk)
    sys_stdout.write(b'\n')
    sys_stdout.flush()
125562
def print_treemap(self, format=None, output=sys.stdout, **kwargs):
        
        treemap = self.as_treemap()
        treemap.print(format=format, output=output, **kwargs)
1025944
def dump_autogen_code(fpath, autogen_text, codetype='python', fullprint=None,
                      show_diff=None, dowrite=None):
    
    import utool as ut
    if dowrite is None:
        dowrite = ut.get_argflag(('-w', '--write'))
    if show_diff is None:
        show_diff = ut.get_argflag('--diff')
    num_context_lines = ut.get_argval('--diff', type_=int, default=None)
    show_diff = show_diff or num_context_lines is not None

    num_context_lines = ut.get_argval('--diff', type_=int, default=None)

    if fullprint is None:
        fullprint = True

    if fullprint is False:
        fullprint = ut.get_argflag('--print')

    print('[autogen] Autogenerated %s...\n+---\n' % (fpath,))
    if not dowrite:
        if fullprint:
            ut.print_code(autogen_text, lexer_name=codetype)
            print('\nL___')
        else:
            print('specify --print to write to stdout')
            pass
        print('specify -w to write, or --diff to compare')
        print('...would write to: %s' % fpath)
    if show_diff:
        if ut.checkpath(fpath, verbose=True):
            prev_text = ut.read_from(fpath)
            textdiff = ut.get_textdiff(prev_text, autogen_text,
                                       num_context_lines=num_context_lines)
            try:
                ut.print_difftext(textdiff)
            except UnicodeDecodeError:
                import unicodedata
                textdiff = unicodedata.normalize('NFKD', textdiff).encode('ascii', 'ignore')
                ut.print_difftext(textdiff)

        if dowrite:
            print('WARNING: Not writing. Remove --diff from command line')
    elif dowrite:
        ut.write_to(fpath, autogen_text)
500932
def print_ast(f):
    
    for linenum,indent,value in iter_lines(f):
        print("{0}{1}|{2}".format(str(linenum).rjust(3), ' ' * indent, value))
393125
def build_ast(expression, debug = False):
    """"""
    #use a directed graph to store the tree
    G = DiGraph()
    stack = []


    for n in expression:
        # Since the graph does not maintain the order of adding nodes/edges
        # add an extra attribute 'pos' so we can always sort to the correct order
        if isinstance(n,OperatorNode):
            if n.ttype == "operator-infix":
                arg2 = stack.pop()
                arg1 = stack.pop()
                # Hack to write the name of sheet in 2argument address
                if(n.tvalue == ':'):
                    if '!' in arg1.tvalue and arg2.ttype == 'operand' and '!' not in arg2.tvalue:
                        arg2.tvalue = arg1.tvalue.split('!')[0] + '!' + arg2.tvalue

                G.add_node(arg1,pos = 1)
                G.add_node(arg2,pos = 2)
                G.add_edge(arg1, n)
                G.add_edge(arg2, n)
            else:
                arg1 = stack.pop()
                G.add_node(arg1,pos = 1)
                G.add_edge(arg1, n)

        elif isinstance(n,FunctionNode):
            args = []
            for _ in range(n.num_args):
                try:
                    args.append(stack.pop())
                except:
                    raise Exception()
            #try:
                # args = [stack.pop() for _ in range(n.num_args)]
            #except:
            #        print 'STACK', stack, type(n)
            #        raise Exception('prut')
            args.reverse()
            for i,a in enumerate(args):
                G.add_node(a,pos = i)
                G.add_edge(a,n)
        else:
            G.add_node(n,pos=0)

        stack.append(n)

    return G,stack.pop()
219206
def debug_object(obj, log_level: int = logging.DEBUG) -> None:
    
    msgs = ["For {o!r}:".format(o=obj)]
    for attrname in dir(obj):
        attribute = getattr(obj, attrname)
        msgs.append("- {an!r}: {at!r}, of type {t!r}".format(
            an=attrname, at=attribute, t=type(attribute)))
    log.log(log_level, "{}", "\n".join(msgs))
433632
def debugDumpAttrList(self, output, depth):
        
        libxml2mod.xmlDebugDumpAttrList(output, self._o, depth)
316443
def _print_config_text(tree, indentation=0):
    '''
    
    '''
    config = ''
    for key, value in six.iteritems(tree):
        config += '{indent}{line}\n'.format(indent=' '*indentation, line=key)
        if value:
            config += _print_config_text(value, indentation=indentation+1)
    return config
524626
def debug(version=False):
    """"""
    if version:
        print(__version__)
        return
    print(json.dumps(MANAGE_DICT, indent=2))
810578
void printDotNodesAtLevel(PrintStream os, int levelToPrint, boolean detail, PrintMojo.PrintTreeOptions treeOptions) {
    if (getDepth() == levelToPrint) {
      printDotNode(os, detail, treeOptions);
      return;
    }

    assert (getDepth() < levelToPrint);

    if (leftChild != null) {
      leftChild.printDotNodesAtLevel(os, levelToPrint, detail, treeOptions);
    }
    if (rightChild != null) {
      rightChild.printDotNodesAtLevel(os, levelToPrint, detail, treeOptions);
    }
  }
1148176
def format_python2_stmts(python_stmts, show_tokens=False, showast=False,
                         showgrammar=False, compile_mode='exec'):
    

    parser_debug = {'rules': False, 'transition': False,
                    'reduce': showgrammar,
                    'errorstack': True, 'context': True, 'dups': True }
    parsed = parse_python2(python_stmts, show_tokens=show_tokens,
                           parser_debug=parser_debug)
    assert parsed == 'file_input', 'Should have parsed grammar start'

    formatter = Python2Formatter()

    if showast:
        print(parsed)

    # What we've been waiting for: Generate source from AST!
    python2_formatted_str = formatter.traverse(parsed)

    return python2_formatted_str
239961
def debug_print_tree( self, spacing='' ):
        '''  '''
        print (spacing+" "+str(self.word_id)+" "+str(self.text))
        if (self.children):
            spacing=spacing+"  "
            for child in self.children:
                child.debug_print_tree(spacing)