text:
#include "opt_bus.h"

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/malloc.h>
#include <sys/module.h>
#include <sys/linker.h>
#include <sys/fcntl.h>
#include <sys/conf.h>
#include <sys/kernel.h>
#include <sys/queue.h>
#include <sys/sysctl.h>
#include <sys/types.h>

#include <vm/vm.h>
#include <vm/pmap.h>
#include <vm/vm_extern.h>

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

#include <sys/pciio.h>
#include <dev/pci/pcireg.h>
#include <dev/pci/pcivar.h>
#include <dev/pci/pci_private.h>

#include "pcib_if.h"
#include "pci_if.h"

static u_int32_t	pci_mapbase(unsigned mapreg);
static int		pci_maptype(unsigned mapreg);
static int		pci_mapsize(unsigned testval);
static int		pci_maprange(unsigned mapreg);
static void		pci_fixancient(pcicfgregs *cfg);
static void		pci_hdrtypedata(device_t pcib, int b, int s, int f,
					pcicfgregs *cfg);
static void		pci_read_extcap(device_t pcib, pcicfgregs *cfg);

static int		pci_porten(device_t pcib, int b, int s, int f);
static int		pci_memen(device_t pcib, int b, int s, int f);
static int		pci_add_map(device_t pcib, int b, int s, int f, int reg,
				    struct resource_list *rl);
static void		pci_add_resources(device_t pcib, device_t dev);
static int		pci_probe(device_t dev);
static int		pci_attach(device_t dev);
static void		pci_load_vendor_data(void);
static int		pci_describe_parse_line(char **ptr, int *vendor,
						int *device, char **desc);
static char		*pci_describe_device(device_t dev);
static int		pci_modevent(module_t mod, int what, void *arg);

static device_method_t pci_methods[] = {
	/* Device interface */
	DEVMETHOD(device_probe,		pci_probe),
	DEVMETHOD(device_attach,	pci_attach),
	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
	DEVMETHOD(device_suspend,	bus_generic_suspend),
	DEVMETHOD(device_resume,	bus_generic_resume),

	/* Bus interface */
	DEVMETHOD(bus_print_child,	pci_print_child),
	DEVMETHOD(bus_probe_nomatch,	pci_probe_nomatch),
	DEVMETHOD(bus_read_ivar,	pci_read_ivar),
	DEVMETHOD(bus_write_ivar,	pci_write_ivar),
	DEVMETHOD(bus_driver_added,	bus_generic_driver_added),
	DEVMETHOD(bus_setup_intr,	bus_generic_setup_intr),
	DEVMETHOD(bus_teardown_intr,	bus_generic_teardown_intr),

	DEVMETHOD(bus_get_resource_list,pci_get_resource_list),
	DEVMETHOD(bus_set_resource,	bus_generic_rl_set_resource),
	DEVMETHOD(bus_get_resource,	bus_generic_rl_get_resource),
	DEVMETHOD(bus_delete_resource,	pci_delete_resource),
	DEVMETHOD(bus_alloc_resource,	pci_alloc_resource),
	DEVMETHOD(bus_release_resource,	bus_generic_rl_release_resource),
	DEVMETHOD(bus_activate_resource, bus_generic_activate_resource),
	DEVMETHOD(bus_deactivate_resource, bus_generic_deactivate_resource),

	/* PCI interface */
	DEVMETHOD(pci_read_config,	pci_read_config_method),
	DEVMETHOD(pci_write_config,	pci_write_config_method),
	DEVMETHOD(pci_enable_busmaster,	pci_enable_busmaster_method),
	DEVMETHOD(pci_disable_busmaster, pci_disable_busmaster_method),
	DEVMETHOD(pci_enable_io,	pci_enable_io_method),
	DEVMETHOD(pci_disable_io,	pci_disable_io_method),
	DEVMETHOD(pci_get_powerstate,	pci_get_powerstate_method),
	DEVMETHOD(pci_set_powerstate,	pci_set_powerstate_method),

	{ 0, 0 }
};

static driver_t pci_driver = {
	"pci",
	pci_methods,
	0,			/* no softc */
};

devclass_t	pci_devclass;
DRIVER_MODULE(pci, pcib, pci_driver, pci_devclass, pci_modevent, 0);
MODULE_VERSION(pci, 1);

static char	*pci_vendordata;
static size_t	pci_vendordata_size;

struct pci_quirk {
	u_int32_t devid;	/* Vendor/device of the card */
	int	type;
#define PCI_QUIRK_MAP_REG	1 /* PCI map register in weird place */
	int	arg1;
	int	arg2;
};

struct pci_quirk pci_quirks[] = {
	/* The Intel 82371AB and 82443MX has a map register at offset 0x90. */
	{ 0x71138086, PCI_QUIRK_MAP_REG,	0x90,	 0 },
	{ 0x719b8086, PCI_QUIRK_MAP_REG,	0x90,	 0 },
	/* As does the Serverworks OSB4 (the SMBus mapping register) */
	{ 0x02001166, PCI_QUIRK_MAP_REG,	0x90,	 0 },

	{ 0 }
};

/* map register information */
#define PCI_MAPMEM	0x01	/* memory map */
#define PCI_MAPMEMP	0x02	/* prefetchable memory map */
#define PCI_MAPPORT	0x04	/* port map */

struct devlist pci_devq;
u_int32_t pci_generation;
u_int32_t pci_numdevs = 0;

/* sysctl vars */
SYSCTL_NODE(_hw, OID_AUTO, pci, CTLFLAG_RD, 0, "PCI bus tuning parameters");

static int pci_enable_io_modes = 1;
TUNABLE_INT("hw.pci.enable_io_modes", (int *)&pci_enable_io_modes);
SYSCTL_INT(_hw_pci, OID_AUTO, enable_io_modes, CTLFLAG_RW,
    &pci_enable_io_modes, 1,
    "Enable I/O and memory bits in the config register.  Some BIOSes do not\n\
enable these bits correctly.  We'd like to do this all the time, but there\n\
are some peripherals that this causes problems with.");

/* Find a device_t by bus/slot/function */

device_t
pci_find_bsf(u_int8_t bus, u_int8_t slot, u_int8_t func)
{
	struct pci_devinfo *dinfo;

	STAILQ_FOREACH(dinfo, &pci_devq, pci_links) {
		if ((dinfo->cfg.bus == bus) &&
		    (dinfo->cfg.slot == slot) &&
		    (dinfo->cfg.func == func)) {
			return (dinfo->cfg.dev);
		}
	}

	return (NULL);
}

/* Find a device_t by vendor/device ID */

device_t
pci_find_device(u_int16_t vendor, u_int16_t device)
{
	struct pci_devinfo *dinfo;

	STAILQ_FOREACH(dinfo, &pci_devq, pci_links) {
		if ((dinfo->cfg.vendor == vendor) &&
		    (dinfo->cfg.device == device)) {
			return (dinfo->cfg.dev);
		}
	}

	return (NULL);
}

/* return base address of memory or port map */

static u_int32_t
pci_mapbase(unsigned mapreg)
{
	int mask = 0x03;
	if ((mapreg & 0x01) == 0)
		mask = 0x0f;
	return (mapreg & ~mask);
}

/* return map type of memory or port map */

static int
pci_maptype(unsigned mapreg)
{
	static u_int8_t maptype[0x10] = {
		PCI_MAPMEM,		PCI_MAPPORT,
		PCI_MAPMEM,		0,
		PCI_MAPMEM,		PCI_MAPPORT,
		0,			0,
		PCI_MAPMEM|PCI_MAPMEMP,	PCI_MAPPORT,
		PCI_MAPMEM|PCI_MAPMEMP, 0,
		PCI_MAPMEM|PCI_MAPMEMP,	PCI_MAPPORT,
		0,			0,
	};

	return maptype[mapreg & 0x0f];
}

/* return log2 of map size decoded for memory or port map */

static int
pci_mapsize(unsigned testval)
{
	int ln2size;

	testval = pci_mapbase(testval);
	ln2size = 0;
	if (testval != 0) {
		while ((testval & 1) == 0)
		{
			ln2size++;
			testval >>= 1;
		}
	}
	return (ln2size);
}

/* return log2 of address range supported by map register */

static int
pci_maprange(unsigned mapreg)
{
	int ln2range = 0;
	switch (mapreg & 0x07) {
	case 0x00:
	case 0x01:
	case 0x05:
		ln2range = 32;
		break;
	case 0x02:
		ln2range = 20;
		break;
	case 0x04:
		ln2range = 64;
		break;
	}
	return (ln2range);
}

/* adjust some values from PCI 1.0 devices to match 2.0 standards ... */

static void
pci_fixancient(pcicfgregs *cfg)
{
	if (cfg->hdrtype != 0)
		return;

	/* PCI to PCI bridges use header type 1 */
	if (cfg->baseclass == PCIC_BRIDGE && cfg->subclass == PCIS_BRIDGE_PCI)
		cfg->hdrtype = 1;
}

/* extract header type specific config data */

static void
pci_hdrtypedata(device_t pcib, int b, int s, int f, pcicfgregs *cfg)
{
#define REG(n, w)	PCIB_READ_CONFIG(pcib, b, s, f, n, w)
	switch (cfg->hdrtype) {
	case 0:
		cfg->subvendor      = REG(PCIR_SUBVEND_0, 2);
		cfg->subdevice      = REG(PCIR_SUBDEV_0, 2);
		cfg->nummaps	    = PCI_MAXMAPS_0;
		break;
	case 1:
		cfg->subvendor      = REG(PCIR_SUBVEND_1, 2);
		cfg->subdevice      = REG(PCIR_SUBDEV_1, 2);
		cfg->nummaps	    = PCI_MAXMAPS_1;
		break;
	case 2:
		cfg->subvendor      = REG(PCIR_SUBVEND_2, 2);
		cfg->subdevice      = REG(PCIR_SUBDEV_2, 2);
		cfg->nummaps	    = PCI_MAXMAPS_2;
		break;
	}
#undef REG
}

/* read configuration header into pcicfgregs structure */

struct pci_devinfo *
pci_read_device(device_t pcib, int b, int s, int f, size_t size)
{
#define REG(n, w)	PCIB_READ_CONFIG(pcib, b, s, f, n, w)
	pcicfgregs *cfg = NULL;
	struct pci_devinfo *devlist_entry;
	struct devlist *devlist_head;

	devlist_head = &pci_devq;

	devlist_entry = NULL;

	if (PCIB_READ_CONFIG(pcib, b, s, f, PCIR_DEVVENDOR, 4) != -1) {
		devlist_entry = malloc(size, M_DEVBUF, M_WAITOK | M_ZERO);
		if (devlist_entry == NULL)
			return (NULL);

		cfg = &devlist_entry->cfg;

		cfg->bus		= b;
		cfg->slot		= s;
		cfg->func		= f;
		cfg->vendor		= REG(PCIR_VENDOR, 2);
		cfg->device		= REG(PCIR_DEVICE, 2);
		cfg->cmdreg		= REG(PCIR_COMMAND, 2);
		cfg->statreg		= REG(PCIR_STATUS, 2);
		cfg->baseclass		= REG(PCIR_CLASS, 1);
		cfg->subclass		= REG(PCIR_SUBCLASS, 1);
		cfg->progif		= REG(PCIR_PROGIF, 1);
		cfg->revid		= REG(PCIR_REVID, 1);
		cfg->hdrtype		= REG(PCIR_HEADERTYPE, 1);
		cfg->cachelnsz		= REG(PCIR_CACHELNSZ, 1);
		cfg->lattimer		= REG(PCIR_LATTIMER, 1);
		cfg->intpin		= REG(PCIR_INTPIN, 1);
		cfg->intline		= REG(PCIR_INTLINE, 1);

		cfg->mingnt		= REG(PCIR_MINGNT, 1);
		cfg->maxlat		= REG(PCIR_MAXLAT, 1);

		cfg->mfdev		= (cfg->hdrtype & PCIM_MFDEV) != 0;
		cfg->hdrtype		&= ~PCIM_MFDEV;

		pci_fixancient(cfg);
		pci_hdrtypedata(pcib, b, s, f, cfg);

		if (REG(PCIR_STATUS, 2) & PCIM_STATUS_CAPPRESENT)
			pci_read_extcap(pcib, cfg);

		STAILQ_INSERT_TAIL(devlist_head, devlist_entry, pci_links);

		devlist_entry->conf.pc_sel.pc_bus = cfg->bus;
		devlist_entry->conf.pc_sel.pc_dev = cfg->slot;
		devlist_entry->conf.pc_sel.pc_func = cfg->func;
		devlist_entry->conf.pc_hdr = cfg->hdrtype;

		devlist_entry->conf.pc_subvendor = cfg->subvendor;
		devlist_entry->conf.pc_subdevice = cfg->subdevice;
		devlist_entry->conf.pc_vendor = cfg->vendor;
		devlist_entry->conf.pc_device = cfg->device;

		devlist_entry->conf.pc_class = cfg->baseclass;
		devlist_entry->conf.pc_subclass = cfg->subclass;
		devlist_entry->conf.pc_progif = cfg->progif;
		devlist_entry->conf.pc_revid = cfg->revid;

		pci_numdevs++;
		pci_generation++;
	}
	return (devlist_entry);
#undef REG
}

