text:
/*
 * X11 headers define 'Bool' type which is used in qmetatype.h. we must include X11 files at last, i.e. XVRenderer_p.h. otherwise compile error
*/
#include "QtAV/VideoRenderer.h"
#include "QtAV/private/VideoRenderer_p.h"
#include "QtAV/FilterContext.h"
#include <QWidget>
#include <QResizeEvent>
#include <QtCore/qmath.h>
//#error qtextstream.h must be included before any header file that defines Status. Xlib.h defines Status
#include <QtCore/QTextStream> //build error
#include <sys/shm.h>
#include <X11/Xlib.h>
#include <X11/extensions/Xvlib.h>
#include "QtAV/private/factory.h"
//http://huangbster.i.sohu.com/blog/view/256490057.htm

namespace QtAV {

inline int scaleEQValue(int val, int min, int max)
{
    // max-min?
    return (val + 100)*((qAbs(min) + qAbs(max)))/200 - qAbs(min);
}

class XVRendererPrivate;
class XVRenderer: public QWidget, public VideoRenderer
{
    Q_OBJECT
    DPTR_DECLARE_PRIVATE(XVRenderer)
public:
    XVRenderer(QWidget* parent = 0, Qt::WindowFlags f = 0);
    virtual VideoRendererId id() const Q_DECL_OVERRIDE;
    virtual bool isSupported(VideoFormat::PixelFormat pixfmt) const Q_DECL_OVERRIDE;

    /* WA_PaintOnScreen: To render outside of Qt's paint system, e.g. If you require
     * native painting primitives, you need to reimplement QWidget::paintEngine() to
     * return 0 and set this flag
     * If paintEngine != 0, the window will flicker when drawing without QPainter.
     * Make sure that paintEngine returns 0 to avoid flicking.
     */
    virtual QPaintEngine* paintEngine() const Q_DECL_OVERRIDE;
    /*http://lists.trolltech.com/qt4-preview-feedback/2005-04/thread00609-0.html
     * true: paintEngine is QPainter. Painting with QPainter support double buffer
     * false: no double buffer, should reimplement paintEngine() to return 0 to avoid flicker
     */
    virtual QWidget* widget() Q_DECL_OVERRIDE { return this; }
protected:
    virtual bool receiveFrame(const VideoFrame& frame) Q_DECL_OVERRIDE;
    virtual bool needUpdateBackground() const Q_DECL_OVERRIDE;
    //called in paintEvent before drawFrame() when required
    virtual void drawBackground() Q_DECL_OVERRIDE;
    virtual bool needDrawFrame() const Q_DECL_OVERRIDE;
    //draw the current frame using the current paint engine. called by paintEvent()
    virtual void drawFrame() Q_DECL_OVERRIDE;
    virtual void paintEvent(QPaintEvent *) Q_DECL_OVERRIDE;
    virtual void resizeEvent(QResizeEvent *) Q_DECL_OVERRIDE;
    //stay on top will change parent, hide then show(windows). we need GetDC() again
    virtual void showEvent(QShowEvent *) Q_DECL_OVERRIDE;
private:
    virtual bool onSetBrightness(qreal b) Q_DECL_OVERRIDE;
    virtual bool onSetContrast(qreal c) Q_DECL_OVERRIDE;
    virtual bool onSetHue(qreal h) Q_DECL_OVERRIDE;
    virtual bool onSetSaturation(qreal s) Q_DECL_OVERRIDE;
};
typedef XVRenderer VideoRendererXV;
extern VideoRendererId VideoRendererId_XV;
#if 0
FACTORY_REGISTER_ID_AUTO(VideoRenderer, XV, "XVideo")
#else
void RegisterVideoRendererXV_Man()
{
    VideoRenderer::Register<XVRenderer>(VideoRendererId_XV, "XVideo");
}
#endif

VideoRendererId XVRenderer::id() const
{
    return VideoRendererId_XV;
}
#define FOURCC(a,b,c,d) ((a) | ((b)<<8) | ((c)<<16) | ((unsigned)(d)<<24))
static const struct xv_format_entry_t {
    VideoFormat::PixelFormat format;
    int fourcc;
} xv_fmt[] = {
{ VideoFormat::Format_YUV420P, FOURCC('Y', 'V', '1', '2')},
{ VideoFormat::Format_YUV420P, FOURCC('I', '4', '2', '0')},
{ VideoFormat::Format_UYVY, FOURCC('U', 'Y', 'V', 'Y')},
{ VideoFormat::Format_YUYV, FOURCC('Y', 'U', 'Y', '2')},
// split nv12 in xv to reduce copy times(no need to convert in sws)
{ VideoFormat::Format_NV12, FOURCC('Y', 'V', '1', '2')},
{ VideoFormat::Format_NV21, FOURCC('Y', 'V', '1', '2')},
};
#undef FOURCC
int pixelFormatToXv(VideoFormat::PixelFormat fmt)
{
    for (int i = 0; i < sizeof(xv_fmt)/sizeof(xv_fmt[0]); ++i) {
        if (xv_fmt[i].format == fmt)
            return xv_fmt[i].fourcc;
    }
    return 0;
}

int xvFormatInPort(Display* disp, XvPortID port, VideoFormat::PixelFormat fmt) {
    const int xv_id = pixelFormatToXv(fmt);
    if (!xv_id)
        return 0;
    const int xv_type = VideoFormat::isRGB(fmt) ? XvRGB : XvYUV;
    const int xv_plane = VideoFormat::isPlanar(fmt) ? XvPlanar : XvPacked;
    int count = 0;
    XvImageFormatValues *xvifmts = XvListImageFormats(disp, port, &count);
    for (const XvImageFormatValues *xvifmt = xvifmts; xvifmt <  xvifmts+count; ++xvifmt) {
        qDebug("XvImageFormatValues: %s", xvifmt->guid);
        if (xvifmt->type == xv_type
                && xvifmt->format == xv_plane
                && xvifmt->id == xv_id
                ) {
            if (XvGrabPort(disp, port, 0) == Success) {
                XFree(xvifmts);
                return xv_id;
            }
        }
    }
    XFree(xvifmts);
    return 0;
}

class XVRendererPrivate : public VideoRendererPrivate
{
public:
    DPTR_DECLARE_PUBLIC(XVRenderer)
    XVRendererPrivate():
        use_shm(true)
      , num_adaptors(0)
      , xv_image(0)
      , format_id(0x32315659) /*YV12*/
      , xv_image_width(0)
      , xv_image_height(0)
      , xv_port(0)
      , gc(NULL)
      , format(VideoFormat::Format_Invalid)
    {
        XInitThreads();
#ifndef _XSHM_H_
        use_shm = false;
#endif //_XSHM_H_
       //XvQueryExtension()
        display = XOpenDisplay(NULL);
        if (XvQueryAdaptors(display, DefaultRootWindow(display), &num_adaptors, &xv_adaptor_info) != Success) {
            available = false;
            qCritical("Query adaptors failed!");
            return;
        }
        if (num_adaptors < 1) {
            available = false;
            qCritical("No adaptor found!");
            return;
        }
    }
    ~XVRendererPrivate() {
        if (xv_adaptor_info) {
            XvFreeAdaptorInfo(xv_adaptor_info);
            xv_adaptor_info = 0;
        }
        destroyXVImage();
        if (gc) {
            XFreeGC(display, gc);
            gc = 0;
        }
        if (xv_port) {
            XvUngrabPort(display, xv_port, 0);
            xv_port = 0;
        }
        XCloseDisplay(display);
    }
    void destroyXVImage() {
        if (!xv_image)
            return;
#ifdef _XSHM_H_
        if (use_shm) {
            if (shm.shmaddr) {
                XShmDetach(display, &shm);
                shmctl(shm.shmid, IPC_RMID, 0);
                shmdt(shm.shmaddr);
            }
        } else
#endif //_XSHM_H_
        {
            // free if use copy (e.g. shm)
            free(xv_image->data);
        }
        XFree(xv_image);
        xv_image_width = 0;
        xv_image_height = 0;
    }
    bool prepareDeviceResource() {
        if (gc) {
            XFreeGC(display, gc);
            gc = 0;
        }
        gc = XCreateGC(display, q_func().winId(), 0, 0);
        if (!gc) {
            available = false;
            qCritical("Create GC failed!");
            return false;
        }
        XSetBackground(display, gc, BlackPixel(display, DefaultScreen(display)));
        if (filter_context)
            ((X11FilterContext*)filter_context)->resetX11((X11FilterContext::Display*)display, (X11FilterContext::GC)gc, (X11FilterContext::Drawable)q_func().winId());
        return true;
    }

    bool ensureImage(int w, int h, VideoFormat::PixelFormat pixfmt) {
        if (xv_image_width == w && xv_image_height == h && xv_image && format == pixfmt)
            return true;
        destroyXVImage();
        qDebug("port count: %d", num_adaptors);
        for (uint i = 0; i < num_adaptors; ++i) {
            //??
            if ((xv_adaptor_info[i].type & (XvInputMask | XvImageMask)) == (XvInputMask | XvImageMask)) {
                for (XvPortID p = xv_adaptor_info[i].base_id; p < xv_adaptor_info[i].base_id + xv_adaptor_info[i].num_ports; ++p) {
                    qDebug("XvAdaptorInfo: %s", xv_adaptor_info[i].name);
                    format_id = xvFormatInPort(display, p, pixfmt);
                    if (format_id) {
                        xv_port = p;
                        break;
                    }
                }
            }
            if (xv_port)
                break;
        }
        if (!xv_port) {
            qWarning("xv port not found!");
        }
        format = pixfmt;
        xv_image_width = w;
        xv_image_height = h;
#ifdef _XSHM_H_
        use_shm = XShmQueryExtension(display);
        qDebug("use xv shm: %d", use_shm);
        if (!use_shm)
            goto no_shm;
        xv_image = XvShmCreateImage(display, xv_port, format_id, 0, xv_image_width, xv_image_height, &shm);
        if (!xv_image)
            goto no_shm;
        shm.shmid = shmget(IPC_PRIVATE, xv_image->data_size, IPC_CREAT | 0777);
        qDebug("shmid: %d xv_image->data_size: %d, %dx%d", shm.shmid, xv_image->data_size, xv_image_width, xv_image_height);
        if (shm.shmid < 0) {
            qWarning("get shm failed. try to use none shm");
            goto no_shm;
        }
        shm.shmaddr = (char *)shmat(shm.shmid, 0, 0);
        if (shm.shmaddr == (char*)-1) {
            XFree(xv_image);
            qWarning("Shared memory error,disabling ( seg id error )");
            goto no_shm;
        }
        xv_image->data = shm.shmaddr;
        shm.readOnly = False;
        if (!XShmAttach(display, &shm)) {
            qWarning("Attach to shm failed! try to use none shm");
            goto no_shm;
        }
        XSync(display, False);
        shmctl(shm.shmid, IPC_RMID, 0);
        return true;
#endif //_XSHM_H_
no_shm:
        xv_image = XvCreateImage(display, xv_port, format_id, 0, xv_image_width, xv_image_height);
        if (!xv_image)
            return false;
        // malloc if use copy (e.g. shm)
        xv_image->data = (char*)malloc(xv_image->data_size);
        if (!xv_image->data)
            return false;
        XSync(display, False);
        return true;
    }

