Formats given exception as an html text.

        :param \*args: Arguments.
        :type \*args: \*
        :return: Exception html text.
        :rtype: unicode
350645
def format_html_exception(*args):
        

        escape = lambda x: foundations.strings.replace(x,
                                                       OrderedDict([("&", "&amp;"), ("<", "&lt;"), (">", "&gt;")]))
        format = lambda x: foundations.strings.replace(x.expandtabs(8),
                                                       OrderedDict(
                                                           [("\n\n", "\n \n"), ("\n\n", "\n \n"), (" ", "&nbsp;"),
                                                            ("\n", "<br/>\n")]))

        verbose = 10
        cls, instance, trcback = args
        stack = foundations.exceptions.extract_stack(foundations.exceptions.get_inner_most_frame(trcback), verbose)

        python = "Python {0}: {1}".format(sys.version.split()[0], sys.executable)
        date = time.ctime(time.time())

        html = []
        html.append(
            "<div class=\"header\"><span class=\"floatRight textAlignRight\"><h4>{0}<br/>{1}</h4></span><h2>{2}</h2></div>".format(
                python, date, escape(foundations.strings.to_string(cls))))

        html.append("<div class=\"traceback\">")
        for line in foundations.exceptions.format_exception(cls, instance, trcback):
            html.append("{0}<br/>".format(format(escape(line))))
        html.append("</div>")

        html.append("<div class=\"content\">")
        html.append("<p>An unhandled exception occured in <b>{0} {1}</b>! \
                Sequence of calls leading up to the exception, in their occurring order:</p>".format(
            Constants.application_name, Constants.version))
        html.append("<br/>")
        html.append("<div class=\"stack\">")
        for frame, file_name, line_number, name, context, index in stack:
            location = "<b>{0}{1}</b>".format(escape(name) if name != "<module>" else "",
                                              inspect.formatargvalues(*inspect.getargvalues(frame)))
            html.append(
                "<div class=\"location\">File <a href=file://{0}>\"{0}\"</a>, line <b>{1}</b>, in {2}</div><br>".format(
                    file_name, line_number, location))
            html.append("<div class=\"context\">")
            for i, line in enumerate(context):
                if i == index:
                    html.append("<span class=\"highlight\">{0}&nbsp;{1}</span>".format(
                        line_number - index + i, format(line)))
                else:
                    html.append("{0}&nbsp;{1}".format(line_number - index + i, format(line)))
            html.append("</div>")
            html.append("<br/>")
        html.append("</div>")
        html.append("</div>")
        html.append("<div class=\"exception\">")
        for line in traceback.format_exception_only(cls, instance):
            html.append("<b>{0}</b>".format(format(line)))
        html.append("</div>")

        html.append("<div class=\"debug\">")
        html.append("<p>Frames locals by stack ordering, innermost last:</p>")
        for frame, locals in foundations.exceptions.extract_locals(trcback):
            name, file_name, line_number = frame
            html.append(
                "<div class=\"frame\">Frame \"{0}\" in <a href=file://{1}>\"{1}\"</a> file, line <b>{2}</b>:</div>".format(
                    escape(name), file_name, line_number))
            html.append("<br/>")
            html.append("<div class=\"locals\">")
            arguments, nameless_args, keyword_args, locals = locals
            has_arguments, has_locals = any((arguments, nameless_args, keyword_args)), any(locals)
            has_arguments and html.append("<div class=\"cls\"><b>{0}</b></div><ul>".format("Arguments:"))
            for key, value in arguments.iteritems():
                html.append("<li><b>{0}</b> = {1}</li>".format(key, escape(value)))
            for value in nameless_args:
                html.append("<li><b>{0}</b></li>".format(escape(value)))
            for key, value in sorted(keyword_args.iteritems()):
                html.append("<li><b>{0}</b> = {1}</li>".format(key, escape(value)))
            has_arguments and html.append("</ul>")
            has_locals and html.append("<div class=\"cls\"><b>{0}</b></div><ul>".format("Locals:"))
            for key, value in sorted(locals.iteritems()):
                html.append("<li><b>{0}</b> = {1}</li>".format(key, escape(value)))
            has_locals and html.append("</ul>")
            html.append("</div>")
            html.append("<br/>")
        html.append("</div>")

        return "".join(html)
634882
def text(self):
        
        t = self.t
        if t is None:
            return u''
        text = t.text
        return to_unicode(text) if text is not None else u''
1085995
def format_errors(errors):
        

        def _get_message(node):
            """
            Get the message to display in the error output.
            """
            messages = set()

            try:
                messages.update([node['message']])
            except KeyError:
                pass

            for check_group in ['any', 'all', 'none']:
                try:
                    for check in node[check_group]:
                        messages.update([check.get('message')])
                except KeyError:
                    pass

            messages = messages.difference([''])
            return '; '.join(messages)

        lines = []
        for error_type in errors:
            lines.append(u"Severity: {}".format(error_type.get("impact")))
            lines.append(u"Rule ID: {}".format(error_type.get("id")))
            lines.append(u"Help URL: {}\n".format(error_type.get('helpUrl')))

            for node in error_type['nodes']:
                msg = u"Message: {}".format(_get_message(node))
                html = u"Html: {}".format(node.get('html').encode('utf-8'))
                target = u"Target: {}".format(node.get('target'))
                fill_opts = {
                    'width': 100,
                    'initial_indent': '\t',
                    'subsequent_indent': '\t\t',
                }
                lines.append(fill(msg, **fill_opts))
                lines.append(fill(html, **fill_opts))
                lines.append(fill(target, **fill_opts))
                lines.append('\n')

        return '\n'.join(lines)