static void
pci_read_extcap(device_t pcib, pcicfgregs *cfg)
{
#define REG(n, w)	PCIB_READ_CONFIG(pcib, cfg->bus, cfg->slot, cfg->func, n, w)
	int	ptr, nextptr, ptrptr;

	switch (cfg->hdrtype) {
	case 0:
		ptrptr = 0x34;
		break;
	case 2:
		ptrptr = 0x14;
		break;
	default:
		return;		/* no extended capabilities support */
	}
	nextptr = REG(ptrptr, 1);	/* sanity check? */

	/*
	 * Read capability entries.
	 */
	while (nextptr != 0) {
		/* Sanity check */
		if (nextptr > 255) {
			printf("illegal PCI extended capability offset %d\n",
			    nextptr);
			return;
		}
		/* Find the next entry */
		ptr = nextptr;
		nextptr = REG(ptr + 1, 1);

		/* Process this entry */
		switch (REG(ptr, 1)) {
		case 0x01:		/* PCI power management */
			if (cfg->pp_cap == 0) {
				cfg->pp_cap = REG(ptr + PCIR_POWER_CAP, 2);
				cfg->pp_status = ptr + PCIR_POWER_STATUS;
				cfg->pp_pmcsr = ptr + PCIR_POWER_PMCSR;
				if ((nextptr - ptr) > PCIR_POWER_DATA)
					cfg->pp_data = ptr + PCIR_POWER_DATA;
			}
			break;
		default:
			break;
		}
	}
#undef REG
}

/* free pcicfgregs structure and all depending data structures */

int
pci_freecfg(struct pci_devinfo *dinfo)
{
	struct devlist *devlist_head;

	devlist_head = &pci_devq;

	/* XXX this hasn't been tested */
	STAILQ_REMOVE(devlist_head, dinfo, pci_devinfo, pci_links);
	free(dinfo, M_DEVBUF);

	/* increment the generation count */
	pci_generation++;

	/* we're losing one device */
	pci_numdevs--;
	return (0);
}

/*
 * PCI power manangement
 */
int
pci_set_powerstate_method(device_t dev, device_t child, int state)
{
	struct pci_devinfo *dinfo = device_get_ivars(child);
	pcicfgregs *cfg = &dinfo->cfg;
	u_int16_t status;
	int result;

	if (cfg->pp_cap != 0) {
		status = PCI_READ_CONFIG(dev, child, cfg->pp_status, 2) & ~PCIM_PSTAT_DMASK;
		result = 0;
		switch (state) {
		case PCI_POWERSTATE_D0:
			status |= PCIM_PSTAT_D0;
			break;
		case PCI_POWERSTATE_D1:
			if (cfg->pp_cap & PCIM_PCAP_D1SUPP) {
				status |= PCIM_PSTAT_D1;
			} else {
				result = EOPNOTSUPP;
			}
			break;
		case PCI_POWERSTATE_D2:
			if (cfg->pp_cap & PCIM_PCAP_D2SUPP) {
				status |= PCIM_PSTAT_D2;
			} else {
				result = EOPNOTSUPP;
			}
			break;
		case PCI_POWERSTATE_D3:
			status |= PCIM_PSTAT_D3;
			break;
		default:
			result = EINVAL;
		}
		if (result == 0)
			PCI_WRITE_CONFIG(dev, child, cfg->pp_status, status, 2);
	} else {
		result = ENXIO;
	}
	return(result);
}

int
pci_get_powerstate_method(device_t dev, device_t child)
{
	struct pci_devinfo *dinfo = device_get_ivars(child);
	pcicfgregs *cfg = &dinfo->cfg;
	u_int16_t status;
	int result;

	if (cfg->pp_cap != 0) {
		status = PCI_READ_CONFIG(dev, child, cfg->pp_status, 2);
		switch (status & PCIM_PSTAT_DMASK) {
		case PCIM_PSTAT_D0:
			result = PCI_POWERSTATE_D0;
			break;
		case PCIM_PSTAT_D1:
			result = PCI_POWERSTATE_D1;
			break;
		case PCIM_PSTAT_D2:
			result = PCI_POWERSTATE_D2;
			break;
		case PCIM_PSTAT_D3:
			result = PCI_POWERSTATE_D3;
			break;
		default:
			result = PCI_POWERSTATE_UNKNOWN;
			break;
		}
	} else {
		/* No support, device is always at D0 */
		result = PCI_POWERSTATE_D0;
	}
	return(result);
}

/*
 * Some convenience functions for PCI device drivers.
 */

static __inline void
pci_set_command_bit(device_t dev, device_t child, u_int16_t bit)
{
	u_int16_t	command;

	command = PCI_READ_CONFIG(dev, child, PCIR_COMMAND, 2);
	command |= bit;
	PCI_WRITE_CONFIG(dev, child, PCIR_COMMAND, command, 2);
}

static __inline void
pci_clear_command_bit(device_t dev, device_t child, u_int16_t bit)
{
	u_int16_t	command;

	command = PCI_READ_CONFIG(dev, child, PCIR_COMMAND, 2);
	command &= ~bit;
	PCI_WRITE_CONFIG(dev, child, PCIR_COMMAND, command, 2);
}

void
pci_enable_busmaster_method(device_t dev, device_t child)
{
	pci_set_command_bit(dev, child, PCIM_CMD_BUSMASTEREN);
}

void
pci_disable_busmaster_method(device_t dev, device_t child)
{
	pci_clear_command_bit(dev, child, PCIM_CMD_BUSMASTEREN);
}

void
pci_enable_io_method(device_t dev, device_t child, int space)
{
	switch(space) {
	case SYS_RES_IOPORT:
		pci_set_command_bit(dev, child, PCIM_CMD_PORTEN);
		break;
	case SYS_RES_MEMORY:
		pci_set_command_bit(dev, child, PCIM_CMD_MEMEN);
		break;
	}
}

void
pci_disable_io_method(device_t dev, device_t child, int space)
{
	switch(space) {
	case SYS_RES_IOPORT:
		pci_clear_command_bit(dev, child, PCIM_CMD_PORTEN);
		break;
	case SYS_RES_MEMORY:
		pci_clear_command_bit(dev, child, PCIM_CMD_MEMEN);
		break;
	}
}

/*
 * New style pci driver.  Parent device is either a pci-host-bridge or a
 * pci-pci-bridge.  Both kinds are represented by instances of pcib.
 */

void
pci_print_verbose(struct pci_devinfo *dinfo)
{
	if (bootverbose) {
		pcicfgregs *cfg = &dinfo->cfg;

		printf("found->\tvendor=0x%04x, dev=0x%04x, revid=0x%02x\n",
		    cfg->vendor, cfg->device, cfg->revid);
		printf("\tbus=%d, slot=%d, func=%d\n",
		    cfg->bus, cfg->slot, cfg->func);
		printf("\tclass=%02x-%02x-%02x, hdrtype=0x%02x, mfdev=%d\n",
		    cfg->baseclass, cfg->subclass, cfg->progif, cfg->hdrtype,
		    cfg->mfdev);
		printf("\tcmdreg=0x%04x, statreg=0x%04x, cachelnsz=%d (dwords)\n",
		    cfg->cmdreg, cfg->statreg, cfg->cachelnsz);
		printf("\tlattimer=0x%02x (%d ns), mingnt=0x%02x (%d ns), maxlat=0x%02x (%d ns)\n",
		    cfg->lattimer, cfg->lattimer * 30, cfg->mingnt,
		    cfg->mingnt * 250, cfg->maxlat, cfg->maxlat * 250);
		if (cfg->intpin > 0)
			printf("\tintpin=%c, irq=%d\n",
			    cfg->intpin +'a' -1, cfg->intline);
		if (cfg->pp_cap) {
			u_int16_t status;

			status = pci_read_config(cfg->dev, cfg->pp_status, 2);
			printf("\tpowerspec %d  supports D0%s%s D3  current D%d\n",
			    cfg->pp_cap & PCIM_PCAP_SPEC,
			    cfg->pp_cap & PCIM_PCAP_D1SUPP ? " D1" : "",
			    cfg->pp_cap & PCIM_PCAP_D2SUPP ? " D2" : "",
			    status & PCIM_PSTAT_DMASK);
		}
	}
}

static int
pci_porten(device_t pcib, int b, int s, int f)
{
	return (PCIB_READ_CONFIG(pcib, b, s, f, PCIR_COMMAND, 2)
		& PCIM_CMD_PORTEN) != 0;
}

static int
pci_memen(device_t pcib, int b, int s, int f)
{
	return (PCIB_READ_CONFIG(pcib, b, s, f, PCIR_COMMAND, 2)
		& PCIM_CMD_MEMEN) != 0;
}

/*
 * Add a resource based on a pci map register. Return 1 if the map
 * register is a 32bit map register or 2 if it is a 64bit register.
 */
static int
pci_add_map(device_t pcib, int b, int s, int f, int reg,
	    struct resource_list *rl)
{
	u_int32_t map;
	u_int64_t base;
	u_int8_t ln2size;
	u_int8_t ln2range;
	u_int32_t testval;
	u_int16_t cmd;
	int type;

	map = PCIB_READ_CONFIG(pcib, b, s, f, reg, 4);

	if (map == 0 || map == 0xffffffff)
		return (1); /* skip invalid entry */

	PCIB_WRITE_CONFIG(pcib, b, s, f, reg, 0xffffffff, 4);
	testval = PCIB_READ_CONFIG(pcib, b, s, f, reg, 4);
	PCIB_WRITE_CONFIG(pcib, b, s, f, reg, map, 4);

	base = pci_mapbase(map);
	if (pci_maptype(map) & PCI_MAPMEM)
		type = SYS_RES_MEMORY;
	else
		type = SYS_RES_IOPORT;
	ln2size = pci_mapsize(testval);
	ln2range = pci_maprange(testval);
	if (ln2range == 64) {
		/* Read the other half of a 64bit map register */
		base |= (u_int64_t) PCIB_READ_CONFIG(pcib, b, s, f, reg + 4, 4) << 32;
	}

	if (bootverbose) {
		printf("\tmap[%02x]: type %x, range %2d, base %08x, size %2d",
		    reg, pci_maptype(map), ln2range,
		    (unsigned int) base, ln2size);
		if (type == SYS_RES_IOPORT && !pci_porten(pcib, b, s, f))
			printf(", port disabled\n");
		else if (type == SYS_RES_MEMORY && !pci_memen(pcib, b, s, f))
			printf(", memory disabled\n");
		else
			printf(", enabled\n");
	}

	/*
	 * This code theoretically does the right thing, but has
	 * undesirable side effects in some cases where
	 * peripherals respond oddly to having these bits
	 * enabled.  Leave them alone by default.
	 */
	if (pci_enable_io_modes) {
		/* Turn on resources that have been left off by a lazy BIOS */
		if (type == SYS_RES_IOPORT && !pci_porten(pcib, b, s, f)) {
			cmd = PCIB_READ_CONFIG(pcib, b, s, f, PCIR_COMMAND, 2);
			cmd |= PCIM_CMD_PORTEN;
			PCIB_WRITE_CONFIG(pcib, b, s, f, PCIR_COMMAND, cmd, 2);
		}
		if (type == SYS_RES_MEMORY && !pci_memen(pcib, b, s, f)) {
			cmd = PCIB_READ_CONFIG(pcib, b, s, f, PCIR_COMMAND, 2);
			cmd |= PCIM_CMD_MEMEN;
			PCIB_WRITE_CONFIG(pcib, b, s, f, PCIR_COMMAND, cmd, 2);
		}
	} else {
		if (type == SYS_RES_IOPORT && !pci_porten(pcib, b, s, f))
			return (1);
		if (type == SYS_RES_MEMORY && !pci_memen(pcib, b, s, f))
			return (1);
	}
	resource_list_add(rl, type, reg, base, base + (1 << ln2size) - 1,
	    (1 << ln2size));

	return ((ln2range == 64) ? 2 : 1);
}

