Formats Python code to conform to the PEP 8 style guide.
964493
def rpc_fix_code(self, source, directory):
        
        source = get_source(source)
        return fix_code(source, directory)
1328492
def _format_type(lines, element, spacer=""):
    """"""
    rlines = []
    rlines.append(element.signature)
    _format_summary(rlines, element)

    rlines.append("")
    _format_generic(rlines, element, ["summary"])

    if len(element.executables) > 0:
        rlines.append("\nEMBEDDED PROCEDURES")
        for key, value in list(element.executables.items()):
            rlines.append("  {}".format(value.__str__()))
            target = value.target
            if target is not None:
                _format_executable(rlines, target, "  ")

    if len(element.members) > 0:
        rlines.append("\nEMBEDDED MEMBERS")
        for key, value in list(element.members.items()):
            _format_value_element(rlines, value, "  ")

    lines.extend([spacer + l for l in rlines])
140243
def fixcode(**kwargs):
    
    # repository direcotry
    repo_dir = Path(__file__).parent.absolute()

    # source code directory
    source_dir = Path(repo_dir, package.__name__)

    if source_dir.exists():
        print("Source code locate at: '%s'." % source_dir)
        print("Auto pep8 all python file ...")
        source_dir.autopep8(**kwargs)
    else:
        print("Source code directory not found!")

    # unittest code directory
    unittest_dir = Path(repo_dir, "tests")
    if unittest_dir.exists():
        print("Unittest code locate at: '%s'." % unittest_dir)
        print("Auto pep8 all python file ...")
        unittest_dir.autopep8(**kwargs)
    else:
        print("Unittest code directory not found!")

    print("Complete!")
568797
def short_form_one_format(jupytext_format):
    """"""
    if not isinstance(jupytext_format, dict):
        return jupytext_format
    fmt = jupytext_format['extension']
    if 'suffix' in jupytext_format:
        fmt = jupytext_format['suffix'] + fmt
    elif fmt.startswith('.'):
        fmt = fmt[1:]

    if 'prefix' in jupytext_format:
        fmt = jupytext_format['prefix'] + '/' + fmt

    if jupytext_format.get('format_name'):
        if jupytext_format['extension'] not in ['.md', '.Rmd'] or jupytext_format['format_name'] == 'pandoc':
            fmt = fmt + ':' + jupytext_format['format_name']

    return fmt