    bool XvSetPortAttributeIfExists(const char *key, int value);

    bool use_shm; //TODO: set by user
    unsigned int num_adaptors;
    XvAdaptorInfo *xv_adaptor_info;
    Display *display;
    XvImage *xv_image;
    int format_id;
    int xv_image_width, xv_image_height;
    XvPortID xv_port;
    GC gc;
#ifdef _XSHM_H_
    XShmSegmentInfo shm;
#endif //_XSHM_H_
    VideoFormat::PixelFormat format;
};

bool XVRendererPrivate::XvSetPortAttributeIfExists(const char *key, int value)
{
    int nb_attributes;
    XvAttribute *attributes = XvQueryPortAttributes(display, xv_port, &nb_attributes);
    if (!attributes) {
        qWarning("XvQueryPortAttributes error");
        return false;
    }
    for (int i = 0; i < nb_attributes; ++i) {
        const XvAttribute &attribute = ((XvAttribute*)attributes)[i];
        if (!qstrcmp(attribute.name, key) && (attribute.flags & XvSettable)) {
            XvSetPortAttribute(display, xv_port, XInternAtom(display, key, false), scaleEQValue(value, attribute.min_value, attribute.max_value));
            return true;
        }
    }
    qWarning("Can not set Xv attribute at key '%s'", key);
    return false;
}

XVRenderer::XVRenderer(QWidget *parent, Qt::WindowFlags f):
    QWidget(parent, f)
  , VideoRenderer(*new XVRendererPrivate())
{
    setPreferredPixelFormat(VideoFormat::Format_YUV420P);
    DPTR_INIT_PRIVATE(XVRenderer);
    setAcceptDrops(true);
    setFocusPolicy(Qt::StrongFocus);
    /* To rapidly update custom widgets that constantly paint over their entire areas with
     * opaque content, e.g., video streaming widgets, it is better to set the widget's
     * Qt::WA_OpaquePaintEvent, avoiding any unnecessary overhead associated with repainting the
     * widget's background
     */
    setAttribute(Qt::WA_OpaquePaintEvent);
    //setAttribute(Qt::WA_NoSystemBackground);
    //setAutoFillBackground(false);
    setAttribute(Qt::WA_PaintOnScreen, true);
    d_func().filter_context = VideoFilterContext::create(VideoFilterContext::X11);
    if (!d_func().filter_context) {
        qWarning("No filter context for X11");
    } else {
        d_func().filter_context->paint_device = this;
    }
}

bool XVRenderer::isSupported(VideoFormat::PixelFormat pixfmt) const
{
    // TODO: rgb use copyplane
    return pixfmt == VideoFormat::Format_YUV420P || pixfmt == VideoFormat::Format_YV12
            || pixfmt == VideoFormat::Format_NV12|| pixfmt == VideoFormat::Format_NV21
            || pixfmt == VideoFormat::Format_UYVY || pixfmt == VideoFormat::Format_YUYV
            ;
}

static void SplitPlanes(quint8 *dstu, size_t dstu_pitch,
                        quint8 *dstv, size_t dstv_pitch,
                        const quint8 *src, size_t src_pitch,
                        unsigned width, unsigned height)
{
    for (unsigned y = 0; y < height; y++) {
        for (unsigned x = 0; x < width; x++) {
            dstu[x] = src[2*x+0];
            dstv[x] = src[2*x+1];
        }
        src  += src_pitch;
        dstu += dstu_pitch;
        dstv += dstv_pitch;
    }
}

void CopyFromNv12(quint8 *dst[], size_t dst_pitch[],
                  const quint8 *src[2], size_t src_pitch[2],
                  unsigned width, unsigned height)
{
    VideoFrame::copyPlane(dst[0], dst_pitch[0], src[0], src_pitch[0], width, height);
    SplitPlanes(dst[2], dst_pitch[2], dst[1], dst_pitch[1], src[1], src_pitch[1], width/2, height/2);
}

void CopyFromYv12(quint8 *dst[], size_t dst_pitch[],
                  const quint8 *src[3], size_t src_pitch[3],
                  unsigned width, unsigned height)
{
     VideoFrame::copyPlane(dst[0], dst_pitch[0], src[0], src_pitch[0], width, height);
     VideoFrame::copyPlane(dst[1], dst_pitch[1], src[1], src_pitch[1], width/2, height/2);
     VideoFrame::copyPlane(dst[2], dst_pitch[2], src[2], src_pitch[2], width/2, height/2);
}

void CopyFromYv12_2(quint8 *dst[], size_t dst_pitch[],
                  const quint8 *src[3], size_t src_pitch[3],
                  unsigned width, unsigned height)
{
     VideoFrame::copyPlane(dst[0], dst_pitch[0], src[0], src_pitch[0], width, height);
     width /= 2;
     height /= 2;
     if (width == dst_pitch[1] && dst_pitch[1] == src_pitch[1]) {
         VideoFrame::copyPlane(dst[1], dst_pitch[1], src[1], src_pitch[1], width, height);
         VideoFrame::copyPlane(dst[2], dst_pitch[2], src[2], src_pitch[2], width, height);
     } else {
         for (unsigned i = 0; i < height; ++i) {
             memcpy(dst[2], src[2], width);
             memcpy(dst[1], src[1], width);
             src[1] += src_pitch[1];
             src[2] += src_pitch[2];
             dst[1] += dst_pitch[1];
             dst[2] += dst_pitch[2];
         }
     }
}

bool XVRenderer::receiveFrame(const VideoFrame& frame)
{
    DPTR_D(XVRenderer);
    if (!frame.isValid()) {
        d.update_background = true;
        d.video_frame = VideoFrame(); // fill background
        updateUi();
        return true;
    }
    if (!d.ensureImage(frame.width(), frame.height(), frame.format().pixelFormat()))
        return false;
    if (frame.constBits(0))
        d.video_frame = frame;
    else // FIXME: not work
        d.video_frame = frame.to(frame.pixelFormat()); // assume frame format is supported
    int nb_planes = d.video_frame.planeCount();
    QVector<size_t> src_linesize(nb_planes);
    QVector<const quint8*> src(nb_planes);
    for (int i = 0; i < nb_planes; ++i) {
        src[i] = d.video_frame.constBits(i);
        src_linesize[i] = d.video_frame.bytesPerLine(i);
    }
    //swap UV
    quint8* dst[] = {
        (quint8*)(d.xv_image->data + d.xv_image->offsets[0]),
        (quint8*)(d.xv_image->data + d.xv_image->offsets[2]),
        (quint8*)(d.xv_image->data + d.xv_image->offsets[1])
    };
    size_t dst_linesize[] = {
        (size_t)d.xv_image->pitches[0],
        (size_t)d.xv_image->pitches[2],
        (size_t)d.xv_image->pitches[1]
    };
    // TODO: if not using shm and linesizes match, no copy is required. but seems no benefit
    switch (d.video_frame.pixelFormat()) {
    case VideoFormat::Format_YUV420P:
    case VideoFormat::Format_YV12:
        CopyFromYv12_2(dst, dst_linesize, src.data(), src_linesize.data(), dst_linesize[0], d.xv_image->height);
        break;
    case VideoFormat::Format_NV12:
        std::swap(dst[1], dst[2]);
        std::swap(dst_linesize[1], dst_linesize[2]);
        CopyFromNv12(dst, dst_linesize, src.data(), src_linesize.data(), dst_linesize[0], d.xv_image->height);
        break;
    case VideoFormat::Format_NV21:
        CopyFromNv12(dst, dst_linesize, src.data(), src_linesize.data(), dst_linesize[0], d.xv_image->height);
        break;
    case VideoFormat::Format_UYVY:
    case VideoFormat::Format_YUYV:
        VideoFrame::copyPlane(dst[0], dst_linesize[0], src[0], src_linesize[0], dst_linesize[0], d.xv_image->height);
        break;
    case VideoFormat::Format_BGR24:
        break;
    default:
        break;
    }
    update();
    return true;
}

QPaintEngine* XVRenderer::paintEngine() const
{
    return 0; //use native engine
}

bool XVRenderer::needUpdateBackground() const
{
    DPTR_D(const XVRenderer);
    return d.update_background && d.out_rect != rect();/* || d.data.isEmpty()*/ //data is always empty because we never copy it now.
}

void XVRenderer::drawBackground()
{
    if (autoFillBackground())
        return;
    DPTR_D(XVRenderer);
    if (d.video_frame.isValid()) {
        if (d.out_rect.width() < width()) {
            XFillRectangle(d.display, winId(), d.gc, 0, 0, (width() - d.out_rect.width())/2, height());
            XFillRectangle(d.display, winId(), d.gc, d.out_rect.right(), 0, (width() - d.out_rect.width())/2, height());
        }
        if (d.out_rect.height() < height()) {
            XFillRectangle(d.display, winId(), d.gc, 0, 0,  width(), (height() - d.out_rect.height())/2);
            XFillRectangle(d.display, winId(), d.gc, 0, d.out_rect.bottom(), width(), (height() - d.out_rect.height())/2);
        }
    } else {
        XFillRectangle(d.display, winId(), d.gc, 0, 0, width(), height());
    }
    XFlush(d.display);
}

bool XVRenderer::needDrawFrame() const
{
    DPTR_D(const XVRenderer);
    return  d.xv_image || d.video_frame.isValid();
}

void XVRenderer::drawFrame()
{
    DPTR_D(XVRenderer);
    QRect roi = realROI();
#ifdef _XSHM_H_
        if (d.use_shm) {
            XvShmPutImage(d.display, d.xv_port, winId(), d.gc, d.xv_image
                          , roi.x(), roi.y(), roi.width(), roi.height()
                          , d.out_rect.x(), d.out_rect.y(), d.out_rect.width(), d.out_rect.height()
                          , false /*true: send event*/);
            XSync(d.display, False); // update immediately
            return;
        }
#endif
        XvPutImage(d.display, d.xv_port, winId(), d.gc, d.xv_image
                   , roi.x(), roi.y(), roi.width(), roi.height()
                   , d.out_rect.x(), d.out_rect.y(), d.out_rect.width(), d.out_rect.height());
        XSync(d.display, False);
}

void XVRenderer::paintEvent(QPaintEvent *)
{
    handlePaintEvent();
}

void XVRenderer::resizeEvent(QResizeEvent *e)
{
    DPTR_D(XVRenderer);
    d.update_background = true;
    resizeRenderer(e->size());
    update(); //update background
}

void XVRenderer::showEvent(QShowEvent *event)
{
    Q_UNUSED(event);
    DPTR_D(XVRenderer);
    d.update_background = true;
    /*
     * Do something that depends on widget below! e.g. recreate render target for direct2d.
     * When Qt::WindowStaysOnTopHint changed, window will hide first then show. If you
     * don't do anything here, the widget content will never be updated.
     */
    d.prepareDeviceResource();
}

bool XVRenderer::onSetBrightness(qreal b)
{
    DPTR_D(XVRenderer);
    return d.XvSetPortAttributeIfExists("XV_BRIGHTNESS", b*100);
}

bool XVRenderer::onSetContrast(qreal c)
{
    DPTR_D(XVRenderer);
    return d.XvSetPortAttributeIfExists("XV_CONTRAST",c*100);
}

bool XVRenderer::onSetHue(qreal h)
{
    DPTR_D(XVRenderer);
    return d.XvSetPortAttributeIfExists("XV_HUE", h*100);
}

bool XVRenderer::onSetSaturation(qreal s)
{
    DPTR_D(XVRenderer);
    return d.XvSetPortAttributeIfExists("XV_SATURATION", s*100);
}

} //namespace QtAV