static void
pci_add_resources(device_t pcib, device_t dev)
{
	struct pci_devinfo *dinfo = device_get_ivars(dev);
	pcicfgregs *cfg = &dinfo->cfg;
	struct resource_list *rl = &dinfo->resources;
	struct pci_quirk *q;
	int b, i, f, s;

	b = cfg->bus;
	s = cfg->slot;
	f = cfg->func;
	for (i = 0; i < cfg->nummaps;) {
		i += pci_add_map(pcib, b, s, f, PCIR_MAPS + i*4, rl);
	}

	for (q = &pci_quirks[0]; q->devid; q++) {
		if (q->devid == ((cfg->device << 16) | cfg->vendor)
		    && q->type == PCI_QUIRK_MAP_REG)
			pci_add_map(pcib, b, s, f, q->arg1, rl);
	}

	if (cfg->intpin > 0 && PCI_INTERRUPT_VALID(cfg->intline)) {
#ifdef __ia64__
		/*
		 * Re-route interrupts on ia64 so that we can get the
		 * I/O SAPIC interrupt numbers (the BIOS leaves legacy
		 * PIC interrupt numbers in the intline registers).
		 */
		cfg->intline = PCIB_ROUTE_INTERRUPT(pcib, dev, cfg->intpin);
#endif
		resource_list_add(rl, SYS_RES_IRQ, 0, cfg->intline,
		  cfg->intline, 1);
	}
}

void
pci_add_children(device_t dev, int busno, size_t dinfo_size)
{
	device_t pcib = device_get_parent(dev);
	struct pci_devinfo *dinfo;
	int maxslots;
	int s, f, pcifunchigh;

	KASSERT(dinfo_size >= sizeof(struct pci_devinfo),
	    ("dinfo_size too small"));
	maxslots = PCIB_MAXSLOTS(pcib);
	for (s = 0; s <= maxslots; s++) {
		pcifunchigh = 0;
		for (f = 0; f <= pcifunchigh; f++) {
			dinfo = pci_read_device(pcib, busno, s, f, dinfo_size);
			if (dinfo != NULL) {
				if (dinfo->cfg.mfdev)
					pcifunchigh = PCI_FUNCMAX;
				pci_add_child(dev, dinfo);
			}
		}
	}
}

void
pci_add_child(device_t bus, struct pci_devinfo *dinfo)
{
	device_t pcib;

	pcib = device_get_parent(bus);
	dinfo->cfg.dev = device_add_child(bus, NULL, -1);
	device_set_ivars(dinfo->cfg.dev, dinfo);
	pci_add_resources(pcib, dinfo->cfg.dev);
	pci_print_verbose(dinfo);
}

static int
pci_probe(device_t dev)
{

	device_set_desc(dev, "PCI bus");

	/* Allow other subclasses to override this driver. */
	return (-1000);
}

static int
pci_attach(device_t dev)
{
	int busno;

	/*
	 * Since there can be multiple independantly numbered PCI
	 * busses on some large alpha systems, we can't use the unit
	 * number to decide what bus we are probing. We ask the parent
	 * pcib what our bus number is.
	 */
	busno = pcib_get_bus(dev);
	if (bootverbose)
		device_printf(dev, "physical bus=%d\n", busno);

	pci_add_children(dev, busno, sizeof(struct pci_devinfo));

	return (bus_generic_attach(dev));
}

static void
pci_load_vendor_data(void)
{
	caddr_t vendordata, info;

	if ((vendordata = preload_search_by_type("pci_vendor_data")) != NULL) {
		info = preload_search_info(vendordata, MODINFO_ADDR);
		pci_vendordata = *(char **)info;
		info = preload_search_info(vendordata, MODINFO_SIZE);
		pci_vendordata_size = *(size_t *)info;
		/* terminate the database */
		pci_vendordata[pci_vendordata_size] = '\n';
	}
}

int
pci_print_child(device_t dev, device_t child)
{
	struct pci_devinfo *dinfo;
	struct resource_list *rl;
	pcicfgregs *cfg;
	int retval = 0;

	dinfo = device_get_ivars(child);
	cfg = &dinfo->cfg;
	rl = &dinfo->resources;

	retval += bus_print_child_header(dev, child);

	retval += resource_list_print_type(rl, "port", SYS_RES_IOPORT, "%#lx");
	retval += resource_list_print_type(rl, "mem", SYS_RES_MEMORY, "%#lx");
	retval += resource_list_print_type(rl, "irq", SYS_RES_IRQ, "%ld");
	if (device_get_flags(dev))
		retval += printf(" flags %#x", device_get_flags(dev));

	retval += printf(" at device %d.%d", pci_get_slot(child),
	    pci_get_function(child));

	retval += bus_print_child_footer(dev, child);

	return (retval);
}

static struct
{
	int	class;
	int	subclass;
	char	*desc;
} pci_nomatch_tab[] = {
	{PCIC_OLD,		-1,			"old"},
	{PCIC_OLD,		PCIS_OLD_NONVGA,	"non-VGA display device"},
	{PCIC_OLD,		PCIS_OLD_VGA,		"VGA-compatible display device"},
	{PCIC_STORAGE,		-1,			"mass storage"},
	{PCIC_STORAGE,		PCIS_STORAGE_SCSI,	"SCSI"},
	{PCIC_STORAGE,		PCIS_STORAGE_IDE,	"ATA"},
	{PCIC_STORAGE,		PCIS_STORAGE_FLOPPY,	"floppy disk"},
	{PCIC_STORAGE,		PCIS_STORAGE_IPI,	"IPI"},
	{PCIC_STORAGE,		PCIS_STORAGE_RAID,	"RAID"},
	{PCIC_NETWORK,		-1,			"network"},
	{PCIC_NETWORK,		PCIS_NETWORK_ETHERNET,	"ethernet"},
	{PCIC_NETWORK,		PCIS_NETWORK_TOKENRING,	"token ring"},
	{PCIC_NETWORK,		PCIS_NETWORK_FDDI,	"fddi"},
	{PCIC_NETWORK,		PCIS_NETWORK_ATM,	"ATM"},
	{PCIC_DISPLAY,		-1,			"display"},
	{PCIC_DISPLAY,		PCIS_DISPLAY_VGA,	"VGA"},
	{PCIC_DISPLAY,		PCIS_DISPLAY_XGA,	"XGA"},
	{PCIC_MULTIMEDIA,	-1,			"multimedia"},
	{PCIC_MULTIMEDIA,	PCIS_MULTIMEDIA_VIDEO,	"video"},
	{PCIC_MULTIMEDIA,	PCIS_MULTIMEDIA_AUDIO,	"audio"},
	{PCIC_MEMORY,		-1,			"memory"},
	{PCIC_MEMORY,		PCIS_MEMORY_RAM,	"RAM"},
	{PCIC_MEMORY,		PCIS_MEMORY_FLASH,	"flash"},
	{PCIC_BRIDGE,		-1,			"bridge"},
	{PCIC_BRIDGE,		PCIS_BRIDGE_HOST,	"HOST-PCI"},
	{PCIC_BRIDGE,		PCIS_BRIDGE_ISA,	"PCI-ISA"},
	{PCIC_BRIDGE,		PCIS_BRIDGE_EISA,	"PCI-EISA"},
	{PCIC_BRIDGE,		PCIS_BRIDGE_MCA,	"PCI-MCA"},
	{PCIC_BRIDGE,		PCIS_BRIDGE_PCI,	"PCI-PCI"},
	{PCIC_BRIDGE,		PCIS_BRIDGE_PCMCIA,	"PCI-PCMCIA"},
	{PCIC_BRIDGE,		PCIS_BRIDGE_NUBUS,	"PCI-NuBus"},
	{PCIC_BRIDGE,		PCIS_BRIDGE_CARDBUS,	"PCI-CardBus"},
	{PCIC_BRIDGE,		PCIS_BRIDGE_OTHER,	"PCI-unknown"},
	{PCIC_SIMPLECOMM,	-1,			"simple comms"},
	{PCIC_SIMPLECOMM,	PCIS_SIMPLECOMM_UART,	"UART"},	/* could detect 16550 */
	{PCIC_SIMPLECOMM,	PCIS_SIMPLECOMM_PAR,	"parallel port"},
	{PCIC_BASEPERIPH,	-1,			"base peripheral"},
	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_PIC,	"interrupt controller"},
	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_DMA,	"DMA controller"},
	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_TIMER,	"timer"},
	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_RTC,	"realtime clock"},
	{PCIC_INPUTDEV,		-1,			"input device"},
	{PCIC_INPUTDEV,		PCIS_INPUTDEV_KEYBOARD,	"keyboard"},
	{PCIC_INPUTDEV,		PCIS_INPUTDEV_DIGITIZER,"digitizer"},
	{PCIC_INPUTDEV,		PCIS_INPUTDEV_MOUSE,	"mouse"},
	{PCIC_DOCKING,		-1,			"docking station"},
	{PCIC_PROCESSOR,	-1,			"processor"},
	{PCIC_SERIALBUS,	-1,			"serial bus"},
	{PCIC_SERIALBUS,	PCIS_SERIALBUS_FW,	"FireWire"},
	{PCIC_SERIALBUS,	PCIS_SERIALBUS_ACCESS,	"AccessBus"},
	{PCIC_SERIALBUS,	PCIS_SERIALBUS_SSA,	"SSA"},
	{PCIC_SERIALBUS,	PCIS_SERIALBUS_USB,	"USB"},
	{PCIC_SERIALBUS,	PCIS_SERIALBUS_FC,	"Fibre Channel"},
	{PCIC_SERIALBUS,	PCIS_SERIALBUS_SMBUS,	"SMBus"},
	{0, 0,		NULL}
};

void
pci_probe_nomatch(device_t dev, device_t child)
{
	int	i;
	char	*cp, *scp, *device;

	/*
	 * Look for a listing for this device in a loaded device database.
	 */
	if ((device = pci_describe_device(child)) != NULL) {
		device_printf(dev, "<%s>", device);
		free(device, M_DEVBUF);
	} else {
		/*
		 * Scan the class/subclass descriptions for a general
		 * description.
		 */
		cp = "unknown";
		scp = NULL;
		for (i = 0; pci_nomatch_tab[i].desc != NULL; i++) {
			if (pci_nomatch_tab[i].class == pci_get_class(child)) {
				if (pci_nomatch_tab[i].subclass == -1) {
					cp = pci_nomatch_tab[i].desc;
				} else if (pci_nomatch_tab[i].subclass ==
				    pci_get_subclass(child)) {
					scp = pci_nomatch_tab[i].desc;
				}
			}
		}
		device_printf(dev, "<%s%s%s>",
		    cp ? cp : "",
		    ((cp != NULL) && (scp != NULL)) ? ", " : "",
		    scp ? scp : "");
	}
	printf(" at device %d.%d (no driver attached)\n",
	    pci_get_slot(child), pci_get_function(child));
	return;
}

/*
 * Parse the PCI device database, if loaded, and return a pointer to a
 * description of the device.
 *
 * The database is flat text formatted as follows:
 *
 * Any line not in a valid format is ignored.
 * Lines are terminated with newline '\n' characters.
 *
 * A VENDOR line consists of the 4 digit (hex) vendor code, a TAB, then
 * the vendor name.
 *
 * A DEVICE line is entered immediately below the corresponding VENDOR ID.
 * - devices cannot be listed without a corresponding VENDOR line.
 * A DEVICE line consists of a TAB, the 4 digit (hex) device code,
 * another TAB, then the device name.
 */

/*
 * Assuming (ptr) points to the beginning of a line in the database,
 * return the vendor or device and description of the next entry.
 * The value of (vendor) or (device) inappropriate for the entry type
 * is set to -1.  Returns nonzero at the end of the database.
 *
 * Note that this is slightly unrobust in the face of corrupt data;
 * we attempt to safeguard against this by spamming the end of the
 * database with a newline when we initialise.
 */
static int
pci_describe_parse_line(char **ptr, int *vendor, int *device, char **desc)
{
	char	*cp = *ptr;
	int	left;

	*device = -1;
	*vendor = -1;
	**desc = '\0';
	for (;;) {
		left = pci_vendordata_size - (cp - pci_vendordata);
		if (left <= 0) {
			*ptr = cp;
			return(1);
		}

		/* vendor entry? */
		if (*cp != '\t' &&
		    sscanf(cp, "%x\t%80[^\n]", vendor, *desc) == 2)
			break;
		/* device entry? */
		if (*cp == '\t' &&
		    sscanf(cp, "%x\t%80[^\n]", device, *desc) == 2)
			break;

		/* skip to next line */
		while (*cp != '\n' && left > 0) {
			cp++;
			left--;
		}
		if (*cp == '\n') {
			cp++;
			left--;
		}
	}
	/* skip to next line */
	while (*cp != '\n' && left > 0) {
		cp++;
		left--;
	}
	if (*cp == '\n' && left > 0)
		cp++;
	*ptr = cp;
	return(0);
}

