text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Win32.SafeHandles;

namespace DevO2.Shared
{
    public sealed class PrinterLinea
    {
        #region Variables
        private string propTexto;
        private float propTamanoFuente;
        private bool propNegrita;
        private bool propCursiva;
        private PrinterAlineacionLinea propAlineacion = PrinterAlineacionLinea.Izquierda;
        #endregion

        #region Constructor
        public PrinterLinea(string texto, float tamanoFuente, bool negrita, bool cursiva, PrinterAlineacionLinea alineacion)
        {
            this.propTexto = texto;
            this.propTamanoFuente = tamanoFuente;
            this.propNegrita = negrita;
            this.propCursiva = cursiva;
            this.propAlineacion = alineacion;
        }
        #endregion

        #region Propiedades
        public string Texto
        {
            get { return this.propTexto; }
            set { this.propTexto = value; }
        }

        public float TamanoFuente
        {
            get { return this.propTamanoFuente; }
            set { this.propTamanoFuente = value; }
        }

        public bool Negrita
        {
            get { return this.propNegrita; }
            set { this.propNegrita = value; }
        }

        public bool Cursiva
        {
            get { return this.propCursiva; }
            set { this.propCursiva = value; }
        }

        public PrinterAlineacionLinea Alineacion
        {
            get { return this.propAlineacion; }
            set { this.propAlineacion = value; }
        }
        #endregion
    }

    public sealed class Printer
    {
        #region Constantes
        private const short FILE_ATTRIBUTE_NORMAL = 0x80;
        private const short INVALID_HANDLE_VALUE = -1;
        private const uint GENERIC_READ = 0x80000000;
        private const uint GENERIC_WRITE = 0x40000000;
        private const uint CREATE_NEW = 1;
        private const uint CREATE_ALWAYS = 2;
        private const uint OPEN_EXISTING = 3;
        #endregion

        #region Variables
        private string propImpresora;
        private Font propFuente = null;
        private int propLargoMaximoCaracteres = 40;
        private Image propImagenCabecera = null;
        private int propAltoImagen = 0;
        private int propMargenIzquierdo = 0;
        private int propMargenSuperior = 3;
        private short propCopias = 1;
        private PrinterTipoGuillotina propTipoGuillotina = PrinterTipoGuillotina.Epson;

        private ArrayList lineas = new ArrayList();
        private Graphics gfx = null;
        private int contador = 0;
        #endregion

        #region DLL Import
        [DllImport("kernel32.dll", SetLastError = true)]
        static extern SafeFileHandle CreateFile(string lpFileName, uint dwDesiredAccess,
            uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition,
            uint dwFlagsAndAttributes, IntPtr hTemplateFile);
        #endregion

        #region Propiedades
        public string Impresora
        {
            get { return this.propImpresora; }
            set { this.propImpresora = value; }
        }

        public Font Fuente
        {
            get { return this.propFuente; }
            set { this.propFuente = value; }
        }

        public int LargoMaximoCaracteres
        {
            get { return this.propLargoMaximoCaracteres; }
            set { this.propLargoMaximoCaracteres = value; }
        }

        public Image ImagenCabecera
        {
            get { return this.propImagenCabecera; }
            set { this.propImagenCabecera = value; }
        }

        public int AltoImagen
        {
            get { return this.propAltoImagen; }
            set { this.propAltoImagen = value; }
        }

        public int MargenIzquierdo
        {
            get { return this.propMargenIzquierdo; }
            set { this.propMargenIzquierdo = value; }
        }

        public int MargenSuperior
        {
            get { return this.propMargenSuperior; }
            set { this.propMargenSuperior = value; }
        }

        public short Copias
        {
            get { return this.propCopias; }
            set { this.propCopias = value; }
        }

        public PrinterTipoGuillotina TipoGuillotina
        {
            get { return this.propTipoGuillotina; }
            set { this.propTipoGuillotina = value; }
        }
        #endregion

        #region Metodos
        public bool ExisteImpresora(string impresora)
        {
            foreach (string _impresora in PrinterSettings.InstalledPrinters)
            {
                if (impresora == _impresora)
                    return true;
            }

            return false;
        }

        public bool ExisteImpresora()
        {
            return this.ExisteImpresora(propImpresora);
        }

        public void AgregarLineaTexto(string texto, float tamanoFuente, bool negrita, bool cursiva, PrinterAlineacionLinea alineacion)
        {
            if (texto.Length > this.propLargoMaximoCaracteres)
                texto = texto.Substring(0, this.propLargoMaximoCaracteres);
            //else
            //    texto = string.Format("{0,-" + this.propLargoMaximoCaracteres + "}", texto);

            PrinterLinea linea = new PrinterLinea(texto, tamanoFuente, negrita, cursiva, alineacion);
            this.lineas.Add(linea);
        }

        public void AgregarLineaTexto(string texto, float tamanoFuente, bool negrita, PrinterAlineacionLinea alineacion)
        {
            this.AgregarLineaTexto(texto, tamanoFuente, negrita, false, alineacion);
        }

        public void AgregarLineaTexto(string texto, bool negrita, PrinterAlineacionLinea alineacion)
        {
            this.AgregarLineaTexto(texto, 0, negrita, false, alineacion);
        }

        public void AgregarLineaTexto(string texto, bool negrita)
        {
            this.AgregarLineaTexto(texto, 0, negrita, false, PrinterAlineacionLinea.Izquierda);
        }

        public void AgregarLineaTexto(string texto)
        {
            this.AgregarLineaTexto(texto, 0, false, false, PrinterAlineacionLinea.Izquierda);
        }

        public void AgregarLineaEnBlanco()
        {
            PrinterLinea linea = new PrinterLinea("", 0, false, false, PrinterAlineacionLinea.Izquierda);
            this.lineas.Add(linea);
        }

        public void AgregarLineaSimple(bool negrita)
        {
            string lineaSimple = "";

            for (int i = 0; i < this.propLargoMaximoCaracteres; i++)
            {
                lineaSimple += "-";
            }

            this.AgregarLineaTexto(lineaSimple, negrita);
        }

        public void AgregarLineaSimple()
        {
            this.AgregarLineaSimple(false);
        }

        public void AgregarLineaPuntos(bool negrita)
        {
            string lineaPuntos = "";

            for (int i = 0; i < this.propLargoMaximoCaracteres; i++)
            {
                lineaPuntos += "=";
            }

            this.AgregarLineaTexto(lineaPuntos, negrita);
        }

        public void AgregarLineaPuntos()
        {
            this.AgregarLineaPuntos(false);
        }

        private void ImpresionTermica(string puerto, bool cortarPapel)
        {
            SafeFileHandle sfh = CreateFile(puerto, GENERIC_WRITE, 0, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);

            /* Is bad handle? INVALID_HANDLE_VALUE */
            if (sfh.IsInvalid)
            {
                /* ask the framework to marshall the win32 error code to an exception */
                Marshal.ThrowExceptionForHR(Marshal.GetLastWin32Error());
            }
            else
            {
                //This is the cut command on Star TSP 600 Printer
                //                char[] prnCmdCut = { (char)29, (char)86, (char)1 };

                FileStream port = new FileStream(sfh, FileAccess.ReadWrite);
                Byte[] buffer = new Byte[propLargoMaximoCaracteres];

                for (int i = 0; i < this.propCopias; i++)
                {
                    foreach (PrinterLinea linea in lineas)
                    {
                        // Establesco la alineacion
                        //int x = this.propMargenIzquierdo;

                        switch (linea.Alineacion)
                        {
                            /*case TicketAlineacionLinea.Izquierda:
                                linea.Texto = string.Format("|{0:-" + propLargoMaximoCaracteres.ToString() + "}|", linea.Texto);

                                break;
                            case TicketAlineacionLinea.Centro:
                                x = (int)(gfx.ClipBounds.Width - gfx.MeasureString(linea.Texto, fuente).Width) / 2;

                                break;*/
                            case PrinterAlineacionLinea.Derecha:
                                string espacios = "";
                                int largo = linea.Texto.Trim().Length;

                                if (largo != this.propLargoMaximoCaracteres)
                                    largo = this.propLargoMaximoCaracteres - largo;

                                for (int x = 0; x < largo; x++)
                                    espacios += " ";

                                linea.Texto = espacios + linea.Texto;

                                break;
                        }

                        buffer = System.Text.Encoding.ASCII.GetBytes(linea.Texto + "\n");
                        port.Write(buffer, 0, buffer.Length);
                    }

                    if (cortarPapel)
                    {
                        // Verifica el tipo de guillotina termica
                        if (this.propTipoGuillotina == PrinterTipoGuillotina.Epson)
                        {
                            buffer = System.Text.Encoding.ASCII.GetBytes(Convert.ToChar(29).ToString() + Convert.ToChar(86).ToString() + "1");
                            port.Write(buffer, 0, buffer.Length);
                        }
                        else
                        {
                            buffer = System.Text.Encoding.ASCII.GetBytes(Convert.ToChar(27).ToString() + Convert.ToChar(100).ToString() + Convert.ToChar(51).ToString());
                            port.Write(buffer, 0, buffer.Length);
                        }
                    }
                }

                port.Close();
            }
        }

        public void Imprimir(bool esTermica, bool cortarPapel)
        {
            if (!esTermica)
            {
                PrintDocument pd = new PrintDocument();
                pd.PrintController = new StandardPrintController();
                pd.PrinterSettings.PrinterName = this.propImpresora;
                pd.PrinterSettings.Copies = this.propCopias;
                pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
                pd.Print();
            }
            else
            {
                ImpresionTermica(propImpresora, cortarPapel);
            }
        }

        public void Imprimir(bool esTermica)
        {
            this.Imprimir(esTermica, false);
        }

        public void Imprimir()
        {
            this.Imprimir(false, false);
        }

        public void Limpiar()
        {
            this.lineas.Clear();
        }

        private float PosicionY()
        {
            return this.propMargenSuperior + (contador * this.propFuente.GetHeight(gfx) + this.propAltoImagen);
        }

        private void DibujarImagen()
        {
            if (this.propImagenCabecera != null)
            {
                try
                {
                    gfx.DrawImage(this.propImagenCabecera, new Point(this.propMargenIzquierdo, (int)PosicionY()));
                    double alto = ((double)this.propImagenCabecera.Height / 58) * 15;
                    this.propAltoImagen = (int)Math.Round(alto) + 3;
                }
                catch { }
            }
        }

        private void DibujarLineas()
        {
            foreach (PrinterLinea linea in lineas)
            {
                float tamanoFuente = propFuente.Size;
                FontStyle estiloFuente = new FontStyle();

                if (linea.TamanoFuente != 0)
                    tamanoFuente = linea.TamanoFuente;

                if (linea.Negrita)
                    estiloFuente = FontStyle.Bold;

                if (linea.Cursiva)
                    estiloFuente = FontStyle.Italic;

                if (linea.Negrita && linea.Cursiva)
                    estiloFuente = FontStyle.Bold | FontStyle.Italic;

                // Construyo la fuente especifica para la linea
                Font fuente = new Font(propFuente.FontFamily, tamanoFuente, estiloFuente);

                // Establesco la alineacion
                int x = this.propMargenIzquierdo;

                switch (linea.Alineacion)
                {
                    /*case TicketAlineacionLinea.Izquierda:
                        linea.Texto = string.Format("|{0:-" + propLargoMaximoCaracteres.ToString() + "}|", linea.Texto);

                        break;
                    case TicketAlineacionLinea.Centro:
                        x = (int)(gfx.ClipBounds.Width - gfx.MeasureString(linea.Texto, fuente).Width) / 2;

                        break;*/
                    case PrinterAlineacionLinea.Derecha:
                        string espacios = "";
                        int largo = linea.Texto.Length;

                        if (largo != this.propLargoMaximoCaracteres)
                            largo = this.propLargoMaximoCaracteres - largo;

                        for (int i = 0; i < largo; i++)
                            espacios += " ";

                        linea.Texto = espacios + linea.Texto;

                        break;
                }

                // Dibujo la linea
                gfx.DrawString(linea.Texto, fuente, new SolidBrush(Color.Black), x, PosicionY(), new StringFormat());

                contador++;
            }
        }
        #endregion

        #region Eventos
        private void pd_PrintPage(object sender, PrintPageEventArgs e)
        {
            e.Graphics.PageUnit = GraphicsUnit.Millimeter;
            gfx = e.Graphics;

            DibujarImagen();
            DibujarLineas();

            if (this.propImagenCabecera != null)
                this.propImagenCabecera.Dispose();

            //throw new NotImplementedException();
        }
        #endregion
    }
}


text:
/* Driver for VirtIO block devices. */

#include <sys/cdefs.h>
__FBSDID("$FreeBSD: soc2013/dpl/head/sys/dev/virtio/block/virtio_blk.c 249030 2013-03-05 07:00:05Z bryanv $");

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/bio.h>
#include <sys/malloc.h>
#include <sys/module.h>
#include <sys/sglist.h>
#include <sys/lock.h>
#include <sys/mutex.h>
#include <sys/queue.h>
#include <sys/taskqueue.h>

#include <geom/geom_disk.h>

#include <machine/bus.h>
#include <machine/resource.h>
#include <sys/bus.h>
#include <sys/rman.h>

#include <dev/virtio/virtio.h>
#include <dev/virtio/virtqueue.h>
#include <dev/virtio/block/virtio_blk.h>

