Code take from black formatter. Just want to see if this is still python.
    :param src:
    :return:
770762
def check(src, dst):  # type: (str,str)->None
    
    was_bad = False
    try:
        _ = ast.parse(src)
    except Exception as exc:
        was_bad = True
        major, minor = sys.version_info[:2]
        logger.warning(
            "failed to parse source file "
            "with Python {0}.{1}'s builtin AST. Switch to manual "
            "or stop using deprecated Python 2 syntax. AST error message: {2}".format(
                major, minor, exc
            )
        )

    try:
        _ = ast.parse(dst)
    except Exception as exc:
        if was_bad:
            # I didn't make it worse.
            pass
        else:
            # ok, this made the file worse. It must be jiggle_version's fault.
            print(dst)
            logger.error(dst)
            raise
7516
def _looks_like_script(self, path):
        
        fp = open(path, 'rb')
        try:
            sample = fp.read(512).decode('latin-1')
            return not set(sample).difference(string.printable)
        finally:
            fp.close()
635784
def remove(src, new_file=None):
    
    output_is_file = False
    if src[0:2] == b"\xff\xd8":
        src_data = src
        file_type = "jpeg"
    elif src[0:4] == b"RIFF" and src[8:12] == b"WEBP":
        src_data = src
        file_type = "webp"
    else:
        with open(src, 'rb') as f:
            src_data = f.read()
        output_is_file = True
        if src_data[0:2] == b"\xff\xd8":
            file_type = "jpeg"
        elif src_data[0:4] == b"RIFF" and src_data[8:12] == b"WEBP":
            file_type = "webp"

    if file_type == "jpeg":
        segments = split_into_segments(src_data)
        exif = get_exif_seg(segments)
        if exif:
            new_data = src_data.replace(exif, b"")
        else:
            new_data = src_data
    elif file_type == "webp":
        try:
            new_data = _webp.remove(src_data)
        except ValueError:
            new_data = src_data
        except e:
            print(e.args)
            raise ValueError("Error occurred.")

    if isinstance(new_file, io.BytesIO):
        new_file.write(new_data)
        new_file.seek(0)
    elif new_file:
        with open(new_file, "wb+") as f:
            f.write(new_data)
    elif output_is_file:
        with open(src, "wb+") as f:
            f.write(new_data)
    else:
        raise ValueError("Give a second argument to 'remove' to output file")
290080
def code( *args, &blk )
  # check for optional hash for options
  opts = args.last.kind_of?(Hash) ? args.pop : {}
  
  name_plus_part = args.first   # check for optional filename
    
  if name_plus_part 
    name, part = name_plus_part.split( '#' ) # split off optional part/anchor 
    
    content = find_content_from( name, part ) 
    
    # add name and part to opts so engine can use paras too  
    opts[ :name ] = name  
    opts[ :part ] = part if part
    
    return format_code( content, opts )
  elsif blk # inline code via block?
    content = capture_erb(&blk)
    return if content.empty?

    concat_erb( format_code( content, opts ), blk.binding )
    return
  else
    msg = '*** warning: empty code directive; inline code or file para expected'
    puts msg 
    return wrap_markup( "<!-- #{msg} -->" )
  end
end
1279177
def color_code(self, fore=None, back=None, style=None):
        
        # Map from style type to raw code formatter function.
        colorcodes = []
        resetcodes = []
        userstyles = {'style': style, 'back': back, 'fore': fore}
        for stype in userstyles:
            stylearg = userstyles.get(stype, None)
            if not stylearg:
                # No value for this style name, don't use it.
                continue
            # Get escape code for this style.
            code = self.get_escape_code(stype, stylearg)
            stylename = str(stylearg).lower()
            if (stype == 'style') and (stylename in ('0', )):
                resetcodes.append(code)
            elif stylename.startswith('reset'):
                resetcodes.append(code)
            else:
                colorcodes.append(code)
        # Reset codes come first, to not override colors.
        return ''.join((''.join(resetcodes), ''.join(colorcodes)))
