Replace Django's generic error messages with MTP-specific versions
    NB: avoid trailing full stops visually, they are added for screen readers in templates
2269
def replace_default_error_messages():
    
    forms.Field.default_error_messages['required'] = _('This field is required')
    forms.CharField.default_error_messages['min_length'] = _('You’ve entered too few characters')
    forms.CharField.default_error_messages['max_length'] = _('You’ve entered too many characters')
    forms.IntegerField.default_error_messages['invalid'] = _('Enter a whole number')
    forms.FloatField.default_error_messages['invalid'] = _('Enter a number')
    forms.DecimalField.default_error_messages['invalid'] = _('Enter a number')
    forms.DateField.default_error_messages['invalid'] = _('Enter a valid date')
    forms.TimeField.default_error_messages['invalid'] = _('Enter a valid time')
    forms.DateTimeField.default_error_messages['invalid'] = _('Enter a valid date and time')
    forms.FileField.default_error_messages.update({
        'invalid': _('No file was submitted'),
        'missing': _('No file was submitted'),
        'empty': _('The submitted file is empty'),
    })
    forms.SplitDateTimeField.default_error_messages['invalid_date'] = _('Enter a valid date')
    forms.SplitDateTimeField.default_error_messages['invalid_time'] = _('Enter a valid time')
    validators.EmailValidator.message = _('Enter a valid email address')
1277117
def error_404(request, exception):
    """"""
    return django.http.HttpResponseNotFound(
        d1_common.types.exceptions.NotFound(
            0,
            'Invalid API endpoint',
            # Include the regexes the URL was tested against
            # traceInformation=str(exception),
            nodeId=django.conf.settings.NODE_IDENTIFIER,
        ).serialize_to_transport(xslt_url=django.urls.base.reverse('home_xslt')),
        d1_common.const.CONTENT_TYPE_XML,
    )
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)
398383
def error(message):
    
    fail = '\033[91m'
    end = '\033[0m'
    sys.exit(fail + "Error: {}".format(message) + end)
866406
def flake(self, message):
        
        err_range = {
            'start': {'line': message.lineno - 1, 'character': message.col},
            'end': {'line': message.lineno - 1, 'character': len(self.lines[message.lineno - 1])},
        }

        severity = lsp.DiagnosticSeverity.Warning
        for message_type in PYFLAKES_ERROR_MESSAGES:
            if isinstance(message, message_type):
                severity = lsp.DiagnosticSeverity.Error
                break

        self.diagnostics.append({
            'source': 'pyflakes',
            'range': err_range,
            'message': message.message % message.message_args,
            'severity': severity
        })