#include "virtio_if.h"

struct vtblk_request {
	struct virtio_blk_outhdr	 vbr_hdr;
	struct bio			*vbr_bp;
	uint8_t				 vbr_ack;

	TAILQ_ENTRY(vtblk_request)	 vbr_link;
};

struct vtblk_softc {
	device_t		 vtblk_dev;
	struct mtx		 vtblk_mtx;
	uint64_t		 vtblk_features;
	uint32_t		 vtblk_flags;
#define VTBLK_FLAG_INDIRECT	0x0001
#define VTBLK_FLAG_READONLY	0x0002
#define VTBLK_FLAG_DETACH	0x0004
#define VTBLK_FLAG_SUSPEND	0x0008
#define VTBLK_FLAG_DUMPING	0x0010
#define VTBLK_FLAG_BARRIER	0x0020

	struct virtqueue	*vtblk_vq;
	struct sglist		*vtblk_sglist;
	struct disk		*vtblk_disk;

	struct bio_queue_head	 vtblk_bioq;
	TAILQ_HEAD(, vtblk_request)
				 vtblk_req_free;
	TAILQ_HEAD(, vtblk_request)
				 vtblk_req_ready;
	struct vtblk_request	*vtblk_req_ordered;

	struct taskqueue	*vtblk_tq;
	struct task		 vtblk_intr_task;

	int			 vtblk_max_nsegs;
	int			 vtblk_request_count;

	struct vtblk_request	 vtblk_dump_request;
};

static struct virtio_feature_desc vtblk_feature_desc[] = {
	{ VIRTIO_BLK_F_BARRIER,		"HostBarrier"	},
	{ VIRTIO_BLK_F_SIZE_MAX,	"MaxSegSize"	},
	{ VIRTIO_BLK_F_SEG_MAX,		"MaxNumSegs"	},
	{ VIRTIO_BLK_F_GEOMETRY,	"DiskGeometry"	},
	{ VIRTIO_BLK_F_RO,		"ReadOnly"	},
	{ VIRTIO_BLK_F_BLK_SIZE,	"BlockSize"	},
	{ VIRTIO_BLK_F_SCSI,		"SCSICmds"	},
	{ VIRTIO_BLK_F_FLUSH,		"FlushCmd"	},
	{ VIRTIO_BLK_F_TOPOLOGY,	"Topology"	},

	{ 0, NULL }
};

static int	vtblk_modevent(module_t, int, void *);

static int	vtblk_probe(device_t);
static int	vtblk_attach(device_t);
static int	vtblk_detach(device_t);
static int	vtblk_suspend(device_t);
static int	vtblk_resume(device_t);
static int	vtblk_shutdown(device_t);

static int	vtblk_open(struct disk *);
static int	vtblk_close(struct disk *);
static int	vtblk_ioctl(struct disk *, u_long, void *, int,
		    struct thread *);
static int	vtblk_dump(void *, void *, vm_offset_t, off_t, size_t);
static void	vtblk_strategy(struct bio *);

static void	vtblk_negotiate_features(struct vtblk_softc *);
static int	vtblk_maximum_segments(struct vtblk_softc *,
		    struct virtio_blk_config *);
static int	vtblk_alloc_virtqueue(struct vtblk_softc *);
static void	vtblk_alloc_disk(struct vtblk_softc *,
		    struct virtio_blk_config *);
static void	vtblk_create_disk(struct vtblk_softc *);

static int	vtblk_quiesce(struct vtblk_softc *);
static void	vtblk_startio(struct vtblk_softc *);
static struct vtblk_request * vtblk_bio_request(struct vtblk_softc *);
static int	vtblk_execute_request(struct vtblk_softc *,
		    struct vtblk_request *);

static int	vtblk_vq_intr(void *);
static void	vtblk_intr_task(void *, int);

static void	vtblk_stop(struct vtblk_softc *);

static void	vtblk_get_ident(struct vtblk_softc *);
static void	vtblk_prepare_dump(struct vtblk_softc *);
static int	vtblk_write_dump(struct vtblk_softc *, void *, off_t, size_t);
static int	vtblk_flush_dump(struct vtblk_softc *);
static int	vtblk_poll_request(struct vtblk_softc *,
		    struct vtblk_request *);

static void	vtblk_finish_completed(struct vtblk_softc *);
static void	vtblk_drain_vq(struct vtblk_softc *, int);
static void	vtblk_drain(struct vtblk_softc *);

static int	vtblk_alloc_requests(struct vtblk_softc *);
static void	vtblk_free_requests(struct vtblk_softc *);
static struct vtblk_request * vtblk_dequeue_request(struct vtblk_softc *);
static void	vtblk_enqueue_request(struct vtblk_softc *,
		    struct vtblk_request *);

static struct vtblk_request * vtblk_dequeue_ready(struct vtblk_softc *);
static void	vtblk_enqueue_ready(struct vtblk_softc *,
		    struct vtblk_request *);

static int	vtblk_request_error(struct vtblk_request *);
static void	vtblk_finish_bio(struct bio *, int);

/* Tunables. */
static int vtblk_no_ident = 0;
TUNABLE_INT("hw.vtblk.no_ident", &vtblk_no_ident);

/* Features desired/implemented by this driver. */
#define VTBLK_FEATURES \
    (VIRTIO_BLK_F_BARRIER		| \
     VIRTIO_BLK_F_SIZE_MAX		| \
     VIRTIO_BLK_F_SEG_MAX		| \
     VIRTIO_BLK_F_GEOMETRY		| \
     VIRTIO_BLK_F_RO			| \
     VIRTIO_BLK_F_BLK_SIZE		| \
     VIRTIO_BLK_F_FLUSH			| \
     VIRTIO_RING_F_INDIRECT_DESC)

#define VTBLK_MTX(_sc)		&(_sc)->vtblk_mtx
#define VTBLK_LOCK_INIT(_sc, _name) \
				mtx_init(VTBLK_MTX((_sc)), (_name), \
				    "VTBLK Lock", MTX_DEF)
#define VTBLK_LOCK(_sc)		mtx_lock(VTBLK_MTX((_sc)))
#define VTBLK_UNLOCK(_sc)	mtx_unlock(VTBLK_MTX((_sc)))
#define VTBLK_LOCK_DESTROY(_sc)	mtx_destroy(VTBLK_MTX((_sc)))
#define VTBLK_LOCK_ASSERT(_sc)	mtx_assert(VTBLK_MTX((_sc)), MA_OWNED)
#define VTBLK_LOCK_ASSERT_NOTOWNED(_sc) \
				mtx_assert(VTBLK_MTX((_sc)), MA_NOTOWNED)

#define VTBLK_DISK_NAME		"vtbd"
#define VTBLK_QUIESCE_TIMEOUT	(30 * hz)

/*
 * Each block request uses at least two segments - one for the header
 * and one for the status.
 */
#define VTBLK_MIN_SEGMENTS	2

static device_method_t vtblk_methods[] = {
	/* Device methods. */
	DEVMETHOD(device_probe,		vtblk_probe),
	DEVMETHOD(device_attach,	vtblk_attach),
	DEVMETHOD(device_detach,	vtblk_detach),
	DEVMETHOD(device_suspend,	vtblk_suspend),
	DEVMETHOD(device_resume,	vtblk_resume),
	DEVMETHOD(device_shutdown,	vtblk_shutdown),

	DEVMETHOD_END
};

static driver_t vtblk_driver = {
	"vtblk",
	vtblk_methods,
	sizeof(struct vtblk_softc)
};
static devclass_t vtblk_devclass;

DRIVER_MODULE(virtio_blk, virtio_pci, vtblk_driver, vtblk_devclass,
    vtblk_modevent, 0);
MODULE_VERSION(virtio_blk, 1);
MODULE_DEPEND(virtio_blk, virtio, 1, 1, 1);

static int
vtblk_modevent(module_t mod, int type, void *unused)
{
	int error;

	error = 0;

	switch (type) {
	case MOD_LOAD:
	case MOD_QUIESCE:
	case MOD_UNLOAD:
	case MOD_SHUTDOWN:
		break;
	default:
		error = EOPNOTSUPP;
		break;
	}

	return (error);
}

static int
vtblk_probe(device_t dev)
{

	if (virtio_get_device_type(dev) != VIRTIO_ID_BLOCK)
		return (ENXIO);

	device_set_desc(dev, "VirtIO Block Adapter");

	return (BUS_PROBE_DEFAULT);
}

static int
vtblk_attach(device_t dev)
{
	struct vtblk_softc *sc;
	struct virtio_blk_config blkcfg;
	int error;

	sc = device_get_softc(dev);
	sc->vtblk_dev = dev;

	VTBLK_LOCK_INIT(sc, device_get_nameunit(dev));

	bioq_init(&sc->vtblk_bioq);
	TAILQ_INIT(&sc->vtblk_req_free);
	TAILQ_INIT(&sc->vtblk_req_ready);

	virtio_set_feature_desc(dev, vtblk_feature_desc);
	vtblk_negotiate_features(sc);

	if (virtio_with_feature(dev, VIRTIO_RING_F_INDIRECT_DESC))
		sc->vtblk_flags |= VTBLK_FLAG_INDIRECT;
	if (virtio_with_feature(dev, VIRTIO_BLK_F_RO))
		sc->vtblk_flags |= VTBLK_FLAG_READONLY;
	if (virtio_with_feature(dev, VIRTIO_BLK_F_BARRIER))
		sc->vtblk_flags |= VTBLK_FLAG_BARRIER;

	/* Get local copy of config. */
	virtio_read_device_config(dev, 0, &blkcfg,
	    sizeof(struct virtio_blk_config));

	/*
	 * With the current sglist(9) implementation, it is not easy
	 * for us to support a maximum segment size as adjacent
	 * segments are coalesced. For now, just make sure it's larger
	 * than the maximum supported transfer size.
	 */
	if (virtio_with_feature(dev, VIRTIO_BLK_F_SIZE_MAX)) {
		if (blkcfg.size_max < MAXPHYS) {
			error = ENOTSUP;
			device_printf(dev, "host requires unsupported "
			    "maximum segment size feature\n");
			goto fail;
		}
	}

	sc->vtblk_max_nsegs = vtblk_maximum_segments(sc, &blkcfg);
	if (sc->vtblk_max_nsegs <= VTBLK_MIN_SEGMENTS) {
		error = EINVAL;
		device_printf(dev, "fewer than minimum number of segments "
		    "allowed: %d\n", sc->vtblk_max_nsegs);
		goto fail;
	}

	sc->vtblk_sglist = sglist_alloc(sc->vtblk_max_nsegs, M_NOWAIT);
	if (sc->vtblk_sglist == NULL) {
		error = ENOMEM;
		device_printf(dev, "cannot allocate sglist\n");
		goto fail;
	}

	error = vtblk_alloc_virtqueue(sc);
	if (error) {
		device_printf(dev, "cannot allocate virtqueue\n");
		goto fail;
	}

	error = vtblk_alloc_requests(sc);
	if (error) {
		device_printf(dev, "cannot preallocate requests\n");
		goto fail;
	}

	vtblk_alloc_disk(sc, &blkcfg);

	TASK_INIT(&sc->vtblk_intr_task, 0, vtblk_intr_task, sc);
	sc->vtblk_tq = taskqueue_create_fast("vtblk_taskq", M_NOWAIT,
	    taskqueue_thread_enqueue, &sc->vtblk_tq);
	if (sc->vtblk_tq == NULL) {
		error = ENOMEM;
		device_printf(dev, "cannot allocate taskqueue\n");
		goto fail;
	}

	error = virtio_setup_intr(dev, INTR_TYPE_BIO | INTR_ENTROPY);
	if (error) {
		device_printf(dev, "cannot setup virtqueue interrupt\n");
		goto fail;
	}

	taskqueue_start_threads(&sc->vtblk_tq, 1, PI_DISK, "%s taskq",
	    device_get_nameunit(dev));

	vtblk_create_disk(sc);

	virtqueue_enable_intr(sc->vtblk_vq);

fail:
	if (error)
		vtblk_detach(dev);

	return (error);
}

static int
vtblk_detach(device_t dev)
{
	struct vtblk_softc *sc;

	sc = device_get_softc(dev);

	VTBLK_LOCK(sc);
	sc->vtblk_flags |= VTBLK_FLAG_DETACH;
	if (device_is_attached(dev))
		vtblk_stop(sc);
	VTBLK_UNLOCK(sc);

	if (sc->vtblk_tq != NULL) {
		taskqueue_drain(sc->vtblk_tq, &sc->vtblk_intr_task);
		taskqueue_free(sc->vtblk_tq);
		sc->vtblk_tq = NULL;
	}

	vtblk_drain(sc);

	if (sc->vtblk_disk != NULL) {
		disk_destroy(sc->vtblk_disk);
		sc->vtblk_disk = NULL;
	}

	if (sc->vtblk_sglist != NULL) {
		sglist_free(sc->vtblk_sglist);
		sc->vtblk_sglist = NULL;
	}

	VTBLK_LOCK_DESTROY(sc);

	return (0);
}

static int
vtblk_suspend(device_t dev)
{
	struct vtblk_softc *sc;
	int error;

	sc = device_get_softc(dev);

	VTBLK_LOCK(sc);
	sc->vtblk_flags |= VTBLK_FLAG_SUSPEND;
	/* XXX BMV: virtio_stop(), etc needed here? */
	error = vtblk_quiesce(sc);
	if (error)
		sc->vtblk_flags &= ~VTBLK_FLAG_SUSPEND;
	VTBLK_UNLOCK(sc);

	return (error);
}