1057240
def FormatProblem(self, d=None):
    
    if not d:
      d = self.GetDictToFormat()

    output_error_text = self.__class__.ERROR_TEXT % d
    if ('reason' in d) and d['reason']:
      return '%s\n%s' % (output_error_text, d['reason'])
    else:
      return output_error_text
1333598
def _wrap_tracebackexception_format(redact: Callable[[str], str]):
    
    original_format = getattr(TracebackException, '_original', None)
    if original_format is None:
        original_format = TracebackException.format
        setattr(TracebackException, '_original', original_format)

    @wraps(original_format)
    def tracebackexception_format(self, *, chain=True):
        for line in original_format(self, chain=chain):
            yield redact(line)

    setattr(TracebackException, 'format', tracebackexception_format)
254430
def get_traceback_stxt():
        
        #/
        exc_cls, exc_obj, tb_obj = sys.exc_info()
        
        #/
        txt_s = traceback.format_exception(exc_cls, exc_obj, tb_obj)
    
        #/
        res = ''.join(txt_s)
    
        return res
566450
def _print_exception_list(exceptions, message, output_file=None):
    
    output_file = output_file or sys.stderr
    message = 'Exception %s:\n' % message
    for exc_type, exc_value, exc_traceback in exceptions:
        output_file.write(message)
        traceback.print_exception(exc_type, exc_value, exc_traceback,
                                  file=output_file)
        output_file.write('\n')
311128
def _GetFormatter(self, format_str):
        
        formatter, args, func_type = self.formatters.LookupWithType(format_str)
        if formatter:
            return formatter, args, func_type
        else:
            raise BadFormatter('%r is not a valid formatter' % format_str)
1198290
def exception(self, msg=None, *args, **kwargs):
        
        kwargs['exc_info'] = 1
        return self._log(logging.ERROR, msg, args, kwargs)
753991
def handle_exception(self, message, exc):
        # type: (Text, Exception) -> Any
        
        return self.handle_invalid_value(
            message     = message,
            exc_info    = True,
            context     = getattr(exc, 'context', {}),
        )
385667
def raise_exception(self, exception, tup=None):
        
        if tup:
            message = (
                "Python {exception_name} raised while processing Tuple "
                "{tup!r}\n{traceback}"
            )
        else:
            message = "Python {exception_name} raised\n{traceback}"
        message = message.format(
            exception_name=exception.__class__.__name__, tup=tup, traceback=format_exc()
        )
        self.send_message({"command": "error", "msg": str(message)})
        self.send_message({"command": "sync"})
463188
def format_train_exception
      backend, host = formatted_host()
      if host.nil?
        t.CHEFTRN002.text(exception.message)
      else
        t.CHEFTRN001.text(backend, host, exception.message)
      end
    end
880690
def _repr_html_(self):
        
        # Use StringIO to avoid a large number of memory allocations with string concat
        with io.StringIO() as out:
            out.write('<{tag}'.format(tag=escape(self.tag_name)))
            if self.style:
                # Important values are in double quotes - cgi.escape only escapes double quotes, not single quotes!
                out.write(' style="{css}"'.format(
                    css=escape(self._to_inline_css(self.style))))

            for k, v in self.attributes.items():
                k2 = k
                if k2 == 'class_':
                    k2 = 'class'
                # Important values are in double quotes - cgi.escape only escapes double quotes, not single quotes!
                if isinstance(v, string_types):
                    out.write(' {key}="{value}"'.format(
                        key=escape(k2), value=escape(v)))
                if isinstance(v, bool) and v:
                    out.write(' {key}'.format(key=escape(k2)))
            out.write('>')

            for c in self.children:
                if isinstance(c, string_types):
                    out.write(escape(safe_unicode(c)))
                else:
                    out.write(c._repr_html_())

            out.write('</{tag}>'.format(tag=escape(self.tag_name)))

            return out.getvalue()
1176845
def html2text(__html: str, *, width: int = 80,
              ascii_replacements: bool = False) -> str:
    
    html2.BODY_WIDTH = width
    html2.UNICODE_SNOB = ascii_replacements
    return html2.html2text(__html).strip()
475558
def __get_exception_message(self):
        
        exception_info = sys.exc_info()[1]
        if hasattr(exception_info, 'msg'):
            exc_message = exception_info.msg
        elif hasattr(exception_info, 'message'):
            exc_message = exception_info.message
        else:
            exc_message = '(Unknown Exception)'
        return exc_message
995278
def safe_format(format_string, *args, **kwargs):
    
    try:
        if not args and not kwargs:
            return format_string
        else:
            return format_string.format(*args, **kwargs)

    # catch encoding errors and transform everything into utf-8 string
    # before logging:
    except (UnicodeEncodeError, UnicodeDecodeError):
        format_string = to_utf8(format_string)
        args = [to_utf8(p) for p in args]
        kwargs = {k: to_utf8(v) for k, v in six.iteritems(kwargs)}
        return format_string.format(*args, **kwargs)

    # ignore other errors
    except:
        return u''
254758
def format_exception(etype, value, tback, limit=None):
    

    rtn = ['Traceback (most recent call last):\n']

    if limit is None or limit >= 0:
        rtn.extend(traceback.format_tb(tback, limit))
    else:
        rtn.extend(traceback.format_list(traceback.extract_tb(tback)[limit:]))

    rtn.extend(traceback.format_exception_only(etype, value))

    return rtn