1285324
def format(self, format_spec='f'):
        
        """
        if format_spec == '' or format_spec == 'f':
            cpf = CPF.clean(self._cpf)
            return '{0}.{1}.{2}-{3}'.format(cpf[0:3], cpf[3:6], cpf[6:9], cpf[9:11])
        if format_spec == 'r':
            return self._cpf
        raise ValueError(
            "Unknown format code '{0}' for object of type '{1}'".format(format_spec, CPF.__name__))
1098267
def lines(self, code):
        """"""
        if isinstance(code, str):
            fix_indentation = self.fix_indentation
            if fix_indentation:
                code = fix_indentation(code)
            return self.append(code)
        else:
            return self.append(code)
36167
def makefig(code, code_path, output_dir, output_base, config):
    

    # -- Parse format list
    default_dpi = {'png': 80, 'hires.png': 200, 'pdf': 50}
    formats = []
    for fmt in config.plot_formats:
        if isinstance(fmt, str):
            formats.append((fmt, default_dpi.get(fmt, 80)))
        elif type(fmt) in (tuple, list) and len(fmt)==2:
            formats.append((str(fmt[0]), int(fmt[1])))
        else:
            raise PlotError('invalid image format "%r" in plot_formats' % fmt)

    # -- Try to determine if all images already exist

    code_pieces = split_code_at_show(code)

    # Look for single-figure output files first
    all_exists = True
    img = ImageFile(output_base, output_dir)
    for format, dpi in formats:
        if out_of_date(code_path, img.filename(format)):
            all_exists = False
            break
        img.formats.append(format)

    if all_exists:
        return [(code, [img])]

    # Then look for multi-figure output files
    results = []
    all_exists = True
    for i, code_piece in enumerate(code_pieces):
        images = []
        for j in range(1000):
            img = ImageFile('%s_%02d_%02d' % (output_base, i, j), output_dir)
            for format, dpi in formats:
                if out_of_date(code_path, img.filename(format)):
                    all_exists = False
                    break
                img.formats.append(format)

            # assume that if we have one, we have them all
            if not all_exists:
                all_exists = (j > 0)
                break
            images.append(img)
        if not all_exists:
            break
        results.append((code_piece, images))

    if all_exists:
        return results

    # -- We didn't find the files, so build them

    results = []
    ns = {}

    for i, code_piece in enumerate(code_pieces):
        # Clear between runs
        plt.close('all')

        # Run code
        run_code(code_piece, code_path, ns)

        # Collect images
        images = []
        fig_managers = _pylab_helpers.Gcf.get_all_fig_managers()
        for j, figman in enumerate(fig_managers):
            if len(fig_managers) == 1 and len(code_pieces) == 1:
                img = ImageFile(output_base, output_dir)
            else:
                img = ImageFile("%s_%02d_%02d" % (output_base, i, j),
                                output_dir)
            images.append(img)
            for format, dpi in formats:
                try:
                    figman.canvas.figure.savefig(img.filename(format), dpi=dpi)
                except exceptions.BaseException as err:
                    raise PlotError(traceback.format_exc())
                img.formats.append(format)

        # Results
        results.append((code_piece, images))

    return results
1257200
def displayformat(codes=[], fg=None, bg=None):
        """"""
        if isinstance(codes, basestring):
            codes = [codes]
        else:
            codes = list(codes)
        for code in codes:
            if code not in Magic.DISPLAY.keys():
                raise ValueError("'%s' not a valid display value" % code)
        for color in (fg, bg):
            if color != None:
                if color not in Magic.COLORS.keys():
                    raise ValueError("'%s' not a valid color" % color)
        return [codes, fg, bg]
286156
def format_directive(module, package=None):
    # type: (unicode, unicode) -> unicode
    """"""
    directive = '.. automodule:: %s\n' % makename(package, module)
    for option in OPTIONS:
        directive += '    :%s:\n' % option
    return directive
1182454
function(code)
        {
            var html = '',
                classes = [ 'syntaxhighlighter' ],
                tabSize,
                matches,
                lineNumbers
                ;

            // process light mode
            if (this.getParam('light') == true)
                this.params.toolbar = this.params.gutter = false;

            className = 'syntaxhighlighter';

            if (this.getParam('collapse') == true)
                classes.push('collapsed');

            if ((gutter = this.getParam('gutter')) == false)
                classes.push('nogutter');

            // add custom user style name
            classes.push(this.getParam('class-name'));

            // add brush alias to the class name for custom CSS
            classes.push(this.getParam('brush'));

            code = trimFirstAndLastLines(code)
                .replace(/\r/g, ' ') // IE lets these buggers through
            ;

            tabSize = this.getParam('tab-size');

            // replace tabs with spaces
            code = this.getParam('smart-tabs') == true
                ? processSmartTabs(code, tabSize)
                : processTabs(code, tabSize)
            ;

            // unindent code by the common indentation
            if (this.getParam('unindent'))
                code = unindent(code);

            if (gutter)
                lineNumbers = this.figureOutLineNumbers(code);

            // find matches in the code using brushes regex list
            matches = this.findMatches(this.regexList, code);
            // processes found matches into the html
            html = this.getMatchesHtml(code, matches);
            // finally, split all lines so that they wrap well
            html = this.getCodeLinesHtml(html, lineNumbers);

            // finally, process the links
            if (this.getParam('auto-links'))
                html = processUrls(html);

            if (typeof(navigator) != 'undefined' && navigator.userAgent && navigator.userAgent.match(/MSIE/))
                classes.push('ie');

            html =
                '<div id="' + getHighlighterId(this.id) + '" class="' + classes.join(' ') + '">'
                    + (this.getParam('toolbar') ? sh.toolbar.getHtml(this) : '')
                    + '<table border="0" cellpadding="0" cellspacing="0">'
                    + this.getTitleHtml(this.getParam('title'))
                    + '<tbody>'
                    + '<tr>'
                    + (gutter ? '<td class="gutter">' + this.getLineNumbersHtml(code) + '</td>' : '')
                    + '<td class="code">'
                    + '<div class="container">'
                    + html
                    + '</div>'
                    + '</td>'
                    + '</tr>'
                    + '</tbody>'
                    + '</table>'
                    + '</div>'
            ;

            return html;
        }
281882
def format(self, format_spec='f'):
        
        """
        if format_spec == '' or format_spec == 'f':
            cnpj = CNPJ.clean(self._cnpj)
            return '{0}.{1}.{2}/{3}-{4}'.format(cnpj[0:2], cnpj[2:5], cnpj[5:8], cnpj[8:12], cnpj[12:14])
        if format_spec == 'r':
            return self._cnpj
        raise ValueError(
            "Unknown format code '{0}' for object of type '{1}'".format(format_spec, CNPJ.__name__))