static int
vtblk_resume(device_t dev)
{
	struct vtblk_softc *sc;

	sc = device_get_softc(dev);

	VTBLK_LOCK(sc);
	/* XXX BMV: virtio_reinit(), etc needed here? */
	sc->vtblk_flags &= ~VTBLK_FLAG_SUSPEND;
	vtblk_startio(sc);
	VTBLK_UNLOCK(sc);

	return (0);
}

static int
vtblk_shutdown(device_t dev)
{

	return (0);
}

static int
vtblk_open(struct disk *dp)
{
	struct vtblk_softc *sc;

	if ((sc = dp->d_drv1) == NULL)
		return (ENXIO);

	return (sc->vtblk_flags & VTBLK_FLAG_DETACH ? ENXIO : 0);
}

static int
vtblk_close(struct disk *dp)
{
	struct vtblk_softc *sc;

	if ((sc = dp->d_drv1) == NULL)
		return (ENXIO);

	return (0);
}

static int
vtblk_ioctl(struct disk *dp, u_long cmd, void *addr, int flag,
    struct thread *td)
{
	struct vtblk_softc *sc;

	if ((sc = dp->d_drv1) == NULL)
		return (ENXIO);

	return (ENOTTY);
}

static int
vtblk_dump(void *arg, void *virtual, vm_offset_t physical, off_t offset,
    size_t length)
{
	struct disk *dp;
	struct vtblk_softc *sc;
	int error;

	dp = arg;

	if ((sc = dp->d_drv1) == NULL)
		return (ENXIO);

	VTBLK_LOCK(sc);

	if ((sc->vtblk_flags & VTBLK_FLAG_DUMPING) == 0) {
		vtblk_prepare_dump(sc);
		sc->vtblk_flags |= VTBLK_FLAG_DUMPING;
	}

	if (length > 0)
		error = vtblk_write_dump(sc, virtual, offset, length);
	else if (virtual == NULL && offset == 0)
		error = vtblk_flush_dump(sc);
	else {
		error = EINVAL;
		sc->vtblk_flags &= ~VTBLK_FLAG_DUMPING;
	}

	VTBLK_UNLOCK(sc);

	return (error);
}

static void
vtblk_strategy(struct bio *bp)
{
	struct vtblk_softc *sc;

	if ((sc = bp->bio_disk->d_drv1) == NULL) {
		vtblk_finish_bio(bp, EINVAL);
		return;
	}

	/*
	 * Fail any write if RO. Unfortunately, there does not seem to
	 * be a better way to report our readonly'ness to GEOM above.
	 */
	if (sc->vtblk_flags & VTBLK_FLAG_READONLY &&
	    (bp->bio_cmd == BIO_WRITE || bp->bio_cmd == BIO_FLUSH)) {
		vtblk_finish_bio(bp, EROFS);
		return;
	}

#ifdef INVARIANTS
	/*
	 * Prevent read/write buffers spanning too many segments from
	 * getting into the queue. This should only trip if d_maxsize
	 * was incorrectly set.
	 */
	if (bp->bio_cmd == BIO_READ || bp->bio_cmd == BIO_WRITE) {
		int nsegs, max_nsegs;

		nsegs = sglist_count(bp->bio_data, bp->bio_bcount);
		max_nsegs = sc->vtblk_max_nsegs - VTBLK_MIN_SEGMENTS;

		KASSERT(nsegs <= max_nsegs,
		    ("bio %p spanned too many segments: %d, max: %d",
		    bp, nsegs, max_nsegs));
	}
#endif

	VTBLK_LOCK(sc);
	if (sc->vtblk_flags & VTBLK_FLAG_DETACH)
		vtblk_finish_bio(bp, ENXIO);
	else {
		bioq_disksort(&sc->vtblk_bioq, bp);

		if ((sc->vtblk_flags & VTBLK_FLAG_SUSPEND) == 0)
			vtblk_startio(sc);
	}
	VTBLK_UNLOCK(sc);
}

static void
vtblk_negotiate_features(struct vtblk_softc *sc)
{
	device_t dev;
	uint64_t features;

	dev = sc->vtblk_dev;
	features = VTBLK_FEATURES;

	sc->vtblk_features = virtio_negotiate_features(dev, features);
}

static int
vtblk_maximum_segments(struct vtblk_softc *sc,
    struct virtio_blk_config *blkcfg)
{
	device_t dev;
	int nsegs;

	dev = sc->vtblk_dev;
	nsegs = VTBLK_MIN_SEGMENTS;

	if (virtio_with_feature(dev, VIRTIO_BLK_F_SEG_MAX)) {
		nsegs += MIN(blkcfg->seg_max, MAXPHYS / PAGE_SIZE + 1);
		if (sc->vtblk_flags & VTBLK_FLAG_INDIRECT)
			nsegs = MIN(nsegs, VIRTIO_MAX_INDIRECT);
	} else
		nsegs += 1;

	return (nsegs);
}

static int
vtblk_alloc_virtqueue(struct vtblk_softc *sc)
{
	device_t dev;
	struct vq_alloc_info vq_info;

	dev = sc->vtblk_dev;

	VQ_ALLOC_INFO_INIT(&vq_info, sc->vtblk_max_nsegs,
	    vtblk_vq_intr, sc, &sc->vtblk_vq,
	    "%s request", device_get_nameunit(dev));

	return (virtio_alloc_virtqueues(dev, 0, 1, &vq_info));
}

static void
vtblk_alloc_disk(struct vtblk_softc *sc, struct virtio_blk_config *blkcfg)
{
	device_t dev;
	struct disk *dp;

	dev = sc->vtblk_dev;

	sc->vtblk_disk = dp = disk_alloc();
	dp->d_open = vtblk_open;
	dp->d_close = vtblk_close;
	dp->d_ioctl = vtblk_ioctl;
	dp->d_strategy = vtblk_strategy;
	dp->d_name = VTBLK_DISK_NAME;
	dp->d_unit = device_get_unit(dev);
	dp->d_drv1 = sc;

	if ((sc->vtblk_flags & VTBLK_FLAG_READONLY) == 0)
		dp->d_dump = vtblk_dump;

	/* Capacity is always in 512-byte units. */
	dp->d_mediasize = blkcfg->capacity * 512;

	if (virtio_with_feature(dev, VIRTIO_BLK_F_BLK_SIZE))
		dp->d_sectorsize = blkcfg->blk_size;
	else
		dp->d_sectorsize = 512;

	/*
	 * The VirtIO maximum I/O size is given in terms of segments.
	 * However, FreeBSD limits I/O size by logical buffer size, not
	 * by physically contiguous pages. Therefore, we have to assume
	 * no pages are contiguous. This may impose an artificially low
	 * maximum I/O size. But in practice, since QEMU advertises 128
	 * segments, this gives us a maximum IO size of 125 * PAGE_SIZE,
	 * which is typically greater than MAXPHYS. Eventually we should
	 * just advertise MAXPHYS and split buffers that are too big.
	 *
	 * Note we must subtract one additional segment in case of non
	 * page aligned buffers.
	 */
	dp->d_maxsize = (sc->vtblk_max_nsegs - VTBLK_MIN_SEGMENTS - 1) *
	    PAGE_SIZE;
	if (dp->d_maxsize < PAGE_SIZE)
		dp->d_maxsize = PAGE_SIZE; /* XXX */

	if (virtio_with_feature(dev, VIRTIO_BLK_F_GEOMETRY)) {
		dp->d_fwsectors = blkcfg->geometry.sectors;
		dp->d_fwheads = blkcfg->geometry.heads;
	}

	if (virtio_with_feature(dev, VIRTIO_BLK_F_FLUSH))
		dp->d_flags |= DISKFLAG_CANFLUSHCACHE;
}

static void
vtblk_create_disk(struct vtblk_softc *sc)
{
	struct disk *dp;

	dp = sc->vtblk_disk;

	/*
	 * Retrieving the identification string must be done after
	 * the virtqueue interrupt is setup otherwise it will hang.
	 */
	vtblk_get_ident(sc);

	device_printf(sc->vtblk_dev, "%juMB (%ju %u byte sectors)\n",
	    (uintmax_t) dp->d_mediasize >> 20,
	    (uintmax_t) dp->d_mediasize / dp->d_sectorsize,
	    dp->d_sectorsize);

	disk_create(dp, DISK_VERSION);
}

static int
vtblk_quiesce(struct vtblk_softc *sc)
{
	int error;

	error = 0;

	VTBLK_LOCK_ASSERT(sc);

	while (!virtqueue_empty(sc->vtblk_vq)) {
		if (mtx_sleep(&sc->vtblk_vq, VTBLK_MTX(sc), PRIBIO, "vtblkq",
		    VTBLK_QUIESCE_TIMEOUT) == EWOULDBLOCK) {
			error = EBUSY;
			break;
		}
	}

	return (error);
}

static void
vtblk_startio(struct vtblk_softc *sc)
{
	struct virtqueue *vq;
	struct vtblk_request *req;
	int enq;

	vq = sc->vtblk_vq;
	enq = 0;

	VTBLK_LOCK_ASSERT(sc);

	while (!virtqueue_full(vq)) {
		if ((req = vtblk_dequeue_ready(sc)) == NULL)
			req = vtblk_bio_request(sc);
		if (req == NULL)
			break;

		if (vtblk_execute_request(sc, req) != 0) {
			vtblk_enqueue_ready(sc, req);
			break;
		}

		enq++;
	}

	if (enq > 0)
		virtqueue_notify(vq);
}

static struct vtblk_request *
vtblk_bio_request(struct vtblk_softc *sc)
{
	struct bio_queue_head *bioq;
	struct vtblk_request *req;
	struct bio *bp;

	bioq = &sc->vtblk_bioq;

	if (bioq_first(bioq) == NULL)
		return (NULL);

	req = vtblk_dequeue_request(sc);
	if (req == NULL)
		return (NULL);

	bp = bioq_takefirst(bioq);
	req->vbr_bp = bp;
	req->vbr_ack = -1;
	req->vbr_hdr.ioprio = 1;

	switch (bp->bio_cmd) {
	case BIO_FLUSH:
		req->vbr_hdr.type = VIRTIO_BLK_T_FLUSH;
		break;
	case BIO_READ:
		req->vbr_hdr.type = VIRTIO_BLK_T_IN;
		req->vbr_hdr.sector = bp->bio_offset / 512;
		break;
	case BIO_WRITE:
		req->vbr_hdr.type = VIRTIO_BLK_T_OUT;
		req->vbr_hdr.sector = bp->bio_offset / 512;
		break;
	default:
		panic("%s: bio with unhandled cmd: %d", __FUNCTION__,
		    bp->bio_cmd);
	}

	return (req);
}

static int
vtblk_execute_request(struct vtblk_softc *sc, struct vtblk_request *req)
{
	struct virtqueue *vq;
	struct sglist *sg;
	struct bio *bp;
	int ordered, readable, writable, error;

	vq = sc->vtblk_vq;
	sg = sc->vtblk_sglist;
	bp = req->vbr_bp;
	ordered = 0;
	writable = 0;

	VTBLK_LOCK_ASSERT(sc);

	/*
	 * Wait until the ordered request completes before
	 * executing subsequent requests.
	 */
	if (sc->vtblk_req_ordered != NULL)
		return (EBUSY);

	if (bp->bio_flags & BIO_ORDERED) {
		if ((sc->vtblk_flags & VTBLK_FLAG_BARRIER) == 0) {
			/*
			 * This request will be executed once all
			 * the in-flight requests are completed.
			 */
			if (!virtqueue_empty(vq))
				return (EBUSY);
			ordered = 1;
		} else
			req->vbr_hdr.type |= VIRTIO_BLK_T_BARRIER;
	}

	sglist_reset(sg);

	sglist_append(sg, &req->vbr_hdr, sizeof(struct virtio_blk_outhdr));

	if (bp->bio_cmd == BIO_READ || bp->bio_cmd == BIO_WRITE) {
		error = sglist_append(sg, bp->bio_data, bp->bio_bcount);
		if (error || sg->sg_nseg == sg->sg_maxseg)
			panic("%s: data buffer too big bio:%p error:%d",
			    __FUNCTION__, bp, error);

		/* BIO_READ means the host writes into our buffer. */
		if (bp->bio_cmd == BIO_READ)
			writable = sg->sg_nseg - 1;
	}

	writable++;
	sglist_append(sg, &req->vbr_ack, sizeof(uint8_t));
	readable = sg->sg_nseg - writable;

	error = virtqueue_enqueue(vq, req, sg, readable, writable);
	if (error == 0 && ordered)
		sc->vtblk_req_ordered = req;

	return (error);
}

static int
vtblk_vq_intr(void *xsc)
{
	struct vtblk_softc *sc;

	sc = xsc;

	virtqueue_disable_intr(sc->vtblk_vq);
	taskqueue_enqueue_fast(sc->vtblk_tq, &sc->vtblk_intr_task);

	return (1);
}