#include "XVRenderer.moc"


text:
package http

import (
	bm "go-common/library/net/http/blademaster"
)

func anniversaryInfo(c *bm.Context) {
	var (
		mid int64
	)
	midInter, _ := c.Get("mid")
	mid = midInter.(int64)
	c.JSON(artSrv.AnniversaryInfo(c, mid))
}

redpajama_set_name: RedPajamaGithub


text:
namespace System.Web.Util {
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Diagnostics.CodeAnalysis;
    using System.Globalization;
    using System.Linq;
    using System.Reflection;
    using System.Runtime.CompilerServices;
    using System.Runtime.InteropServices;
    using System.Security;
    using System.Security.Permissions;
    using System.Text;
    using System.Threading;
    using System.Web;

    internal static class AppVerifier {

        // It's possible that multiple error codes might get mapped to the same description string.
        // This can happen if there might be multiple ways for a single problem to manifest itself.
        private static readonly Dictionary<AppVerifierErrorCode, string> _errorStringMappings = new Dictionary<AppVerifierErrorCode, string>() {
            { AppVerifierErrorCode.HttpApplicationInstanceWasNull, SR.AppVerifier_Errors_HttpApplicationInstanceWasNull },
            { AppVerifierErrorCode.BeginHandlerDelegateWasNull, SR.AppVerifier_Errors_BeginHandlerDelegateWasNull },
            { AppVerifierErrorCode.AsyncCallbackInvokedMultipleTimes, SR.AppVerifier_Errors_AsyncCallbackInvokedMultipleTimes },
            { AppVerifierErrorCode.AsyncCallbackInvokedWithNullParameter, SR.AppVerifier_Errors_AsyncCallbackInvokedWithNullParameter },
            { AppVerifierErrorCode.AsyncCallbackGivenAsyncResultWhichWasNotCompleted, SR.AppVerifier_Errors_AsyncCallbackGivenAsyncResultWhichWasNotCompleted },
            { AppVerifierErrorCode.AsyncCallbackInvokedSynchronouslyButAsyncResultWasNotMarkedCompletedSynchronously, SR.AppVerifier_Errors_AsyncCallbackInvokedSynchronouslyButAsyncResultWasNotMarkedCompletedSynchronously },
            { AppVerifierErrorCode.AsyncCallbackInvokedAsynchronouslyButAsyncResultWasMarkedCompletedSynchronously, SR.AppVerifier_Errors_AsyncCallbackInvokedAsynchronouslyButAsyncResultWasMarkedCompletedSynchronously },
            { AppVerifierErrorCode.AsyncCallbackInvokedWithUnexpectedAsyncResultInstance, SR.AppVerifier_Errors_AsyncCallbackInvokedWithUnexpectedAsyncResultInstance },
            { AppVerifierErrorCode.AsyncCallbackInvokedAsynchronouslyThenBeginHandlerThrew, SR.AppVerifier_Errors_AsyncCallbackInvokedEvenThoughBeginHandlerThrew },
            { AppVerifierErrorCode.BeginHandlerThrewThenAsyncCallbackInvokedAsynchronously, SR.AppVerifier_Errors_AsyncCallbackInvokedEvenThoughBeginHandlerThrew },
            { AppVerifierErrorCode.AsyncCallbackInvokedSynchronouslyThenBeginHandlerThrew, SR.AppVerifier_Errors_AsyncCallbackInvokedEvenThoughBeginHandlerThrew },
            { AppVerifierErrorCode.AsyncCallbackInvokedWithUnexpectedAsyncResultAsyncState, SR.AppVerifier_Errors_AsyncCallbackInvokedWithUnexpectedAsyncResultAsyncState },
            { AppVerifierErrorCode.AsyncCallbackCalledAfterHttpApplicationReassigned, SR.AppVerifier_Errors_AsyncCallbackCalledAfterHttpApplicationReassigned },
            { AppVerifierErrorCode.BeginHandlerReturnedNull, SR.AppVerifier_Errors_BeginHandlerReturnedNull },
            { AppVerifierErrorCode.BeginHandlerReturnedAsyncResultMarkedCompletedSynchronouslyButWhichWasNotCompleted, SR.AppVerifier_Errors_BeginHandlerReturnedAsyncResultMarkedCompletedSynchronouslyButWhichWasNotCompleted },
            { AppVerifierErrorCode.BeginHandlerReturnedAsyncResultMarkedCompletedSynchronouslyButAsyncCallbackNeverCalled, SR.AppVerifier_Errors_BeginHandlerReturnedAsyncResultMarkedCompletedSynchronouslyButAsyncCallbackNeverCalled },
            { AppVerifierErrorCode.BeginHandlerReturnedUnexpectedAsyncResultInstance, SR.AppVerifier_Errors_AsyncCallbackInvokedWithUnexpectedAsyncResultInstance },
            { AppVerifierErrorCode.BeginHandlerReturnedUnexpectedAsyncResultAsyncState, SR.AppVerifier_Errors_BeginHandlerReturnedUnexpectedAsyncResultAsyncState },
            { AppVerifierErrorCode.SyncContextSendOrPostCalledAfterRequestCompleted, SR.AppVerifier_Errors_SyncContextSendOrPostCalledAfterRequestCompleted },
            { AppVerifierErrorCode.SyncContextSendOrPostCalledBetweenNotifications, SR.AppVerifier_Errors_SyncContextSendOrPostCalledBetweenNotifications },
            { AppVerifierErrorCode.SyncContextPostCalledInNestedNotification, SR.AppVerifier_Errors_SyncContextPostCalledInNestedNotification },
            { AppVerifierErrorCode.RequestNotificationCompletedSynchronouslyWithNotificationContextPending, SR.AppVerifier_Errors_RequestNotificationCompletedSynchronouslyWithNotificationContextPending },
            { AppVerifierErrorCode.NotificationContextHasChangedAfterSynchronouslyProcessingNotification, SR.AppVerifier_Errors_NotificationContextHasChangedAfterSynchronouslyProcessingNotification },
            { AppVerifierErrorCode.PendingProcessRequestNotificationStatusAfterCompletingNestedNotification, SR.AppVerifier_Errors_PendingProcessRequestNotificationStatusAfterCompletingNestedNotification },
        };

        // Provides an option for different wrappers to specify whether to collect the call stacks traces
        [FlagsAttribute]
        internal enum CallStackCollectionBitMasks : int {
            AllMask = -1,

            // used for a 3-parameter Begin* method [(T, AsyncCallback, object) -> IAsyncResult] wrapper
            BeginCallHandlerMask = 1,
            CallHandlerCallbackMask = 2,

            // used for a BeginEventHandler method [(object, sender, EventArgs, object) -> IAsyncResult] wrapper
            BeginExecutionStepMask = 4,
            ExecutionStepCallbackMask = 8,

            // when adding new bits above also update the following:
            AllHandlerMask = BeginCallHandlerMask | CallHandlerCallbackMask,
            AllStepMask = BeginExecutionStepMask | ExecutionStepCallbackMask,

            AllBeginMask = BeginCallHandlerMask | BeginExecutionStepMask,
            AllCallbackMask = CallHandlerCallbackMask | ExecutionStepCallbackMask
        };

        // The declarative order of these two fields is important; don't swap them!
        private static Action<AppVerifierException> DefaultAppVerifierBehavior = GetAppVerifierBehaviorFromRegistry();
        internal static readonly bool IsAppVerifierEnabled = (DefaultAppVerifierBehavior != null);
        private static long AppVerifierErrorCodeCollectCallStackMask;
        private static long AppVerifierErrorCodeEnableAssertMask;
        private static CallStackCollectionBitMasks AppVerifierCollectCallStackMask;

        private delegate void AssertDelegate(bool condition, AppVerifierErrorCode errorCode);
        private delegate void AppendAdditionalInfoDelegate(StringBuilder errorString);

        // Returns an AppVerifier handler (something that can record exceptions appropriately)
        // appropriate to what was set in the system registry. If the key we're looking for
        // doesn't exist or doesn't have a known value, we return 'null', signifying that
        // AppVerifier is disabled.
        private static Action<AppVerifierException> GetAppVerifierBehaviorFromRegistry() {
            // use 0 as the default value if the key doesn't exist or is of the wrong type
            int valueFromRegistry = (Misc.GetAspNetRegValue(subKey: null, valueName: "RuntimeVerificationBehavior", defaultValue: null) as int?) ?? 0;

            // REG_QWORD used as a mask to disable individual asserts. No key means all asserts are enabled
            AppVerifierErrorCodeEnableAssertMask = (Misc.GetAspNetRegValue(subKey: null, valueName: "AppVerifierErrorCodeEnableAssertMask", defaultValue: (long)(-1)) as long?) ?? (long)(-1);

            // REG_QWORD used as a mask to control call stack collection on individual asserts (useful if we event log only). No key means all asserts will collect stack traces
            AppVerifierErrorCodeCollectCallStackMask = (Misc.GetAspNetRegValue(subKey: null, valueName: "AppVerifierErrorCodeCollectCallstackMask", defaultValue: (long)(-1)) as long?) ?? (long)(-1);

            // REG_DWORD mask to disable call stack collection on begin* / end* methods. No key means all call stacks are collected
            AppVerifierCollectCallStackMask = (CallStackCollectionBitMasks)((Misc.GetAspNetRegValue(subKey: null, valueName: "AppVerifierCollectCallStackMask", defaultValue: (int)(-1)) as int?) ?? (int)(-1));

            switch (valueFromRegistry) {
                case 1:
                    // Just write to the event log
                    return WriteToEventLog;

                case 2:
                    // Write to the event log and Debugger.Launch / Debugger.Break
                    return WriteToEventLogAndSoftBreak;

                case 3:
                    // Write to the event log and kernel32!DebugBreak
                    return WriteToEventLogAndHardBreak;

                default:
                    // not enabled
                    return null;
            }
        }

