Run format_code() on a file.

    Returns `True` if any changes are needed and they are not being done
    in-place.
430338
def format_file(filename, args, standard_out):
    
    encoding = detect_encoding(filename)
    with open_with_encoding(filename, encoding=encoding) as input_file:
        source = input_file.read()
        formatted_source = format_code(
            source,
            preferred_quote=args.quote)

    if source != formatted_source:
        if args.in_place:
            with open_with_encoding(filename, mode='w',
                                    encoding=encoding) as output_file:
                output_file.write(formatted_source)
        else:
            import difflib
            diff = difflib.unified_diff(
                source.splitlines(),
                formatted_source.splitlines(),
                'before/' + filename,
                'after/' + filename,
                lineterm='')
            standard_out.write('\n'.join(list(diff) + ['']))

            return True
986343
def run(files, temp_folder):
    ""
    try:
        import flake8  # NOQA
    except ImportError:
        return NO_FLAKE_MSG
    try:
        from flake8.engine import get_style_guide
    except ImportError:
        # We're on a new version of flake8
        from flake8.api.legacy import get_style_guide

    py_files = filter_python_files(files)
    if not py_files:
        return
    DEFAULT_CONFIG = join(temp_folder, get_config_file())

    with change_folder(temp_folder):
        flake8_style = get_style_guide(config_file=DEFAULT_CONFIG)
        out, err = StringIO(), StringIO()
        with redirected(out, err):
            flake8_style.check_files(py_files)
    return out.getvalue().strip() + err.getvalue().strip()
613787
def handle_command_exit_code(self, code):
        
        ca = self.call_args
        exc_class = get_exc_exit_code_would_raise(code, ca["ok_code"],
                ca["piped"])
        if exc_class:
            exc = exc_class(self.ran, self.process.stdout, self.process.stderr,
                    ca["truncate_exc"])
            raise exc
1277308
def _format_changes(changes, orchestration=False):
    '''
    
    '''
    if not changes:
        return False, ''

    if orchestration:
        return True, _nested_changes(changes)

    if not isinstance(changes, dict):
        return True, 'Invalid Changes data: {0}'.format(changes)

    ret = changes.get('ret')
    if ret is not None and changes.get('out') == 'highstate':
        ctext = ''
        changed = False
        for host, hostdata in six.iteritems(ret):
            s, c = _format_host(host, hostdata)
            ctext += '\n' + '\n'.join((' ' * 14 + l) for l in s.splitlines())
            changed = changed or c
    else:
        changed = True
        ctext = _nested_changes(changes)
    return changed, ctext
648644
def run_changed_file_cmd(cmd, fp, pretty):
    
    with open(fp) as f:
        raw = f.read()
    # go sure regarding quotes:
    for ph in (dir_mon_filepath_ph, dir_mon_content_raw,
                dir_mon_content_pretty):
        if ph in cmd and not ('"%s"' % ph) in cmd \
                        and not ("'%s'" % ph) in cmd:
            cmd = cmd.replace(ph, '"%s"' % ph)

    cmd = cmd.replace(dir_mon_filepath_ph, fp)
    print col('Running %s' % cmd, H1)
    for r, what in ((dir_mon_content_raw, raw),
                    (dir_mon_content_pretty, pretty)):
        cmd = cmd.replace(r, what.encode('base64'))

    # yeah, i know, sub bla bla...
    if os.system(cmd):
        print col('(the command failed)', R)
1297409
def run(files, temp_folder):
    ""
    errors = []
    for py_file in filter_python_files(files):
        # We only want to show errors if we CAN'T compile to py3.
        # but we want to show all the errors at once.
        b = bash('python3 -m py_compile {0}'.format(py_file))
        if b.stderr:
            b = bash('2to3-2.7 {file}'.format(file=py_file))
            errors.append(b.value())
    return "\n".join(errors)
359165
def format_code(source, preferred_quote="'"):
    """"""
    try:
        return _format_code(source, preferred_quote)
    except (tokenize.TokenError, IndentationError):
        return source
160071
def run(self, value):
        
        if self.pass_ and not value.strip():
            return True

        if len((value.strip() if self.strip else value)) != self.length:
            self.error = self.error.format(value, self.length)
            return False
        return True