static void
vtblk_intr_task(void *arg, int pending)
{
	struct vtblk_softc *sc;
	struct virtqueue *vq;

	sc = arg;
	vq = sc->vtblk_vq;

	VTBLK_LOCK(sc);
	if (sc->vtblk_flags & VTBLK_FLAG_DETACH) {
		VTBLK_UNLOCK(sc);
		return;
	}

	vtblk_finish_completed(sc);

	if ((sc->vtblk_flags & VTBLK_FLAG_SUSPEND) == 0)
		vtblk_startio(sc);
	else
		wakeup(&sc->vtblk_vq);

	if (virtqueue_enable_intr(vq) != 0) {
		virtqueue_disable_intr(vq);
		VTBLK_UNLOCK(sc);
		taskqueue_enqueue_fast(sc->vtblk_tq,
		    &sc->vtblk_intr_task);
		return;
	}

	VTBLK_UNLOCK(sc);
}

static void
vtblk_stop(struct vtblk_softc *sc)
{

	virtqueue_disable_intr(sc->vtblk_vq);
	virtio_stop(sc->vtblk_dev);
}

static void
vtblk_get_ident(struct vtblk_softc *sc)
{
	struct bio buf;
	struct disk *dp;
	struct vtblk_request *req;
	int len, error;

	dp = sc->vtblk_disk;
	len = MIN(VIRTIO_BLK_ID_BYTES, DISK_IDENT_SIZE);

	if (vtblk_no_ident != 0)
		return;

	req = vtblk_dequeue_request(sc);
	if (req == NULL)
		return;

	req->vbr_ack = -1;
	req->vbr_hdr.type = VIRTIO_BLK_T_GET_ID;
	req->vbr_hdr.ioprio = 1;
	req->vbr_hdr.sector = 0;

	req->vbr_bp = &buf;
	bzero(&buf, sizeof(struct bio));

	buf.bio_cmd = BIO_READ;
	buf.bio_data = dp->d_ident;
	buf.bio_bcount = len;

	VTBLK_LOCK(sc);
	error = vtblk_poll_request(sc, req);
	VTBLK_UNLOCK(sc);

	vtblk_enqueue_request(sc, req);

	if (error) {
		device_printf(sc->vtblk_dev,
		    "error getting device identifier: %d\n", error);
	}
}

static void
vtblk_prepare_dump(struct vtblk_softc *sc)
{
	device_t dev;
	struct virtqueue *vq;

	dev = sc->vtblk_dev;
	vq = sc->vtblk_vq;

	vtblk_stop(sc);

	/*
	 * Drain all requests caught in-flight in the virtqueue,
	 * skipping biodone(). When dumping, only one request is
	 * outstanding at a time, and we just poll the virtqueue
	 * for the response.
	 */
	vtblk_drain_vq(sc, 1);

	if (virtio_reinit(dev, sc->vtblk_features) != 0)
		panic("cannot reinit VirtIO block device during dump");

	virtqueue_disable_intr(vq);
	virtio_reinit_complete(dev);
}

static int
vtblk_write_dump(struct vtblk_softc *sc, void *virtual, off_t offset,
    size_t length)
{
	struct bio buf;
	struct vtblk_request *req;

	req = &sc->vtblk_dump_request;
	req->vbr_ack = -1;
	req->vbr_hdr.type = VIRTIO_BLK_T_OUT;
	req->vbr_hdr.ioprio = 1;
	req->vbr_hdr.sector = offset / 512;

	req->vbr_bp = &buf;
	bzero(&buf, sizeof(struct bio));

	buf.bio_cmd = BIO_WRITE;
	buf.bio_data = virtual;
	buf.bio_bcount = length;

	return (vtblk_poll_request(sc, req));
}

static int
vtblk_flush_dump(struct vtblk_softc *sc)
{
	struct bio buf;
	struct vtblk_request *req;

	req = &sc->vtblk_dump_request;
	req->vbr_ack = -1;
	req->vbr_hdr.type = VIRTIO_BLK_T_FLUSH;
	req->vbr_hdr.ioprio = 1;
	req->vbr_hdr.sector = 0;

	req->vbr_bp = &buf;
	bzero(&buf, sizeof(struct bio));

	buf.bio_cmd = BIO_FLUSH;

	return (vtblk_poll_request(sc, req));
}

static int
vtblk_poll_request(struct vtblk_softc *sc, struct vtblk_request *req)
{
	struct virtqueue *vq;
	struct vtblk_request *r;
	int error;

	vq = sc->vtblk_vq;

	if (!virtqueue_empty(vq))
		return (EBUSY);

	error = vtblk_execute_request(sc, req);
	if (error)
		return (error);

	virtqueue_notify(vq);

	r = virtqueue_poll(vq, NULL);
	KASSERT(r == req, ("unexpected request response: %p/%p", r, req));

	error = vtblk_request_error(req);
	if (error && bootverbose) {
		device_printf(sc->vtblk_dev,
		    "%s: IO error: %d\n", __FUNCTION__, error);
	}

	return (error);
}

static void
vtblk_finish_completed(struct vtblk_softc *sc)
{
	struct vtblk_request *req;
	struct bio *bp;
	int error;

	while ((req = virtqueue_dequeue(sc->vtblk_vq, NULL)) != NULL) {
		bp = req->vbr_bp;

		if (sc->vtblk_req_ordered != NULL) {
			/* This should be the only outstanding request. */
			MPASS(sc->vtblk_req_ordered == req);
			sc->vtblk_req_ordered = NULL;
		}

		error = vtblk_request_error(req);
		if (error)
			disk_err(bp, "hard error", -1, 1);

		vtblk_finish_bio(bp, error);
		vtblk_enqueue_request(sc, req);
	}
}

static void
vtblk_drain_vq(struct vtblk_softc *sc, int skip_done)
{
	struct virtqueue *vq;
	struct vtblk_request *req;
	int last;

	vq = sc->vtblk_vq;
	last = 0;

	while ((req = virtqueue_drain(vq, &last)) != NULL) {
		if (!skip_done)
			vtblk_finish_bio(req->vbr_bp, ENXIO);

		vtblk_enqueue_request(sc, req);
	}

	sc->vtblk_req_ordered = NULL;
	KASSERT(virtqueue_empty(vq), ("virtqueue not empty"));
}

static void
vtblk_drain(struct vtblk_softc *sc)
{
	struct bio_queue_head *bioq;
	struct vtblk_request *req;
	struct bio *bp;

	bioq = &sc->vtblk_bioq;

	if (sc->vtblk_vq != NULL) {
		vtblk_finish_completed(sc);
		vtblk_drain_vq(sc, 0);
	}

	while ((req = vtblk_dequeue_ready(sc)) != NULL) {
		vtblk_finish_bio(req->vbr_bp, ENXIO);
		vtblk_enqueue_request(sc, req);
	}

	while (bioq_first(bioq) != NULL) {
		bp = bioq_takefirst(bioq);
		vtblk_finish_bio(bp, ENXIO);
	}

	vtblk_free_requests(sc);
}

#ifdef INVARIANTS
static void
vtblk_request_invariants(struct vtblk_request *req)
{
	int hdr_nsegs, ack_nsegs;

	hdr_nsegs = sglist_count(&req->vbr_hdr, sizeof(req->vbr_hdr));
	ack_nsegs = sglist_count(&req->vbr_ack, sizeof(req->vbr_ack));

	KASSERT(hdr_nsegs == 1, ("request header crossed page boundary"));
	KASSERT(ack_nsegs == 1, ("request ack crossed page boundary"));
}
#endif

static int
vtblk_alloc_requests(struct vtblk_softc *sc)
{
	struct vtblk_request *req;
	int i, nreqs;

	nreqs = virtqueue_size(sc->vtblk_vq);

	/*
	 * Preallocate sufficient requests to keep the virtqueue full. Each
	 * request consumes VTBLK_MIN_SEGMENTS or more descriptors so reduce
	 * the number allocated when indirect descriptors are not available.
	 */
	if ((sc->vtblk_flags & VTBLK_FLAG_INDIRECT) == 0)
		nreqs /= VTBLK_MIN_SEGMENTS;

	for (i = 0; i < nreqs; i++) {
		req = malloc(sizeof(struct vtblk_request), M_DEVBUF, M_NOWAIT);
		if (req == NULL)
			return (ENOMEM);

#ifdef INVARIANTS
		vtblk_request_invariants(req);
#endif

		sc->vtblk_request_count++;
		vtblk_enqueue_request(sc, req);
	}

	return (0);
}

static void
vtblk_free_requests(struct vtblk_softc *sc)
{
	struct vtblk_request *req;

	KASSERT(TAILQ_EMPTY(&sc->vtblk_req_ready),
	    ("ready requests left on queue"));

	while ((req = vtblk_dequeue_request(sc)) != NULL) {
		sc->vtblk_request_count--;
		free(req, M_DEVBUF);
	}

	KASSERT(sc->vtblk_request_count == 0,
	    ("leaked requests: %d", sc->vtblk_request_count));
}

static struct vtblk_request *
vtblk_dequeue_request(struct vtblk_softc *sc)
{
	struct vtblk_request *req;

	req = TAILQ_FIRST(&sc->vtblk_req_free);
	if (req != NULL)
		TAILQ_REMOVE(&sc->vtblk_req_free, req, vbr_link);

	return (req);
}

static void
vtblk_enqueue_request(struct vtblk_softc *sc, struct vtblk_request *req)
{

	bzero(req, sizeof(struct vtblk_request));
	TAILQ_INSERT_HEAD(&sc->vtblk_req_free, req, vbr_link);
}

static struct vtblk_request *
vtblk_dequeue_ready(struct vtblk_softc *sc)
{
	struct vtblk_request *req;

	req = TAILQ_FIRST(&sc->vtblk_req_ready);
	if (req != NULL)
		TAILQ_REMOVE(&sc->vtblk_req_ready, req, vbr_link);

	return (req);
}

static void
vtblk_enqueue_ready(struct vtblk_softc *sc, struct vtblk_request *req)
{

	TAILQ_INSERT_HEAD(&sc->vtblk_req_ready, req, vbr_link);
}

static int
vtblk_request_error(struct vtblk_request *req)
{
	int error;

	switch (req->vbr_ack) {
	case VIRTIO_BLK_S_OK:
		error = 0;
		break;
	case VIRTIO_BLK_S_UNSUPP:
		error = ENOTSUP;
		break;
	default:
		error = EIO;
		break;
	}

	return (error);
}

static void
vtblk_finish_bio(struct bio *bp, int error)
{

	if (error) {
		bp->bio_resid = bp->bio_bcount;
		bp->bio_error = error;
		bp->bio_flags |= BIO_ERROR;
	}

	biodone(bp);
}

redpajama_set_name: RedPajamaGithub


text:
package com.xiang.modules.crm.web;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.mapper.JsonMapper;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.xiang.modules.crm.entity.CrmCustomer;
import com.xiang.modules.crm.service.CrmCustomerService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 客户管理Controller
 * @author Xiang
 * @version 2017-02-28
 */
@Controller
@RequestMapping(value = "${adminPath}/crm/crmCustomer")
public class CrmCustomerController extends BaseController {

	@Autowired
	private CrmCustomerService crmCustomerService;

	@ModelAttribute
	public CrmCustomer get(@RequestParam(required=false) String id) {
		CrmCustomer entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = crmCustomerService.get(id);
		}
		if (entity == null){
			entity = new CrmCustomer();
		}
		return entity;
	}

	@RequiresPermissions("crm:crmCustomer:view")
	@RequestMapping(value = {"list", ""})
	public String list(CrmCustomer crmCustomer, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<CrmCustomer> page = crmCustomerService.findPage(new Page<CrmCustomer>(request, response), crmCustomer);
		model.addAttribute("page", page);
		return "modules/crm/crmCustomerList";
	}

	@RequiresPermissions("crm:crmCustomer:view")
	@RequestMapping(value = "form")
	public String form(CrmCustomer crmCustomer, Model model) {
		model.addAttribute("crmCustomer", crmCustomer);
		return "modules/crm/crmCustomerForm";
	}

	@RequiresPermissions("crm:crmCustomer:edit")
	@RequestMapping(value = "save")
	public String save(CrmCustomer crmCustomer, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, crmCustomer)){
			return form(crmCustomer, model);
		}
		crmCustomerService.save(crmCustomer);
		addMessage(redirectAttributes, "保存客户成功");
		return "redirect:"+Global.getAdminPath()+"/crm/crmCustomer/?repage";
	}

	@RequiresPermissions("crm:crmCustomer:edit")
	@RequestMapping(value = "delete")
	public String delete(CrmCustomer crmCustomer, RedirectAttributes redirectAttributes) {
		crmCustomerService.delete(crmCustomer);
		addMessage(redirectAttributes, "删除客户成功");
		return "redirect:"+Global.getAdminPath()+"/crm/crmCustomer/?repage";
	}

	@RequiresPermissions("crm:crmCustomer:view")
	@RequestMapping(value = {"select"})
	public String select(CrmCustomer crmCustomer, HttpServletRequest request, HttpServletResponse response, Model model) {
		return "modules/crm/crmCustomerSelect";
	}

	/**
	 * 通过编号获取文章标题
	 */
	@RequiresPermissions("cms:article:view")
	@ResponseBody
	@RequestMapping(value = "findById")
	public String findById(String id) {
		return JsonMapper.toJsonString(crmCustomerService.get(id));
	}

}


text:
package com.infmme.readilyapp.util;

import android.support.v7.app.ActionBarActivity;
import com.flurry.android.FlurryAgent;