        // Writes an exception to the Windows Event Log (Application section)
        private static void WriteToEventLog(AppVerifierException ex) {
            Misc.WriteUnhandledExceptionToEventLog(AppDomain.CurrentDomain, ex); // method won't throw
        }

        [SecurityPermission(SecurityAction.Assert, UnmanagedCode = true)] // safe since AppVerifier can only be enabled via registry, which already requires admin privileges
        private static void WriteToEventLogAndSoftBreak(AppVerifierException ex) {
            // A "soft" break means that we prompt to launch a debugger, and if one is attached we'll signal it.
            WriteToEventLog(ex);
            if (Debugger.Launch()) {
                Debugger.Break();
            }
        }

        [SecurityPermission(SecurityAction.Assert, UnmanagedCode = true)] // safe since AppVerifier can only be enabled via registry, which already requires admin privileges
        private static void WriteToEventLogAndHardBreak(AppVerifierException ex) {
            // A "hard" break means that we'll signal any attached debugger, and if none is attached
            // we'll just INT 3 and hope for the best. (This may cause a Watson dump depending on environment.)
            WriteToEventLog(ex);
            if (Debugger.IsAttached) {
                Debugger.Break();
            }
            else {
                NativeMethods.DebugBreak();
            }
        }

        // Instruments a 3-parameter Begin* method [(T, AsyncCallback, object) -> IAsyncResult].
        // If AppVerifier is disabled, returns the original method unmodified.
        public static Func<T, AsyncCallback, object, IAsyncResult> WrapBeginMethod<T>(HttpApplication httpApplication, Func<T, AsyncCallback, object, IAsyncResult> originalDelegate) {
            if (!IsAppVerifierEnabled) {
                return originalDelegate;
            }

            return (arg, callback, state) => WrapBeginMethodImpl(
                httpApplication: httpApplication,
                beginMethod: (innerCallback, innerState) => originalDelegate(arg, innerCallback, innerState),
                originalDelegate: originalDelegate,
                errorHandler: HandleAppVerifierException,
                callStackMask: CallStackCollectionBitMasks.AllHandlerMask)
                (callback, state);
        }

        // Instruments a BeginEventHandler method [(object, sender, EventArgs, object) -> IAsyncResult].
        // This pattern is commonly used, such as by IHttpModule, PageAsyncTask, and others.
        // If AppVerifier is disabled, returns the original method unmodified.
        public static BeginEventHandler WrapBeginMethod(HttpApplication httpApplication, BeginEventHandler originalDelegate) {
            if (!IsAppVerifierEnabled) {
                return originalDelegate;
            }

            return (sender, e, cb, extraData) => WrapBeginMethodImpl(
                httpApplication: httpApplication,
                beginMethod: (innerCallback, innerState) => originalDelegate(sender, e, innerCallback, innerState),
                originalDelegate: originalDelegate,
                errorHandler: HandleAppVerifierException,
                callStackMask: CallStackCollectionBitMasks.AllStepMask)
                (cb, extraData);
        }

