The body of the event data as a string if the data is of a
        compatible type.

        :param encoding: The encoding to use for decoding message data.
         Default is 'UTF-8'
        :rtype: str or unicode
968097
def body_as_str(self, encoding='UTF-8'):
        
        data = self.body
        try:
            return "".join(b.decode(encoding) for b in data)
        except TypeError:
            return six.text_type(data)
        except:  # pylint: disable=bare-except
            pass
        try:
            return data.decode(encoding)
        except Exception as e:
            raise TypeError("Message data is not compatible with string type: {}".format(e))
237447
def guess_encoding(request):
    
    ctype = request.headers.get('content-type')
    if not ctype:
        # we don't have a content-type, somehow, so...
        LOGGER.warning("%s: no content-type; headers are %s",
                       request.url, request.headers)
        return 'utf-8'

    # explicit declaration
    match = re.search(r'charset=([^ ;]*)(;| |$)', ctype)
    if match:
        return match[1]

    # html default
    if ctype.startswith('text/html'):
        return 'iso-8859-1'

    # everything else's default
    return 'utf-8'
1185361
def encoded(text, encoding=DEFAULT_ENCODING):
    
    # already a string item
    if type(text) == bytes_type:
        return text

    elif type(text) != unicode_type:
        # convert a QString value
        if type(text).__name__ == 'QString':
            if encoding == 'utf-8':
                return unicode_type(text.toUtf8(), 'utf-8')
            elif encoding == 'latin-1':
                return unicode_type(text.toLatin1(), 'latin-1')
            elif encoding == 'ascii':
                return unicode_type(text.toAscii(), 'ascii')
            else:
                return unicode_type(text, encoding)

        # convert a standard item
        else:
            try:
                return bytes_type(text)
            except StandardError:
                return '????'

    if encoding:
        try:
            return text.encode(encoding)
        except StandardError:
            return text.encode(encoding, errors='ignore')

    else:
        for enc in SUPPORTED_ENCODINGS:
            try:
                return text.encode(enc)
            except StandardError:
                pass

    return '????'
125204
def to_str(data):
    
    if isinstance(data, bytes):
        return codecs.decode(data, TEXT_ENCODING)
    return data
222936
def _unicode(value):
    
    if isinstance(value, _TO_UNICODE_TYPES):
        return value
    if not isinstance(value, bytes_type):
        raise TypeError(
            "Expected bytes, unicode, or None; got %r" % type(value)
        )
    return value.decode("utf-8")
4178
def tostr(s, encoding='ascii'):
    
    if PY3K:
        if isinstance(s, str): # str == unicode in PY3K
            return s
        else: # s is type bytes
            return s.decode(encoding)
    else:
        # for py2.6 on (before 3.0), bytes is same as str;  2.5 has no bytes
        # but handle if unicode is passed
        if isinstance(s, unicode):
            return s.encode(encoding)
        else:
            return s
609451
def _FormatMessage(self, format_string, event_values):
    
    if not isinstance(format_string, py2to3.UNICODE_TYPE):
      logger.warning('Format string: {0:s} is non-Unicode.'.format(
          format_string))

      # Plaso code files should be in UTF-8 any thus binary strings are
      # assumed UTF-8. If this is not the case this should be fixed.
      format_string = format_string.decode('utf-8', errors='ignore')

    try:
      message_string = format_string.format(**event_values)

    except KeyError as exception:
      data_type = event_values.get('data_type', 'N/A')
      display_name = event_values.get('display_name', 'N/A')
      event_identifier = event_values.get('uuid', 'N/A')
      parser_chain = event_values.get('parser', 'N/A')

      error_message = (
          'unable to format string: "{0:s}" event object is missing required '
          'attributes: {1!s}').format(format_string, exception)
      error_message = (
          'Event: {0:s} data type: {1:s} display name: {2:s} '
          'parser chain: {3:s} with error: {4:s}').format(
              event_identifier, data_type, display_name, parser_chain,
              error_message)
      logger.error(error_message)

      attribute_values = []
      for attribute, value in iter(event_values.items()):
        attribute_values.append('{0:s}: {1!s}'.format(attribute, value))

      message_string = ' '.join(attribute_values)

    except UnicodeDecodeError as exception:
      data_type = event_values.get('data_type', 'N/A')
      display_name = event_values.get('display_name', 'N/A')
      event_identifier = event_values.get('uuid', 'N/A')
      parser_chain = event_values.get('parser', 'N/A')

      error_message = 'Unicode decode error: {0!s}'.format(exception)
      error_message = (
          'Event: {0:s} data type: {1:s} display name: {2:s} '
          'parser chain: {3:s} with error: {4:s}').format(
              event_identifier, data_type, display_name, parser_chain,
              error_message)
      logger.error(error_message)

      message_string = ''

    # Strip carriage return and linefeed form the message strings.
    # Using replace function here because it is faster than re.sub() or
    # string.strip().
    return message_string.replace('\r', '').replace('\n', '')
522677
def encode(value, encoding='utf-8', encoding_errors='strict'):
    
    if isinstance(value, bytes):
        return value
    if not isinstance(value, basestring):
        value = str(value)
    if isinstance(value, unicode):
        value = value.encode(encoding, encoding_errors)
    return value
949796
def utf8(value):
    
    if isinstance(value, _UTF8_TYPES):
        return value
    if not isinstance(value, unicode_type):
        raise TypeError(
            "Expected bytes, unicode, or None; got %r" % type(value)
        )
    return value.encode("utf-8")
472612
def unicode_compatible(cls):
    
    if PY3:
        cls.__str__ = cls.__unicode__
        cls.__bytes__ = lambda self: self.__str__().encode("utf-8")
    else:
        cls.__str__ = lambda self: self.__unicode__().encode("utf-8")

    return cls
451008
def to_bytes(s):
    
    if bytes != str:
        if type(s) == str:
            return s.encode('utf-8')
    return s
1313568
def get_encoding_name(self, encoding):
        
        encoding = CodePages.get_encoding_name(encoding)
        if encoding not in self.codepages:
            raise ValueError((
                'Encoding "{}" cannot be used for the current profile. '
                'Valid encodings are: {}'
                ).format(encoding, ','.join(self.codepages.keys())))
        return encoding
265382
def to_utf8(value):
  
  if isinstance(value, unicode):
    return value.encode('utf-8')

  assert isinstance(value, str)
  return value
155717
def tostring(self, encoding):
        
        if self.kind == 'string':
            if encoding is not None:
                return self.converted
            return '"{converted}"'.format(converted=self.converted)
        elif self.kind == 'float':
            # python 2 str(float) is not always
            # round-trippable so use repr()
            return repr(self.converted)
        return self.converted
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.')
590676
def ensure_text(str_or_bytes, encoding='utf-8'):
    
    if not isinstance(str_or_bytes, six.text_type):
        return str_or_bytes.decode(encoding)
    return str_or_bytes
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