1332796
def code(self, code):
        
        allowed_values = [400, 401, 404]
        if code not in allowed_values:
            raise ValueError(
                "Invalid value for `code` ({0}), must be one of {1}"
                .format(code, allowed_values)
            )

        self._code = code
1206395
def _format_code(source, preferred_quote):
    """"""
    if not source:
        return source

    modified_tokens = []

    sio = io.StringIO(source)
    for (token_type,
         token_string,
         start,
         end,
         line) in tokenize.generate_tokens(sio.readline):

        if token_type == tokenize.STRING:
            token_string = unify_quotes(token_string,
                                        preferred_quote=preferred_quote)

        modified_tokens.append(
            (token_type, token_string, start, end, line))

    return untokenize.untokenize(modified_tokens)
409035
def code_deparse_align(co, out=sys.stderr, version=None, is_pypy=None,
                       debug_opts=DEFAULT_DEBUG_OPTS,
                       code_objects={}, compile_mode='exec'):
    

    assert iscode(co)

    if version is None:
        version = float(sys.version[0:3])
    if is_pypy is None:
        is_pypy = IS_PYPY


    # store final output stream for case of error
    scanner = get_scanner(version, is_pypy=is_pypy)

    tokens, customize = scanner.ingest(co, code_objects=code_objects)
    show_asm = debug_opts.get('asm', None)
    maybe_show_asm(show_asm, tokens)

    debug_parser = dict(PARSER_DEFAULT_DEBUG)
    show_grammar = debug_opts.get('grammar', None)
    show_grammar = debug_opts.get('grammar', None)
    if show_grammar:
        debug_parser['reduce'] = show_grammar
        debug_parser['errorstack'] = True

    #  Build a parse tree from tokenized and massaged disassembly.
    show_ast = debug_opts.get('ast', None)
    deparsed = AligningWalker(version, scanner, out, showast=show_ast,
                            debug_parser=debug_parser, compile_mode=compile_mode,
                            is_pypy = is_pypy)

    isTopLevel = co.co_name == '<module>'
    deparsed.ast = deparsed.build_ast(tokens, customize, isTopLevel=isTopLevel)

    assert deparsed.ast == 'stmts', 'Should have parsed grammar start'

    del tokens # save memory

    deparsed.mod_globs = find_globals(deparsed.ast, set())

    # convert leading '__doc__ = "..." into doc string
    try:
        if deparsed.ast[0][0] == ASSIGN_DOC_STRING(co.co_consts[0]):
            deparsed.print_docstring('', co.co_consts[0])
            del deparsed.ast[0]
        if deparsed.ast[-1] == RETURN_NONE:
            deparsed.ast.pop() # remove last node
            # todo: if empty, add 'pass'
    except:
        pass

    # What we've been waiting for: Generate Python source from the parse tree!
    deparsed.gen_source(deparsed.ast, co.co_name, customize)

    for g in sorted(deparsed.mod_globs):
        deparsed.write('# global %s ## Warning: Unused global\n' % g)

    if deparsed.ERROR:
        raise SourceWalkerError("Deparsing stopped due to parse error")
    return deparsed