static char *
pci_describe_device(device_t dev)
{
	int	vendor, device;
	char	*desc, *vp, *dp, *line;

	desc = vp = dp = NULL;

	/*
	 * If we have no vendor data, we can't do anything.
	 */
	if (pci_vendordata == NULL)
		goto out;

	/*
	 * Scan the vendor data looking for this device
	 */
	line = pci_vendordata;
	if ((vp = malloc(80, M_DEVBUF, M_NOWAIT)) == NULL)
		goto out;
	for (;;) {
		if (pci_describe_parse_line(&line, &vendor, &device, &vp))
			goto out;
		if (vendor == pci_get_vendor(dev))
			break;
	}
	if ((dp = malloc(80, M_DEVBUF, M_NOWAIT)) == NULL)
		goto out;
	for (;;) {
		if (pci_describe_parse_line(&line, &vendor, &device, &dp)) {
			*dp = 0;
			break;
		}
		if (vendor != -1) {
			*dp = 0;
			break;
		}
		if (device == pci_get_device(dev))
			break;
	}
	if (dp[0] == '\0')
		snprintf(dp, 80, "0x%x", pci_get_device(dev));
	if ((desc = malloc(strlen(vp) + strlen(dp) + 3, M_DEVBUF, M_NOWAIT)) !=
	    NULL)
		sprintf(desc, "%s, %s", vp, dp);
 out:
	if (vp != NULL)
		free(vp, M_DEVBUF);
	if (dp != NULL)
		free(dp, M_DEVBUF);
	return(desc);
}

int
pci_read_ivar(device_t dev, device_t child, int which, uintptr_t *result)
{
	struct pci_devinfo *dinfo;
	pcicfgregs *cfg;

	dinfo = device_get_ivars(child);
	cfg = &dinfo->cfg;

	switch (which) {
	case PCI_IVAR_ETHADDR:
		/*
		 * The generic accessor doesn't deal with failure, so
		 * we set the return value, then return an error.
		 */
		*((u_int8_t **) result) = NULL;
		return (EINVAL);
	case PCI_IVAR_SUBVENDOR:
		*result = cfg->subvendor;
		break;
	case PCI_IVAR_SUBDEVICE:
		*result = cfg->subdevice;
		break;
	case PCI_IVAR_VENDOR:
		*result = cfg->vendor;
		break;
	case PCI_IVAR_DEVICE:
		*result = cfg->device;
		break;
	case PCI_IVAR_DEVID:
		*result = (cfg->device << 16) | cfg->vendor;
		break;
	case PCI_IVAR_CLASS:
		*result = cfg->baseclass;
		break;
	case PCI_IVAR_SUBCLASS:
		*result = cfg->subclass;
		break;
	case PCI_IVAR_PROGIF:
		*result = cfg->progif;
		break;
	case PCI_IVAR_REVID:
		*result = cfg->revid;
		break;
	case PCI_IVAR_INTPIN:
		*result = cfg->intpin;
		break;
	case PCI_IVAR_IRQ:
		*result = cfg->intline;
		break;
	case PCI_IVAR_BUS:
		*result = cfg->bus;
		break;
	case PCI_IVAR_SLOT:
		*result = cfg->slot;
		break;
	case PCI_IVAR_FUNCTION:
		*result = cfg->func;
		break;
	default:
		return (ENOENT);
	}
	return (0);
}

int
pci_write_ivar(device_t dev, device_t child, int which, uintptr_t value)
{
	struct pci_devinfo *dinfo;
	pcicfgregs *cfg;

	dinfo = device_get_ivars(child);
	cfg = &dinfo->cfg;

	switch (which) {
	case PCI_IVAR_ETHADDR:
	case PCI_IVAR_SUBVENDOR:
	case PCI_IVAR_SUBDEVICE:
	case PCI_IVAR_VENDOR:
	case PCI_IVAR_DEVICE:
	case PCI_IVAR_DEVID:
	case PCI_IVAR_CLASS:
	case PCI_IVAR_SUBCLASS:
	case PCI_IVAR_PROGIF:
	case PCI_IVAR_REVID:
	case PCI_IVAR_INTPIN:
	case PCI_IVAR_IRQ:
	case PCI_IVAR_BUS:
	case PCI_IVAR_SLOT:
	case PCI_IVAR_FUNCTION:
		return (EINVAL);	/* disallow for now */

	default:
		return (ENOENT);
	}
	return (0);
}

#include "opt_ddb.h"
#ifdef DDB
#include <ddb/ddb.h>
#include <sys/cons.h>

/*
 * List resources based on pci map registers, used for within ddb
 */

DB_SHOW_COMMAND(pciregs, db_pci_dump)
{
	struct pci_devinfo *dinfo;
	struct devlist *devlist_head;
	struct pci_conf *p;
	const char *name;
	int i, error, none_count, nl;

	none_count = 0;
	nl = 0;
	/* get the head of the device queue */
	devlist_head = &pci_devq;

	/*
	 * Go through the list of devices and print out devices
	 */
	for (error = 0, i = 0,
	     dinfo = STAILQ_FIRST(devlist_head);
	     (dinfo != NULL) && (error == 0) && (i < pci_numdevs);
	     dinfo = STAILQ_NEXT(dinfo, pci_links), i++) {

		/* Populate pd_name and pd_unit */
		name = NULL;
		if (dinfo->cfg.dev)
			name = device_get_name(dinfo->cfg.dev);

		p = &dinfo->conf;
		/*
		 * XXX just take 20 for now...
		 */
		if (nl++ == 20) {
			int c;

			db_printf("--More--");
			c = cngetc();
			db_printf("\r");
			/*
			 * A whole screenfull or just one line?
			 */
			switch (c) {
			case '\n':              /* just one line */
				nl = 20;
				break;
			case ' ':
				nl = 0;         /* another screenfull */
				break;
			default:                /* exit */
				db_printf("\n");
				return;
			}
		}

		db_printf("%s%d@pci%d:%d:%d:\tclass=0x%06x card=0x%08x "
			"chip=0x%08x rev=0x%02x hdr=0x%02x\n",
			(name && *name) ? name : "none",
			(name && *name) ? (int)device_get_unit(dinfo->cfg.dev) :
			none_count++,
			p->pc_sel.pc_bus, p->pc_sel.pc_dev,
			p->pc_sel.pc_func, (p->pc_class << 16) |
			(p->pc_subclass << 8) | p->pc_progif,
			(p->pc_subdevice << 16) | p->pc_subvendor,
			(p->pc_device << 16) | p->pc_vendor,
			p->pc_revid, p->pc_hdr);
	}
}
#endif /* DDB */

struct resource *
pci_alloc_resource(device_t dev, device_t child, int type, int *rid,
		   u_long start, u_long end, u_long count, u_int flags)
{
	struct pci_devinfo *dinfo = device_get_ivars(child);
	struct resource_list *rl = &dinfo->resources;
	pcicfgregs *cfg = &dinfo->cfg;

	/*
	 * Perform lazy resource allocation
	 *
	 * XXX add support here for SYS_RES_IOPORT and SYS_RES_MEMORY
	 */
	if (device_get_parent(child) == dev) {
		/*
		 * If the child device doesn't have an interrupt routed
		 * and is deserving of an interrupt, try to assign it one.
		 */
		if ((type == SYS_RES_IRQ) &&
		    !PCI_INTERRUPT_VALID(cfg->intline) &&
		    (cfg->intpin != 0)) {
			cfg->intline = PCIB_ROUTE_INTERRUPT(
				device_get_parent(dev), child, cfg->intpin);
			if (PCI_INTERRUPT_VALID(cfg->intline)) {
				pci_write_config(child, PCIR_INTLINE,
				    cfg->intline, 1);
				resource_list_add(rl, SYS_RES_IRQ, 0,
				    cfg->intline, cfg->intline, 1);
			}
		}
	}

	return (resource_list_alloc(rl, dev, child, type, rid,
	    start, end, count, flags));
}

void
pci_delete_resource(device_t dev, device_t child, int type, int rid)
{
	struct pci_devinfo *dinfo;
	struct resource_list *rl;
	struct resource_list_entry *rle;

	if (device_get_parent(child) != dev)
		return;

	dinfo = device_get_ivars(child);
	rl = &dinfo->resources;
	rle = resource_list_find(rl, type, rid);
	if (rle) {
		if (rle->res) {
			if (rle->res->r_dev != dev ||
			    rman_get_flags(rle->res) & RF_ACTIVE) {
				device_printf(dev, "delete_resource: "
				    "Resource still owned by child, oops. "
				    "(type=%d, rid=%d, addr=%lx)\n",
				    rle->type, rle->rid,
				    rman_get_start(rle->res));
				return;
			}
			bus_release_resource(dev, type, rid, rle->res);
		}
		resource_list_delete(rl, type, rid);
	}
	/*
	 * Why do we turn off the PCI configuration BAR when we delete a
	 * resource? -- imp
	 */
	pci_write_config(child, rid, 0, 4);
	BUS_DELETE_RESOURCE(device_get_parent(dev), child, type, rid);
}

struct resource_list *
pci_get_resource_list (device_t dev, device_t child)
{
	struct pci_devinfo *	dinfo = device_get_ivars(child);
	struct resource_list *  rl = &dinfo->resources;

	if (!rl)
		return (NULL);

	return (rl);
}

u_int32_t
pci_read_config_method(device_t dev, device_t child, int reg, int width)
{
	struct pci_devinfo *dinfo = device_get_ivars(child);
	pcicfgregs *cfg = &dinfo->cfg;

	return (PCIB_READ_CONFIG(device_get_parent(dev),
	    cfg->bus, cfg->slot, cfg->func, reg, width));
}

void
pci_write_config_method(device_t dev, device_t child, int reg,
    u_int32_t val, int width)
{
	struct pci_devinfo *dinfo = device_get_ivars(child);
	pcicfgregs *cfg = &dinfo->cfg;

	PCIB_WRITE_CONFIG(device_get_parent(dev),
	    cfg->bus, cfg->slot, cfg->func, reg, val, width);
}

static int
pci_modevent(module_t mod, int what, void *arg)
{
	static dev_t pci_cdev;

	switch (what) {
	case MOD_LOAD:
		STAILQ_INIT(&pci_devq);
		pci_generation = 0;
		pci_cdev = make_dev(&pcicdev, 0, UID_ROOT, GID_WHEEL, 0644,
		    "pci");
		pci_load_vendor_data();
		break;

	case MOD_UNLOAD:
		destroy_dev(pci_cdev);
		break;
	}

	return (0);
}


text:
package com.emitrom.ti4j.desktop.client.process;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArrayString;

/**
 * A module for creating processes.
 */
public class Process {

    public static final String SIGABRT = Process.SIGABRT();
    public static final String SIGALRM = Process.SIGALRM();
    public static final String SIGABUS = Process.SIGABUS();
    public static final String SIGCHLD = Process.SIGCHLD();
    public static final String SIGEMT = Process.SIGEMT();
    public static final String SIGFPE = Process.SIGFPE();
    public static final String SIGHUP = Process.SIGHUP();
    public static final String SIGILL = Process.SIGILL();
    public static final String SIGINFO = Process.SIGINFO();
    public static final String SIGINT = Process.SIGINT();
    public static final String SIGIO = Process.SIGIO();
    public static final String SIGKILL = Process.SIGKILL();
    public static final String SIGPIPE = Process.SIGPIPE();
    public static final String SIGPROF = Process.SIGPROF();
    public static final String SIGQUIT = Process.SIGQUIT();
    public static final String SIGSEGV = Process.SIGSEGV();
    public static final String SIGSTOP = Process.SIGSTOP();
    public static final String SIGSYS = Process.SIGSYS();
    public static final String SIGTERM = Process.SIGTERM();
    public static final String SIGTRAP = Process.SIGTRAP();
    public static final String SIGTSTP = Process.SIGTSTP();
    public static final String SIGTTIN = Process.SIGTTIN();
    public static final String SIGTTOU = Process.SIGTTOU();
    public static final String SIGURG = Process.SIGURG();
    public static final String SIGUSR1 = Process.SIGUSR1();
    public static final String SIGUSR2 = Process.SIGUSR2();
    public static final String SIGVTALRM = Process.SIGVTALRM();
    public static final String SIGWINCH = Process.SIGWINCH();
    public static final String SIGXCPU = Process.SIGXCPU();
    public static final String SIGXFSZ = Process.SIGXFSZ();

    private Process() {

    }

    public static native Pipe createPipe()/*-{
		var obj = Ti.Process.createPipe();
		return @com.emitrom.ti4j.desktop.client.process.Pipe::new(Lcom/google/gwt/core/client/JavaScriptObject;)(obj);
    }-*/;

    public static native ProcessInstance createProcess(JsArrayString arguments)/*-{
		var obj = Ti.Process.createProcess({
			args : arguments
		});
		return @com.emitrom.ti4j.desktop.client.process.ProcessInstance::new(Lcom/google/gwt/core/client/JavaScriptObject;)(obj);
    }-*/;

    public static native ProcessInstance createProcess(JsArrayString arguments, JavaScriptObject environment)/*-{
		var obj = Ti.Process.createProcess({
			args : arguments,
			env : environment
		});
		return @com.emitrom.ti4j.desktop.client.process.ProcessInstance::new(Lcom/google/gwt/core/client/JavaScriptObject;)(obj);
    }-*/;