        /// <summary>
        /// Wraps the Begin* part of a Begin / End method pair to allow for signaling when assertions have been violated.
        /// The instrumentation can be a performance hit, so this method should not be called if AppVerifier is not enabled.
        /// </summary>
        /// <param name="httpApplication">The HttpApplication instance for this request, used to get HttpContext and related items.</param>
        /// <param name="beginMethod">The Begin* part of a Begin / End method pair, likely wrapped in a lambda so only the AsyncCallback and object parameters are exposed.</param>
        /// <param name="originalDelegate">The original user-provided delegate, e.g. the thing that 'beginMethod' wraps. Provided so that we can show correct methods when asserting.</param>
        /// <param name="errorHandler">The listener that can handle verification failures.</param>
        /// <returns>The instrumented Begin* method.</returns>
        internal static Func<AsyncCallback, object, IAsyncResult> WrapBeginMethodImpl(HttpApplication httpApplication, Func<AsyncCallback, object, IAsyncResult> beginMethod, Delegate originalDelegate, Action<AppVerifierException> errorHandler, CallStackCollectionBitMasks callStackMask) {
            return (callback, state) => {
                // basic diagnostic info goes at the top since it's used during generation of the error message
                AsyncCallbackInvocationHelper asyncCallbackInvocationHelper = new AsyncCallbackInvocationHelper();
                CallStackCollectionBitMasks myBeginMask = callStackMask & CallStackCollectionBitMasks.AllBeginMask;
                bool captureBeginStack = (myBeginMask & (CallStackCollectionBitMasks)AppVerifierCollectCallStackMask) == myBeginMask;

                InvocationInfo beginHandlerInvocationInfo = InvocationInfo.Capture(captureBeginStack);
                string requestUrl = null;
                RequestNotification? currentNotification = null;
                bool isPostNotification = false;
                Type httpHandlerType = null;

                // need to collect all this up-front since it might go away during the async operation
                if (httpApplication != null) {
                    HttpContext context = httpApplication.Context;
                    if (context != null) {
                        if (!context.HideRequestResponse && context.Request != null) {
                            requestUrl = TryGetRequestUrl(context);
                        }

                        if (context.NotificationContext != null) {
                            currentNotification = context.NotificationContext.CurrentNotification;
                            isPostNotification = context.NotificationContext.IsPostNotification;
                        }

                        if (context.Handler != null) {
                            httpHandlerType = context.Handler.GetType();
                        }
                    }
                }

                // If the condition passed to this method evaluates to false, we will raise an error to whoever is listening.
                AssertDelegate assert = (condition, errorCode) => {
                    long mask = 1L<<(int)errorCode;
                    // assert only if it was not masked out by a bit set
                    bool enableAssert = (AppVerifierErrorCodeEnableAssertMask & mask) == mask;

                    if (!condition && enableAssert) {
                        // capture the stack only if it was not masked out by a bit set
                        bool captureStack = (AppVerifierErrorCodeCollectCallStackMask & mask) == mask;

                        InvocationInfo assertInvocationInfo = InvocationInfo.Capture(captureStack);

                        // header
                        StringBuilder errorString = new StringBuilder();
                        errorString.AppendLine(FormatErrorString(SR.AppVerifier_Title));
                        errorString.AppendLine(FormatErrorString(SR.AppVerifier_Subtitle));
                        errorString.AppendLine();

                        // basic info (about the assert)
                        errorString.AppendLine(FormatErrorString(SR.AppVerifier_BasicInfo_URL, requestUrl));
                        errorString.AppendLine(FormatErrorString(SR.AppVerifier_BasicInfo_ErrorCode, (int)errorCode));
                        errorString.AppendLine(FormatErrorString(SR.AppVerifier_BasicInfo_Description, GetLocalizedDescriptionStringForError(errorCode)));
                        errorString.AppendLine(FormatErrorString(SR.AppVerifier_BasicInfo_ThreadInfo, assertInvocationInfo.ThreadId, assertInvocationInfo.Timestamp.ToLocalTime()));
                        errorString.AppendLine(assertInvocationInfo.StackTrace.ToString());

                        // Begin* method info
                        errorString.AppendLine(FormatErrorString(SR.AppVerifier_BeginMethodInfo_EntryMethod, PrettyPrintDelegate(originalDelegate)));
                        if (currentNotification != null) {
                            errorString.AppendLine(FormatErrorString(SR.AppVerifier_BeginMethodInfo_RequestNotification_Integrated, currentNotification, isPostNotification));
                        }
                        else {
                            errorString.AppendLine(FormatErrorString(SR.AppVerifier_BeginMethodInfo_RequestNotification_NotIntegrated));
                        }
                        errorString.AppendLine(FormatErrorString(SR.AppVerifier_BeginMethodInfo_CurrentHandler, httpHandlerType));
                        errorString.AppendLine(FormatErrorString(SR.AppVerifier_BeginMethodInfo_ThreadInfo, beginHandlerInvocationInfo.ThreadId, beginHandlerInvocationInfo.Timestamp.ToLocalTime()));
                        errorString.AppendLine(beginHandlerInvocationInfo.StackTrace.ToString());

                        // AsyncCallback info
                        int totalAsyncInvocationCount;
                        InvocationInfo firstAsyncInvocation = asyncCallbackInvocationHelper.GetFirstInvocationInfo(out totalAsyncInvocationCount);
                        errorString.AppendLine(FormatErrorString(SR.AppVerifier_AsyncCallbackInfo_InvocationCount, totalAsyncInvocationCount));
                        if (firstAsyncInvocation != null) {
                            errorString.AppendLine(FormatErrorString(SR.AppVerifier_AsyncCallbackInfo_FirstInvocation_ThreadInfo, firstAsyncInvocation.ThreadId, firstAsyncInvocation.Timestamp.ToLocalTime()));
                            errorString.AppendLine(firstAsyncInvocation.StackTrace.ToString());
                        }

                        AppVerifierException ex = new AppVerifierException(errorCode, errorString.ToString());
                        errorHandler(ex);
                        throw ex;
                    }
                };

                assert(httpApplication != null, AppVerifierErrorCode.HttpApplicationInstanceWasNull);
                assert(originalDelegate != null, AppVerifierErrorCode.BeginHandlerDelegateWasNull);

                object lockObj = new object(); // used to synchronize access to certain locals which can be touched by multiple threads
                IAsyncResult asyncResultReturnedByBeginHandler = null;
                IAsyncResult asyncResultPassedToCallback = null;
                object beginHandlerReturnValueHolder = null; // used to hold the IAsyncResult returned by or Exception thrown by BeginHandler; see comments on Holder<T> for more info
                Thread threadWhichCalledBeginHandler = Thread.CurrentThread; // used to determine whether the callback was invoked synchronously
                bool callbackRanToCompletion = false; // don't need to lock when touching this local since it's only read in the synchronous case

                HttpContext assignedContextUponCallingBeginHandler = httpApplication.Context; // used to determine whether the underlying request disappeared

                try {
                    asyncResultReturnedByBeginHandler = beginMethod(
                       asyncResult => {
                           try {
                               CallStackCollectionBitMasks myCallbackMask = callStackMask & CallStackCollectionBitMasks.AllCallbackMask;
                               bool captureEndCallStack = (myCallbackMask & AppVerifierCollectCallStackMask ) == myCallbackMask;
                               // The callback must never be called more than once.
                               int newAsyncCallbackInvocationCount = asyncCallbackInvocationHelper.RecordInvocation(captureEndCallStack);
                               assert(newAsyncCallbackInvocationCount == 1, AppVerifierErrorCode.AsyncCallbackInvokedMultipleTimes);

                               // The 'asyncResult' parameter must never be null.
                               assert(asyncResult != null, AppVerifierErrorCode.AsyncCallbackInvokedWithNullParameter);

                               object tempBeginHandlerReturnValueHolder;
                               Thread tempThreadWhichCalledBeginHandler;
                               lock (lockObj) {
                                   asyncResultPassedToCallback = asyncResult;
                                   tempBeginHandlerReturnValueHolder = beginHandlerReturnValueHolder;
                                   tempThreadWhichCalledBeginHandler = threadWhichCalledBeginHandler;
                               }

                               // At this point, 'IsCompleted = true' is mandatory.
                               assert(asyncResult.IsCompleted, AppVerifierErrorCode.AsyncCallbackGivenAsyncResultWhichWasNotCompleted);

                               if (tempBeginHandlerReturnValueHolder == null) {
                                   // BeginHandler hasn't yet returned, so this call may be synchronous or asynchronous.
                                   // We can tell by comparing the current thread with the thread which called BeginHandler.
                                   // From a correctness perspective, it is valid to invoke the AsyncCallback delegate either
                                   // synchronously or asynchronously. From [....]: if 'CompletedSynchronously = true', then
                                   // AsyncCallback invocation can happen either on the same thread or on a different thread,
                                   // just as long as BeginHandler hasn't yet returned (which in true in this case).
                                   if (!asyncResult.CompletedSynchronously) {
                                       // If 'CompletedSynchronously = false', we must be on a different thread than the BeginHandler invocation.
                                       assert(tempThreadWhichCalledBeginHandler != Thread.CurrentThread, AppVerifierErrorCode.AsyncCallbackInvokedSynchronouslyButAsyncResultWasNotMarkedCompletedSynchronously);
                                   }
                               }
                               else {
                                   // BeginHandler already returned, so this invocation is definitely asynchronous.

                                   Holder<IAsyncResult> asyncResultHolder = tempBeginHandlerReturnValueHolder as Holder<IAsyncResult>;
                                   if (asyncResultHolder != null) {
                                       // We need to verify that the IAsyncResult we're given is the same that was returned by BeginHandler
                                       // and that the IAsyncResult is marked 'CompletedSynchronously = false'.
                                       assert(asyncResult == asyncResultHolder.Value, AppVerifierErrorCode.AsyncCallbackInvokedWithUnexpectedAsyncResultInstance);
                                       assert(!asyncResult.CompletedSynchronously, AppVerifierErrorCode.AsyncCallbackInvokedAsynchronouslyButAsyncResultWasMarkedCompletedSynchronously);
                                   }
                                   else {
                                       // If we reached this point, BeginHandler threw an exception.
                                       // The AsyncCallback should never be invoked if BeginHandler has already failed.
                                       assert(false, AppVerifierErrorCode.BeginHandlerThrewThenAsyncCallbackInvokedAsynchronously);
                                   }
                               }

                               // AsyncState must match the 'state' parameter passed to BeginHandler
                               assert(asyncResult.AsyncState == state, AppVerifierErrorCode.AsyncCallbackInvokedWithUnexpectedAsyncResultAsyncState);

                               // Make sure the underlying HttpApplication is still assigned to the captured HttpContext instance.
                               // If not, this AsyncCallback invocation could end up completing *some other request's* operation,
                               // resulting in data corruption.
                               assert(assignedContextUponCallingBeginHandler == httpApplication.Context, AppVerifierErrorCode.AsyncCallbackCalledAfterHttpApplicationReassigned);
                           }
                           catch (AppVerifierException) {
                               // We want to ---- any exceptions thrown by our verification logic, as the failure
                               // has already been recorded by the appropriate listener. Just go straight to
                               // invoking the callback.
                           }

                           // all checks complete - delegate control to the actual callback
                           if (callback != null) {
                               callback(asyncResult);
                           }
                           callbackRanToCompletion = true;
                       },
                       state);

                    // The return value must never be null.
                    assert(asyncResultReturnedByBeginHandler != null, AppVerifierErrorCode.BeginHandlerReturnedNull);

                    lock (lockObj) {
                        beginHandlerReturnValueHolder = new Holder<IAsyncResult>(asyncResultReturnedByBeginHandler);
                    }

                    if (asyncResultReturnedByBeginHandler.CompletedSynchronously) {
                        // If 'CompletedSynchronously = true', the IAsyncResult must be marked 'IsCompleted = true'
                        // and the AsyncCallback must have been invoked synchronously (checked in the AsyncCallback verification logic).
                        assert(asyncResultReturnedByBeginHandler.IsCompleted, AppVerifierErrorCode.BeginHandlerReturnedAsyncResultMarkedCompletedSynchronouslyButWhichWasNotCompleted);
                        assert(asyncCallbackInvocationHelper.TotalInvocations != 0, AppVerifierErrorCode.BeginHandlerReturnedAsyncResultMarkedCompletedSynchronouslyButAsyncCallbackNeverCalled);
                    }

                    IAsyncResult tempAsyncResultPassedToCallback;
                    lock (lockObj) {
                        tempAsyncResultPassedToCallback = asyncResultPassedToCallback;
                    }

                    // The AsyncCallback may have been invoked (either synchronously or asynchronously). If it has been
                    // invoked, we need to verify that it was given the same IAsyncResult returned by BeginHandler.
                    // If the AsyncCallback hasn't yet been called, we skip this check, as the AsyncCallback verification
                    // logic will eventually perform the check at the appropriate time.
                    if (tempAsyncResultPassedToCallback != null) {
                        assert(tempAsyncResultPassedToCallback == asyncResultReturnedByBeginHandler, AppVerifierErrorCode.BeginHandlerReturnedUnexpectedAsyncResultInstance);
                    }

                    // AsyncState must match the 'state' parameter passed to BeginHandler
                    assert(asyncResultReturnedByBeginHandler.AsyncState == state, AppVerifierErrorCode.BeginHandlerReturnedUnexpectedAsyncResultAsyncState);

                    // all checks complete
                    return asyncResultReturnedByBeginHandler;
                }
                catch (AppVerifierException) {
                    // We want to ---- any exceptions thrown by our verification logic, as the failure
                    // has already been recorded by the appropriate listener. Just return the original
                    // IAsyncResult so that the application continues to run.
                    return asyncResultReturnedByBeginHandler;
                }
                catch (Exception ex) {
                    if (asyncResultReturnedByBeginHandler == null) {
                        // If we reached this point, an exception was thrown by BeginHandler, so we need to
                        // record it and rethrow it.

                        IAsyncResult tempAsyncResultPassedToCallback;
                        lock (lockObj) {
                            beginHandlerReturnValueHolder = new Holder<Exception>(ex);
                            tempAsyncResultPassedToCallback = asyncResultPassedToCallback;
                        }

                        try {
                            // The AsyncCallback should only be invoked if BeginHandler ran to completion.
                            if (tempAsyncResultPassedToCallback != null) {

                                // If AsyncCallback was invoked asynchronously, then by definition it was
                                // scheduled prematurely since BeginHandler hadn't yet run to completion
                                // (since whatever additional work it did after invoking the callback failed).
                                // Therefore it is always wrong for BeginHandler to both throw and
                                // asynchronously invoke AsyncCallback.
                                assert(tempAsyncResultPassedToCallback.CompletedSynchronously, AppVerifierErrorCode.AsyncCallbackInvokedAsynchronouslyThenBeginHandlerThrew);

                                // If AsyncCallback was invoked synchronously, then it must have been invoked
                                // before BeginHandler surfaced the exception (since otherwise BeginHandler
                                // wouldn't have reached the line of code that invoked AsyncCallback). But
                                // AsyncCallback itself could have thrown, bubbling the exception up through
                                // BeginHandler and back to us. If AsyncCallback ran to completion, then this
                                // means BeginHandler did extra work (which failed) after invoking AsyncCallback,
                                // so BeginHandler by definition hadn't yet run to completion.
                                assert(!callbackRanToCompletion, AppVerifierErrorCode.AsyncCallbackInvokedSynchronouslyThenBeginHandlerThrew);
                            }
                        }
                        catch (AppVerifierException) {
                            // We want to ---- any exceptions thrown by our verification logic, as the failure
                            // has already been recorded by the appropriate listener. Propagate the original
                            // exception upward.
                        }

                        throw;
                    }
                    else {
                        // We want to ---- any exceptions thrown by our verification logic, as the failure
                        // has already been recorded by the appropriate listener. Just return the original
                        // IAsyncResult so that the application continues to run.
                        return asyncResultReturnedByBeginHandler;
                    }
                }
                finally {
                    // Since our local variables are GC-rooted in an anonymous object, we should
                    // clear references to objects we no longer need so that the GC can reclaim
                    // them if appropriate.
                    lock (lockObj) {
                        threadWhichCalledBeginHandler = null;
                    }
                }
            };
        }

        // Gets a delegate that checks for application code trying to call into the SyncContext after
        // the request or the request notification is already completed.
        // The Action returned by this method could be null.
        public static Action<bool> GetSyncContextCheckDelegate(ISyncContext syncContext) {
            if (!IsAppVerifierEnabled) {
                return null;
            }

            return GetSyncContextCheckDelegateImpl(syncContext, HandleAppVerifierException);
        }

        /// <summary>
        /// Returns an Action<bool> that determines whether SynchronizationContext.Send or Post was called after the underlying request
        /// or the request notification finished. The bool parameter controls whether to check if Post is attempted in nested notification.
        /// The instrumentation can be a performance hit, so this method should not be called if AppVerifier is not enabled.
        /// </summary>
        /// <param name="syncContext">The ISyncContext (HttpApplication, WebSocketPipeline, etc.) on which to perform the check.</param>
        /// <param name="errorHandler">The listener that can handle verification failures.</param>
        /// <returns>A callback which performs the verification.</returns>
        internal static Action<bool> GetSyncContextCheckDelegateImpl(ISyncContext syncContext, Action<AppVerifierException> errorHandler) {
            string requestUrl = null;
            object originalThreadContextId = null;

            // collect all of the diagnostic information upfront
            HttpContext originalHttpContext = (syncContext != null) ? syncContext.HttpContext : null;
            if (originalHttpContext != null) {
                if (!originalHttpContext.HideRequestResponse && originalHttpContext.Request != null) {
                    requestUrl = TryGetRequestUrl(originalHttpContext);
                }

                // This will be used as a surrogate for the captured HttpContext so that we don't
                // have a long-lived reference to a heavy object graph. See comments on ThreadContextId
                // for more info.
                originalThreadContextId = originalHttpContext.ThreadContextId;
                originalHttpContext = null;
            }

            // If the condition passed to this method evaluates to false, we will raise an error to whoever is listening.
            AssertDelegate assert = GetAssertDelegateImpl(requestUrl, errorHandler, appendAdditionalInfoDelegate: null);

            return (checkForReEntry) => {
                try {
                    // Make sure that the ISyncContext is still associated with the same HttpContext that
                    // we captured earlier.
                    HttpContext currentHttpContext = (syncContext != null) ? syncContext.HttpContext : null;
                    object currentThreadContextId = (currentHttpContext != null) ? currentHttpContext.ThreadContextId : null;
                    assert(currentThreadContextId != null && ReferenceEquals(originalThreadContextId, currentThreadContextId), AppVerifierErrorCode.SyncContextSendOrPostCalledAfterRequestCompleted);

                    if (HttpRuntime.UsingIntegratedPipeline && !currentHttpContext.HasWebSocketRequestTransitionCompleted) {
                        var notificationContext = (currentHttpContext != null) ? currentHttpContext.NotificationContext : null;
                        assert(notificationContext != null, AppVerifierErrorCode.SyncContextSendOrPostCalledBetweenNotifications);

                        if (checkForReEntry && notificationContext != null) {
                            assert(!notificationContext.IsReEntry, AppVerifierErrorCode.SyncContextPostCalledInNestedNotification);
                        }
                    }
                }
                catch (AppVerifierException) {
                    // We want to ---- any exceptions thrown by our verification logic, as the failure
                    // has already been recorded by the appropriate listener. Propagate the original
                    // exception upward.
                }
            };
        }