952287
def guess_format(text, ext):
    """"""
    lines = text.splitlines()

    metadata = read_metadata(text, ext)

    if ('jupytext' in metadata and set(metadata['jupytext'])
            .difference(['encoding', 'executable', 'main_language'])) or \
            set(metadata).difference(['jupytext']):
        return format_name_for_ext(metadata, ext), {}

    # Is this a Hydrogen-like script?
    # Or a Sphinx-gallery script?
    if ext in _SCRIPT_EXTENSIONS:
        comment = _SCRIPT_EXTENSIONS[ext]['comment']
        twenty_hash = ''.join(['#'] * 20)
        magic_re = re.compile(r'^(%|%%|%%%)[a-zA-Z]')
        double_percent_re = re.compile(r'^{}( %%|%%)$'.format(comment))
        double_percent_and_space_re = re.compile(r'^{}( %%|%%)\s'.format(comment))
        nbconvert_script_re = re.compile(r'^{}( <codecell>| In\[[0-9 ]*\]:?)'.format(comment))
        vim_folding_markers_re = re.compile(r'^{}\s*'.format(comment) + '{{{')
        vscode_folding_markers_re = re.compile(r'^{}\s*region'.format(comment))

        twenty_hash_count = 0
        double_percent_count = 0
        magic_command_count = 0
        rspin_comment_count = 0
        vim_folding_markers_count = 0
        vscode_folding_markers_count = 0

        parser = StringParser(language='R' if ext in ['.r', '.R'] else 'python')
        for line in lines:
            parser.read_line(line)
            if parser.is_quoted():
                continue

            # Don't count escaped Jupyter magics (no space between %% and command) as cells
            if double_percent_re.match(line) or double_percent_and_space_re.match(line) or \
                    nbconvert_script_re.match(line):
                double_percent_count += 1

            if magic_re.match(line):
                magic_command_count += 1

            if line.startswith(twenty_hash) and ext == '.py':
                twenty_hash_count += 1

            if line.startswith("#'") and ext in ['.R', '.r']:
                rspin_comment_count += 1

            if vim_folding_markers_re.match(line):
                vim_folding_markers_count += 1

            if vscode_folding_markers_re.match(line):
                vscode_folding_markers_count += 1

        if double_percent_count >= 1:
            if magic_command_count:
                return 'hydrogen', {}
            return 'percent', {}

        if vim_folding_markers_count:
            return 'light', {'cell_markers': '{{{,}}}'}

        if vscode_folding_markers_count:
            return 'light', {'cell_markers': 'region,endregion'}

        if twenty_hash_count >= 2:
            return 'sphinx', {}

        if rspin_comment_count >= 1:
            return 'spin', {}

    if ext == '.md':
        for line in lines:
            if line.startswith(':::'):  # Pandoc div
                return 'pandoc', {}

    # Default format
    return get_format_implementation(ext).format_name, {}
348817
def format_frame_info(frame):
    
    # Same as in traceback.extract_stack
    line_no = frame.f_lineno
    code = frame.f_code
    filename = code.co_filename
    method_name = code.co_name
    linecache.checkcache(filename)

    try:
        # Try to get the type of the calling object
        instance = frame.f_locals["self"]
        method_name = "{0}::{1}".format(type(instance).__name__, method_name)
    except KeyError:
        # Not called from a bound method
        pass

    # File & line
    output_lines = [
        '  File "{0}", line {1}, in {2}'.format(filename, line_no, method_name)
    ]

    # Arguments
    if frame.f_locals:
        # Pypy keeps f_locals as an empty dictionary
        arg_info = inspect.getargvalues(frame)
        for name in arg_info.args:
            try:
                output_lines.append(
                    "    - {0:s} = {1}".format(name, repr(frame.f_locals[name]))
                )
            except TypeError:
                # Happens in dict/list-comprehensions in Python 2.x
                name = name[0]
                output_lines.append(
                    "    - {0:s} = {1}".format(name, repr(frame.f_locals[name]))
                )

        if arg_info.varargs:
            output_lines.append(
                "    - *{0:s} = {1}".format(
                    arg_info.varargs, frame.f_locals[arg_info.varargs]
                )
            )

        if arg_info.keywords:
            output_lines.append(
                "    - **{0:s} = {1}".format(
                    arg_info.keywords, frame.f_locals[arg_info.keywords]
                )
            )

    # Line block
    lines = _extract_lines(filename, frame.f_globals, line_no, 3)
    if lines:
        output_lines.append("")
        prefix = "      "
        output_lines.append(
            "{0}{1}".format(prefix, "\n{0}".format(prefix).join(lines))
        )
    return "\n".join(output_lines)
389631
def is_valid_python(code, reraise=True, ipy_magic_workaround=False):
    
    import ast
    try:
        if ipy_magic_workaround:
            code = '\n'.join(['pass' if re.match(r'\s*%[a-z]*', line) else line for line in code.split('\n')])
        ast.parse(code)
    except SyntaxError:
        if reraise:
            import utool as ut
            print('Syntax Error')
            ut.print_python_code(code)
            raise
        return False
    return True