    public static native ProcessInstance createProcess(JsArrayString arguments, JavaScriptObject environment,
                    Pipe stdinPipe)/*-{
		var obj = Ti.Process
				.createProcess({
					args : arguments,
					env : environment,
					stdin : stdinPipe.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()()
				});
		return @com.emitrom.ti4j.desktop.client.process.ProcessInstance::new(Lcom/google/gwt/core/client/JavaScriptObject;)(obj);
    }-*/;

    public static native ProcessInstance createProcess(JsArrayString arguments, JavaScriptObject environment,
                    Pipe stdinPipe, Pipe stdoutPipe)/*-{
		var obj = Ti.Process
				.createProcess({
					args : arguments,
					env : environment,
					stdin : stdinPipe.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()(),
					stdout : stdoutPipe.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()()
				});
		return @com.emitrom.ti4j.desktop.client.process.ProcessInstance::new(Lcom/google/gwt/core/client/JavaScriptObject;)(obj);
    }-*/;

    public static native ProcessInstance createProcess(JsArrayString arguments, JavaScriptObject environment,
                    Pipe stdinPipe, Pipe stdoutPipe, Pipe stdErrPipe)/*-{
		var obj = Ti.Process
				.createProcess({
					args : arguments,
					env : environment,
					stdin : stdinPipe.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()(),
					stdout : stdoutPipe.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()(),
					stderr : stdErrPipe.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()()
				});
		return @com.emitrom.ti4j.desktop.client.process.ProcessInstance::new(Lcom/google/gwt/core/client/JavaScriptObject;)(obj);
    }-*/;

    private static native String SIGABRT()/*-{
		return Ti.Process.SIGABRT;
    }-*/;

    private static native String SIGALRM()/*-{
		return Ti.Process.SIGALRM;
    }-*/;

    private static native String SIGABUS()/*-{
		return Ti.Process.SIGABUS;
    }-*/;

    private static native String SIGCHLD()/*-{
		return Ti.Process.SIGCHLD;
    }-*/;

    private static native String SIGEMT()/*-{
		return Ti.Process.SIGEMT;
    }-*/;

    private static native String SIGFPE()/*-{
		return Ti.Process.SIGFPE;
    }-*/;

    private static native String SIGHUP()/*-{
		return Ti.Process.SIGHUP;
    }-*/;

    private static native String SIGILL()/*-{
		return Ti.Process.SIGILL;
    }-*/;

    private static native String SIGINFO()/*-{
		return Ti.Process.SIGINFO;
    }-*/;

    private static native String SIGINT()/*-{
		return Ti.Process.SIGINT;
    }-*/;

    private static native String SIGIO()/*-{
		return Ti.Process.SIGIO;
    }-*/;

    private static native String SIGKILL()/*-{
		return Ti.Process.SIGKILL;
    }-*/;

    private static native String SIGPIPE()/*-{
		return Ti.Process.SIGPIPE;
    }-*/;

    private static native String SIGPROF()/*-{
		return Ti.Process.SIGPROF;
    }-*/;

    private static native String SIGQUIT()/*-{
		return Ti.Process.SIGQUIT;
    }-*/;

    private static native String SIGSEGV()/*-{
		return Ti.Process.SIGSEGV;
    }-*/;

    private static native String SIGSTOP()/*-{
		return Ti.Process.SIGSTOP;
    }-*/;

    private static native String SIGSYS()/*-{
		return Ti.Process.SIGSYS;
    }-*/;

    private static native String SIGTERM()/*-{
		return Ti.Process.SIGTERM;
    }-*/;

    private static native String SIGTRAP()/*-{
		return Ti.Process.SIGTRAP;
    }-*/;

    private static native String SIGTSTP()/*-{
		return Ti.Process.SIGTSTP;
    }-*/;

    private static native String SIGTTIN()/*-{
		return Ti.Process.SIGTTIN;
    }-*/;

    private static native String SIGTTOU()/*-{
		return Ti.Process.SIGTTOU;
    }-*/;

    private static native String SIGURG()/*-{
		return Ti.Process.SIGURG;
    }-*/;

    private static native String SIGUSR1()/*-{
		return Ti.Process.SIGUSR1;
    }-*/;

    private static native String SIGUSR2()/*-{
		return Ti.Process.SIGUSR2;
    }-*/;

    private static native String SIGVTALRM()/*-{
		return Ti.Process.SIGVTALRM;
    }-*/;

    private static native String SIGWINCH()/*-{
		return Ti.Process.SIGWINCH;
    }-*/;

    private static native String SIGXCPU()/*-{
		return Ti.Process.SIGXCPU;
    }-*/;

    private static native String SIGXFSZ()/*-{
		return Ti.Process.SIGXFSZ;
    }-*/;

}

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
 * Class Base_Controller
 * @property Twig $twig
 * @property Doctrine $doctrine
 */
class Base_Controller extends CI_Controller
{
    /** @var \Doctrine\ORM\EntityManager $em */
    protected $em;
    /** @var \DebugBar\StandardDebugBar $debugBar  */
    protected $debugBar;
    /** @var  bool $debuggerEnabled */
    protected $debuggerEnabled = false;

    function __construct() {
        parent::__construct();
        $this->load->library('Twig', null, 'twig');
        $this->load->library('Doctrine', true, 'doctrine');
        $this->em = $this->doctrine->getEntityManager();
        $this->setDebugging();
    }

    /**
     * Sets up Php Debug Bar
     * @throws \DebugBar\DebugBarException
     */
    private function setDebugging() {
        // check debug
        $this->load->config('php_debug_bar', true, true);
        $debugConfig = $this->config->item('php_debug_bar');
        $this->twig->addGlobal('debug', $debugConfig['init_debug_bar']);
        $this->debuggerEnabled = $debugConfig['init_debug_bar'];
        if ($debugConfig['init_debug_bar']) {
            $this->load->helper('url');
            $this->debugBar = new \DebugBar\StandardDebugBar();
            $this->twig->addGlobal(
                'debugger',
                $this->debugBar->getJavascriptRenderer()->setBaseUrl(base_url() . 'debug/')
            );

            // attach doctrine hook
            if ($debugConfig['doctrine_hook']) {
                $stack =  $this->doctrine->getDebugStack();
                if ($stack) {
                    $this->debugBar->addCollector(
                        new DebugBar\Bridge\DoctrineCollector($stack)
                    );
                }
            }
        }
    }