        // This generic method invokes a delegate that was created by AppVerifier at an earlier time.
        // It is safe to call it even if the returned delegate is null (e.g. AppVerifier is off).
        // Here is the typical usage scenario:
        //      var verifierCheck = AppVerifier.Get*CheckDelegate(...);         // get the delegate which can capture some state
        //      T result = <...>                                                // the result of some code execution
        //      AppVerifier.InvokeVerifierCheck(verifierCheckDelegate, result); // invoke the verification of the result
        internal static void InvokeVerifierCheck<T>(Action<T> verifierCheckDelegate, T result)
        {
            if (verifierCheckDelegate != null) {
                try {
                    verifierCheckDelegate(result);
                }
                catch (AppVerifierException) {
                    // We want to ---- any exceptions thrown by our verification logic, as the failure
                    // has already been recorded by the appropriate listener.
                }
            }
        }

        // Gets a delegate that checks for inconsistencies after managed code finished processing one or more request notifications.
        // The Action returned by this method could be null.
        internal static Action<RequestNotificationStatus> GetRequestNotificationStatusCheckDelegate(HttpContext context, RequestNotification currentNotification, bool isPostNotification) {
            if (!IsAppVerifierEnabled) {
                return null;
            }
            return GetRequestNotificationStatusCheckDelegateImpl(context, currentNotification, isPostNotification, HandleAppVerifierException);
        }

        /// <summary>
        /// Returns an Action<RequestNotificationStatus> that will check for inconsistencies after
        /// managed code has finished processing one or more notifications and about to return back to IIS.
        /// </summary>
        /// <returns>A callback which performs the verification.</returns>
        internal static Action<RequestNotificationStatus> GetRequestNotificationStatusCheckDelegateImpl(HttpContext context, RequestNotification currentNotification, bool isPostNotification, Action<AppVerifierException> errorHandler) {
            // collect all of the diagnostic information upfront
            NotificationContext originalNotificationContext = context.NotificationContext;
            bool isReentry = originalNotificationContext.IsReEntry;
            string requestUrl = null;
            if (!context.HideRequestResponse && context.Request != null) {
                requestUrl = TryGetRequestUrl(context);
            }

            AppendAdditionalInfoDelegate appendCurrentNotificationInfo = (errorString) => {
                errorString.AppendLine(FormatErrorString(SR.AppVerifier_BasicInfo_NotificationInfo, currentNotification, isPostNotification, isReentry));
            };

            AssertDelegate assert = GetAssertDelegateImpl(requestUrl, errorHandler, appendAdditionalInfoDelegate: appendCurrentNotificationInfo);

            return (RequestNotificationStatus status) => {
                if (status == RequestNotificationStatus.Pending) {
                    // We don't expect nested notifications to complete asynchronously
                    assert(!isReentry, AppVerifierErrorCode.PendingProcessRequestNotificationStatusAfterCompletingNestedNotification);
                }
                else {
                    // Completing synchronously with pending NotificationContext means a bug in either user code or the pipeline.
                    // NotificationContext being null means we already completed asynchronously before completing synchronously.
                    // Both cases indicate that we have some async operations we failed to account for.
                    assert(context.NotificationContext != null && !context.NotificationContext.PendingAsyncCompletion,
                            AppVerifierErrorCode.RequestNotificationCompletedSynchronouslyWithNotificationContextPending);

                    // Can't have a different NotificationContext after finishing the notification
                    // Even if it was changed while processing nested notifications it should be restored back before we unwind
                    assert(context.NotificationContext == originalNotificationContext,
                            AppVerifierErrorCode.NotificationContextHasChangedAfterSynchronouslyProcessingNotification);
                }
            };
        }

        /// <summary>
        /// This method returns the default implementation of the assert code which takes care of
        /// evaluating the assert contition, handing assert and stack collection enabling masks,
        /// and creating an AppVerifierException with basic information
        /// </summary>
        /// <param name="requestUrl">The Url of the request.</param>
        /// <param name="errorHandler">The listener that can handle verification failures.</param>
        /// <param name="appendAdditionalInfoDelegate">The caller can provide this delegate to append additional information to the exception. Could be null.</param>
        /// <returns>A callback which performs the verification.</returns>
        private static AssertDelegate GetAssertDelegateImpl(string requestUrl, Action<AppVerifierException> errorHandler, AppendAdditionalInfoDelegate appendAdditionalInfoDelegate) {
            // If the condition passed to this method evaluates to false, we will raise an error to whoever is listening.
            return (condition, errorCode) => {
                long mask = 1L << (int)errorCode;
                // assert only if it was not masked out by a bit set
                bool enableAssert = (AppVerifierErrorCodeEnableAssertMask & mask) == mask;

                if (!condition && enableAssert) {
                    // capture the stack only if it was not masked out by a bit set
                    bool captureStack = (AppVerifierErrorCodeCollectCallStackMask & mask) == mask;
                    InvocationInfo assertInvocationInfo = InvocationInfo.Capture(captureStack);

                    // header
                    StringBuilder errorString = new StringBuilder();
                    errorString.AppendLine(FormatErrorString(SR.AppVerifier_Title));
                    errorString.AppendLine(FormatErrorString(SR.AppVerifier_Subtitle));
                    errorString.AppendLine();

                    // basic info (about the assert)
                    errorString.AppendLine(FormatErrorString(SR.AppVerifier_BasicInfo_URL, requestUrl));
                    errorString.AppendLine(FormatErrorString(SR.AppVerifier_BasicInfo_ErrorCode, (int)errorCode));
                    errorString.AppendLine(FormatErrorString(SR.AppVerifier_BasicInfo_Description, GetLocalizedDescriptionStringForError(errorCode)));
                    errorString.AppendLine(FormatErrorString(SR.AppVerifier_BasicInfo_ThreadInfo, assertInvocationInfo.ThreadId, assertInvocationInfo.Timestamp.ToLocalTime()));

                    // append additional info if needed
                    if (appendAdditionalInfoDelegate != null) {
                        appendAdditionalInfoDelegate(errorString);
                    }

                    // append the stack trace
                    errorString.AppendLine(assertInvocationInfo.StackTrace.ToString());

                    AppVerifierException ex = new AppVerifierException(errorCode, errorString.ToString());
                    errorHandler(ex);
                    throw ex;
                }
            };
        }

        // This is the default implementation of an AppVerifierException handler;
        // it just delegates to the configured behavior.
        [SuppressMessage("Microsoft.Reliability", "CA2004:RemoveCallsToGCKeepAlive", Justification = "Want to keep these locals on the stack to assist with debugging.")]
        [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
        private static void HandleAppVerifierException(AppVerifierException ex) {
            // This method is specifically written to maximize the chance of
            // useful information being on the stack as a local, where it's more
            // easily observed by the debugger.

            AppVerifierErrorCode errorCode = ex.ErrorCode;
            string fullMessage = ex.Message;

            DefaultAppVerifierBehavior(ex);

            GC.KeepAlive(errorCode);
            GC.KeepAlive(fullMessage);
            GC.KeepAlive(ex);
        }

        private static string TryGetRequestUrl(HttpContext context) {
            try {
                return context.Request.EnsureRawUrl();
            }
            catch (HttpException) {
                return null;
            }
        }

        internal static string PrettyPrintDelegate(Delegate del) {
            return PrettyPrintMemberInfo((del != null) ? del.Method : null);
        }

        // prints "TResult MethodName(TArg1, TArg2, ...) [Module.dll!Namespace.TypeName]"
        internal static string PrettyPrintMemberInfo(MethodInfo method) {
            if (method == null) {
                return null;
            }

            string retVal = method.ToString();

            Type type = method.ReflectedType;
            if (type != null) {
                retVal = retVal + " [";
                if (type.Module != null) {
                    retVal += type.Module.Name + "!";
                }

                retVal += type.FullName + "]";
            }

            return retVal;
        }

        internal static string GetLocalizedDescriptionStringForError(AppVerifierErrorCode errorCode) {
            return FormatErrorString(_errorStringMappings[errorCode]);
        }

        // We use InstalledUICulture rather than CurrentCulture / CurrentUICulture since these strings will
        // be stored in the system event log.
        [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.IFormatProvider,System.String,System.Object[])",
            Justification = "Matches culture specified in Misc.WriteUnhandledExceptionToEventLog.")]
        internal static string FormatErrorString(string name, params object[] args) {
            return String.Format(CultureInfo.InstalledUICulture, SR.Resources.GetString(name, CultureInfo.InstalledUICulture), args);
        }

        // contains a counter and invocation information for an AsyncCallback delegate
        private sealed class AsyncCallbackInvocationHelper {
            private InvocationInfo _firstInvocationInfo;
            private int _totalInvocationCount;

            public int TotalInvocations {
                [MethodImpl(MethodImplOptions.Synchronized)]
                get { return _totalInvocationCount; }
            }

            [MethodImpl(MethodImplOptions.Synchronized)]
            public InvocationInfo GetFirstInvocationInfo(out int totalInvocationCount) {
                totalInvocationCount = _totalInvocationCount;
                return _firstInvocationInfo;
            }

            [MethodImpl(MethodImplOptions.Synchronized)]
            public int RecordInvocation(bool captureCallStack) {
                _totalInvocationCount++;
                if (_firstInvocationInfo == null) {
                    _firstInvocationInfo = InvocationInfo.Capture(captureCallStack);
                }
                return _totalInvocationCount;
            }
        }

        // We use a special class for holding data so that we can store the local's
        // intended type alongside its real value. Prevents us from misinterpreting
        // the degenerate case of "----CustomType : Exception, IAsyncResult" so that
        // we know whether it was returned as an IAsyncResult or thrown as an Exception.
        private sealed class Holder<T> {
            public readonly T Value;

            public Holder(T value) {
                Value = value;
            }
        }

        // holds diagnostic information about a particular invocation
        private sealed class InvocationInfo {
            public readonly int ThreadId;
            public readonly DateTimeOffset Timestamp;
            public readonly string StackTrace;

            private InvocationInfo(bool captureStack) {
                ThreadId = Thread.CurrentThread.ManagedThreadId;
                Timestamp = DateTimeOffset.UtcNow; // UTC is faster, will convert to local on error
                StackTrace = captureStack? CaptureStackTrace(): "n/a";
            }