/**
 * created on 7/15/14 by infm. Enjoy ;)
 */
public class BaseActivity extends ActionBarActivity {
	@Override
	protected void onStart(){
		super.onStart();
		FlurryAgent.onStartSession(this, "6CNDCMYSWHYDFYDVKDMD");
	}

	@Override
	protected void onStop(){
		super.onStop();
		FlurryAgent.onEndSession(this);
	}
}


text:
package org.apache.maven.model.building;

import java.io.File;

import org.apache.maven.model.Model;

/**
 * Builds the effective model from a POM.
 *
 * @author Benjamin Bentmann
 */
public interface ModelBuilder
{

    /**
     * Builds the effective model of the specified POM.
     *
     * @param request The model building request that holds the parameters, must not be {@code null}.
     * @return The result of the model building, never {@code null}.
     * @throws ModelBuildingException If the effective model could not be built.
     */
    ModelBuildingResult build( ModelBuildingRequest request )
        throws ModelBuildingException;

    /**
     * Builds the effective model by completing the specified interim result which was produced by a previous call to
     * {@link #build(ModelBuildingRequest)} with {@link ModelBuildingRequest#isTwoPhaseBuilding()} being {@code true}.
     * The model building request passed to this method must be the same as the one used for the first phase of the
     * model building.
     *
     * @param request The model building request that holds the parameters, must not be {@code null}.
     * @param result The interim result of the first phase of model building, must not be {@code null}.
     * @return The result of the model building, never {@code null}.
     * @throws ModelBuildingException If the effective model could not be built.
     */
    ModelBuildingResult build( ModelBuildingRequest request, ModelBuildingResult result )
        throws ModelBuildingException;

    /**
     * Performs only the part of {@link ModelBuilder#build(ModelBuildingRequest)} that loads the raw model
     */
    Result<? extends Model> buildRawModel( File pomFile, int validationLevel, boolean locationTracking );

}


text:
using Zombus.MessageContracts;

namespace Zombus.IntegrationTests.Tests.BusStartingAndStopping.MessageContracts
{
    public class QuickCommand : IBusCommand
    {
    }
}


text:
package spring.dao3;

/**
 * 使用线程本地化信息,保存当前使用的DB信息
 * @author ly
 *
 */
public class DatabaseContextHolder {

    private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();

    public static void setCustomerType(String customerType) {
        contextHolder.set(customerType);
    }

    public static String getCustomerType() {
        return contextHolder.get();
    }

    public static void clearCustomerType() {
        contextHolder.remove();
    }
}


text:
<?php echo $judul; ?>

					1. Data Pribadi
					2. Riwayat Pendidikan
					3. Riwayat Pekerjaan
					4. Anggota Keluarga
					5. Evaluasi Diri
					6. Selesai

			<?php if (isset($_SESSION['pesan'])) { ?>

				<button type="button" class="close" data-dismiss="alert">

				</button>
				<?php echo $this->session->flashdata('pesan'); ?>

			<?php } ?>

						Riwayat
						Pekerjaan

							 Tambah

Silahkan mengisi riwayat pekerjaan Anda sesuai dengan yang pernah Anda tempuh.

					              No.
					              Nama
					              Periode
					              Jabatan Akhir
					              Gaji Per Bulan
					              Opsi

					            <?php
					            $no = 1;
					            foreach($pekerjaan as $j) { ?>

					              <?php echo $no; ?>.
					              <?php echo $j->NAMA_PERUSAHAAN; ?>
					              <?php
					              $tahun = explode("-", $j->TANGGAL_SELESAI)[0];
					              if($tahun == 9999) $tahun = "Sekarang";
					              else $tahun = date("Y", strtotime($j->TANGGAL_SELESAI));
					              ?>
					              <?php echo date("Y", strtotime($j->TANGGAL_MULAI))." - ".$tahun; ?>
					              <?php echo $j->JABATAN_AKHIR; ?>
					              <?php echo "Rp".str_replace(",", ".", number_format($j->GAJI_PERBULAN)); ?>

					                  <a class="btn btn-xs btn-success" href="#modal-edit" data-toggle="modal" role="button" onclick="edit('<?php echo $j->ID; ?>',
					                  '<?php echo $j->NAMA_PERUSAHAAN; ?>', '<?php echo $j->TANGGAL_MULAI; ?>', '<?php echo $j->TANGGAL_SELESAI; ?>',
					                  '<?php echo $j->JABATAN_AKHIR; ?>', '<?php echo $j->GAJI_PERBULAN; ?>')">
					                     Ubah

					                  <a class="btn btn-xs btn-danger" href="<?php echo base_url().'index.php/page/riwayat_pekerjaan_act/'.$pendaftar->NO_PENDAFTARAN.'/hapus/'.$j->ID; ?>"
					                  onclick="return confirm('Anda yakin?');">
					                     Hapus

					            <?php $no++; } ?>

						<a href="<?php echo base_url().'index.php/page/anggota_keluarga/'.$pendaftar->NO_PENDAFTARAN; ?>" class="btn grey">Lewati
						<a href="<?php echo base_url().'index.php/page/anggota_keluarga/'.$pendaftar->NO_PENDAFTARAN; ?>" class="btn green pull-right">Lanjut

2016 © PMB LP3I Surabaya by @obyzz

          <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
            ×
          </button>
          Tambah Riwayat Pekerjaan

      <form class='form-horizontal' role='form' action='<?php echo base_url()."index.php/page/riwayat_pekerjaan_act/".$pendaftar->NO_PENDAFTARAN."/tambah"; ?>' method='post' enctype="multipart/form-data">

        <input type='hidden' id='id' name="id" class='form-control' readonly="" required="" value="<?php echo $id; ?>" />

          Nama Perusahaan

            <input type="text" id='nama' name="nama" placeholder='Contoh: PT. ABDI BERKAH CAHAYA' class='form-control' required="" />

			Mulai/Masuk

				<input class="form-control form-control-inline input-medium " id="mulai" name="mulai" size="16" type="date" placeholder="DD/MM/YYYY" />

			Selesai/Keluar

				<input class="form-control form-control-inline input-medium" id="selesai" name="selesai" size="16" type="date" placeholder="DD/MM/YYYY" />

          Jabatan Terakhir

            <input type="text" id='jabatan' name="jabatan" placeholder='Jabatan' class='form-control' />

          Gaji Per Bulan

            <input type="number" id='gaji' name="gaji" placeholder='1000000' class='form-control' />

        <button class='btn btn-sm btn-danger pull-left' data-dismiss='modal'>
           Tutup
        </button>
        <button class='btn btn-primary btn-sm' type='submit'>
           Simpan
        </button>

      </form>

          <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
            ×
          </button>
          Ubah Riwayat Pekerjaan

      <form class='form-horizontal' role='form' action='<?php echo base_url()."index.php/page/riwayat_pekerjaan_act/".$pendaftar->NO_PENDAFTARAN."/ubah"; ?>' method='post' enctype="multipart/form-data">

        <input type='hidden' id='id-u' name="id-u" class='form-control' readonly="" required="" value="<?php echo $id; ?>" />

          Nama Perusahaan

            <input type="text" id='nama-u' name="nama-u" placeholder='Contoh: PT. ABDI BERKAH CAHAYA' class='form-control' required="" />

			Mulai/Masuk

				<input class="form-control form-control-inline input-medium " id="mulai-u" name="mulai-u" size="16" type="date" placeholder="DD/MM/YYYY" />

			Selesai/Keluar

				<input class="form-control form-control-inline input-medium " id="selesai-u" name="selesai-u" size="16" type="date" placeholder="DD/MM/YYYY" />

          Jabatan Terakhir

            <input type="text" id='jabatan-u' name="jabatan-u" placeholder='Jabatan' class='form-control' />

          Gaji Per Bulan

            <input type="number" id='gaji-u' name="gaji-u" placeholder='1000000' class='form-control' />

        <button class='btn btn-sm btn-danger pull-left' data-dismiss='modal'>
           Tutup
        </button>
        <button class='btn btn-primary btn-sm' type='submit'>
           Simpan
        </button>

      </form>


text:
import {Component, OnInit, Input} from '@angular/core';

import {AgentService} from './agent.service'
import {Merchant} from "../../../class/merchant";

import {IMyDpOptions, IMyDateModel} from 'mydatepicker';
import {FormGroup, FormBuilder, Validators} from "@angular/forms";
import { Logger } from "angular2-logger/core";
@Component({

  selector:'agent',
  templateUrl:'./agent.component.html',
  styleUrls: ['./agent.component.css'],
  providers:[AgentService]

})

export class AgentComponent implements OnInit{

  private qrtext;
  private loading = false;
//data store
  data
  filterdata;

  //filterQuery = "";
  rowsOnPage = 10;

  merchantqrcode = false;
  merchantId="";
  type="";
  todate = { year: 2016, month: 10, day: 9 };
  fromdate = { year: 2016, month: 10, day: 9 };
  role ="merchant";

  agents;
  agentId;

  day = false;
  daytoday =false;

  //error handling
  transctionError = false;
  transctionInfo = false;
  infomassage =""
  errormassage=""

  //selectedDate = "2017-09-11";
  private selectedDateFrom: Object = { date: { year: 2016, month: 10, day: 9 } };
  private selectedDateTo: Object = { date: { year: 2017, month: 10, day: 9 } };
  private myDatePickerOptions: IMyDpOptions = {
    // other options...
    dateFormat: 'yyyy-mm-dd',
    markCurrentDay:true,
    todayBtnTxt:'Today',

  };

  constructor(private agentService: AgentService,private _logger: Logger) {

  }
  ngOnInit() {
    //initiate current date
    this.initiateDate();
    this.agentService.getAgents(this.role).then(
      (data) =>{

        if(data.data != null){
          this._logger.debug("AgentComponent:agent List response",data);
          console.log(data.data);
          if(data.data[0] != null){
            this.agents = data.data[0].Resources;

            console.log(this.agents);
          }

        }
        else {
          this._logger.debug("error","network network error");
        }

      }
    );
  }

  initiateDate(){
     let date  = new Date();
     var currentdate ={
        date:{
          year : date.getFullYear(),
          month :date.getMonth()+1,
          day : date.getDate()

        }

      }
    this.selectedDateFrom = currentdate;
    this.selectedDateTo = currentdate;
    this.fromdate.year = currentdate.date.year;
    this.fromdate.month = currentdate.date.month;
    this.fromdate.day = currentdate.date.day;
    this.todate.year = currentdate.date.year;
    this.todate.month = currentdate.date.month;
    this.todate.day = currentdate.date.day;

  }

  showQrcode(merchant:Merchant){

    this.merchantId=merchant.merchantId;
    this.merchantqrcode = true;
  }
  onDateChangedTo(event: IMyDateModel) {

      this.todate =  event.date;
    this.selectedDateTo = event;

  }
  onDateChangedFrom(event: IMyDateModel) {

    this.fromdate = event.date;
    this.selectedDateFrom = event;
    console.log(event.date);

  }
   selectType(){
    this._logger.error('This is a priority level 1 error message...'+this.type);
    this._logger.debug('tyoe ',""+this.type)
  }

  getAgentTransaction(){
    this.loading = true;
    this.transctionInfo=false;
    this.transctionError =false;
    this.filterdata = [];

    if(+this.type == 0){
      this.nextDate();
      this.getByDateToDate()

    }
    if(+this.type == 1){
      this.getByDateToDate()
    }

  }
  filterDate(){

    if(+this.type == 0){

      this.day = true;
      this.daytoday =false;

    }
    if(+this.type == 1){

      this.day = true;
      this.daytoday =true;
    }

  }
  getByDateToDate(){
    console.log(this.fromdate);
    console.log(this.todate);
    this.agentService.getAgentTransactionByDateToDate(this.agentId,this.fromdate,this.todate).then((data) => {

      if(data.data.length==0){
        this.infomassage = "Transaction not avilable";
        this.transctionInfo = true;
      }
      else if(data.data != null){
        this.data = data.data;
        this.filterdata = this.data;

      }
      else {
        if(data.errors != null){
          this.errormassage = data.errors[0].source.title;
          this.transctionError = true;
        }

      }
      this.loading = false;
    });

  }

  nextDate(){
    console.log(this.fromdate);
    var date = new Date(this.fromdate.year,+this.fromdate.month-1,this.fromdate.day);
    date.setDate(date.getDate()+1);
    this.todate.year = date.getFullYear();
    this.todate.month = date.getMonth()+1;
    this.todate.day = date.getDate();

  }

}


text:
package org.apache.syncope.core.persistence.jpa.entity.task;

import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.apache.syncope.core.persistence.api.entity.task.PushTask;
import org.apache.syncope.core.persistence.api.entity.task.SchedTask;
import org.apache.syncope.core.persistence.api.entity.task.TaskExec;

@Entity
@Table(name = JPAPushTaskExec.TABLE)
public class JPAPushTaskExec extends AbstractTaskExec<SchedTask> implements TaskExec<SchedTask> {

    private static final long serialVersionUID = 1909033231464074554L;

    public static final String TABLE = "PushTaskExec";

    @ManyToOne(optional = false)
    private JPAPushTask task;

    @Override
    public PushTask getTask() {
        return task;
    }

    @Override
    public void setTask(final SchedTask task) {
        checkType(task, PushTask.class);
        this.task = (JPAPushTask) task;
    }
}