848102
def partition_source(src):
    
    # In python2, ast.parse(text_string_with_encoding_pragma) raises
    # SyntaxError: encoding declaration in Unicode string
    ast_obj = ast.parse(src.encode('UTF-8'))
    visitor = TopLevelImportVisitor()
    visitor.visit(ast_obj)

    line_offsets = get_line_offsets_by_line_no(src)

    chunks = []
    startpos = 0
    pending_chunk_type = None
    possible_ending_tokens = None
    seen_import = False
    for (
            token_type, token_text, (srow, scol), (erow, ecol), _,
    ) in tokenize.generate_tokens(io.StringIO(src).readline):
        # Searching for a start of a chunk
        if pending_chunk_type is None:
            if not seen_import and token_type == tokenize.COMMENT:
                if 'noreorder' in token_text:
                    chunks.append(CodePartition(CodeType.CODE, src[startpos:]))
                    break
                else:
                    pending_chunk_type = CodeType.PRE_IMPORT_CODE
                    possible_ending_tokens = TERMINATES_COMMENT
            elif not seen_import and token_type == tokenize.STRING:
                pending_chunk_type = CodeType.PRE_IMPORT_CODE
                possible_ending_tokens = TERMINATES_DOCSTRING
            elif scol == 0 and srow in visitor.top_level_import_line_numbers:
                seen_import = True
                pending_chunk_type = CodeType.IMPORT
                possible_ending_tokens = TERMINATES_IMPORT
            elif token_type == tokenize.NL:
                # A NL token is a non-important newline, we'll immediately
                # append a NON_CODE partition
                endpos = line_offsets[erow] + ecol
                srctext = src[startpos:endpos]
                startpos = endpos
                chunks.append(CodePartition(CodeType.NON_CODE, srctext))
            elif token_type == tokenize.COMMENT:
                if 'noreorder' in token_text:
                    chunks.append(CodePartition(CodeType.CODE, src[startpos:]))
                    break
                else:
                    pending_chunk_type = CodeType.CODE
                    possible_ending_tokens = TERMINATES_COMMENT
            elif token_type == tokenize.ENDMARKER:
                # Token ended right before end of file or file was empty
                pass
            else:
                # We've reached a `CODE` block, which spans the rest of the
                # file (intentionally timid).  Let's append that block and be
                # done
                chunks.append(CodePartition(CodeType.CODE, src[startpos:]))
                break
        # Attempt to find ending of token
        elif token_type in possible_ending_tokens:
            endpos = line_offsets[erow] + ecol
            srctext = src[startpos:endpos]
            startpos = endpos
            chunks.append(CodePartition(pending_chunk_type, srctext))
            pending_chunk_type = None
            possible_ending_tokens = None
        elif token_type == tokenize.COMMENT and 'noreorder' in token_text:
            chunks.append(CodePartition(CodeType.CODE, src[startpos:]))
            break

    chunks = [chunk for chunk in chunks if chunk.src]

    # Make sure we're not removing any code
    assert _partitions_to_src(chunks) == src
    return chunks
42168
def format(tokens, formatter, outfile=None):  # pylint: disable=redefined-builtin
    
    try:
        if not outfile:
            realoutfile = getattr(formatter, 'encoding', None) and BytesIO() or StringIO()
            formatter.format(tokens, realoutfile)
            return realoutfile.getvalue()
        else:
            formatter.format(tokens, outfile)
    except TypeError as err:
        if (isinstance(err.args[0], str) and
            ('unbound method format' in err.args[0] or
             'missing 1 required positional argument' in err.args[0])):
            raise TypeError('format() argument must be a formatter instance, '
                            'not a class')
        raise