    protected function _debug($message = '', $logLevel = \Psr\Log\LogLevel::DEBUG) {
        if ($this->debuggerEnabled) {
            /** @var DebugBar\DataCollector\MessagesCollector $messagesCollector */
            $messagesCollector = $this->debugBar["messages"];
            $messagesCollector->addMessage($message, $logLevel);
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0">
  <groupId>org.apache.maven.plugins.site-plugin-test</groupId>
  <modelVersion>4.0.0</modelVersion>
  <artifactId>site-plugin-test12</artifactId>
  <version>1.0-SNAPSHOT</version>
  <description>MSITE-201: ${modules} renders as [] causing parse error</description>
</project>


text:
#if !LESSTHAN_NET35
using System;
using System.Collections.Generic;

namespace CodeJam.Ranges
{
	/// <summary>
	/// Helper comparer for operations over <see cref="Range{T}.To"/>.
	/// </summary>
	/// <typeparam name="T">The type of the range values.</typeparam>
	[Serializable]
	internal sealed class RangeBoundaryToDescendingComparer<T> : IComparer<RangeBoundaryTo<T>>
	{
		/// <summary>Default comparer instance.</summary>
		public static readonly RangeBoundaryToDescendingComparer<T> Instance = new RangeBoundaryToDescendingComparer<T>();

		#region Implementation of IComparer<in Range<T>>
		/// <summary>
		/// Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other.
		/// </summary>
		/// <param name="x">The first object to compare.</param>
		/// <param name="y">The second object to compare.</param>
		/// <returns>
		/// A signed integer that indicates the relative values of <paramref name="x"/> and <paramref name="y"/>
		/// </returns>
		public int Compare(RangeBoundaryTo<T> x, RangeBoundaryTo<T> y) =>
			// DONTTOUCH: order by descending, args are swapped.
			y.CompareTo(x);
		#endregion
	}
}
#endif


text:
namespace Microsoft.Protocols.TestSuites.MS_OXORULE
{
    using System;
    using System.Collections.Generic;
    using Microsoft.Protocols.TestSuites.Common;

    /// <summary>
    /// Action Data buffer format for ActionType: OP_REPLY, OP_OOF_REPLY
    /// </summary>
    public class ReplyActionDataOfExtendedRule : IActionData
    {
        /// <summary>
        /// An integer that specifies the size, in bytes, of the ReplyTemplateMessageEID field.
        /// </summary>
        private uint messageEIDSize;

        /// <summary>
        /// A Message EntryID structure, as specified in [MS-OXCDATA] section 2.2.4.2, that contains the entry ID of the reply template.
        /// </summary>
        private byte[] replyTemplateMessageEID;

        /// <summary>
        /// The ReplyTemplateGUID field in the Reply ActionData buffer is the value of the GUID generated by the client in the process of creating a Reply template
        /// </summary>
        private byte[] replyTemplateGUID;

        /// <summary>
        /// Gets or sets an integer that specifies the size, in bytes, of the ReplyTemplateMessageEID field.ReplyTemplate FID which obtained from a Message Template
        /// </summary>
        public uint MessageEIDSize
        {
            get { return this.messageEIDSize; }
            set { this.messageEIDSize = value; }
        }

        /// <summary>
        /// Gets or sets a Message EntryID structure, as specified in [MS-OXCDATA] section 2.2.4.2, that contains the entry ID of the reply template.
        /// </summary>
        public byte[] ReplyTemplateMessageEID
        {
            get { return this.replyTemplateMessageEID; }
            set { this.replyTemplateMessageEID = value; }
        }

        /// <summary>
        /// Gets or sets the ReplyTemplateGUID
        /// </summary>
        public byte[] ReplyTemplateGUID
        {
            get { return this.replyTemplateGUID; }
            set { this.replyTemplateGUID = value; }
        }

        /// <summary>
        /// The total Size of this ActionData buffer
        /// </summary>
        /// <returns>Number of bytes in this ActionData buffer.</returns>
        public int Size()
        {
            return this.Serialize().Length;
        }

        /// <summary>
        /// Get serialized byte array for this ActionData
        /// </summary>
        /// <returns>Serialized byte array.</returns>
        public byte[] Serialize()
        {
            List<byte> result = new List<byte>();
            result.AddRange(BitConverter.GetBytes(this.MessageEIDSize));
            result.AddRange(this.ReplyTemplateMessageEID);
            result.AddRange(this.ReplyTemplateGUID);

            return result.ToArray();
        }

        /// <summary>
        /// Deserialized byte array to a ReplyActionData instance
        /// </summary>
        /// <param name="buffer">Byte array contains data of an ActionData instance.</param>
        /// <returns>Bytes count that deserialized in buffer.</returns>
        public uint Deserialize(byte[] buffer)
        {
            BufferReader bufferReader = new BufferReader(buffer);
            this.messageEIDSize = bufferReader.ReadUInt32();
            this.replyTemplateMessageEID = bufferReader.ReadBytes(this.messageEIDSize);
            uint guidLength = (uint)Guid.NewGuid().ToByteArray().Length;
            this.ReplyTemplateGUID = bufferReader.ReadBytes((uint)guidLength);

            return bufferReader.Position;
        }
    }
}


text:
module Artifactory
  module Error
    # Base class for all errors
    class ArtifactoryError < StandardError; end

    # Class for all HTTP errors
    class HTTPError < ArtifactoryError
      attr_reader :code

      def initialize(hash = {})
        @code = hash['status'].to_i
        @http = hash['message'].to_s

        super "The Artifactory server responded with an HTTP Error " \
              "#{@code}: `#{@http}'"
      end
    end

    # A general connection error with a more informative message
    class ConnectionError < ArtifactoryError
      def initialize(endpoint)
        super "The Artifactory server at `#{endpoint}' is not currently " \
              "accepting connections. Please ensure that the server is " \
              "running an that your authentication information is correct."
      end
    end

    # A general connection error with a more informative message
    class InvalidBuildType < ArtifactoryError
      def initialize(given_type)
        super <<-EOH
'#{given_type}' is not a valid build type.

Valid build types include:

    #{Resource::Build::BUILD_TYPES.join("\n    ")}"

EOH
      end
    end
  end
end


text: Simple javascript/canvas demo for a simple skinning algorithm


text:
package mariculture.core.handlers;

import mariculture.core.lib.Modules;
import mariculture.fishery.Fish;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import cpw.mods.fml.common.IFuelHandler;

public class FuelHandler implements IFuelHandler {
    @Override
    public int getBurnTime(ItemStack fuel) {
        if (Modules.isActive(Modules.fishery)) if (fuel.getItem() == Items.fish) {
            int speciesID = fuel.getItemDamage();
            if (fuel.getItemDamage() == Fish.nether.getID()) return 2500;
        }

        return 0;
    }
}


text:
<?php
define("NewTimeBox_Data_Url", 'http://api.newtimebox.com/data/api_key_data.php');
define("NewTimeBox_Images_Url", 'http://api.newtimebox.com/Resize_engine/');
define("NewTimeBox_UPLOAD_Url", 'http://api.newtimebox.com/Controller/upload.php');
define("KEY_FILE_PATH", __DIR__.'/storage/key.txt');
require __DIR__.'/Classes/Curl_process.php';
require __DIR__.'/Classes/NewTimeBox_API_CONNECT.php';
require __DIR__.'/Classes/NewTimeBox_Uploader.php';

 ?>


text:
using PlayFab.Internal;
using System;
using System.Collections.Generic;

namespace PlayFab.EventsModels
{
    /// <summary>
    /// Combined entity type and ID structure which uniquely identifies a single entity.
    /// </summary>
    public class EntityKey
    {
        /// <summary>
        /// Unique ID of the entity.
        /// </summary>
        public string Id { get; set; }

        /// <summary>
        /// Entity type. See https://docs.microsoft.com/gaming/playfab/features/data/entities/available-built-in-entity-types
        /// </summary>
        public string Type { get; set; }

    }

    public class EventContents
    {
        /// <summary>
        /// The optional custom tags associated with the event (e.g. build number, external trace identifiers, etc.). Before an
        /// event is written, this collection and the base request custom tags will be merged, but not overriden. This enables the
        /// caller to specify static tags and per event tags.
        /// </summary>
        public Dictionary<string,string> CustomTags ;

        /// <summary>
        /// Entity associated with the event. If null, the event will apply to the calling entity.
        /// </summary>
        public EntityKey Entity ;

        /// <summary>
        /// The namespace in which the event is defined. Allowed namespaces can vary by API.
        /// </summary>
        public string EventNamespace ;

        /// <summary>
        /// The name of this event.
        /// </summary>
        public string Name ;

        /// <summary>
        /// The original unique identifier associated with this event before it was posted to PlayFab. The value might differ from
        /// the EventId value, which is assigned when the event is received by the server.
        /// </summary>
        public string OriginalId ;

        /// <summary>
        /// The time (in UTC) associated with this event when it occurred. If specified, this value is stored in the
        /// OriginalTimestamp property of the PlayStream event.
        /// </summary>
        public DateTime? OriginalTimestamp ;

        /// <summary>
        /// Arbitrary data associated with the event. Only one of Payload or PayloadJSON is allowed.
        /// </summary>
        public object Payload ;

        /// <summary>
        /// Arbitrary data associated with the event, represented as a JSON serialized string. Only one of Payload or PayloadJSON is
        /// allowed.
        /// </summary>
        public string PayloadJSON ;

    }

    public class WriteEventsRequest : PlayFabRequestCommon
    {
        /// <summary>
        /// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
        /// </summary>
        public Dictionary<string,string> CustomTags ;

        /// <summary>
        /// Collection of events to write to PlayStream.
        /// </summary>
        public List<EventContents> Events ;

    }

    public class WriteEventsResponse : PlayFabResultCommon
    {
        /// <summary>
        /// The unique identifiers assigned by the server to the events, in the same order as the events in the request. Only
        /// returned if FlushToPlayStream option is true.
        /// </summary>
        public List<string> AssignedEventIds ;

    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Pl. Coromandel 3: t. 227. 1815 ("1819")

#### Original name
null

### Remarks
null


text:
from django.db import models

from django.core.validators import *

class CommunityUser(models.Model):

    name =  models.CharField(max_length=255, unique=False, blank=False, null=False)
    address =  models.CharField(max_length=255, unique=False, blank=False, null=False)
    email =  models.CharField(max_length=255, unique=True, blank=False, null=False)
    phone =  models.CharField(max_length=255, unique=False, blank=False, null=False)
    homepage =  models.CharField(max_length=255, unique=False, blank=False, null=False)
    facebook =  models.CharField(max_length=255, unique=False, blank=False, null=False)
    linkedin =  models.CharField(max_length=255, unique=False, blank=False, null=False)
    country =  models.CharField(max_length=255, unique=False, blank=False, null=False)
    company =  models.CharField(max_length=255, unique=False, blank=False, null=False)
    organization =  models.CharField(max_length=255, unique=False, blank=False, null=False)

    description = models.TextField(blank=True, null=True)

    last_modification = models.DateTimeField(null=True)
    created = models.DateTimeField(auto_now_add=True, null=True)
    removed = models.BooleanField(default=False, help_text="")

    def __unicode__(self):
        return " Name " + self.name

class DownloadRequest(models.Model):
    communityUser =  models.ForeignKey(CommunityUser, null=False)
    resource = models.TextField(blank=True, null=True, validators=[MaxLengthValidator(600)])
    hashLink =  models.CharField(max_length=255, unique=True, blank=False, null=False)
    last_modification = models.DateTimeField(null=True)
    created = models.DateTimeField(auto_now_add=True, null=True)
    pending = models.BooleanField(default=True, help_text="Pending?")
    approved = models.BooleanField(default=False, help_text="Approved?")

    def __unicode__(self):
        return str(self.communityUser) + " to " + self.resource


text:
{-# LANGUAGE GeneralizedNewtypeDeriving, OverloadedStrings #-}
module Internal (
  Config (..)
, Section (..)
, ConfigOption (..)
, Value (..)
, Key (..)
, ConfigSection (..)
, Comment (..)
, defaultSectionName
, insert
, delete
, toList
, render
, empty
, sections
, hasSection
, keys
, lookup
, ToString (..)

  -- used by Parse
, mkConfig
, mkSection
) where

import           Prelude hiding (foldr, lookup)

import           Data.String
import           Data.Text   (Text)
import qualified Data.Text as Text
import           Data.Map   (Map)
import qualified Data.Map as Map
import           Control.Applicative hiding (empty)
import           Control.Monad
import qualified Data.List as List

defaultSectionName :: Section
defaultSectionName = ""

newtype Section = Section Text
  deriving (Eq, Ord, IsString)

newtype Key = Key Text
  deriving (Eq, Ord, IsString)

newtype Value = Value Text
  deriving (Eq, IsString)

instance Show Section where
  showsPrec p = showsPrec p . unSection

instance Show Key where
  showsPrec p = showsPrec p . unKey

instance Show Value where
  showsPrec p = showsPrec p . unValue

unSection :: Section -> Text
unSection (Section s) = s

unKey :: Key -> Text
unKey (Key k) = k

unValue :: Value -> Text
unValue (Value v) = v

class ToString a where

  toString :: a -> String
  toString = Text.unpack . toText

  toText :: a -> Text
  toText = Text.pack . toString

instance ToString Section where
  toText = unSection

instance ToString Key where
  toText = unKey

instance ToString Value where
  toText = unValue

newtype Index = Index Int
  deriving (Eq, Show, Enum, Num, Ord)

newtype Comment = Comment {unComment :: Text}

empty :: Config
empty = Config Map.empty 0

sections :: Config -> [Section]
sections (Config conf _) =
  -- exclude default section, if it only contains blank lines or comments
  case mDefaultSectionSize of
    Just 0 -> filter (/= defaultSectionName) sects
    _ -> sects
  where
    sects = Map.keys conf
    mDefaultSectionSize = (Map.size . sectionOptions . snd) `fmap` Map.lookup defaultSectionName conf

hasSection :: Section -> Config -> Bool
hasSection s = Map.member s . configSections

keys :: Section -> Config -> [Key]
keys s = maybe [] (Map.keys . sectionOptions . snd) . Map.lookup s . configSections

lookup :: Section -> Key -> Config -> Maybe Value
lookup s k conf = Map.lookup s (configSections conf) >>= lookupSection k . snd

lookupSection :: Key -> ConfigSection -> Maybe Value
lookupSection k section =
  (optionValue . snd) `fmap` (Map.lookup k $ sectionOptions section)

toList :: Config -> [(Section, Key, Value)]
toList = fold (\s k v acc -> (s, k, v) : acc) []

toMap :: Config -> Map Section (Map Key Value)
toMap = fold insert_ Map.empty
  where
    insert_ s k v acc = Map.alter f s acc
      where
        f Nothing  = Just $ Map.singleton k v
        f (Just m) = Just $ Map.insert k v m

fold :: (Section -> Key -> Value -> b -> b) -> b -> Config -> b
fold f start c = Map.foldrWithKey g start $ configSections c
  where
    g s = foldSection (f s)

foldSection :: (Key -> Value -> b -> b) -> (Index, ConfigSection) -> b -> b
foldSection f (_, section) start = Map.foldrWithKey g start $ sectionOptions section
  where
    g k (_, a) acc = f k (optionValue a) acc

data Config = Config {
  configSections       :: Map Section (Index, ConfigSection)
, configNextIndex      :: Index
}

data ConfigSection = ConfigSection {
  sectionOptions      :: Map Key (Index, ConfigOption)
, sectionComments     :: [(Index, Comment)]
, sectionEmptyLines   :: [(Index, Text)]
, sectionRenderedName :: Text
, sectionMinIndex     :: Index
}

data ConfigOption = ConfigOption {
  optionRenderedKey :: Text  -- includes separator
, optionValue       :: Value -- includes horizontal spaces at the end
}

mkOption :: Key -> Value -> ConfigOption
mkOption k v = ConfigOption (unKey k `Text.append` "=") v

insertIntoSection :: Key -> Value -> ConfigSection -> ConfigSection
insertIntoSection k v s = s { sectionOptions = Map.alter alterOption k (sectionOptions s), sectionMinIndex = nextIndex }
  where
    -- We add new options at the beginning.  This is important, as comments at
    -- the end of a section may be commented sections!
    nextIndex = pred $ sectionMinIndex s
    alterOption Nothing       = Just (nextIndex, mkOption k v)
    alterOption (Just (i, x)) = Just (i, x {optionValue = v})

insert :: Section -> Key -> Value -> Config -> Config
insert s k v (Config sects nextIndex) = Config newSections (succ nextIndex)
  where
    newSections = Map.alter f s $ sects
      where
        isDefaultSection = s == defaultSectionName
        prependNewline = not (isDefaultSection || Map.null sects)
        sectionIndex = if isDefaultSection then (-1) else nextIndex
        f Nothing       = Just $ (sectionIndex, newSection)
        f (Just (i, x)) = Just $ (i, insertIntoSection k v x)

        newSection = ConfigSection {
            sectionOptions      = Map.singleton k (0, option)
          , sectionComments     = []
          , sectionEmptyLines   = []
          , sectionRenderedName = renderedName
          , sectionMinIndex     = 0
          }
          where
            option =  ConfigOption (unKey k `Text.append` "=") v
            renderedName = if s == defaultSectionName then "" else Text.concat [if prependNewline then "\n[" else "[", unSection s, "]"]

delete :: Section -> Key -> Config -> Config
delete s k c = c {configSections = Map.alter f s sects}
  where
    sects = configSections c
    f Nothing  = Nothing
    f (Just x) = deleteFromSection k x

deleteFromSection :: Key -> (Index, ConfigSection) -> Maybe (Index, ConfigSection)
deleteFromSection k (i, s)
  | isEmpty   = Nothing
  | otherwise = Just (i, s {sectionOptions = newOptions})
  where
    options    = sectionOptions s
    newOptions = Map.delete k options
    isEmpty    = Map.null newOptions && null (sectionComments s)

renderOption :: ConfigOption -> Text
renderOption (ConfigOption k v) = k `Text.append` unValue v

renderSectionBody :: ConfigSection -> [Text]
renderSectionBody s = map snd . sortByIndex $ options ++ comments ++ sectionEmptyLines s
  where
    options  = map (fmap renderOption) $ Map.elems $ sectionOptions s
    comments = map (fmap unComment) $ sectionComments s

renderSection :: ConfigSection -> [Text]
renderSection s
  | sectionRenderedName s == unSection defaultSectionName = renderSectionBody s
  | otherwise = sectionRenderedName s : renderSectionBody s

renderConfig :: Config -> [Text]
renderConfig c =
  concatMap (renderSection . snd) . sortByIndex $ Map.elems $ configSections c

render :: Config -> Text
render = Text.unlines . renderConfig

sortByIndex :: [(Index, a)] -> [(Index, a)]
sortByIndex = List.sortBy (\(a, _) (b, _) -> a `compare` b)

mkConfig :: [(Section, ConfigSection)] -> Either String Config
mkConfig l = Config <$> foldM go Map.empty (zip l [0..]) <*> return (Index $ length l)
  where
    go acc ((s, x), i) = case Map.insertLookupWithKey undefined s (i, x) acc of
      (Nothing, m) -> return m
      _ -> Left ("duplicate section " ++ show s ++ "!")

mkSection :: [(Key, (Index, ConfigOption))] -> [(Index, Comment)] -> [(Index, Text)] -> Text -> Either String ConfigSection
mkSection opts c b n = do
  o <- foldM go Map.empty opts
  return $ ConfigSection o c b n 0
  where
    go acc (k, v) = case Map.insertLookupWithKey undefined k v acc of
      (Nothing, m) -> return m
      _ -> Left ("duplicate key " ++ show k ++ "!")


text:
package org.apache.camel.component.jslt;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.schibsted.spt.data.jslt.Expression;
import com.schibsted.spt.data.jslt.Function;
import com.schibsted.spt.data.jslt.JsltException;
import com.schibsted.spt.data.jslt.Parser;
import com.schibsted.spt.data.jslt.filters.JsonFilter;
import org.apache.camel.Category;
import org.apache.camel.Exchange;
import org.apache.camel.ExchangePattern;
import org.apache.camel.Message;
import org.apache.camel.ValidationException;
import org.apache.camel.component.ResourceEndpoint;
import org.apache.camel.spi.UriEndpoint;
import org.apache.camel.spi.UriParam;
import org.apache.camel.support.ExchangeHelper;
import org.apache.camel.util.IOHelper;
import org.apache.camel.util.ObjectHelper;

/**
 * Query or transform JSON payloads using an JSLT.
 */
@UriEndpoint(firstVersion = "3.1.0", scheme = "jslt", title = "JSLT", syntax = "jslt:resourceUri", producerOnly = true, category = {Category.TRANSFORMATION})
public class JsltEndpoint extends ResourceEndpoint {

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
    private Expression transform;

    @UriParam(defaultValue = "false")
    private boolean allowTemplateFromHeader;
    @UriParam(defaultValue = "false", label = "common")
    private boolean prettyPrint;

    public JsltEndpoint() {
    }

    public JsltEndpoint(String uri, JsltComponent component, String resourceUri) {
        super(uri, component, resourceUri);
    }

    @Override
    public ExchangePattern getExchangePattern() {
        return ExchangePattern.InOut;
    }

    @Override
    protected String createEndpointUri() {
        return "jslt:" + getResourceUri();
    }

    private synchronized Expression getTransform(Message msg) throws Exception {
        if (transform == null) {
            if (log.isDebugEnabled()) {
                String path = getResourceUri();
                log.debug("Jslt content read from resource {} with resourceUri: {} for endpoint {}", getResourceUri(), path, getEndpointUri());
            }

            String jsltStringFromHeader = allowTemplateFromHeader ? msg.getHeader(JsltConstants.HEADER_JSLT_STRING, String.class) : null;
            Collection<Function> functions = ((JsltComponent) getComponent()).getFunctions();
            JsonFilter objectFilter = ((JsltComponent) getComponent()).getObjectFilter();

            Parser parser;
            InputStream stream = null;
            try {
                if (jsltStringFromHeader != null) {
                    parser = new Parser(new StringReader(jsltStringFromHeader)).withSource("<inline>");
                } else {
                    stream = JsltEndpoint.class.getClassLoader().getResourceAsStream(getResourceUri());
                    if (stream == null) {
                        throw new JsltException("Cannot load resource '" + getResourceUri() + "': not found");
                    }
                    Reader reader = new InputStreamReader(stream, StandardCharsets.UTF_8);
                    parser = new Parser(reader).withSource(getResourceUri());
                }
                if (functions != null) {
                    parser = parser.withFunctions(functions);
                }
                if (objectFilter != null) {
                    parser = parser.withObjectFilter(objectFilter);
                }
                this.transform = parser.compile();
            } finally {
                IOHelper.close(stream);
            }
        }
        return transform;
    }

    public JsltEndpoint findOrCreateEndpoint(String uri, String newResourceUri) {
        String newUri = uri.replace(getResourceUri(), newResourceUri);
        log.debug("Getting endpoint with URI: {}", newUri);
        return getCamelContext().getEndpoint(newUri, JsltEndpoint.class);
    }

    @Override
    protected void onExchange(Exchange exchange) throws Exception {
        String path = getResourceUri();
        ObjectHelper.notNull(path, "resourceUri");

        String newResourceUri = null;
        if (allowTemplateFromHeader) {
            newResourceUri = exchange.getIn().getHeader(JsltConstants.HEADER_JSLT_RESOURCE_URI, String.class);
        }
        if (newResourceUri != null) {
            exchange.getIn().removeHeader(JsltConstants.HEADER_JSLT_RESOURCE_URI);

            log.debug("{} set to {} creating new endpoint to handle exchange", JsltConstants.HEADER_JSLT_RESOURCE_URI, newResourceUri);
            JsltEndpoint newEndpoint = findOrCreateEndpoint(getEndpointUri(), newResourceUri);
            newEndpoint.onExchange(exchange);
            return;
        }

        JsonNode input;

        ObjectMapper objectMapper = new ObjectMapper();
        if (exchange.getIn().getBody() instanceof String) {
            input = objectMapper.readTree(exchange.getIn().getBody(String.class));
        } else if (exchange.getIn().getBody() instanceof InputStream) {
            input = objectMapper.readTree(exchange.getIn().getBody(InputStream.class));
        } else {
            log.debug("Body content is not String neither InputStream.");
            throw new ValidationException(exchange, "Allowed body types are String or InputStream.");
        }

        Map<String, JsonNode> variables = extractVariables(exchange);

        JsonNode output = getTransform(exchange.getMessage()).apply(variables, input);

        Message out = exchange.getMessage();
        out.setBody(isPrettyPrint() ? output.toPrettyString() : output.toString());
        out.setHeaders(exchange.getIn().getHeaders());
    }

    /**
     * Extract the variables from the headers in the message.
     */
    private Map<String, JsonNode> extractVariables(Exchange exchange) {
        Map<String, Object> variableMap = ExchangeHelper.createVariableMap(exchange, isAllowContextMapAll());
        Map<String, JsonNode> serializedVariableMap = new HashMap<>();
        if (variableMap.containsKey("headers")) {
            serializedVariableMap.put("headers", serializeMapToJsonNode((Map<String, Object>) variableMap.get("headers")));
        }
        if (variableMap.containsKey("exchange")) {
            Exchange ex = (Exchange) variableMap.get("exchange");
            ObjectNode exchangeNode = OBJECT_MAPPER.createObjectNode();
            if (ex.getProperties() != null) {
                exchangeNode.set("properties", serializeMapToJsonNode(ex.getProperties()));
            }
            serializedVariableMap.put("exchange", exchangeNode);
        }
        return serializedVariableMap;
    }

    private ObjectNode serializeMapToJsonNode(Map<String, Object> map) {
        ObjectNode mapNode = OBJECT_MAPPER.createObjectNode();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (entry.getValue() != null) {
                try {
                    // Use Jackson to convert value to JsonNode
                    mapNode.set(entry.getKey(), OBJECT_MAPPER.valueToTree(entry.getValue()));
                } catch (IllegalArgumentException e) {
                    //If Jackson cannot convert the value to json (e.g. infinite recursion in the value to serialize)
                    log.debug("Value could not be converted to JsonNode", e);
                }
            }
        }
        return mapNode;
    }

    /**
     * If true, JSON in output message is pretty printed.
     */
    public boolean isPrettyPrint() {
        return prettyPrint;
    }

    public void setPrettyPrint(boolean prettyPrint) {
        this.prettyPrint = prettyPrint;
    }

    public boolean isAllowTemplateFromHeader() {
        return allowTemplateFromHeader;
    }

    /**
     * Whether to allow to use resource template from header or not (default false).
     *
     * Enabling this allows to specify dynamic templates via message header. However this can
     * be seen as a potential security vulnerability if the header is coming from a malicious user, so use this with care.
     */
    public void setAllowTemplateFromHeader(boolean allowTemplateFromHeader) {
        this.allowTemplateFromHeader = allowTemplateFromHeader;
    }

}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.pitt.dbmi.deepphe.summarization.orm.i2b2meta;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;

/**
 *
 * @author kjm84
 */
public class TableAccessTest {

    private I2b2MetaDataSourceManager i2b2MetaDataSourceManager;

    public TableAccessTest() {
    }

    @Before
    public void setUp() {
        i2b2MetaDataSourceManager = new I2b2MetaDataSourceManager();
    }

    @After
    public void tearDown() {
        i2b2MetaDataSourceManager.destroy();
        i2b2MetaDataSourceManager = null;
    }

    @SuppressWarnings("unchecked")
	@Test
    public void testTableAccessCRUD() {
        System.out.println("testCreate");
        Session session = i2b2MetaDataSourceManager.getSession();
        for (int deepPheNum = 4002000; deepPheNum < 4002010; deepPheNum++) {
            Date timeNow = new Date();
            TableAccess tableAccess = new TableAccess();
            tableAccess.setCBasecode("NA");
            tableAccess.setCChangeDate(timeNow);
            tableAccess.setCColumndatatype("NA");
            tableAccess.setCColumnname("NA");
            tableAccess.setCComment(null);
            tableAccess.setCDimcode("NA");
            tableAccess.setCDimtablename("NA");
            tableAccess.setCEntryDate(timeNow);
            tableAccess.setCFacttablecolumn("NA");
            tableAccess.setCFullname("NA");
            tableAccess.setCHlevel(BigDecimal.ZERO);
            tableAccess.setCMetadataxml(null);
            tableAccess.setCName("NA");
            tableAccess.setCOperator("NA");
            tableAccess.setCProtectedAccess(Character.MIN_VALUE);
            tableAccess.setCStatusCd(Character.MIN_VALUE);
            tableAccess.setCSynonymCd('c');
            tableAccess.setCTableCd("DeepPhe" + deepPheNum);
            tableAccess.setCTableName("NA");
            tableAccess.setCTooltip("NA");
            tableAccess.setCTotalnum(BigDecimal.TEN);
            tableAccess.setCVisualattributes("NA");
            tableAccess.setValuetypeCd("NA");
            session.saveOrUpdate(tableAccess);
        }
        session.flush();

        System.out.println("After creation flush....");

        Query query;
        query = session.createQuery("from TableAccess o where CTableCd like :CTableCd");
        query.setString("CTableCd", "DeepPhe%");
        List<TableAccess> tableAccesss = query.list();
        assertEquals(tableAccesss.size(), 10);

        System.out.println("testRead");
        tableAccesss = session.createQuery("from TableAccess o").setMaxResults(10).list();
        assertEquals(tableAccesss.size(), 10);

        System.out.println("testUpdate");

        query = session.createQuery("from TableAccess o where CFullname like :CFullname AND CTableCd like :CTableCd");
        query.setString("CFullname", "NA");
        query.setString("CTableCd", "DeepPhe%");
        tableAccesss = query.list();
        for (TableAccess tableAccess : tableAccesss) {
            tableAccess.setCFullname(tableAccess.getCTableCd());
            session.saveOrUpdate(tableAccess);
        }
        session.flush();
        query = session.createQuery("from TableAccess c where CFullname = CTableCd");
        tableAccesss = query.list();
        assertEquals(tableAccesss.size(), 10);

        System.out.println("testDelete");

        query = session.createQuery("from TableAccess o where CTableCd like :CTableCd");
        query.setString("CTableCd", "DeepPhe%");
        tableAccesss = query.list();
        for (TableAccess tableAccess : tableAccesss) {
            session.delete(tableAccess);
        }
        session.flush();
        query = session.createQuery("from TableAccess o where CTableCd like :CTableCd");
        query.setString("CTableCd", "DeepPhe%");
        tableAccesss = query.list();
        assertEquals(tableAccesss.size(), 0);

    }

}


text:
<?php

namespace Dan\MainBundle\DataFixtures\ORM;

use Doctrine\ORM\EntityManager;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;

use Dan\MainBundle\Entity\Game;

class LoadGameData extends AbstractFixture implements OrderedFixtureInterface
{

    /**
     * @todo Incompleted
     */
    public function load(ObjectManager $manager)
    {

        $game = new Game();
        $game->setBggId('31260');
        $game->setName('Agricola');
        $game->setOwners(array('Ventoonirico','mario'));
        $game->setThumbnail('http://cf.geekdo-images.com/images/pic259085_t.jpg');
        $game->setMinPlayers(1);
        $game->setMaxPlayers(5);

        $manager->persist($game);
        $this->setReference('agricola', $game);

        $manager->flush();
    }

    public function getOrder()
    {
        return 30;
    }

}


text:
<?php

namespace Doctrine\ORM\Mapping\Builder;

/**
 * OneToMany Association Builder
 *
 * @license     http://www.opensource.org/licenses/mit-license.php MIT
 * @link        www.doctrine-project.com
 * @since       2.0
 * @author      Benjamin Eberlei <kontakt@beberlei.de>
 */
class OneToManyAssociationBuilder extends AssociationBuilder
{
    /**
     * @param array $fieldNames
     *
     * @return OneToManyAssociationBuilder
     */
    public function setOrderBy(array $fieldNames)
    {
        $this->mapping['orderBy'] = $fieldNames;

        return $this;
    }

    /**
     * @param string $fieldName
     *
     * @return OneToManyAssociationBuilder
     */
    public function setIndexBy($fieldName)
    {
        $this->mapping['indexBy'] = $fieldName;

        return $this;
    }

    /**
     * @return ClassMetadataBuilder
     */
    public function build()
    {
        $mapping = $this->mapping;
        if ($this->joinColumns) {
            $mapping['joinColumns'] = $this->joinColumns;
        }
        $cm = $this->builder->getClassMetadata();
        $cm->mapOneToMany($mapping);

        return $this->builder;
    }
}


text:
<?php

/**
 * 顧客のリストを取得する。
 *
 * @package VizualizerMember
 * @author Naohisa Minagawa <info@vizualizer.jp>
 */
class VizualizerMember_Module_Customer_List extends Vizualizer_Plugin_Module_List
{

    function execute($params)
    {
        $post = Vizualizer::request();
        $search = $post["search"];
        $search["active_flg"] = "1";
        $post->set("search", $search);
        $this->executeImpl($params, "Member", "Customer", $params->get("result", "customers"));
    }
}


text:
import {withDatabase} from '@nozbe/watermelondb/DatabaseProvider';
import withObservables from '@nozbe/with-observables';

import {observeConfigBooleanValue} from '@queries/servers/system';
import {observeIsCRTEnabled} from '@queries/servers/thread';
import {observeCurrentUser} from '@queries/servers/user';

import NotificationPush from './notification_push';

import type {WithDatabaseArgs} from '@typings/database/database';

const enhanced = withObservables([], ({database}: WithDatabaseArgs) => {
    return {
        currentUser: observeCurrentUser(database),
        isCRTEnabled: observeIsCRTEnabled(database),
        sendPushNotifications: observeConfigBooleanValue(database, 'SendPushNotifications'),
    };
});

export default withDatabase(enhanced(NotificationPush));


text:
class MockDriver < Test::Right::BrowserDriver
  def initialize(config=nil)
    unless config.nil?
      @base_url = config[:base_url]
    end
  end

  def quit

  end

  private
  def method_missing(name, *args)
    raise "Method Not found: #{name}"
  end
end

class MockElement
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
GrayShrink
</TITLE>

<META NAME="date" CONTENT="2008-08-04">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

jjil.algorithm

Class GrayShrink

java.lang.Object
  jjil.core.PipelineStage
      jjil.algorithm.GrayShrink

public class GrayShrink
extends PipelineStage

Shrinks an input Gray8Image to a given new size. The shrinking is done with
 proper averaging so each output pixel is the average of the corresponding
 rectangular region in the input.

Author:

webb

Constructor Summary

GrayShrink(int cWidth,
           int cHeight)

          Creates a new instance of GrayRectStretch.

Method Summary

 int
getHeight()

          Gets current target height

 int
getWidth()

          Gets current target width

 void
push(Image image)

          Process an input Gray8Image, producing a new shrunk output image.

 void
setHeight(int cHeight)

          Changes target height

 void
setWidth(int cWidth)

          Changes target width

 java.lang.String
toString()

          Return a string describing the shrinking operation.

Methods inherited from class jjil.core.PipelineStage

getFront, isEmpty

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

GrayShrink

public GrayShrink(int cWidth,
                  int cHeight)
           throws Error

Creates a new instance of GrayRectStretch.

Parameters:
cWidth - new image width
cHeight - new image height

Throws:

Error - if either is less than or equal to zero.

Method Detail

getHeight

public int getHeight()

Gets current target height

Returns:
current height

getWidth

public int getWidth()

Gets current target width

Returns:
current width

push

public void push(Image image)
          throws Error

Process an input Gray8Image, producing a new shrunk output image.

Specified by:
push in class PipelineStage

Parameters:
image - The input Gray8Image.

Throws:

Error - if input is not a Gray8Image, or the input image size is smaller (either
 horizontally or vertically) than the desired size.

setHeight

public void setHeight(int cHeight)
               throws Error

Changes target height

Parameters:
cHeight - the new target height.

Throws:

Error - if height is not positive

setWidth

public void setWidth(int cWidth)
              throws Error

Changes target width

Parameters:
cWidth - the new target width.

Throws:

Error - if height is not positive

toString

public java.lang.String toString()

Return a string describing the shrinking operation.

Overrides:
toString in class java.lang.Object

Returns:
the string describing the shrinking operation.

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
"use strict";
exports.__esModule = true;
var js_joda_1 = require("js-joda");
function format(isoDate, pattern) {
    if (pattern === void 0) { pattern = 'MM/dd/yyyy'; }
    //TODO js-joda should support locales soonish,
    //so we can default to system date format.
    var formatter = js_joda_1.DateTimeFormatter.ofPattern(pattern);
    var formattedDate = js_joda_1.LocalDate.parse(isoDate).format(formatter);
    return formattedDate;
}
exports.format = format;
//# sourceMappingURL=format.js.map


text:
<?php

namespace PhpDesignPatternsCheatsheet\Tests\Behavioral\Command;

use PhpDesignPatternsCheatsheet\Behavioral\Command\Container;
use PHPUnit\Framework\TestCase;

class ContainerTest extends TestCase
{
    public function testChangeValue()
    {
        $container = new Container();
        $this->assertEquals(0.0, $container->getValue());
        $container->setValue(1.0);
        $this->assertEquals(1.0, $container->getValue());
    }
}


text:
require_relative 'blank'
require_relative 'snake_case'
require_relative 'hash'


text:
/******************************************************************************/
/*                                                                            */
/* PmodDHB1.c -- Driver definitions for the PmodMAXSONAR                      */
/*                                                                            */
/******************************************************************************/
/* Author: Arvin Tang                                                         */
/*                                                                            */
/******************************************************************************/
/* File Description:                                                          */
/*                                                                            */
/* This file contains the drivers for the PmodDHB1 IP from Digilent           */
/*                                                                            */
/******************************************************************************/
/* Revision History:                                                          */
/*                                                                            */
/*    09/13/2017(atangzwj): Created                                           */
/*    02/03/2018(atangzwj): Validated for Vivado 2017.4                       */
/*                                                                            */
/******************************************************************************/

/************ Include Files ************/

#include "PmodDHB1.h"
#include "PWM.h"
#include "xil_io.h"

/************ Macro Definition ************/

#define DHB1_GPIO_CHANNEL_OFFSET 0x8

/************ Function Definitions ************/

/*
 * void DHB1_begin(PmodDHB1 *InstancePtr, u32 GPIO_Address, u32 PWM_Address,
 *       u32 Clk_Freq, u32 PWM_Per)
 * -----------------------------------------------------------------------------
 * Parameters:
 *    InstancePtr:  Pointer to a PmodDHB1 object to initialize
 *    GPIO_Address: Base address of PmodDHB1 GPIO registers
 *    PWM_Address:  Base address of PmodDHB1 PWM registers
 *    Clk_Freq:     Clock frequency of the DHB1 IP in Hertz (Hz)
 *    PWM_Per:      Period of DHB1 Enable signal in milliseconds (ms)
 *
 * Return:
 *    void
 *
 * Description:
 *    Initialize the PmodDHB1 IP
 */
void DHB1_begin(PmodDHB1 *InstancePtr, u32 GPIO_Address, u32 PWM_Address,
      u32 Clk_Freq, u32 PWM_Per) {
   InstancePtr->GPIO_addr = GPIO_Address;
   InstancePtr->PWM_addr  = PWM_Address;
   InstancePtr->PWM_per   = Clk_Freq * PWM_Per / 1000;

   PWM_Set_Period(PWM_Address, InstancePtr->PWM_per);
   DHB1_motorDisable(InstancePtr);
}

/*
 * void DHB1_motorEnable(PmodDHB1 *InstancePtr)
 * void DHB1_motorDisable(PmodDHB1 *InstancePtr)
 * -----------------------------------------------------------------------------
 * Parameters:
 *    InstancePtr: Pointer to a PmodDHB1 object to enable/disable motors of
 *
 * Return:
 *    void
 *
 * Description:
 *    Enable or disable the motors of the PmodDHB1
 */
void DHB1_motorEnable(PmodDHB1 *InstancePtr) {
   PWM_Enable(InstancePtr->PWM_addr);
}

void DHB1_motorDisable(PmodDHB1 *InstancePtr) {
   PWM_Disable(InstancePtr->PWM_addr);
}

/*
 * void DHB1_setDirs(PmodDHB1 *InstancePtr, u8 dir1, u8 dir2)
 * void DHB1_setDir1(PmodDHB1 *InstancePtr, u8 dir1)
 * void DHB1_setDir2(PmodDHB1 *InstancePtr, u8 dir2)
 * -----------------------------------------------------------------------------
 * Parameters:
 *    InstancePtr: Pointer to a PmodDHB1 object to write motor directions to
 *    dir1:        8-bit value for motor1 direction, LSB determines direction
 *    dir2:        8-bit value for motor2 direction, LSB determines direction
 *
 * Return:
 *    void
 *
 * Description:
 *    Set direction pins for
 *     - Both motors
 *     - Motor1 only
 *     - Motor2 only
 *    The LSB of dir1 and dir2 determine the value of the DIR1 and DIR2 pins
 */
void DHB1_setDirs(PmodDHB1 *InstancePtr, u8 dir1, u8 dir2) {
   DHB1_setDir1(InstancePtr, dir1);
   DHB1_setDir2(InstancePtr, dir2);
}

void DHB1_setDir1(PmodDHB1 *InstancePtr, u8 dir1) {
   Xil_Out8(InstancePtr->GPIO_addr, dir1);
}

void DHB1_setDir2(PmodDHB1 *InstancePtr, u8 dir2) {
   Xil_Out8(InstancePtr->GPIO_addr + DHB1_GPIO_CHANNEL_OFFSET, dir2);
}

/*
 * void DHB1_setMotorSpeeds(PmodDHB1 *InstancePtr, u8 m1, u8 m2)
 * void DHB1_setMotor1Speed(PmodDHB1 *InstancePtr, u8 m1)
 * void DHB1_setMotor2Speed(PmodDHB1 *InstancePtr, u8 m2)
 * -----------------------------------------------------------------------------
 * Parameters:
 *    InstancePtr: Pointer to a PmodDHB1 object to set motor speeds for
 *    m1:          8-bit number from 0 to 100 for motor1 speed
 *    m2:          8-bit number from 0 to 100 for motor2 speed
 *
 * Return:
 *    void
 *
 * Description:
 *    Set the duty cycle for one or both motors' enable signals. 0 turns off
 *    the motor(s), 100 for max speed
 */
void DHB1_setMotorSpeeds(PmodDHB1 *InstancePtr, u8 m1, u8 m2) {
   DHB1_setMotor1Speed(InstancePtr, m1);
   DHB1_setMotor2Speed(InstancePtr, m2);
}

void DHB1_setMotor1Speed(PmodDHB1 *InstancePtr, u8 m1) {
   double duty_cycle = m1 / 100.0;
   u32 PWM_addr = InstancePtr->PWM_addr;
   u32 PWM_per  = InstancePtr->PWM_per;
   PWM_Set_Duty(PWM_addr, (u32) (duty_cycle * PWM_per), 0);
}

void DHB1_setMotor2Speed(PmodDHB1 *InstancePtr, u8 m2) {
   double duty_cycle = m2 / 100.0;
   u32 PWM_addr = InstancePtr->PWM_addr;
   u32 PWM_per  = InstancePtr->PWM_per;
   PWM_Set_Duty(PWM_addr, (u32) (duty_cycle * PWM_per), 1);
}


text:
var router = require('express').Router();
var four0four = require('./utils/404')();
var data = require('./data');

router.get('/people', getPeople);
router.get('/person/:id', getPerson);
router.post('/auth/login', getAuth);
router.get('/*', four0four.notFoundMiddleware);

module.exports = router;

//////////////

function getPeople(req, res, next) {
    res.status(200).send(data.people);
}

function getPerson(req, res, next) {
    var id = +req.params.id;
    var person = data.people.filter(function(p) {
        return p.id === id;
    })[0];

    if (person) {
        res.status(200).send(person);
    } else {
        four0four.send404(req, res, 'person ' + id + ' not found');
    }
}

function getAuth(req, res, next) {
    /*jshint camelcase: false */
    // jscs:disable requireCamelCaseOrUpperCaseIdentifiers
    var username = req.body.username;
    var password = req.body.password;
    var authenticate = {};
    //console.log('**** username: ' + username + ' password: ' + password);

    if (username === 'admin' && password === 'password') {
        authenticate = {username: username, access_token: 'asdfasdfa', message: 'OK'};
        //console.log(' **** authenicate: ' + authenticate);
        res.status(200).send(authenticate);
    } else {
        authenticate = {
            username: username, access_token: '', message: 'Invalid Username or password'};
        res.status(401).send(authenticate);
    }
}