            public static InvocationInfo Capture(bool captureStack) {
                return new InvocationInfo(captureStack);
            }

            // captures a stack trace, removing AppVerifier.* frames from the top of the stack to minimize noise
            private static string CaptureStackTrace() {
                StackTrace fullStackTrace = new StackTrace(fNeedFileInfo: true);
                string[] traceLines = fullStackTrace.ToString().Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
                for (int i = 0; i < fullStackTrace.FrameCount && i < traceLines.Length; i++) {
                    StackFrame thisFrame = fullStackTrace.GetFrame(i);
                    if (thisFrame.GetMethod().Module == typeof(AppVerifier).Module
                        && thisFrame.GetMethod().DeclaringType.FullName.StartsWith("System.Web.Util.AppVerifier", StringComparison.Ordinal)) {
                        // we want to skip this frame since it's an AppVerifier.* frame
                        continue;
                    }
                    else {
                        // this is the first frame that is not an AppVerifier.* frame, so start the stack trace from here
                        return String.Join(Environment.NewLine, traceLines.Skip(i));
                    }
                }

                // if we reached this point, not sure what happened, so just return the original stack trace
                return fullStackTrace.ToString();
            }
        }

        [SuppressUnmanagedCodeSecurityAttribute]
        private static class NativeMethods {
            [DllImport("kernel32.dll")]
            internal extern static void DebugBreak();
        }

    }
}


text:
using PTK.WPF;
using iNGen.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Messaging;
using MahApps.Metro.Controls.Dialogs;
using GalaSoft.MvvmLight.CommandWpf;

namespace iNGen.ViewModels
{
    public class HomeViewModel: ViewModelBase
    {
        public ServerModelSet ServerModelSet {get; set;}
        public bool AttemptReconnectOnServerConnectionFail {get; set;}
        public string ApplicationLog { get; set; }
        public Server SelectedServer { get; set; }

        public RelayCommand DeleteSelectedServerCommand { get; set; }
        public RelayCommand NewServerCommand { get; set; }
        public event EventHandler ApplicationLogUpdated;

        public HomeViewModel()
        {
            ServerModelSet = App.ModelManager.Get<ServerModelSet>();
            ApplicationLog = "";

            #region Connection Related

            App.ArkRcon.ServerConnectionStarting += ArkRcon_ServerConnectionStarting;
            App.ArkRcon.ServerConnectionSucceeded += ArkRcon_ServerConnectionSucceeded;
            App.ArkRcon.ServerConnectionDisconnected += ArkRcon_ServerConnectionDisconnected;
            App.ArkRcon.ServerConnectionFailed += ArkRcon_ServerConnectionFailed;
            App.ArkRcon.ServerConnectionDropped += ArkRcon_ServerConnectionDropped;
            App.ArkRcon.ServerAuthSucceeded += (s, args) => WriteToApplicationLog(args.Message, args.Timestamp);
            App.ArkRcon.ServerAuthFailed += (s, args) => WriteToApplicationLog(args.Message, args.Timestamp);

            #endregion

            Messenger.Default.Register<NotificationMessage<MessageDialogResult>>(this, OnDialogResult);

            DeleteSelectedServerCommand = new RelayCommand(DeleteServer);
            NewServerCommand = new RelayCommand(NewServer);
        }

        #region Connection Methods

        void ArkRcon_ServerConnectionDropped(object sender, Ark.ServerConnectionEventArgs e)
        {
            ((Server)e.ConnectionInfo).IsConnected = false;
            WriteToApplicationLog(e.Message, e.Timestamp);

            if (App.ModelManager.Get<UserSettings>().GeneralSettings.IsAutoReconnectEnabled)
            {
                InitiateReconnect(e.ConnectionInfo as Server);
                AttemptReconnectOnServerConnectionFail = true;
            }
        }

        void ArkRcon_ServerConnectionFailed(object sender, Ark.ServerConnectionEventArgs e)
        {
            ((Server)e.ConnectionInfo).IsConnected = false;
            WriteToApplicationLog(e.Message, e.Timestamp);

            if (AttemptReconnectOnServerConnectionFail && App.ModelManager.Get<UserSettings>().GeneralSettings.IsAutoReconnectEnabled)
                InitiateReconnect(e.ConnectionInfo as Server);
        }

        void ArkRcon_ServerConnectionDisconnected(object sender, Ark.ServerConnectionEventArgs e)
        {
            ((Server)e.ConnectionInfo).IsConnected = false;
            WriteToApplicationLog(e.Message, e.Timestamp);
        }

        void ArkRcon_ServerConnectionSucceeded(object sender, Ark.ServerConnectionEventArgs e)
        {
            WriteToApplicationLog(e.Message, e.Timestamp);

            if (App.ModelManager.Get<UserSettings>().GeneralSettings.DoReconnectEveryFiveMinutes)
            {
                WriteToApplicationLog("Auto Reconnect Every Five minutes is Enabled", e.Timestamp);
                ForceReconnect(e.ConnectionInfo as Server);
            }
        }

        void ArkRcon_ServerConnectionStarting(object sender, Ark.ServerConnectionEventArgs e)
        {
            ((Server)e.ConnectionInfo).IsConnected = true;
            WriteToApplicationLog(e.Message, e.Timestamp);
        }

        #endregion

        private void DeleteServer()
        {
            //if (SelectedServer == null || SelectedServer.IsConnected)
            //    return;
            Messenger.Default.Send(new NotificationMessage<string>(string.Format("Confirm Deleting Server: {0}", SelectedServer.DisplayName), "ShowConfirmDeleteServerDialog"));
        }

        private void OnDialogResult(NotificationMessage<MessageDialogResult> result)
        {
            switch (result.Notification)
            {
                case "ConfirmDeleteServerDialogResult":
                    if (SelectedServer == null) return;
                    if (result.Content == MessageDialogResult.Negative) return;
                    var server = SelectedServer;
                    SelectedServer = null;
                    ServerModelSet.DeleteServer(server);
                    break;
                default:
                    return;
            }
        }

        private void NewServer()
        {
            ServerModelSet.NewServer();
            SelectedServer = ServerModelSet.Servers.Last();
        }

        public override void Cleanup()
        {
            base.Cleanup();
            Messenger.Default.Unregister<NotificationMessage<MessageDialogResult>>(this);
        }

        private void WriteToApplicationLog(string message, DateTime timestamp)
        {
            ApplicationLog += System.Environment.NewLine + timestamp.ToString("(hh:mm tt) ") + message;
            if(ApplicationLogUpdated != null)
                ApplicationLogUpdated(this, null);
        }

        private void InitiateReconnect(Server server)
        {
            WriteToApplicationLog("Auto-Reconnecting in 10 seconds...", DateTime.Now);
            if (!App.ArkRcon.IsConnected)
            {
                NormalReconnect(server);
            }
        }

        private async void ForceReconnect(Server server)
        {
            await Task.Delay(5 * 1000 * 60);
            await App.ArkRcon.Connect(server);
        }

        private async void NormalReconnect(Server server)
        {
            await Task.Delay(10 * 1000);
            await App.ArkRcon.Connect(server);
        }
    }
}


text:
<?php

namespace PHPExiftool\Driver\Tag\Olympus;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class ToneLevel extends AbstractTag
{

    protected $Id = 1326;

    protected $Name = 'ToneLevel';

    protected $FullName = 'Olympus::CameraSettings';

    protected $GroupName = 'Olympus';

    protected $g0 = 'MakerNotes';

    protected $g1 = 'Olympus';

    protected $g2 = 'Camera';

    protected $Type = '?';

    protected $Writable = true;

    protected $Description = 'Tone Level';

    protected $flag_Permanent = true;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.conversantmedia</groupId>
    <artifactId>disruptor</artifactId>
    <packaging>jar</packaging>
    <version>1.2.22-SNAPSHOT</version>
    <name>${project.groupId}:${project.artifactId}</name>
    <url>https://github.com/conversant/disruptor</url>
    <description>Conversant Disruptor - very high throughput Java BlockingQueue</description>

    <inceptionYear>2012</inceptionYear>

    <organization>
        <name>Conversant Engineering</name>
        <url>http://engineering.conversantmedia.com</url>
    </organization>

    <developers>
        <developer>
            <name>John Cairns</name>
            <email>john@2ad.com</email>
            <organizationUrl>https://github.com/jac18281828</organizationUrl>
        </developer>
    </developers>

    <licenses>
        <license>
            <name>The Apache License, Version 2.0</name>
            <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
        </license>
    </licenses>

    <scm>
        <connection>scm:git:https://github.com/conversant/disruptor.git</connection>
        <developerConnection>scm:git:https://github.com/conversant/disruptor.git</developerConnection>
        <url>https://github.com/conversant/disruptor</url>
        <tag>HEAD</tag>
    </scm>

    <distributionManagement>
        <snapshotRepository>
            <id>${snapshots.repo.id}</id>
            <url>${snapshots.repo.url}</url>
        </snapshotRepository>
        <repository>
            <id>ossrh</id>
            <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
        </repository>
    </distributionManagement>

    <issueManagement>
        <system>GitHub</system>
        <url>https://github.com/conversant/disruptor/issues</url>
    </issueManagement>

    <prerequisites>
        <maven>3.0.5</maven>
    </prerequisites>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <snapshots.repo.id>ossrh</snapshots.repo.id>
        <snapshots.repo.url>https://oss.sonatype.org/content/repositories/snapshots</snapshots.repo.url>
        <license.name>apache_v2</license.name>
    </properties>

    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
        </resources>

        <testResources>
            <testResource>
                <directory>src/test/resources</directory>
            </testResource>
        </testResources>