text:
class PleasantLawyer

  ADJECTIVES = File.read(File.expand_path('../../adjectives.txt', __FILE__)).split("\n")
  NOUNS = File.read(File.expand_path('../../nouns.txt', __FILE__)).split("\n")
  WORD_LIST_SIZE = NOUNS.length

  def self.convert(text)
    if text.to_i > 0
      number_to_words text.to_i
    else
      words_to_number *text.downcase.split(' ')
    end
  end

  def self.number_to_words(n)
    div, mod = (n-1).divmod(WORD_LIST_SIZE)
    numbers = [mod, (mod + div) % WORD_LIST_SIZE]
    [ADJECTIVES[numbers[0]], NOUNS[numbers[1]]]
  end

  def self.words_to_number(adjective, noun)
    adjective_index = ADJECTIVES.index{|word| word[0..2] == adjective[0..2]}
    noun_index = NOUNS.index{|word| word[0..2] == noun[0..2]}
    return 0 unless noun_index && adjective_index
    ((noun_index - adjective_index) % WORD_LIST_SIZE ) * WORD_LIST_SIZE + adjective_index + 1
  end

end


text:
<?php
# MantisConnect - A webservice interface to Mantis Bug Tracker
# Copyright (C) 2004-2014  Victor Boctor - vboctor@users.sourceforge.net
# This program is distributed under dual licensing.  These include
# GPL and a commercial licenses.  Victor Boctor reserves the right to
# change the license of future releases.
# See docs/ folder for more details

function mci_account_get_array_by_id( $p_user_id ) {
	$t_result = array();
	$t_result['id'] = $p_user_id;

	if( user_exists( $p_user_id ) ) {

		$t_current_user_id = auth_get_current_user_id();
		$t_access_level = user_get_field ( $t_current_user_id, 'access_level' );
		$t_can_manage = access_has_global_level( config_get( 'manage_user_threshold' ) ) &&
			access_has_global_level( $t_access_level );

		# this deviates from the behaviour of view_user_page.php, but it is more intuitive
		$t_is_same_user = $t_current_user_id === $p_user_id;

		$t_can_see_realname = access_has_project_level( config_get( 'show_user_realname_threshold' ) );
		$t_can_see_email = access_has_project_level( config_get( 'show_user_email_threshold' ) );

		$t_result['name'] = user_get_field( $p_user_id, 'username' );

		if ( $t_is_same_user || $t_can_manage || $t_can_see_realname ) {
			$t_realname = user_get_realname( $p_user_id );

			if( !empty( $t_realname ) ) {
				$t_result['real_name'] = $t_realname;
			}
		}

		if ( $t_is_same_user || $t_can_manage || $t_can_see_email ) {
			$t_email = user_get_email( $p_user_id );

			if( !empty( $t_email ) ) {
				$t_result['email'] = $t_email;
			}
		}
	}
	return $t_result;
}

function mci_account_get_array_by_ids ( $p_user_ids ) {

    $t_result = array();

    foreach ( $p_user_ids as $t_user_id ) {
        $t_result[] = mci_account_get_array_by_id( $t_user_id );
    }

    return $t_result;
}


text:
import {Action, AmpStoryStoreService} from '../amp-story-store-service';
import {ProgressBar} from '../progress-bar';
import {Services} from '../../../../src/services';
import {SystemLayer} from '../amp-story-system-layer';
import {registerServiceBuilder} from '../../../../src/service';

const NOOP = () => {};

describes.fakeWin('amp-story system layer', {amp: true}, env => {
  let win;
  let storeService;
  let systemLayer;
  let progressBarStub;
  let progressBarRoot;

  beforeEach(() => {
    win = env.win;

    storeService = new AmpStoryStoreService(win);
    registerServiceBuilder(win, 'story-store', () => storeService);

    progressBarRoot = win.document.createElement('div');

    progressBarStub = {
      build: sandbox.stub().returns(progressBarRoot),
      getRoot: sandbox.stub().returns(progressBarRoot),
      setActiveSegmentId: sandbox.spy(),
      updateProgress: sandbox.spy(),
    };

    sandbox.stub(ProgressBar, 'create').returns(progressBarStub);

    sandbox.stub(Services, 'vsyncFor').returns({
      mutate: fn => fn(),
    });

    systemLayer = new SystemLayer(win);
  });

  it('should build UI', () => {
    const initializeListeners =
        sandbox.stub(systemLayer, 'initializeListeners_').callsFake(NOOP);

    const root = systemLayer.build();

    expect(root).to.not.be.null;

    expect(initializeListeners).to.have.been.called;
  });

  // TODO(alanorozco, #12476): Make this test work with sinon 4.0.
  it.skip('should attach event handlers', () => {
    const rootMock = {addEventListener: sandbox.spy()};

    sandbox.stub(systemLayer, 'root_').callsFake(rootMock);
    sandbox.stub(systemLayer, 'win_').callsFake(rootMock);

    systemLayer.initializeListeners_();

    expect(rootMock.addEventListener).to.have.been.calledWith('click');
  });

  it('should set the active page index', () => {
    [0, 1, 2, 3, 4].forEach(index => {
      systemLayer.setActivePageId(index);
      progressBarStub.setActiveSegmentId.should.have.been.calledWith(index);
    });
  });

  it('should set an attribute to toggle the UI when an ad is shown', () => {
    systemLayer.build();
    storeService.dispatch(Action.TOGGLE_AD, true);

    expect(systemLayer.getShadowRoot()).to.have.attribute('ad-showing');
  });
});


text:
CFYMailgun
==========

CFYMailgun is an Objective-C wrapper for the Mailgun API.


text:
var app = angular.module('app', ['ngRoute','routeStyles','ngCookies','matchMedia','angularRipple']);

// configure our routes
app.config(function($routeProvider) {
	$routeProvider
		.when('/', {
			templateUrl : 'app/home/home.html',
			controller  : 'homeController',
		})
		.when('/categories', {
			templateUrl : 'app/categories/categories.html',
			controller  : 'categoriesController'
		})
		.when('/categories-filter/:category_id', {
			templateUrl : 'app/categories-filter/categories-filter.html',
			controller  : 'categoriesFilterController'
		})
		.when('/trend', {
			templateUrl : 'app/trend/trend.html',
			controller  : 'trendController'
		})
		.when('/login', {
			templateUrl : 'app/login/login.html',
			controller  : 'apploginController',
		})
		.when('/sign-up', {
			templateUrl : 'app/sign-up/sign-up.html',
			controller  : 'appsignUpController',
		})
		.when('/single-view/:event_id', {
			templateUrl : 'app/single-view/single-view.html',
			controller  : 'appsingleViewController',
		})
		.when('/map-view/:host_id', {
			templateUrl : 'app/map-view/map-view.html',
			controller  : 'appmapViewController',
		})
		.when('/settings', {
			templateUrl : 'app/locale-settings/locale-settings.html',
			controller  : 'appsettingsController'
		})
		.when('/cms-home', {
			templateUrl : 'app/cms/cmshome/cmshome.html',
			controller  : 'cmshomeController',
			css : 'app/cms/cmshome/cmshome.css'
		})
		.when('/categoriesadmin', {
			templateUrl : 'app/cms/categories-admin/categories-admin.html',
			controller  : 'categoriesadminController'
		})
		.when('/add-categories-admin', {
			templateUrl : 'app/cms/add-categories-admin/add-categories-admin.html',
			controller  : 'addcategoriesadminController'
		})
		.when('/edit-categories-admin/:category_id', {
			templateUrl : 'app/cms/edit-categories-admin/edit-categories-admin.html',
			controller  : 'editcategoriesadminController'
		})
		.when('/locale-admin', {
			templateUrl : 'app/cms/locale-admin/locale-admin.html',
			controller  : 'localeadminController'
		})
		.when('/host-admin', {
			templateUrl : 'app/cms/host-admin/host-admin.html',
			controller  : 'hostadminController'
		})
		.when('/add-locale-admin', {
			templateUrl : 'app/cms/add-locale-admin/add-locale-admin.html',
			controller  : 'addLocaleadminController'
		})
		.when('/add-locale-user', {
			templateUrl : 'app/cms/add-locale-user/add-locale-user.html',
			controller  : 'addLocaleuserController'
		})
		.when('/add-host-admin', {
			templateUrl : 'app/cms/add-host-admin/add-host-admin.html',
			controller  : 'addHostadminController'
		})
		.when('/edit-host-admin/:host_id', {
			templateUrl : 'app/cms/edit-host-admin/edit-host-admin.html',
			controller  : 'editHostadminController'
		})
		.when('/event-list-admin', {
			templateUrl : 'app/cms/event-list-admin/event-list-admin.html',
			controller  : 'eventListadminController'
		})
		.when('/edit-locale-admin/:locale_admin', {
			templateUrl : 'app/cms/edit-locale-admin/edit-locale-admin.html',
			controller  : 'editLocaleadminController'
		})
		.when('/edit-locale-user/:locale_user', {
			templateUrl : 'app/cms/edit-locale-user/edit-locale-user.html',
			controller  : 'editLocaleuserController'
		})
		.when('/add-event-admin', {
			templateUrl : 'app/cms/add-event-admin/add-event-admin.html',
			controller  : 'addEventadminController'
		})
		.when('/edit-event-admin/:event_id', {
			templateUrl : 'app/cms/edit-event-admin/edit-event-admin.html',
			controller  : 'editEventadminController'
		})
		.when('/locale-user', {
			templateUrl : 'app/cms/locale-user/locale-user.html',
			controller  : 'localeUserController'
		})
		.when('/event-host', {
			templateUrl : 'app/cms/event-host/event-host.html',
			controller  : 'eventHostController'
		})
		.when('/add-event-host', {
			templateUrl : 'app/cms/add-event-host/add-event-host.html',
			controller  : 'addEventHostController'
		})
		.when('/edit-event-host/:host_id', {
			templateUrl : 'app/cms/edit-event-host/edit-event-host.html',
			controller  : 'editEventHostController'
		})
		.when('/cyd_test', {
			templateUrl : 'app/cyd_test/cyd_test.html',
			controller  : 'cydTestController'
		})
		.when('/cyd_map', {
			templateUrl : 'app/cyd_map/cyd_map.html',
			controller  : 'cydMapController'
		});
});

app.directive('head', ['$rootScope','$compile',
function($rootScope, $compile){
	return {
		restrict: 'E',
		link: function(scope, elem){
			var html = '<link rel="stylesheet" ng-repeat="(routeCtrl, cssUrl) in routeStyles" ng-href="{{cssUrl}}" >';
			elem.append($compile(html)(scope));
			scope.routeStyles = {};
			$rootScope.$on('$routeChangeStart', function (e, next) {
				if(next && next.$$route && next.$$route.css){
					if(!angular.isArray(next.$$route.css)){
						next.$$route.css = [next.$$route.css];
					}
					angular.forEach(next.$$route.css, function(sheet){
						scope.routeStyles[sheet] = sheet;
					});
				}
			});
			$rootScope.$on('$routeChangeSuccess', function(e, current, previous) {
				if (previous && previous.$$route && previous.$$route.css) {
					if (!angular.isArray(previous.$$route.css)) {
						previous.$$route.css = [previous.$$route.css];
					}
					angular.forEach(previous.$$route.css, function (sheet) {
						scope.routeStyles[sheet] = undefined;
					});
				}
			});
		}
	};
}
]);


text:
<!DOCTYPE html>

    <input type="text" id="one" disabled="disabled"/>
    Should be no red

    Should be no red

    <input type="text" id="two"/>
    Should be no red


text:
package io.machinecode.chainlink.core.util;

import java.util.List;
import java.util.ListIterator;

/**
* @author Brent Douglas
* @since 1.0
*/
public final class Transmute {

    public static <V, X extends Mutable<V>> X item(final X to, final V from, final Creator<X> creator, final Op... ops) throws Exception {
        if (from == null) {
            if (Op.REMOVE.isActive(ops)) {
                return null;
            }
        } else if (to == null) {
            if (Op.ADD.isActive(ops)) {
                final X x = creator.create();
                x.accept(from);
                return x;
            }
        } else {
            if (Op.UPDATE.isActive(ops)) {
                to.accept(from);
            }
        }
        return to;
    }

    public static <V, X extends Mutable<V>> List<X> list(final List<X> to, final List<? extends V> from, final Creator<X> creator, final Op... ops) throws Exception {
        final ListIterator<X> it = to.listIterator();
        outer: while (it.hasNext()) {
            final X t = it.next();
            for (final V f : from) {
                if (t.willAccept(f)) {
                    if (Op.UPDATE.isActive(ops)) {
                        t.accept(f);
                    }
                    continue outer;
                }
            }
            if (Op.REMOVE.isActive(ops)) {
                it.remove();
            }
        }
        outer: for (final V f : from) {
            for (final X t : to) {
                if (t.willAccept(f)) {
                    if (Op.UPDATE.isActive(ops)) {
                        t.accept(f);
                    }
                    continue outer;
                }
            }
            if (Op.ADD.isActive(ops)) {
                final X x = creator.create();
                x.accept(f);
                to.add(x);
            }
        }
        return to;
    }