195073
def get_template_debug(template_name, error):
    '''
    
    '''
    # This is taken from mako.exceptions.html_error_template(), which has an issue
    # in Py3 where files get loaded as bytes but `lines = src.split('\n')` below
    # splits with a string. Not sure if this is a bug or if I'm missing something,
    # but doing a custom debugging template allows a workaround as well as a custom
    # DMP look.
    # I used to have a file in the templates directory for this, but too many users
    # reported TemplateNotFound errors. This function is a bit of a hack, but it only
    # happens during development (and mako.exceptions does this same thing).
    #   /justification
    stacktrace_template = MakoTemplate(r"""
<%! from mako.exceptions import syntax_highlight, pygments_html_formatter %>
<style>
    .stacktrace { margin:5px 5px 5px 5px; }
    .highlight { padding:0px 10px 0px 10px; background-color:#9F9FDF; }
    .nonhighlight { padding:0px; background-color:#DFDFDF; }
    .sample { padding:10px; margin:10px 10px 10px 10px;
                font-family:monospace; }
    .sampleline { padding:0px 10px 0px 10px; }
    .sourceline { margin:5px 5px 10px 5px; font-family:monospace;}
    .location { font-size:80%; }
    .highlight { white-space:pre; }
    .sampleline { white-space:pre; }

    % if pygments_html_formatter:
        ${pygments_html_formatter.get_style_defs() | n}
        .linenos { min-width: 2.5em; text-align: right; }
        pre { margin: 0; }
        .syntax-highlighted { padding: 0 10px; }
        .syntax-highlightedtable { border-spacing: 1px; }
        .nonhighlight { border-top: 1px solid #DFDFDF;
                        border-bottom: 1px solid #DFDFDF; }
        .stacktrace .nonhighlight { margin: 5px 15px 10px; }
        .sourceline { margin: 0 0; font-family:monospace; }
        .code { background-color: #F8F8F8; width: 100%; }
        .error .code { background-color: #FFBDBD; }
        .error .syntax-highlighted { background-color: #FFBDBD; }
    % endif

    ## adjustments to Django css
    table.source {
        background-color: #fdfdfd;
    }
    table.source > tbody > tr > th {
        width: auto;
    }
    table.source > tbody > tr > td {
        font-family: inherit;
        white-space: normal;
        padding: 15px;
    }
    #template {
        background-color: #b3daff;
    }

</style>
<%

    src = tback.source
    line = tback.lineno
    if isinstance(src, bytes):
        src = src.decode()
    if src:
        lines = src.split('\n')
    else:
        lines = None
%>
<h3>${tback.errorname}: ${tback.message}</h3>

% if lines:
    <div class="sample">
    <div class="nonhighlight">
    % for index in range(max(0, line-4),min(len(lines), line+5)):
        <%
        if pygments_html_formatter:
            pygments_html_formatter.linenostart = index + 1
        %>
        % if index + 1 == line:
        <%
        if pygments_html_formatter:
            old_cssclass = pygments_html_formatter.cssclass
            pygments_html_formatter.cssclass = 'error ' + old_cssclass
        %>
            ${lines[index] | n,syntax_highlight(language='mako')}
        <%
        if pygments_html_formatter:
            pygments_html_formatter.cssclass = old_cssclass
        %>
        % else:
            ${lines[index] | n,syntax_highlight(language='mako')}
        % endif
    % endfor
    </div>
    </div>
% endif

<div class="stacktrace">
% for (filename, lineno, function, line) in tback.reverse_traceback:
    <div class="location">${filename}, line ${lineno}:</div>
    <div class="nonhighlight">
    <%
       if pygments_html_formatter:
           pygments_html_formatter.linenostart = lineno
    %>
        <div class="sourceline">${line | n,syntax_highlight(filename)}</div>
    </div>
% endfor
</div>
""")
    tback = RichTraceback(error, error.__traceback__)
    lines = stacktrace_template.render_unicode(tback=tback)
    return {
        'message': '',
        'source_lines': [
            ( '', mark_safe(lines) ),
        ],
        'before': '',
        'during': '',
        'after': '',
        'top': 0,
        'bottom': 0,
        'total': 0,
        'line': tback.lineno or 0,
        'name': template_name,
        'start': 0,
        'end': 0,
    }
187497
def html(self):
        
        formatter = HtmlFormatter(
            cssclass=self.DIV_CSS_CLASS,
            linenos=True,
            linenostart=self._start_line,
            hl_lines=self._shift_lines(
                self._violation_lines,
                self._start_line
            ),
            lineanchors=self._src_filename
        )

        return pygments.format(self.src_tokens(), formatter)
1079568
def get_escape_code(self, codetype, value):
        
        valuefmt = str(value).lower()
        code = codes[codetype].get(valuefmt, None)
        if code:
            # Basic code from fore, back, or style.
            return code

        named_funcs = {
            'fore': format_fore,
            'back': format_back,
            'style': format_style,
        }

        # Not a basic code, try known names.
        converter = named_funcs.get(codetype, None)
        if converter is None:
            raise ValueError(
                'Invalid code type. Expecting {}, got: {!r}'.format(
                    ', '.join(named_funcs),
                    codetype
                )
            )
        # Try as hex.
        with suppress(ValueError):
            value = int(hex2term(value, allow_short=True))
            return converter(value, extended=True)

        named_data = name_data.get(valuefmt, None)
        if named_data is not None:
            # A known named color.
            try:
                return converter(named_data['code'], extended=True)
            except TypeError:
                # Passing a known name as a style?
                if codetype == 'style':
                    raise InvalidStyle(value)
                raise
        # Not a known color name/value, try rgb.
        try:
            r, g, b = (int(x) for x in value)
            # This does not mean we have a 3 int tuple. It could '111'.
            # The converter should catch it though.
        except (TypeError, ValueError):
            # Not an rgb value.
            if codetype == 'style':
                raise InvalidStyle(value)
        try:
            escapecode = converter(value)
        except ValueError as ex:
            raise InvalidColr(value) from ex
        return escapecode
