Used when force_unicode is True (default), the tags and values in the dict
    will be coerced as 'str' (or 'unicode' with Python2).   In Python3 they can
    otherwise end up as a mixtures of 'str' and 'bytes'.
341664
def _unicode(p):
    
    q = {}
    for tag in p:
        vals = []
        for v in p[tag]:
            if type(v) is not str:                                                              # pragma: no cover
                v = v.decode('utf-8')
            vals.append(v)
        if type(tag) is not str:                                                                # pragma: no cover
            tag = tag.decode('utf-8')
        q[tag] = vals
    return q
976307
def str_on_2_unicode_on_3(s):
    

    if not PY3:
        return str(s)
    else:  # 3+
        if not isinstance(s, str):
            return str(s, encoding="utf-8")
        return s
1307783
def unicode2str(content):
    """"""
    if isinstance(content, dict):
        result = {}
        for key in content.keys():
            result[unicode2str(key)] = unicode2str(content[key])
        return result
    elif isinstance(content, list):
        return [unicode2str(element) for element in content]
    elif isinstance(content, int) or isinstance(content, float):
        return content
    else:
        return content.encode("utf-8")
1034623
def to_unicode(s, encoding=None, errors='strict'):
    
    encoding = encoding or 'utf-8'

    if is_unicode(s):
        return s
    elif is_strlike(s):
        return s.decode(encoding, errors)
    else:
        if six.PY2:
            return str(s).decode(encoding, errors)
        else:
            return str(s)
737269
def to_unicode(value):
    
    if isinstance(value, _TO_UNICODE_TYPES):
        return value
    if not isinstance(value, bytes):
        raise TypeError(
            "Expected bytes, unicode, or None; got %r" % type(value))
    return value.decode("utf-8")
1025667
def python_2_unicode_compatible(cls):
    
    if '__str__' not in cls.__dict__:
        raise ValueError("@python_2_unicode_compatible cannot be applied "
                         "to %s because it doesn't define __str__()." %
                         cls.__name__)

    cls.__unicode__ = cls.__str__

    if PY2:
        cls.__str__ = lambda self: self.__unicode__().encode('utf-8')

    return cls
328891
def _safe_unicode(o):
    
    def clean(s):
        return u''.join([c if c in ASCII_PRINTABLE else '?' for c in s])
    if USING_PYTHON2:
        try:
            return unicode(o)
        except:
            try:
                s = str(o)
                try:
                    return s.decode("utf-8")
                except:
                    return clean(s[:2048]) + u" [Raw error message: " + unicode(s.encode("hex"), 'utf-8') + u"]"
            except:
                return u"(Unable to decode Python exception message)"
    else:
        return str(o)
879709
def force_text(s, encoding='utf-8', errors='strict'):
    
    if isinstance(s, text_type):
        return s

    try:
        if not isinstance(s, string_types):
            if PY3:
                if isinstance(s, bytes):
                    s = text_type(s, encoding, errors)
                else:
                    s = text_type(s)
            elif hasattr(s, '__unicode__'):
                s = s.__unicode__()
            else:
                s = text_type(bytes(s), encoding, errors)
        else:
            s = s.decode(encoding, errors)
    except UnicodeDecodeError as e:
        if not isinstance(s, Exception):
            raise FlaskMailUnicodeDecodeError(s, *e.args)
        else:
            s = ' '.join([force_text(arg, encoding, errors)
                          for arg in s])
    return s
495562
def ensureUtf(s, encoding='utf8'):
    
    # In Python2, str == bytes.
    # In Python3, bytes remains unchanged, but str means unicode
    # while unicode is not defined anymore
    if type(s) == bytes:
        return s.decode(encoding, 'ignore')
    else:
        return s
448294
def unicode_safe(text, encoding=UrlEncoding, errors='ignore'):
    """"""
    try:
        text_type = unicode
    except NameError:
        text_type = str
    if isinstance(text, text_type):
        return text
    return text.decode(encoding, errors)
78856
def utf82unicode(value):
    
    try:
        return value.decode("utf8")
    except Exception as e:
        if not _Log:
            _late_import()

        if not is_binary(value):
            _Log.error("Can not convert {{type}} to unicode because it's not bytes",  type= type(value).__name__)

        e = _Except.wrap(e)
        for i, c in enumerate(value):
            try:
                c.decode("utf8")
            except Exception as f:
                _Log.error("Can not convert charcode {{c}} in string index {{i}}", i=i, c=ord(c), cause=[e, _Except.wrap(f)])

        try:
            latin1 = text_type(value.decode("latin1"))
            _Log.error("Can not explain conversion failure, but seems to be latin1", e)
        except Exception:
            pass

        try:
            a = text_type(value.decode("latin1"))
            _Log.error("Can not explain conversion failure, but seems to be latin1", e)
        except Exception:
            pass

        _Log.error("Can not explain conversion failure of " + type(value).__name__ + "!", e)
7622
def _to_unicode(self, data, encoding, errors='strict'):
    ''''''

    # strip Byte Order Mark (if present)
    if (len(data) >= 4) and (data[:2] == '\xfe\xff') and (data[2:4] != '\x00\x00'):
        encoding = 'utf-16be'
        data = data[2:]
    elif (len(data) >= 4) and (data[:2] == '\xff\xfe') and (data[2:4] != '\x00\x00'):
        encoding = 'utf-16le'
        data = data[2:]
    elif data[:3] == '\xef\xbb\xbf':
        encoding = 'utf-8'
        data = data[3:]
    elif data[:4] == '\x00\x00\xfe\xff':
        encoding = 'utf-32be'
        data = data[4:]
    elif data[:4] == '\xff\xfe\x00\x00':
        encoding = 'utf-32le'
        data = data[4:]
    newdata = unicode(data, encoding, errors)
    return newdata
328521
def ensure_str(s, encoding='utf-8', errors='strict'):
    
    if not isinstance(s, (text_type, binary_type)):
        raise TypeError("not expecting type '%s'" % type(s))
    if PY2 and isinstance(s, text_type):
        s = s.encode(encoding, errors)
    elif PY3 and isinstance(s, binary_type):
        s = s.decode(encoding, errors)
    return s
1131343
def safe_str(value):
    
    if sys.version_info < (3,0) and isinstance(value, unicode):
        return value.encode('utf-8')
    else:
        return str(value)
217541
def encode(cls, value):
        
        coerced = unicode(value)
        if coerced == value:
            return coerced.encode(cls._encoding)

        raise InvalidValue('not text')
559720
def force_string(kwargs):
    
    if isinstance(kwargs, dict):
        # Context: https://github.com/cameronmaske/celery-once/issues/58
        # Keep equivalent to string of dict for backwards compatibility.
        return order_dict_to_string(OrderedDict(
            (force_string(key), force_string(value))
            for key, value in items_sorted_by_key(kwargs)
        ))
    elif isinstance(kwargs, list):
        return [force_string(element) for element in kwargs]
    elif six.PY2 and isinstance(kwargs, unicode):
        return kwargs.encode('utf-8')
    return kwargs
620597
def remove_unicode_dict(input_dict):
    '''
    '''
    if isinstance(input_dict, collections.Mapping):
        return dict(map(remove_unicode_dict, input_dict.iteritems()))
    elif isinstance(input_dict, collections.Iterable):
        return type(input_dict)(map(remove_unicode_dict, input_dict))
    else:
        return input_dict