    public static <V,X> List<X> list(final List<X> to, final List<? extends V> from, final Copy.Transformer<V,X> transformer, final Op... ops) throws Exception {
        final ListIterator<X> it = to.listIterator();
        outer: while (it.hasNext()) {
            final X t = it.next();
            for (final V f : from) {
                if (t.equals(transformer.transform(f))) {
                    continue outer;
                }
            }
            if (Op.REMOVE.isActive(ops)) {
                it.remove();
            }
        }
        outer: for (final V f : from) {
            for (final X t : to) {
                if (t.equals(transformer.transform(f))) {
                    continue outer;
                }
            }
            if (Op.ADD.isActive(ops)) {
                to.add(transformer.transform(f));
            }
        }
        return to;
    }
}


text:
<?php namespace Forma\Tags;

use Forma\Interfaces\TagInterface;
use \DOMDocument;
use \Input;

class BaseTag implements TagInterface
{

    protected $tagName;
    protected $hasValue = false;
    protected $attributes = array();
    protected $childTags = array();
    protected $text;
    protected $rawText = false;

    // Allow traits to add additional processing
    protected $preRenders = array();
    protected $postRenders = array();

    public function render()
    {
        $tagString = '';

        // Pre-Renders
        foreach ($this->preRenders as $func)
        {
            $tagString .= $this->{$func}();
        }

        $tagString .= "<".$this->tagName;

        // Determine value??
        if ($this->hasValue and isset($this->attributes['name']))
        {
            // Try this request first
            if (\Forma\Helpers::input($this->attributes['name']))
            {
                $this->attributes['value'] = \Forma\Helpers::input($this->attributes['name']);
            }

            // Old input
            if (\Forma\Helpers::inputOld($this->attributes['name']))
            {
                $this->attributes['value'] = \Forma\Helpers::inputOld($this->attributes['name']);
            }

            // Try populated values
            if (\Forma\Forma::hasValue($this->attributes['name']))
            {
                $this->attributes['value'] = \Forma\Forma::getValue($this->attributes['name']);
            }
        }

        // Attributes
        foreach ($this->attributes as $a => $v)
        {
            if ($v !== null)
                $tagString .= " " . $a . "=\"" . $this->encode($v) . "\"";
            else
                $tagString .= " " . $a;
        }

        // End start tag
        $tagString .= ">";

        // Child tags
        if (count($this->childTags))
        {
            foreach ($this->childTags as $t)
                $tagString .= $t;

            // Create end tag
            $tagString .= "</".$this->tagName.">";
        }
        elseif (isset($this->text))
        {
            $tagString .= $this->rawText ? $this->text : $this->encode($this->text);

            // Create end tag
            $tagString .= "</".$this->tagName.">";
        }

        // Post-Renders
        foreach ($this->postRenders as $func)
        {
            $tagString .= $this->{$func}();
        }

        return $tagString;
    }

    /**
     * So we can have a method called "class" :-)
     */
    public function __call($name, $arguments)
    {
        if ($name == "class")
        {
            return call_user_func_array(array(__NAMESPACE__ .'\BaseTag', 'addClass'), $arguments);
        }
    }

    public function addClass($class_name)
    {
        if (!isset($this->attributes['class']))
            $this->attributes['class'] = '';

        $this->attributes['class'] .= $class_name . " ";
        return $this;
    }

    public function attr($key,$value)
    {
        $this->attributes[$key] = $value;
        return $this;
    }

    public function attribs($attributes)
    {
        $this->attributes = $attributes;
        return $this;
    }

    public function id($value)
    {
        $this->attributes['id'] = $value;
        return $this;
    }

    public function forceEmpty()
    {
        unset($this->attributes['value']);
        $this->hasValue = false;
        return $this;
    }

    public function allowValue()
    {
        $this->hasValue = true;
        return $this;
    }

    public function child($tag)
    {
        $this->childTags[] = $tag;
        return $this;
    }

    public function __toString()
    {
        return $this->render();
    }

    public function rawText()
    {
        $this->rawText = true;
        return $this;
    }

    protected function encode($string)
    {
        return trim(htmlentities($string, ENT_QUOTES, 'UTF-8', false));
    }

}


text:
require 'spec_helper'

describe 'postgresql::server::tablespace', :type => :define do
  let :facts do
    {
      :osfamily => 'Debian',
      :operatingsystem => 'Debian',
      :operatingsystemrelease => '6.0',
      :kernel => 'Linux',
      :concat_basedir => tmpfilename('tablespace'),
      :id => 'root',
      :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin',
    }
  end

  let :title do
    'test'
  end

  let :params do
    {
      :location => '/srv/data/foo',
    }
  end

  let :pre_condition do
    "class {'postgresql::server':}"
  end

  it { should contain_postgresql__server__tablespace('test') }
end


text:
class Umbrella : public Weapon {
public:
    Umbrella ();
    virtual ~Umbrella ();

    virtual void OnEquip () { }
    virtual void OnUnequip () { }

    virtual void Update ();
    virtual void Render ();

    virtual void OnFire ();
    virtual void OnAlternateFire ();
    virtual void OnAlternateFire2 ();
};


text:
//
// Copyright (c) 2014 Mixpanel. All rights reserved.

#import "Mixpanel.h"
#import "MPABTestDesignerChangeRequestMessage.h"
#import "MPABTestDesignerClearRequestMessage.h"
#import "MPABTestDesignerConnection.h"
#import "MPABTestDesignerDeviceInfoRequestMessage.h"
#import "MPABTestDesignerDisconnectMessage.h"
#import "MPABTestDesignerMessage.h"
#import "MPABTestDesignerSnapshotRequestMessage.h"
#import "MPABTestDesignerSnapshotResponseMessage.h"
#import "MPABTestDesignerTweakRequestMessage.h"
#import "MPDesignerEventBindingMessage.h"
#import "MPDesignerSessionCollection.h"
#import "MPLogger.h"
#import "MPSwizzler.h"

NSString * const kSessionVariantKey = @"session_variant";

@interface MPABTestDesignerConnection () <MPWebSocketDelegate>

@end

@implementation MPABTestDesignerConnection

{
    /* The difference between _open and _connected is that open
     is set when the socket is open, and _connected is set when
     we actually have started sending/receiving messages from
     the server. A connection can become _open/not _open in quick
     succession if the websocket proxy rejects the request, but
     we will only try and reconnect if we were actually _connected.
     */
    BOOL _open;
    BOOL _connected;

    NSURL *_url;
    NSMutableDictionary *_session;
    NSDictionary *_typeToMessageClassMap;
    MPWebSocket *_webSocket;
    NSOperationQueue *_commandQueue;
    UIView *_recordingView;
    void (^_connectCallback)();
    void (^_disconnectCallback)();
}

- (instancetype)initWithURL:(NSURL *)url keepTrying:(BOOL)keepTrying connectCallback:(void (^)())connectCallback disconnectCallback:(void (^)())disconnectCallback
{
    self = [super init];
    if (self) {
        _typeToMessageClassMap = @{
            MPABTestDesignerSnapshotRequestMessageType   : [MPABTestDesignerSnapshotRequestMessage class],
            MPABTestDesignerChangeRequestMessageType     : [MPABTestDesignerChangeRequestMessage class],
            MPABTestDesignerDeviceInfoRequestMessageType : [MPABTestDesignerDeviceInfoRequestMessage class],
            MPABTestDesignerTweakRequestMessageType      : [MPABTestDesignerTweakRequestMessage class],
            MPABTestDesignerClearRequestMessageType      : [MPABTestDesignerClearRequestMessage class],
            MPABTestDesignerDisconnectMessageType        : [MPABTestDesignerDisconnectMessage class],
            MPDesignerEventBindingRequestMessageType     : [MPDesignerEventBindingRequestMesssage class],
        };

        _open = NO;
        _connected = NO;
        _sessionEnded = NO;
        _session = [[NSMutableDictionary alloc] init];
        _url = url;
        _connectCallback = connectCallback;
        _disconnectCallback = disconnectCallback;

        _commandQueue = [[NSOperationQueue alloc] init];
        _commandQueue.maxConcurrentOperationCount = 1;
        _commandQueue.suspended = YES;

        if (keepTrying) {
            [self open:YES maxInterval:30 maxRetries:40];
        } else {
            [self open:YES maxInterval:0 maxRetries:0];
        }
    }

    return self;
}

- (instancetype)initWithURL:(NSURL *)url
{
    return [self initWithURL:url keepTrying:NO connectCallback:nil disconnectCallback:nil];
}

- (void)open:(BOOL)initiate maxInterval:(int)maxInterval maxRetries:(int)maxRetries
{
    static int retries = 0;
    BOOL inRetryLoop = retries > 0;

    MessagingDebug(@"In open. initiate = %d, retries = %d, maxRetries = %d, maxInterval = %d, connected = %d", initiate, retries, maxRetries, maxInterval, _connected);

    if (self.sessionEnded || _connected || (inRetryLoop && retries >= maxRetries) ) {
        // break out of retry loop if any of the success conditions are met.
        retries = 0;
    } else if (initiate ^ inRetryLoop) {
        // If we are initiating a new connection, or we are already in a
        // retry loop (but not both). Then open a socket.
        if (!_open) {
            MessagingDebug(@"Attempting to open WebSocket to: %@, try %d/%d ", _url, retries, maxRetries);
            _open = YES;
            _webSocket = [[MPWebSocket alloc] initWithURL:_url];
            _webSocket.delegate = self;
            [_webSocket open];
        }
        if (retries < maxRetries) {
            __weak MPABTestDesignerConnection *weakSelf = self;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(MIN(pow(1.4, retries), maxInterval) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                MPABTestDesignerConnection *strongSelf = weakSelf;
                [strongSelf open:NO maxInterval:maxInterval maxRetries:maxRetries];
            });
            retries++;
        }
    }
}

- (void)close
{
    [_webSocket close];
    for (NSString *key in [_session keyEnumerator]) {
        id value = [_session valueForKey:key];
        if ([value conformsToProtocol:@protocol(MPDesignerSessionCollection)]) {
            [value cleanup];
        }
    }
    _session = nil;
}

- (void)dealloc
{
    _webSocket.delegate = nil;
    [self close];
}

- (void)setSessionObject:(id)object forKey:(NSString *)key
{
    NSParameterAssert(key != nil);

    @synchronized (_session)
    {
        _session[key] = object ?: [NSNull null];
    }
}

- (id)sessionObjectForKey:(NSString *)key
{
    NSParameterAssert(key != nil);

    @synchronized (_session)
    {
        id object = _session[key];
        return [object isEqual:[NSNull null]] ? nil : object;
    }
}

- (void)sendMessage:(id<MPABTestDesignerMessage>)message
{
    if (_connected) {
        MessagingDebug(@"Sending message: %@", [message debugDescription]);
        NSString *jsonString = [[NSString alloc] initWithData:[message JSONData] encoding:NSUTF8StringEncoding];
        [_webSocket send:jsonString];
    } else {
        MessagingDebug(@"Not sending message as we are not connected: %@", [message debugDescription]);
    }
}

- (id <MPABTestDesignerMessage>)designerMessageForMessage:(id)message
{
    MessagingDebug(@"raw message: %@", message);

    NSParameterAssert([message isKindOfClass:[NSString class]] || [message isKindOfClass:[NSData class]]);

    id <MPABTestDesignerMessage> designerMessage = nil;

    NSData *jsonData = [message isKindOfClass:[NSString class]] ? [(NSString *)message dataUsingEncoding:NSUTF8StringEncoding] : message;

    NSError *error = nil;
    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
    if ([jsonObject isKindOfClass:[NSDictionary class]]) {
        NSDictionary *messageDictionary = (NSDictionary *)jsonObject;
        NSString *type = messageDictionary[@"type"];
        NSDictionary *payload = messageDictionary[@"payload"];

        designerMessage = [_typeToMessageClassMap[type] messageWithType:type payload:payload];
    } else {
        MessagingDebug(@"Badly formed socket message expected JSON dictionary: %@", error);
    }

    return designerMessage;
}

#pragma mark - MPWebSocketDelegate Methods

- (void)webSocket:(MPWebSocket *)webSocket didReceiveMessage:(id)message
{
    if (!_connected) {
        _connected = YES;
        [self showConnectedView];
        if (_connectCallback) {
            _connectCallback();
        }
    }
    id<MPABTestDesignerMessage> designerMessage = [self designerMessageForMessage:message];
    MessagingDebug(@"WebSocket received message: %@", [designerMessage debugDescription]);

    NSOperation *commandOperation = [designerMessage responseCommandWithConnection:self];

    if (commandOperation) {
        [_commandQueue addOperation:commandOperation];
    }
}

- (void)webSocketDidOpen:(MPWebSocket *)webSocket
{
    MessagingDebug(@"WebSocket %@ did open.", webSocket);
    _commandQueue.suspended = NO;
}

- (void)webSocket:(MPWebSocket *)webSocket didFailWithError:(NSError *)error
{
    MessagingDebug(@"WebSocket did fail with error: %@", error);
    _commandQueue.suspended = YES;
    [_commandQueue cancelAllOperations];
    [self hideConnectedView];
    _open = NO;
    if (_connected) {
        _connected = NO;
        [self open:YES maxInterval:10 maxRetries:10];
        if (_disconnectCallback) {
            _disconnectCallback();
        }
    }
}