1210256
function _formatErrorsWarnings(level, list, projectRoot){
    return list.map(x => {
        let file, line, col, endLine, endCol, message
        try{
            // resolve  the relative path 
            let fullFilePath = data_get(x, 'module.resource')
            file = fullFilePath && projectRoot ? path.relative(projectRoot, fullFilePath) : ''
            // file = file.replace(/[\\//]/g, '/')

            line = data_get(x, 'error.error.loc.line') || 0
            col = data_get(x, 'error.error.loc.column') || 0

            // only need first line of message
            let fullMessage = (x.message + '').trim()
            let crPos = fullMessage.indexOf("\n")
            if (crPos >= 0){
                message = fullMessage.substring(0, crPos)
            } else {
                message = fullMessage
            }

            if (!line){
                let linesColsInfo
                let m
                if (x.name === 'ModuleNotFoundError'
                    && (m = fullMessage.match(MODULE_NOT_FOUND_ERR_MSG_PATTERN))){
                    linesColsInfo = _resolveLineColNumInFile(fullFilePath, m[1])
                } else if (fullMessage.indexOf('component lists rendered with v-for should have explicit keys') > 0
                    && (m = fullMessage.match(/([a-zA-Z-_]+)\s+(v-for=['"].*?['"])/))){
                    linesColsInfo = _resolveLineColNumInFile(fullFilePath, m[2], {after: m[1]})
                } else if (m = fullMessage.match(/export ['"](\S+?)['"] was not found/)){
                    linesColsInfo = _resolveLineColNumInFile(fullFilePath, m[1], {after: 'import'})
                } else if (m = fullMessage.match(/Error compiling template:((?:.|[\r\n])*)- Component template/m)){
                    linesColsInfo = _resolveLineColNumInFile(fullFilePath, m[1].trim())
                    message = fullMessage.replace(/\n/g, ' ')
                }

                if (linesColsInfo){
                    line = linesColsInfo.line || 0
                    col = linesColsInfo.col || 0
                    endLine = linesColsInfo.endLine
                    endCol = linesColsInfo.endCol
                }
            }

            let endLinesCols = (endLine || endCol) ? ('~' + (endLine || '') + (endLine ? ',' : '') + (endCol || '0')) : ''

            return `!>${level}: ${file}:${line},${col}${endLinesCols}: ${message || '@see output window'}`            
        } catch (e){
            console.warn(e)
            return ''
        }
    }).join("\n")
}
396786
def server_error(request, template_name='500.html'):
    
    t = loader.get_template(template_name)
    return HttpResponseServerError(
        t.render(Context({'STATIC_URL': settings.STATIC_URL})))
306070
def setting_errors_for(model, attribute)
      if !model[:errors].blank? && model[:errors][attribute.to_sym].present?
        content_tag :span, :class => 'help-block error' do
          I18n.t("views.admin.settings.tab_content.#{attribute.to_s}").downcase.capitalize + ' ' + I18n.t("activerecord.errors.messages.empty")
        end
      end
    end
836951
function removeInvalidNodeErrorsInTemplateLiteral(node) {
            if (typeof node.value.raw === "string") {
                if (ALL_IRREGULARS.test(node.value.raw)) {
                    removeWhitespaceError(node);
                }
            }
        }
52498
def _get_error_message(self, model_class, method_name, action_method_name):
        
        if action_method_name:
            return "'{}' does not have '{}' or '{}' defined.".format(model_class, method_name, action_method_name)
        else:
            return "'{}' does not have '{}' defined.".format(model_class, method_name)
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,
    }
574851
private static String errorReasonFor( URL location, List<String> errors)
    {
    return
      Stream.concat(
        Stream.of( String.format( "%s conformance problem(s) found in Open API document%s", errors.size(), locationId( location))),
        IntStream.range( 0, errors.size()).mapToObj( i -> String.format( "[%s] %s", i, errors.get(i))))
      .collect( joining( "\n"));
    }
21742
private void inflateErrorMessageTextViews() {
        View parent = View.inflate(getContext(), R.layout.error_messages, null);
        addView(parent, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        leftMessage = parent.findViewById(R.id.left_error_message);
        leftMessage.setTag(false);
        rightMessage = parent.findViewById(R.id.right_error_message);
        rightMessage.setTag(false);
    }
1456
def _post_clean(self):
        
        super(NgModelFormMixin, self)._post_clean()
        if self._errors and self.prefix:
            self._errors = ErrorDict((self.add_prefix(name), value) for name, value in self._errors.items())
209831
def _get_jinja_error(trace, context=None):
    '''
    
    '''
    if not context:
        context = {}
    out = ''
    error = _get_jinja_error_slug(trace)
    line = _get_jinja_error_line(trace)
    msg = _get_jinja_error_message(trace)
    # if we failed on a nested macro, output a little more info
    # to help debugging
    # if sls is not found in context, add output only if we can
    # resolve the filename
    add_log = False
    template_path = None
    if 'sls' not in context:
        if (
            (error[0] != '<unknown>')
            and os.path.exists(error[0])
        ):
            template_path = error[0]
            add_log = True
    else:
        # the offender error is not from the called sls
        filen = context['sls'].replace('.', '/')
        if (
            not error[0].endswith(filen)
            and os.path.exists(error[0])
        ):
            add_log = True
            template_path = error[0]
    # if we add a log, format explicitly the exception here
    # by telling to output the macro context after the macro
    # error log place at the beginning
    if add_log:
        if template_path:
            out = '\n{0}\n'.format(msg.splitlines()[0])
            with salt.utils.files.fopen(template_path) as fp_:
                template_contents = salt.utils.stringutils.to_unicode(fp_.read())
            out += salt.utils.stringutils.get_context(
                template_contents,
                line,
                marker='    <======================')
        else:
            out = '\n{0}\n'.format(msg)
        line = 0
    return line, out
1341656
def clean_traceback(tb):
    ''''''
    prefix = __file__[:__file__.find("feat/common/error.py")]
    regex = re.compile("(\s*File\s*\")(%s)([a-zA-Z-_\. \\/]*)(\".*)"
                       % prefix.replace("\\", "\\\\"))

    def cleanup(line):
        m = regex.match(line)
        if m:
            return m.group(1) + ".../" + m.group(3) + m.group(4)
        else:
            return line

    return '\n'.join(map(cleanup, tb.split('\n')))
786304
function formErrorText (info, msg) {
  const hr = '----------'

  return addPlatformInformation(info)
  .then((obj) => {
    const formatted = []

    function add (msg) {
      formatted.push(
        stripIndents(msg)
      )
    }

    add(`
      ${obj.description}

      ${obj.solution}

    `)

    if (msg) {
      add(`
        ${hr}

        ${msg}

      `)
    }

    add(`
      ${hr}

      ${obj.platform}
    `)

    if (obj.footer) {
      add(`

        ${hr}

        ${obj.footer}
      `)
    }

    return formatted.join('\n\n')
  })
}