1075781
function(src, noEscape) {
    var attrLen, newKey;
    if (helper.isArray(src)) {
      var attrLen = src.length;
      for (var i = 0; i < attrLen; i++) {
        src[i] = helper.pasteurize(src[i], noEscape);
      }
    } else if (this.isString(src)) {
      src = helper.scrub(src, noEscape);
    } else if (helper.isObject(src)) {
      var newSrc = {};
      for (key in src) {
        newKey = helper.scrub(key);
        newSrc[newKey] = helper.pasteurize(src[key], noEscape);
      }
      src = newSrc;
    }

    return src;
  }
641448
def crc16_nojit(s, crc=0):
  """"""
  for ch in bytearray(s):  # bytearray's elements are integers in both python 2 and 3
    crc = ((crc << 8) & 0xFFFF) ^ _crc16_tab[((crc >> 8) & 0xFF) ^ (ch & 0xFF)]
    crc &= 0xFFFF
  return crc
248696
def py_syntax_highlight(self, s):
        
        if not self.enable:
            return s
        state = 0
        spaces = " \t\n"
        ops = ".,;:+-*/%&!=|(){}[]^<>"
        i = 0
        cur_token = ""
        color_args = {0: {}, len(s): {}}  # type: typing.Dict[int,typing.Dict[str]]  # pos in s -> color kwargs

        def finish_identifier():
            """
            Reset color to standard for current identifier.
            """
            if cur_token in py_keywords:
                color_args[max([k for k in color_args.keys() if k < i])] = {"color": self.fg_colors[0]}

        while i < len(s):
            c = s[i]
            i += 1
            if c == "\n":
                if state == 3:
                    finish_identifier()
                color_args[i] = {}
                state = 0
            elif state == 0:
                if c in spaces:
                    pass
                elif c in ops:
                    color_args[i - 1] = {"color": self.fg_colors[0]}
                    color_args[i] = {}
                elif c == "#":
                    color_args[i - 1] = {"color": self.fg_colors[3]}
                    state = 6
                elif c == '"':
                    color_args[i - 1] = {"color": self.fg_colors[2]}
                    state = 1
                elif c == "'":
                    color_args[i - 1] = {"color": self.fg_colors[2]}
                    state = 2
                else:
                    cur_token = c
                    color_args[i - 1] = {}
                    state = 3
            elif state == 1:  # string via "
                if c == "\\":
                    state = 4
                elif c == "\"":
                    color_args[i] = {}
                    state = 0
            elif state == 2:  # string via '
                if c == "\\":
                    state = 5
                elif c == "'":
                    color_args[i] = {}
                    state = 0
            elif state == 3:  # identifier
                if c in spaces + ops + "#\"'":
                    finish_identifier()
                    color_args[i] = {}
                    state = 0
                    i -= 1
                else:
                    cur_token += c
            elif state == 4:  # escape in "
                state = 1
            elif state == 5:  # escape in '
                state = 2
            elif state == 6:  # comment
                pass
        if state == 3:
            finish_identifier()
        out = ""
        i = 0
        while i < len(s):
            j = min([k for k in color_args.keys() if k > i])
            out += self.color(s[i:j], **color_args[i])
            i = j
        return out
892600
def highlight(code, lexer='html', formatter='html', output_wrapper=None):
    """"""
    if not pygments:
        raise TypeError("pygments module required")
    if not isinstance(code, six.string_types):
        code = pprint.pformat(code)
    if isinstance(lexer, six.string_types):
        lexer = pygments.lexers.get_lexer_by_name(lexer)
    if isinstance(formatter, six.string_types):
        formatter = pygments.formatters.get_formatter_by_name(formatter)
        if formatter.name.lower() == 'html':
            formatter.full = True
            formatter.cssclass = "pygments-%s" % uuid.uuid4()
            if output_wrapper is None:
                output_wrapper = HTML
    return output_wrapper(pygments.highlight(code, lexer, formatter))
1179491
public String highlight(String code, Lexer lexer, Formatter formatter) {
		PyFunction function = pythonInterpreter.get("highlight", PyFunction.class);
		
		PyString pyCode = new PyString(code);
		PyObject pyLexer = lexer.getLexer();
		PyObject pyFormatter = formatter.getFormatter();
		
		return function.__call__(pyCode, pyLexer, pyFormatter).asString();
	}
1119249
def format(self, *args, **kwargs):
        
        return self.__class__(super(ColorStr, self).format(*args, **kwargs), keep_tags=True)
694447
def ruby_code?(str)
      str = str.to_s
      return false if str.empty?

      checker = FoodCritic::ErrorChecker.new(str)
      checker.parse
      !checker.error?
    end