- (void)webSocket:(MPWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean
{
    MessagingDebug(@"WebSocket did close with code '%d' reason '%@'.", (int)code, reason);

    _commandQueue.suspended = YES;
    [_commandQueue cancelAllOperations];
    [self hideConnectedView];
    _open = NO;
    if (_connected) {
        _connected = NO;
        [self open:YES maxInterval:10 maxRetries:10];
        if (_disconnectCallback) {
            _disconnectCallback();
        }
    }
}

- (void)showConnectedView
{
    if(!_recordingView) {
        UIWindow *mainWindow = [[UIApplication sharedApplication] delegate].window;
        _recordingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, mainWindow.frame.size.width, 1.0)];
        _recordingView.backgroundColor = [UIColor colorWithRed:4/255.0f green:180/255.0f blue:4/255.0f alpha:1.0];
        [mainWindow addSubview:_recordingView];
        [mainWindow bringSubviewToFront:_recordingView];
    }
}

- (void)hideConnectedView
{
    if (_recordingView) {
        [_recordingView removeFromSuperview];
    }
    _recordingView = nil;
}

@end


text:
from xml.dom import minidom

import mock
import webob
import webob.dec
import webob.exc

import nova.api.openstack
from nova.api.openstack import common
from nova.api.openstack import wsgi
from nova import exception
from nova.openstack.common import gettextutils
from nova.openstack.common import jsonutils
from nova import test

class TestFaultWrapper(test.NoDBTestCase):
    """Tests covering `nova.api.openstack:FaultWrapper` class."""

    @mock.patch('nova.openstack.common.gettextutils.get_localized_message')
    def test_safe_exception_translated(self, mock_get_localized):
        msg = gettextutils.Message('Should be translated.', 'nova')
        safe_exception = exception.NotFound()
        safe_exception.msg_fmt = msg
        safe_exception.safe = True
        safe_exception.code = 404

        req = webob.Request.blank('/')

        def fake_translate(mesg, locale):
            if str(mesg) == "Should be translated.":
                return "I've been translated!"
            return mesg

        mock_get_localized.side_effect = fake_translate

        def raiser(*args, **kwargs):
            raise safe_exception

        wrapper = nova.api.openstack.FaultWrapper(raiser)
        response = req.get_response(wrapper)

        self.assertIn("I've been translated!", unicode(response.body))
        mock_get_localized.assert_any_call(
                u'Should be translated.', None)

class TestFaults(test.NoDBTestCase):
    """Tests covering `nova.api.openstack.faults:Fault` class."""

    def _prepare_xml(self, xml_string):
        """Remove characters from string which hinder XML equality testing."""
        xml_string = xml_string.replace("  ", "")
        xml_string = xml_string.replace("\n", "")
        xml_string = xml_string.replace("\t", "")
        return xml_string

    def test_400_fault_json(self):
        # Test fault serialized to JSON via file-extension and/or header.
        requests = [
            webob.Request.blank('/.json'),
            webob.Request.blank('/', headers={"Accept": "application/json"}),
        ]

        for request in requests:
            fault = wsgi.Fault(webob.exc.HTTPBadRequest(explanation='scram'))
            response = request.get_response(fault)

            expected = {
                "badRequest": {
                    "message": "scram",
                    "code": 400,
                },
            }
            actual = jsonutils.loads(response.body)

            self.assertEqual(response.content_type, "application/json")
            self.assertEqual(expected, actual)

    def test_413_fault_json(self):
        # Test fault serialized to JSON via file-extension and/or header.
        requests = [
            webob.Request.blank('/.json'),
            webob.Request.blank('/', headers={"Accept": "application/json"}),
        ]

        for request in requests:
            exc = webob.exc.HTTPRequestEntityTooLarge
            # NOTE(aloga): we intentionally pass an integer for the
            # 'Retry-After' header. It should be then converted to a str
            fault = wsgi.Fault(exc(explanation='sorry',
                        headers={'Retry-After': 4}))
            response = request.get_response(fault)

            expected = {
                "overLimit": {
                    "message": "sorry",
                    "code": 413,
                    "retryAfter": "4",
                },
            }
            actual = jsonutils.loads(response.body)

            self.assertEqual(response.content_type, "application/json")
            self.assertEqual(expected, actual)

    def test_429_fault_json(self):
        # Test fault serialized to JSON via file-extension and/or header.
        requests = [
            webob.Request.blank('/.json'),
            webob.Request.blank('/', headers={"Accept": "application/json"}),
        ]

        for request in requests:
            exc = webob.exc.HTTPTooManyRequests
            # NOTE(aloga): we intentionally pass an integer for the
            # 'Retry-After' header. It should be then converted to a str
            fault = wsgi.Fault(exc(explanation='sorry',
                        headers={'Retry-After': 4}))
            response = request.get_response(fault)

            expected = {
                "overLimit": {
                    "message": "sorry",
                    "code": 429,
                    "retryAfter": "4",
                },
            }
            actual = jsonutils.loads(response.body)

            self.assertEqual(response.content_type, "application/json")
            self.assertEqual(expected, actual)

    def test_raise(self):
        # Ensure the ability to raise :class:`Fault` in WSGI-ified methods.
        @webob.dec.wsgify
        def raiser(req):
            raise wsgi.Fault(webob.exc.HTTPNotFound(explanation='whut?'))

        req = webob.Request.blank('/.xml')
        resp = req.get_response(raiser)
        self.assertEqual(resp.content_type, "application/xml")
        self.assertEqual(resp.status_int, 404)
        self.assertIn('whut?', resp.body)

    def test_raise_403(self):
        # Ensure the ability to raise :class:`Fault` in WSGI-ified methods.
        @webob.dec.wsgify
        def raiser(req):
            raise wsgi.Fault(webob.exc.HTTPForbidden(explanation='whut?'))

        req = webob.Request.blank('/.xml')
        resp = req.get_response(raiser)
        self.assertEqual(resp.content_type, "application/xml")
        self.assertEqual(resp.status_int, 403)
        self.assertNotIn('resizeNotAllowed', resp.body)
        self.assertIn('forbidden', resp.body)

    def test_raise_localize_explanation(self):
        msgid = "String with params: %s"
        params = ('blah', )
        lazy_gettext = gettextutils._
        expl = lazy_gettext(msgid) % params

        @webob.dec.wsgify
        def raiser(req):
            raise wsgi.Fault(webob.exc.HTTPNotFound(explanation=expl))

        req = webob.Request.blank('/.xml')
        resp = req.get_response(raiser)
        self.assertEqual(resp.content_type, "application/xml")
        self.assertEqual(resp.status_int, 404)
        self.assertIn((msgid % params), resp.body)

    def test_fault_has_status_int(self):
        # Ensure the status_int is set correctly on faults.
        fault = wsgi.Fault(webob.exc.HTTPBadRequest(explanation='what?'))
        self.assertEqual(fault.status_int, 400)

    def test_xml_serializer(self):
        # Ensure that a v1.1 request responds with a v1.1 xmlns.
        request = webob.Request.blank('/v1.1',
                                      headers={"Accept": "application/xml"})

        fault = wsgi.Fault(webob.exc.HTTPBadRequest(explanation='scram'))
        response = request.get_response(fault)

        self.assertIn(common.XML_NS_V11, response.body)
        self.assertEqual(response.content_type, "application/xml")
        self.assertEqual(response.status_int, 400)

class FaultsXMLSerializationTestV11(test.NoDBTestCase):
    """Tests covering `nova.api.openstack.faults:Fault` class."""

    def _prepare_xml(self, xml_string):
        xml_string = xml_string.replace("  ", "")
        xml_string = xml_string.replace("\n", "")
        xml_string = xml_string.replace("\t", "")
        return xml_string

    def test_400_fault(self):
        metadata = {'attributes': {"badRequest": 'code'}}
        serializer = wsgi.XMLDictSerializer(metadata=metadata,
                                            xmlns=common.XML_NS_V11)

        fixture = {
            "badRequest": {
                "message": "scram",
                "code": 400,
            },
        }

        output = serializer.serialize(fixture)
        actual = minidom.parseString(self._prepare_xml(output))

        expected = minidom.parseString(self._prepare_xml("""
                <badRequest code="400" xmlns="%s">
                    <message>scram</message>
                </badRequest>
            """) % common.XML_NS_V11)

        self.assertEqual(expected.toxml(), actual.toxml())

    def test_413_fault(self):
        metadata = {'attributes': {"overLimit": 'code'}}
        serializer = wsgi.XMLDictSerializer(metadata=metadata,
                                            xmlns=common.XML_NS_V11)

        fixture = {
            "overLimit": {
                "message": "sorry",
                "code": 413,
                "retryAfter": 4,
            },
        }

        output = serializer.serialize(fixture)
        actual = minidom.parseString(self._prepare_xml(output))

        expected = minidom.parseString(self._prepare_xml("""
                <overLimit code="413" xmlns="%s">
                    <message>sorry</message>
                    <retryAfter>4</retryAfter>
                </overLimit>
            """) % common.XML_NS_V11)

        self.assertEqual(expected.toxml(), actual.toxml())

    def test_429_fault(self):
        metadata = {'attributes': {"overLimit": 'code'}}
        serializer = wsgi.XMLDictSerializer(metadata=metadata,
                                            xmlns=common.XML_NS_V11)

        fixture = {
            "overLimit": {
                "message": "sorry",
                "code": 429,
                "retryAfter": 4,
            },
        }

        output = serializer.serialize(fixture)
        actual = minidom.parseString(self._prepare_xml(output))

        expected = minidom.parseString(self._prepare_xml("""
                <overLimit code="429" xmlns="%s">
                    <message>sorry</message>
                    <retryAfter>4</retryAfter>
                </overLimit>
            """) % common.XML_NS_V11)

        self.assertEqual(expected.toxml(), actual.toxml())

    def test_404_fault(self):
        metadata = {'attributes': {"itemNotFound": 'code'}}
        serializer = wsgi.XMLDictSerializer(metadata=metadata,
                                            xmlns=common.XML_NS_V11)

        fixture = {
            "itemNotFound": {
                "message": "sorry",
                "code": 404,
            },
        }

        output = serializer.serialize(fixture)
        actual = minidom.parseString(self._prepare_xml(output))

        expected = minidom.parseString(self._prepare_xml("""
                <itemNotFound code="404" xmlns="%s">
                    <message>sorry</message>
                </itemNotFound>
            """) % common.XML_NS_V11)

        self.assertEqual(expected.toxml(), actual.toxml())


text:
package org.jf.dexlib;

/**
 * Describes an object that can be converted to a different type
 */
public interface Convertible<T> {
    T convert();
}


text:
describe :kernel_send, :shared => true do
  it "invokes the named method" do
    class KernelSpecs::Foo
      def bar
        'done'
      end
    end
    KernelSpecs::Foo.new.send(@method, :bar).should == 'done'
  end

  it "invokes a class method if called on a class" do
    class KernelSpecs::Foo
      def self.bar
        'done'
      end
    end
    KernelSpecs::Foo.send(@method, :bar).should == 'done'
  end

  it "raises a NameError if the corresponding method can't be found" do
    class KernelSpecs::Foo
      def bar
        'done'
      end
    end
    lambda { KernelSpecs::Foo.new.send(@method, :syegsywhwua) }.should raise_error(NameError)
  end

  it "raises a NameError if the corresponding singleton method can't be found" do
    class KernelSpecs::Foo
      def self.bar
        'done'
      end
    end
    lambda { KernelSpecs::Foo.send(@method, :baz) }.should raise_error(NameError)
  end

  it "raises an ArgumentError if no arguments are given" do
    lambda { KernelSpecs::Foo.new.send }.should raise_error(ArgumentError)
  end

  it "raises an ArgumentError if called with more arguments than available parameters" do
    class KernelSpecs::Foo
      def bar; end
    end

    lambda { KernelSpecs::Foo.new.send(:bar, :arg) }.should raise_error(ArgumentError)
  end

  it "raises an ArgumentError if called with fewer arguments than required parameters" do
    class KernelSpecs::Foo
      def foo(arg); end
    end

    lambda { KernelSpecs::Foo.new.send(@method, :foo) }.should raise_error(ArgumentError)
  end

  it "succeeds if passed an arbitrary number of arguments as a splat parameter" do
    class KernelSpecs::Foo
      def baz(*args) args end
    end

    begin
      KernelSpecs::Foo.new.send(@method, :baz).should == []
      KernelSpecs::Foo.new.send(@method, :baz, :quux).should == [:quux]
      KernelSpecs::Foo.new.send(@method, :baz, :quux, :foo).should == [:quux, :foo]
    rescue
      fail
    end
  end

  it "succeeds when passing 1 or more arguments as a required and a splat parameter" do
    class KernelSpecs::Foo
      def foo(first, *rest) [first, *rest] end
    end

    begin
      KernelSpecs::Foo.new.send(@method, :baz, :quux).should == [:quux]
      KernelSpecs::Foo.new.send(@method, :baz, :quux, :foo).should == [:quux, :foo]
    rescue
      fail
    end
  end

  it "succeeds when passing 0 arguments to a method with one parameter with a default" do
    class KernelSpecs::Foo
      def foo(first = true) first end
    end

    begin
      KernelSpecs::Foo.new.send(@method, :foo).should == true
      KernelSpecs::Foo.new.send(@method, :foo, :arg).should == :arg
    rescue
      fail
    end
  end

  not_compliant_on :rubinius do
    # Confirm commit r24306
    it "has an arity of -1" do
      method(:__send__).arity.should == -1
    end
  end

  deviates_on :rubinius do
    it "has an arity of -2" do
      method(:__send__).arity.should == -2
    end
  end
end