        <pluginManagement>
            <plugins>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.1</version>
                    <inherited>true</inherited>
                    <configuration>
                        <source>11</source>
                        <target>11</target>
                        <encoding>${project.build.sourceEncoding}</encoding>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.codehaus.mojo</groupId>
                    <artifactId>license-maven-plugin</artifactId>
                    <version>1.8</version>
                    <configuration>
                        <licenseName>${license.name}</licenseName>
                        <sectionDelimiter>~~</sectionDelimiter>
                        <verbose>false</verbose>
                        <addSvnKeyWords>false</addSvnKeyWords>
                    </configuration>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.17</version>
                </plugin>
                <plugin>
                    <artifactId>maven-failsafe-plugin</artifactId>
                    <version>2.22.2</version>
                    <executions>
                        <execution>
                            <id>integration-test</id>
                            <goals>
                                <goal>integration-test</goal>
                            </goals>
                        </execution>
                        <execution>
                            <id>verify</id>
                            <goals>
                                <goal>verify</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-report-plugin</artifactId>
                    <version>2.22.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-source-plugin</artifactId>
                    <version>3.2.1</version>
                    <executions>
                        <execution>
                            <id>attach-sources</id>
                            <goals>
                                <goal>jar-no-fork</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
                <plugin>
                    <artifactId>maven-javadoc-plugin</artifactId>
                    <version>3.2.0</version>
                    <executions>
                        <execution>
                            <id>attach-javadocs</id>
                            <goals>
                                <goal>jar</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.3.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-assembly-plugin</artifactId>
                    <version>3.4.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-release-plugin</artifactId>
                    <version>2.5.3</version>
                    <configuration>
                        <tagNameFormat>@{project.version}</tagNameFormat>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.codehaus.mojo</groupId>
                    <artifactId>cobertura-maven-plugin</artifactId>
                    <version>2.7</version>
                    <configuration>
                        <maxmem>1024m</maxmem>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.codehaus.mojo</groupId>
                    <artifactId>build-helper-maven-plugin</artifactId>
                    <version>3.3.0</version>
                    <executions>
                        <execution>
                            <id>add-integration-test-source</id>
                            <phase>generate-test-sources</phase>
                            <goals>
                                <goal>add-test-source</goal>
                            </goals>
                            <configuration>
                                <sources>
                                    <source>src/it/java</source>
                                </sources>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
                <plugin>
                    <artifactId>maven-site-plugin</artifactId>
                    <version>3.3</version>
                </plugin>
                <plugin>
                    <groupId>org.sonatype.plugins</groupId>
                    <artifactId>nexus-staging-maven-plugin</artifactId>
                    <version>1.6.13</version>
                    <extensions>true</extensions>
                    <configuration>
                        <serverId>ossrh</serverId>
                        <nexusUrl>https://oss.sonatype.org/</nexusUrl>
                        <autoReleaseAfterClose>true</autoReleaseAfterClose>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-gpg-plugin</artifactId>
                    <version>1.5</version>
                    <executions>
                        <execution>
                            <id>sign-artifacts</id>
                            <phase>verify</phase>
                            <goals>
                                <goal>sign</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>

    <dependencies>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.30</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <reporting>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>cobertura-maven-plugin</artifactId>
                <version>2.7</version>
            </plugin>
        </plugins>
    </reporting>

</project>


text:
import {Entity, PrimaryColumn, PrimaryGeneratedColumn} from "../../../../src";

@Entity()
export class Post {

    @PrimaryGeneratedColumn()
    id: number;

    @PrimaryColumn()
    name: string;

}


text:
{% extends "django_cradmin/layouts/standalone/focused.django.html" %}
{% load i18n %}

{% block title %}
    {% trans "Signed out" %}
{% endblock title %}

{% block page-cover-title %}
    {% trans "Signed out" %}
{% endblock page-cover-title %}

{% block content %}

            {% trans "Sign back in" %}

{% endblock content %}


text:
"use strict";

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

const assert = require("chai").assert;
const eslint = require("../..");
const espree = require("espree");
const sinon = require("sinon");
const configRule = require("../../tools/config-rule");

//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------

describe("eslint-fuzzer", function() {
    let fakeRule, fuzz;

    /*
     * These tests take awhile because isolating which rule caused an error requires running eslint up to hundreds of
     * times, one rule at a time.
     */
    this.timeout(15000); // eslint-disable-line no-invalid-this -- Mocha timeout

    const linter = new eslint.Linter();
    const coreRules = linter.getRules();
    const fixableRuleNames = Array.from(coreRules)
        .filter(rulePair => rulePair[1].meta && rulePair[1].meta.fixable)
        .map(rulePair => rulePair[0]);
    const CRASH_BUG = new TypeError("error thrown from a rule");

    // A comment to disable all core fixable rules
    const disableFixableRulesComment = `// eslint-disable-line ${fixableRuleNames.join(",")}`;

    before(() => {
        const realCoreRuleConfigs = configRule.createCoreRuleConfigs();

        // Make sure the config generator generates a config for "test-fuzzer-rule"
        sinon.stub(configRule, "createCoreRuleConfigs").returns(Object.assign(realCoreRuleConfigs, { "test-fuzzer-rule": [2] }));

        // Create a closure around `fakeRule` so that tests can reassign it and have the changes take effect.
        linter.defineRule("test-fuzzer-rule", Object.assign(context => fakeRule(context), { meta: { fixable: "code" } }));

        fuzz = require("../../tools/eslint-fuzzer");
    });

    after(() => {
        configRule.createCoreRuleConfigs.restore();
    });

    describe("when running in crash-only mode", () => {
        describe("when a rule crashes on the given input", () => {
            it("should report the crash with a minimal config", () => {
                fakeRule = context => ({
                    Program() {
                        if (context.getSourceCode().text === "foo") {
                            throw CRASH_BUG;
                        }
                    }
                });

                const results = fuzz({ count: 1, codeGenerator: () => "foo", checkAutofixes: false, linter });

                assert.strictEqual(results.length, 1);
                assert.strictEqual(results[0].type, "crash");
                assert.strictEqual(results[0].text, "foo");
                assert.deepStrictEqual(results[0].config.rules, { "test-fuzzer-rule": 2 });
                assert.strictEqual(results[0].error, CRASH_BUG.stack);
            });
        });

        describe("when no rules crash", () => {
            it("should return an empty array", () => {
                fakeRule = () => ({});

                assert.deepStrictEqual(fuzz({ count: 1, codeGenerator: () => "foo", checkAutofixes: false, linter }), []);
            });
        });
    });

    describe("when running in crash-and-autofix mode", () => {
        const INVALID_SYNTAX = "this is not valid javascript syntax";
        let expectedSyntaxError;

        try {
            espree.parse(INVALID_SYNTAX);
        } catch (err) {
            expectedSyntaxError = err;
        }

        describe("when a rule crashes on the given input", () => {
            it("should report the crash with a minimal config", () => {
                fakeRule = context => ({
                    Program() {
                        if (context.getSourceCode().text === "foo") {
                            throw CRASH_BUG;
                        }
                    }
                });

                const results = fuzz({ count: 1, codeGenerator: () => "foo", checkAutofixes: false, linter });

                assert.strictEqual(results.length, 1);
                assert.strictEqual(results[0].type, "crash");
                assert.strictEqual(results[0].text, "foo");
                assert.deepStrictEqual(results[0].config.rules, { "test-fuzzer-rule": 2 });
                assert.strictEqual(results[0].error, CRASH_BUG.stack);
            });
        });

        describe("when a rule's autofix produces valid syntax", () => {
            it("does not report any errors", () => {

                // Replaces programs that start with "foo" with "bar"
                fakeRule = context => ({
                    Program(node) {
                        if (context.getSourceCode().text === `foo ${disableFixableRulesComment}`) {
                            context.report({
                                node,
                                message: "no foos allowed",
                                fix: fixer => fixer.replaceText(node, `bar ${disableFixableRulesComment}`)
                            });
                        }
                    }
                });

                const results = fuzz({
                    count: 1,

                    /*
                     * To ensure that no other rules produce a different autofix and mess up the test, add a big disable
                     * comment for all core fixable rules.
                     */
                    codeGenerator: () => `foo ${disableFixableRulesComment}`,
                    checkAutofixes: true,
                    linter
                });

                assert.deepStrictEqual(results, []);
            });
        });

        describe("when a rule's autofix produces invalid syntax on the first pass", () => {
            it("reports an autofix error with a minimal config", () => {

                // Replaces programs that start with "foo" with invalid syntax
                fakeRule = context => ({
                    Program(node) {
                        const sourceCode = context.getSourceCode();

                        if (sourceCode.text === `foo ${disableFixableRulesComment}`) {
                            context.report({
                                node,
                                message: "no foos allowed",
                                fix: fixer => fixer.replaceTextRange([0, sourceCode.text.length], INVALID_SYNTAX)
                            });
                        }
                    }
                });

                const results = fuzz({
                    count: 1,
                    codeGenerator: () => `foo ${disableFixableRulesComment}`,
                    checkAutofixes: true,
                    linter
                });

                assert.strictEqual(results.length, 1);
                assert.strictEqual(results[0].type, "autofix");
                assert.strictEqual(results[0].text, `foo ${disableFixableRulesComment}`);
                assert.deepStrictEqual(results[0].config.rules, { "test-fuzzer-rule": 2 });
                assert.deepStrictEqual(results[0].error, {
                    ruleId: null,
                    fatal: true,
                    severity: 2,
                    message: `Parsing error: ${expectedSyntaxError.message}`,
                    line: expectedSyntaxError.lineNumber,
                    column: expectedSyntaxError.column
                });
            });
        });

        describe("when a rule's autofix produces invalid syntax on the second pass", () => {
            it("reports an autofix error with a minimal config and the text from the second pass", () => {
                const intermediateCode = `bar ${disableFixableRulesComment}`;

                // Replaces programs that start with "foo" with invalid syntax
                fakeRule = context => ({
                    Program(node) {
                        const sourceCode = context.getSourceCode();

                        if (sourceCode.text.startsWith("foo") || sourceCode.text === intermediateCode) {
                            context.report({
                                node,
                                message: "no foos allowed",
                                fix(fixer) {
                                    return fixer.replaceTextRange(
                                        [0, sourceCode.text.length],
                                        sourceCode.text === intermediateCode ? INVALID_SYNTAX : intermediateCode
                                    );
                                }
                            });
                        }
                    }
                });

                const results = fuzz({
                    count: 1,
                    codeGenerator: () => `foo ${disableFixableRulesComment}`,
                    checkAutofixes: true,
                    linter
                });

                assert.strictEqual(results.length, 1);
                assert.strictEqual(results[0].type, "autofix");
                assert.strictEqual(results[0].text, intermediateCode);
                assert.deepStrictEqual(results[0].config.rules, { "test-fuzzer-rule": 2 });
                assert.deepStrictEqual(results[0].error, {
                    ruleId: null,
                    fatal: true,
                    severity: 2,
                    message: `Parsing error: ${expectedSyntaxError.message}`,
                    line: expectedSyntaxError.lineNumber,
                    column: expectedSyntaxError.column
                });
            });
        });

        describe("when a rule crashes on the second autofix pass", () => {
            it("reports a crash error with a minimal config", () => {

                // Replaces programs that start with "foo" with invalid syntax
                fakeRule = context => ({
                    Program(node) {
                        const sourceCode = context.getSourceCode();

                        if (sourceCode.text.startsWith("foo")) {
                            context.report({
                                node,
                                message: "no foos allowed",
                                fix: fixer => fixer.replaceText(node, "bar")
                            });
                        } else if (sourceCode.text === `bar ${disableFixableRulesComment}`) {
                            throw CRASH_BUG;
                        }
                    }
                });

                const results = fuzz({
                    count: 1,
                    codeGenerator: () => `foo ${disableFixableRulesComment}`,
                    checkAutofixes: true,
                    linter
                });

                assert.strictEqual(results.length, 1);
                assert.strictEqual(results[0].type, "crash");

                assert.strictEqual(results[0].text, `bar ${disableFixableRulesComment}`);
                assert.deepStrictEqual(results[0].config.rules, { "test-fuzzer-rule": 2 });
                assert.strictEqual(results[0].error, CRASH_BUG.stack);
            });
        });
    });
});