Classmethod that applies conditional encoding based on
        mime-type. Given an entry as returned by __call__ return the
        data in the appropriate encoding.
497765
def encode(cls, entry):
        
        (data, info) = entry
        if info['mime_type'] in cls.utf8_mime_types:
            return data.encode('utf-8')
        else:
            return data
1088477
def get_decoder(encoding, *args, **kwargs):
    
    def _get_decoder_class():
        if encoding == AMF0:
            try:
                from cpyamf import amf0
            except ImportError:
                from pyamf import amf0

            return amf0.Decoder
        elif encoding == AMF3:
            try:
                from cpyamf import amf3
            except ImportError:
                from pyamf import amf3

            return amf3.Decoder

        raise ValueError("Unknown encoding %r" % (encoding,))

    return _get_decoder_class()(*args, **kwargs)
1150978
def parse_mimetype(cls, value):
        '''
        '''
        match = re.match(r'([a-zA-Z0-9-]+/[a-zA-Z0-9-]+)', value)

        if match:
            return match.group(1)
442287
def lookupEncoding(encoding):
    """"""
    if isinstance(encoding, binary_type):
        try:
            encoding = encoding.decode("ascii")
        except UnicodeDecodeError:
            return None

    if encoding is not None:
        try:
            return webencodings.lookup(encoding)
        except AttributeError:
            return None
    else:
        return None
988675
private static ParseResults parseMimeType(String mimeType) {
        String[] parts = mimeType.split(";");
        ParseResults results = new ParseResults();
        results.params = new HashMap<>();

        for (int i = 1; i < parts.length; ++i) {
            String p = parts[i];
            String[] subParts = p.split("=");
            if (subParts.length == 2) {
                results.params.put(subParts[0].trim(), subParts[1].trim());
            }
        }
        String fullType = parts[0].trim();

        // Java URLConnection class sends an Accept header that includes a
        // single "*" - Turn it into a legal wildcard.
        if (fullType.equals("*")) {
            fullType = "*/*";
        }

        int slashIndex = fullType.indexOf('/');
        if (slashIndex != -1) {
            results.type = fullType.substring(0, slashIndex);
            results.subType = fullType.substring(slashIndex + 1);
        } else {
            //If the type is invalid, attempt to turn into a wildcard
            results.type = fullType;
            results.subType = "*";
        }

        return results;
    }
841695
def _generate_base_mimetypes(self):
        
        for t in self.type_instances:
            if t.custom_mime:
                continue

            yield t.mime, (t, None, None)
73940
def from_string(cls, value):
        """"""
        match = cls.pattern.search(value)
        if match is None:
            raise ValueError('"%s" is not a valid media type' % value)
        try:
            return cls(match.group('mime_type'), float(match.group('weight') or 1))
        except ValueError:
            return cls(value)
1263572
def mime_type(type, value)
      type = ".#{type}" unless type.to_s[0] == '.'
      ::Rack::Mime::MIME_TYPES[type] = value
    end
940752
def _AddUnicodeMethod(unused_message_descriptor, cls):
  """"""

  def __unicode__(self):
    return text_format.MessageToString(self, as_utf8=True).decode('utf-8')
  cls.__unicode__ = __unicode__
52194
def encoded_class(block, offset=0):
        
        if not block:
            raise InvalidFileFormatNull

        for key in __magicmap__:
            if block.find(key, offset, offset + len(key)) > -1:
                return __magicmap__[key]

        raise InvalidFileFormat
717694
def _ensure_decoded(s):
    
    if isinstance(s, np.bytes_):
        s = s.decode('UTF-8')
    return s
336482
def ctype_for_encoding(self, encoding):
        """"""
        if encoding in self.typecodes:
            return self.typecodes[encoding]
        elif encoding[0:1] == b'^' and encoding[1:] in self.typecodes:
            return POINTER(self.typecodes[encoding[1:]])
        elif encoding[0:1] == b'^' and encoding[1:] in [CGImageEncoding,
                                                        NSZoneEncoding]:
            return c_void_p
        elif encoding[0:1] == b'r' and encoding[1:] in self.typecodes:
            return self.typecodes[encoding[1:]]
        elif encoding[0:2] == b'r^' and encoding[2:] in self.typecodes:
            return POINTER(self.typecodes[encoding[2:]])
        else:
            raise Exception('unknown encoding for %s: %s'
                            % (self.name, encoding))
690766
def encoding(encoding=True):
    """"""
    if isinstance(encoding, str):
        encoding = True

    def dec(f):
        f._nvim_decode = encoding
        return f
    return dec
232350
def _decode(self, infile, encoding):
        
        if isinstance(infile, string_types):
            # can't be unicode
            # NOTE: Could raise a ``UnicodeDecodeError``
            return infile.decode(encoding).splitlines(True)
        for i, line in enumerate(infile):
            # NOTE: The isinstance test here handles mixed lists of unicode/string
            # NOTE: But the decode will break on any non-string values
            # NOTE: Or could raise a ``UnicodeDecodeError``
            if PY3K:
                if not isinstance(line, str):
                    infile[i] = line.decode(encoding)
            else:
                if not isinstance(line, unicode):
                    infile[i] = line.decode(encoding)
        return infile
752126
def guess_mimetype_read(read):
    """"""
    mime = None
    try:
        data = read()[:70]
    except Exception:
        pass
    else:
        for cmime, ro in PARSE_CONTENTS.items():
            if ro.search(data):
                mime = cmime
                break
    return mime
822622
def detect_encoding(data, encoding=None, fallback='latin1', is_html=False):
    '''
    '''
    if encoding:
        encoding = normalize_codec_name(encoding)

    bs4_detector = EncodingDetector(
        data,
        override_encodings=(encoding,) if encoding else (),
        is_html=is_html
    )
    candidates = itertools.chain(bs4_detector.encodings, (fallback,))

    for candidate in candidates:
        if not candidate:
            continue

        candidate = normalize_codec_name(candidate)

        if not candidate:
            continue

        if candidate == 'ascii' and fallback != 'ascii':
            # it's never ascii :)
            # Falling back on UTF-8/CP-1252/Latin-1 reduces chance of
            # failure
            continue

        if try_decoding(data, candidate):
            return candidate

    raise ValueError('Unable to detect encoding.')
1270696
def mime_type(template):
    
    _, ext = os.path.splitext(template.filename)
    return EXTENSION_MAP.get(ext, 'text/html; charset=utf-8')