983623
static function run ($_code)
  {
    if (ctype_space ($_code[0]))
      $_code = ltrim ($_code);
    if (substr ($_code, 0, 5) == '<?php')
      return eval (substr ($_code, 5));
    return eval ($_code);
  }
412854
def do_format(self, format):
        
        if (format is not None):
            raise IIIFError(code=415, parameter="format",
                            text="Null manipulator does not support specification of output format.")
        #
        if (self.outfile is None):
            self.outfile = self.srcfile
        else:
            try:
                shutil.copyfile(self.srcfile, self.outfile)
            except IOError as e:
                raise IIIFError(code=500,
                                text="Failed to copy file (%s)." % (str(e)))
        self.mime_type = None
500778
def check_output_format(fmt, nfiles):
    
    if nfiles < 0:
        raise ValueError('Invalid file count: ' + str(nfiles))
    if nfiles == 1:
        return
    try:
        fmt % nfiles
    except TypeError as err:
        raise ValueError(''.join(
            ('Invalid file format string: ', fmt, ': ', str(err))
        ))
477928
def compile(self, code):
        
        is_plain_text = True
        compiled_regex = r""
        for chunk in self.delimiter_regex().split(code):
            if is_plain_text:
                compiled_regex = compiled_regex + simex_escape(chunk, flexible_whitespace=self._flexible_whitespace)
            else:
                stripped_chunk = chunk.strip()
                if stripped_chunk in self._regexes.keys():
                    compiled_regex = u"{0}{1}".format(
                        compiled_regex,
                        self._regexes[stripped_chunk]
                    )
                else:
                    raise KeyNotFound("'{0}' not found in keys")
            is_plain_text = not is_plain_text
        if self._exact:
            compiled_regex = r"^" + compiled_regex + r"$"
        return compile(compiled_regex)
741851
def _check_syntax(code, lang, temp_dir, enforce=True):
    
    # This function needs the language to be explicitly set, so we can
    # generate an appropriate temp filename.
    if lang == 'python2.7':
        temp_basename = 'inlined_code_from_dxapp_json.py'
    elif lang == 'bash':
        temp_basename = 'inlined_code_from_dxapp_json.sh'
    else:
        raise ValueError('lang must be one of "python2.7" or "bash"')
    # Dump the contents out to a temporary file, then call _check_file_syntax.
    with open(os.path.join(temp_dir, temp_basename), 'w') as ofile:
        ofile.write(code)
    _check_file_syntax(os.path.join(temp_dir, temp_basename), temp_dir, override_lang=lang, enforce=enforce)
1198229
def run(path, code=None, params=None, **meta):
        
        parser = get_parser()
        for option in parser.option_list:
            if option.dest and option.dest in params:
                value = params[option.dest]
                if isinstance(value, str):
                    params[option.dest] = option.convert_value(option, value)

        for key in ["filename", "exclude", "select", "ignore"]:
            if key in params and isinstance(params[key], str):
                params[key] = _parse_multi_options(params[key])

        P8Style = StyleGuide(reporter=_PycodestyleReport, **params)
        buf = StringIO(code)
        return P8Style.input_file(path, lines=buf.readlines())
873041
def compile(file):
    
    log(_("compiling {} into byte code...").format(file))

    try:
        py_compile.compile(file, doraise=True)
    except py_compile.PyCompileError as e:
        log(_("Exception raised: "))
        for line in e.msg.splitlines():
            log(line)

        raise Failure(_("{} raised while compiling {} (rerun with --log for more details)").format(e.exc_type_name, file))
55144
def determine_file_extension_based_on_format(format_specifier):
	
	if format_specifier == FMT_INI:
		return 'ini'
	if format_specifier == FMT_DELIMITED:
		return ''
	if format_specifier == FMT_XML:
		return 'xml'
	if format_specifier == FMT_JSON:
		return 'json'
	if format_specifier == FMT_YAML:
		return 'yml'
	raise ValueError('invalid format specifier: {}'.format(format_specifier))
1222954
def python_2_format_compatible(method):
    
    if six.PY3:
        return method

    def wrapper(self, format_spec):
        formatted = method(self, format_spec)
        if isinstance(format_spec, str):
            # bytestring
            return formatted.encode('utf-8')

        # unicode
        return formatted
    return wrapper