text:
/**
 * Driver for the High Speed USB EHCI module on the TI OMAP3530 SoC.
 *
 * WARNING: I've only tried this driver on a limited number of USB peripherals,
 * it is still very raw and bound to have numerous bugs in it.
 *
 * This driver is based on the FreeBSD IXP4xx EHCI driver with a lot of the
 * setup sequence coming from the Linux community and their EHCI driver for
 * OMAP.  Without these as a base I don't think I would have been able to get
 * this driver working.
 *
 * The driver only contains the EHCI parts, the module also supports OHCI and
 * USB on-the-go (OTG), currently neither are supported.
 *
 * CAUTION: This driver was written to run on the beaglebaord dev board, so I
 * have made some assumptions about the type of PHY used and some of the other
 * settings.  Bare that in mind if you intend to use this driver on another
 * platform.
 *
 * NOTE: This module uses a few different clocks, one being a 60Mhz clock for
 * the TTL part of the module.  This clock is derived from DPPL5 which must be
 * configured prior to loading this driver - it is not configured by the
 * bootloader.  It took me a long time to figure this out, and caused much
 * frustration.  This PLL is now setup in the timer/clocks part of the BSP,
 * check out the omap_prcm_setup_dpll5() function in omap_prcm.c for more info.
 *
 */

#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");

#include "opt_bus.h"

#include <sys/stdint.h>
#include <sys/stddef.h>
#include <sys/param.h>
#include <sys/queue.h>
#include <sys/types.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/bus.h>
#include <sys/rman.h>
#include <sys/linker_set.h>
#include <sys/module.h>
#include <sys/lock.h>
#include <sys/mutex.h>
#include <sys/condvar.h>
#include <sys/sysctl.h>
#include <sys/sx.h>
#include <sys/unistd.h>
#include <sys/callout.h>
#include <sys/malloc.h>
#include <sys/priv.h>
#include <sys/gpio.h>

#include <dev/fdt/fdt_common.h>
#include <dev/ofw/openfirm.h>
#include <dev/ofw/ofw_bus.h>
#include <dev/ofw/ofw_bus_subr.h>

#include <dev/usb/usb.h>
#include <dev/usb/usbdi.h>

#include <dev/usb/usb_core.h>
#include <dev/usb/usb_busdma.h>
#include <dev/usb/usb_process.h>
#include <dev/usb/usb_util.h>

#include <dev/usb/usb_controller.h>
#include <dev/usb/usb_bus.h>
#include <dev/usb/controller/ehci.h>
#include <dev/usb/controller/ehcireg.h>

#include <arm/ti/tivar.h>
#include <arm/ti/ti_prcm.h>
#include <arm/ti/ti_scm.h>

#include <arm/ti/usb/omap_usb.h>

#include "gpio_if.h"

struct omap_ehci_softc {
	ehci_softc_t        base;	/* storage for EHCI code */

	device_t            sc_dev;
	device_t            sc_gpio_dev;

	/* TLL register set */
	struct resource*    tll_mem_res;

	/* UHH register set */
	struct resource*    uhh_mem_res;

	/* The revision of the HS USB HOST read from UHH_REVISION */
	uint32_t            ehci_rev;

	/* The following details are provided by conf hints */
	int                 port_mode[3];
	int                 phy_reset[3];
	int                 reset_gpio_pin[3];
};

static device_attach_t omap_ehci_attach;
static device_detach_t omap_ehci_detach;
static device_shutdown_t omap_ehci_shutdown;
static device_suspend_t omap_ehci_suspend;
static device_resume_t omap_ehci_resume;

/**
 *	omap_tll_read_4 - read a 32-bit value from the USBTLL registers
 *	omap_tll_write_4 - write a 32-bit value from the USBTLL registers
 *	omap_tll_readb - read an 8-bit value from the USBTLL registers
 *	omap_tll_writeb - write an 8-bit value from the USBTLL registers
 *	@sc: omap ehci device context
 *	@off: byte offset within the register set to read from
 *	@val: the value to write into the register
 *
 *
 *	LOCKING:
 *	None
 *
 *	RETURNS:
 *	nothing in case of write function, if read function returns the value read.
 */
static inline uint32_t
omap_tll_read_4(struct omap_ehci_softc *sc, bus_size_t off)
{
	return bus_read_4(sc->tll_mem_res, off);
}

static inline void
omap_tll_write_4(struct omap_ehci_softc *sc, bus_size_t off, uint32_t val)
{
	bus_write_4(sc->tll_mem_res, off, val);
}

static inline uint8_t
omap_tll_readb(struct omap_ehci_softc *sc, bus_size_t off)
{
	return bus_read_1(sc->tll_mem_res, off);
}

static inline void
omap_tll_writeb(struct omap_ehci_softc *sc, bus_size_t off, uint8_t val)
{
	bus_write_1(sc->tll_mem_res, off, val);
}

/**
 *	omap_ehci_read_4 - read a 32-bit value from the EHCI registers
 *	omap_ehci_write_4 - write a 32-bit value from the EHCI registers
 *	@sc: omap ehci device context
 *	@off: byte offset within the register set to read from
 *	@val: the value to write into the register
 *
 *
 *	LOCKING:
 *	None
 *
 *	RETURNS:
 *	nothing in case of write function, if read function returns the value read.
 */
static inline uint32_t
omap_ehci_read_4(struct omap_ehci_softc *sc, bus_size_t off)
{
	return (bus_read_4(sc->base.sc_io_res, off));
}
static inline void
omap_ehci_write_4(struct omap_ehci_softc *sc, bus_size_t off, uint32_t val)
{
	bus_write_4(sc->base.sc_io_res, off, val);
}

/**
 *	omap_uhh_read_4 - read a 32-bit value from the UHH registers
 *	omap_uhh_write_4 - write a 32-bit value from the UHH registers
 *	@sc: omap ehci device context
 *	@off: byte offset within the register set to read from
 *	@val: the value to write into the register
 *
 *
 *	LOCKING:
 *	None
 *
 *	RETURNS:
 *	nothing in case of write function, if read function returns the value read.
 */
static inline uint32_t
omap_uhh_read_4(struct omap_ehci_softc *sc, bus_size_t off)
{
	return bus_read_4(sc->uhh_mem_res, off);
}
static inline void
omap_uhh_write_4(struct omap_ehci_softc *sc, bus_size_t off, uint32_t val)
{
	bus_write_4(sc->uhh_mem_res, off, val);
}

/**
 *	omap_ehci_utmi_init - initialises the UTMI part of the controller
 *	@isc: omap ehci device context
 *
 *
 *
 *	LOCKING:
 *	none
 *
 *	RETURNS:
 *	nothing
 */
static void
omap_ehci_utmi_init(struct omap_ehci_softc *isc, unsigned int en_mask)
{
	unsigned int i;
	uint32_t reg;

	/* There are 3 TLL channels, one per USB controller so set them all up the
	 * same, SDR mode, bit stuffing and no autoidle.
	 */
	for (i=0; i<3; i++) {
		reg = omap_tll_read_4(isc, OMAP_USBTLL_TLL_CHANNEL_CONF(i));

		reg &= ~(TLL_CHANNEL_CONF_UTMIAUTOIDLE
				 | TLL_CHANNEL_CONF_ULPINOBITSTUFF
				 | TLL_CHANNEL_CONF_ULPIDDRMODE);

		omap_tll_write_4(isc, OMAP_USBTLL_TLL_CHANNEL_CONF(i), reg);
	}

	/* Program the common TLL register */
	reg = omap_tll_read_4(isc, OMAP_USBTLL_TLL_SHARED_CONF);

	reg &= ~( TLL_SHARED_CONF_USB_90D_DDR_EN
			| TLL_SHARED_CONF_USB_DIVRATIO_MASK);
	reg |=  ( TLL_SHARED_CONF_FCLK_IS_ON
			| TLL_SHARED_CONF_USB_DIVRATIO_2
			| TLL_SHARED_CONF_USB_180D_SDR_EN);

	omap_tll_write_4(isc, OMAP_USBTLL_TLL_SHARED_CONF, reg);

	/* Enable channels now */
	for (i = 0; i < 3; i++) {
		reg = omap_tll_read_4(isc, OMAP_USBTLL_TLL_CHANNEL_CONF(i));

		/* Enable only the reg that is needed */
		if ((en_mask & (1 << i)) == 0)
			continue;

		reg |= TLL_CHANNEL_CONF_CHANEN;
		omap_tll_write_4(isc, OMAP_USBTLL_TLL_CHANNEL_CONF(i), reg);
	}
}

/**
 *	omap_ehci_soft_phy_reset - resets the phy using the reset command
 *	@isc: omap ehci device context
 *	@port: port to send the reset over
 *
 *
 *	LOCKING:
 *	none
 *
 *	RETURNS:
 *	nothing
 */
static void
omap_ehci_soft_phy_reset(struct omap_ehci_softc *isc, unsigned int port)
{
	unsigned long timeout = (hz < 10) ? 1 : ((100 * hz) / 1000);
	uint32_t reg;

	reg = ULPI_FUNC_CTRL_RESET
		/* FUNCTION_CTRL_SET register */
		| (ULPI_SET(ULPI_FUNC_CTRL) << OMAP_USBHOST_INSNREG05_ULPI_REGADD_SHIFT)
		/* Write */
		| (2 << OMAP_USBHOST_INSNREG05_ULPI_OPSEL_SHIFT)
		/* PORTn */
		| ((port + 1) << OMAP_USBHOST_INSNREG05_ULPI_PORTSEL_SHIFT)
		/* start ULPI access*/
		| (1 << OMAP_USBHOST_INSNREG05_ULPI_CONTROL_SHIFT);

	omap_ehci_write_4(isc, OMAP_USBHOST_INSNREG05_ULPI, reg);

	/* Wait for ULPI access completion */
	while ((omap_ehci_read_4(isc, OMAP_USBHOST_INSNREG05_ULPI)
	       & (1 << OMAP_USBHOST_INSNREG05_ULPI_CONTROL_SHIFT))) {

		/* Sleep for a tick */
		pause("USBPHY_RESET", 1);

		if (timeout-- == 0) {
			device_printf(isc->sc_dev, "PHY reset operation timed out\n");
			break;
		}
	}
}

/**
 *	omap_ehci_init - initialises the USB host EHCI controller
 *	@isc: omap ehci device context
 *
 *	This initialisation routine is quite heavily based on the work done by the
 *	OMAP Linux team (for which I thank them very much).  The init sequence is
 *	almost identical, diverging only for the FreeBSD specifics.
 *
 *	LOCKING:
 *	none
 *
 *	RETURNS:
 *	0 on success, a negative error code on failure.
 */
static int
omap_ehci_init(struct omap_ehci_softc *isc)
{
	unsigned long timeout;
	int ret = 0;
	uint8_t tll_ch_mask = 0;
	uint32_t reg = 0;
	int reset_performed = 0;
	int i;

	device_printf(isc->sc_dev, "Starting TI EHCI USB Controller\n");

	/* Enable Clocks for high speed USBHOST */
	ti_prcm_clk_enable(USBHSHOST_CLK);

	/* Hold the PHY in reset while configuring */
	for (int i = 0; i < 3; i++) {
		if (isc->phy_reset[i]) {
			/* Configure the GPIO to drive low (hold in reset) */
			if ((isc->reset_gpio_pin[i] != -1) && (isc->sc_gpio_dev != NULL)) {
				GPIO_PIN_SETFLAGS(isc->sc_gpio_dev, isc->reset_gpio_pin[i],
				    GPIO_PIN_OUTPUT);
				GPIO_PIN_SET(isc->sc_gpio_dev, isc->reset_gpio_pin[i],
				    GPIO_PIN_LOW);
				reset_performed = 1;
			}
		}
	}

	/* Hold the PHY in RESET for enough time till DIR is high */
	if (reset_performed)
		DELAY(10);

	/* Read the UHH revision */
	isc->ehci_rev = omap_uhh_read_4(isc, OMAP_USBHOST_UHH_REVISION);
	device_printf(isc->sc_dev, "UHH revision 0x%08x\n", isc->ehci_rev);

	/* Initilise the low level interface module(s) */
	if (isc->ehci_rev == OMAP_EHCI_REV1) {

		/* Enable the USB TLL */
		ti_prcm_clk_enable(USBTLL_CLK);

		/* Perform TLL soft reset, and wait until reset is complete */
		omap_tll_write_4(isc, OMAP_USBTLL_SYSCONFIG, TLL_SYSCONFIG_SOFTRESET);

		/* Set the timeout to 100ms*/
		timeout = (hz < 10) ? 1 : ((100 * hz) / 1000);

		/* Wait for TLL reset to complete */
		while ((omap_tll_read_4(isc, OMAP_USBTLL_SYSSTATUS) &
		        TLL_SYSSTATUS_RESETDONE) == 0x00) {

			/* Sleep for a tick */
			pause("USBRESET", 1);

			if (timeout-- == 0) {
				device_printf(isc->sc_dev, "TLL reset operation timed out\n");
				ret = EINVAL;
				goto err_sys_status;
			}
		}

		device_printf(isc->sc_dev, "TLL RESET DONE\n");

		/* CLOCKACTIVITY = 1 : OCP-derived internal clocks ON during idle
		 * SIDLEMODE = 2     : Smart-idle mode. Sidleack asserted after Idlereq
		 *                     assertion when no more activity on the USB.
		 * ENAWAKEUP = 1     : Wakeup generation enabled
		 */
		omap_tll_write_4(isc, OMAP_USBTLL_SYSCONFIG, TLL_SYSCONFIG_ENAWAKEUP |
		                                            TLL_SYSCONFIG_AUTOIDLE |
		                                            TLL_SYSCONFIG_SIDLE_SMART_IDLE |
		                                            TLL_SYSCONFIG_CACTIVITY);

	} else if (isc->ehci_rev == OMAP_EHCI_REV2) {

		/* For OMAP44xx devices you have to enable the per-port clocks:
		 *  PHY_MODE  - External ULPI clock
		 *  TTL_MODE  - Internal UTMI clock
		 *  HSIC_MODE - Internal 480Mhz and 60Mhz clocks
		 */
		if (isc->ehci_rev == OMAP_EHCI_REV2) {
			if (isc->port_mode[0] == EHCI_HCD_OMAP_MODE_PHY) {
				ti_prcm_clk_set_source(USBP1_PHY_CLK, EXT_CLK);
				ti_prcm_clk_enable(USBP1_PHY_CLK);
			} else if (isc->port_mode[0] == EHCI_HCD_OMAP_MODE_TLL)
				ti_prcm_clk_enable(USBP1_UTMI_CLK);
			else if (isc->port_mode[0] == EHCI_HCD_OMAP_MODE_HSIC)
				ti_prcm_clk_enable(USBP1_HSIC_CLK);

			if (isc->port_mode[1] == EHCI_HCD_OMAP_MODE_PHY) {
				ti_prcm_clk_set_source(USBP2_PHY_CLK, EXT_CLK);
				ti_prcm_clk_enable(USBP2_PHY_CLK);
			} else if (isc->port_mode[1] == EHCI_HCD_OMAP_MODE_TLL)
				ti_prcm_clk_enable(USBP2_UTMI_CLK);
			else if (isc->port_mode[1] == EHCI_HCD_OMAP_MODE_HSIC)
				ti_prcm_clk_enable(USBP2_HSIC_CLK);
		}
	}

	/* Put UHH in SmartIdle/SmartStandby mode */
	reg = omap_uhh_read_4(isc, OMAP_USBHOST_UHH_SYSCONFIG);
	if (isc->ehci_rev == OMAP_EHCI_REV1) {
		reg &= ~(UHH_SYSCONFIG_SIDLEMODE_MASK |
		         UHH_SYSCONFIG_MIDLEMODE_MASK);
		reg |= (UHH_SYSCONFIG_ENAWAKEUP |
		        UHH_SYSCONFIG_AUTOIDLE |
		        UHH_SYSCONFIG_CLOCKACTIVITY |
		        UHH_SYSCONFIG_SIDLEMODE_SMARTIDLE |
		        UHH_SYSCONFIG_MIDLEMODE_SMARTSTANDBY);
	} else if (isc->ehci_rev == OMAP_EHCI_REV2) {
		reg &= ~UHH_SYSCONFIG_IDLEMODE_MASK;
		reg |=  UHH_SYSCONFIG_IDLEMODE_NOIDLE;
		reg &= ~UHH_SYSCONFIG_STANDBYMODE_MASK;
		reg |=  UHH_SYSCONFIG_STANDBYMODE_NOSTDBY;
	}
	omap_uhh_write_4(isc, OMAP_USBHOST_UHH_SYSCONFIG, reg);
	device_printf(isc->sc_dev, "OMAP_UHH_SYSCONFIG: 0x%08x\n", reg);

	reg = omap_uhh_read_4(isc, OMAP_USBHOST_UHH_HOSTCONFIG);

	/* Setup ULPI bypass and burst configurations */
	reg |= (UHH_HOSTCONFIG_ENA_INCR4 |
			UHH_HOSTCONFIG_ENA_INCR8 |
			UHH_HOSTCONFIG_ENA_INCR16);
	reg &= ~UHH_HOSTCONFIG_ENA_INCR_ALIGN;

	if (isc->ehci_rev == OMAP_EHCI_REV1) {
		if (isc->port_mode[0] == EHCI_HCD_OMAP_MODE_UNKNOWN)
			reg &= ~UHH_HOSTCONFIG_P1_CONNECT_STATUS;
		if (isc->port_mode[1] == EHCI_HCD_OMAP_MODE_UNKNOWN)
			reg &= ~UHH_HOSTCONFIG_P2_CONNECT_STATUS;
		if (isc->port_mode[2] == EHCI_HCD_OMAP_MODE_UNKNOWN)
			reg &= ~UHH_HOSTCONFIG_P3_CONNECT_STATUS;

		/* Bypass the TLL module for PHY mode operation */
		if ((isc->port_mode[0] == EHCI_HCD_OMAP_MODE_PHY) ||
		    (isc->port_mode[1] == EHCI_HCD_OMAP_MODE_PHY) ||
		    (isc->port_mode[2] == EHCI_HCD_OMAP_MODE_PHY))
			reg &= ~UHH_HOSTCONFIG_P1_ULPI_BYPASS;
		else
			reg |= UHH_HOSTCONFIG_P1_ULPI_BYPASS;

	} else if (isc->ehci_rev == OMAP_EHCI_REV2) {
		reg |=  UHH_HOSTCONFIG_APP_START_CLK;

		/* Clear port mode fields for PHY mode*/
		reg &= ~UHH_HOSTCONFIG_P1_MODE_MASK;
		reg &= ~UHH_HOSTCONFIG_P2_MODE_MASK;

		if (isc->port_mode[0] == EHCI_HCD_OMAP_MODE_TLL)
			reg |= UHH_HOSTCONFIG_P1_MODE_UTMI_PHY;
		else if (isc->port_mode[0] == EHCI_HCD_OMAP_MODE_HSIC)
			reg |= UHH_HOSTCONFIG_P1_MODE_HSIC;

		if (isc->port_mode[1] == EHCI_HCD_OMAP_MODE_TLL)
			reg |= UHH_HOSTCONFIG_P2_MODE_UTMI_PHY;
		else if (isc->port_mode[1] == EHCI_HCD_OMAP_MODE_HSIC)
			reg |= UHH_HOSTCONFIG_P2_MODE_HSIC;
	}

	omap_uhh_write_4(isc, OMAP_USBHOST_UHH_HOSTCONFIG, reg);
	device_printf(isc->sc_dev, "UHH setup done, uhh_hostconfig=0x%08x\n", reg);

	/* I found the code and comments in the Linux EHCI driver - thanks guys :)
	 *
	 * "An undocumented "feature" in the OMAP3 EHCI controller, causes suspended
	 * ports to be taken out of suspend when the USBCMD.Run/Stop bit is cleared
	 * (for example when we do ehci_bus_suspend). This breaks suspend-resume if
	 * the root-hub is allowed to suspend. Writing 1 to this undocumented
	 * register bit disables this feature and restores normal behavior."
	 */
#if 0
	omap_ehci_write_4(isc, OMAP_USBHOST_INSNREG04,
	                 OMAP_USBHOST_INSNREG04_DISABLE_UNSUSPEND);
#endif

	/* If any of the ports are configured in TLL mode, enable them */
	if ((isc->port_mode[0] == EHCI_HCD_OMAP_MODE_TLL) ||
		(isc->port_mode[1] == EHCI_HCD_OMAP_MODE_TLL) ||
		(isc->port_mode[2] == EHCI_HCD_OMAP_MODE_TLL)) {

		if (isc->port_mode[0] == EHCI_HCD_OMAP_MODE_TLL)
			tll_ch_mask |= 0x1;
		if (isc->port_mode[1] == EHCI_HCD_OMAP_MODE_TLL)
			tll_ch_mask |= 0x2;
		if (isc->port_mode[2] == EHCI_HCD_OMAP_MODE_TLL)
			tll_ch_mask |= 0x4;

		/* Enable UTMI mode for required TLL channels */
		omap_ehci_utmi_init(isc, tll_ch_mask);
	}

	/* Release the PHY reset signal now we have configured everything */
	if (reset_performed) {

		/* Delay for 10ms */
		DELAY(10000);

		for (i = 0; i < 3; i++) {
			/* Release reset */

			if (isc->phy_reset[i] && (isc->reset_gpio_pin[i] != -1)
			    && (isc->sc_gpio_dev != NULL)) {
				GPIO_PIN_SET(isc->sc_gpio_dev,
					isc->reset_gpio_pin[i], GPIO_PIN_HIGH);
			}
		}
	}

	/* Set the interrupt threshold control, it controls the maximum rate at
	 * which the host controller issues interrupts.  We set it to 1 microframe
	 * at startup - the default is 8 mircoframes (equates to 1ms).
	 */
	reg = omap_ehci_read_4(isc, OMAP_USBHOST_USBCMD);
	reg &= 0xff00ffff;
	reg |= (1 << 16);
	omap_ehci_write_4(isc, OMAP_USBHOST_USBCMD, reg);

	/* Soft reset the PHY using PHY reset command over ULPI */
	if (isc->port_mode[0] == EHCI_HCD_OMAP_MODE_PHY)
		omap_ehci_soft_phy_reset(isc, 0);
	if (isc->port_mode[1] == EHCI_HCD_OMAP_MODE_PHY)
		omap_ehci_soft_phy_reset(isc, 1);

	return(0);

err_sys_status:

	/* Disable the TLL clocks */
	ti_prcm_clk_disable(USBTLL_CLK);

	/* Disable Clocks for USBHOST */
	ti_prcm_clk_disable(USBHSHOST_CLK);

	return(ret);
}

/**
 *	omap_ehci_fini - shutdown the EHCI controller
 *	@isc: omap ehci device context
 *
 *
 *
 *	LOCKING:
 *	none
 *
 *	RETURNS:
 *	0 on success, a negative error code on failure.
 */
static void
omap_ehci_fini(struct omap_ehci_softc *isc)
{
	unsigned long timeout;

	device_printf(isc->sc_dev, "Stopping TI EHCI USB Controller\n");

	/* Set the timeout */
	if (hz < 10)
		timeout = 1;
	else
		timeout = (100 * hz) / 1000;

	/* Reset the UHH, OHCI and EHCI modules */
	omap_uhh_write_4(isc, OMAP_USBHOST_UHH_SYSCONFIG, 0x0002);
	while ((omap_uhh_read_4(isc, OMAP_USBHOST_UHH_SYSSTATUS) & 0x07) == 0x00) {
		/* Sleep for a tick */
		pause("USBRESET", 1);

		if (timeout-- == 0) {
			device_printf(isc->sc_dev, "operation timed out\n");
			break;
		}
	}

	/* Set the timeout */
	if (hz < 10)
		timeout = 1;
	else
		timeout = (100 * hz) / 1000;

	/* Reset the TLL module */
	omap_tll_write_4(isc, OMAP_USBTLL_SYSCONFIG, 0x0002);
	while ((omap_tll_read_4(isc, OMAP_USBTLL_SYSSTATUS) & (0x01)) == 0x00) {
		/* Sleep for a tick */
		pause("USBRESET", 1);

		if (timeout-- == 0) {
			device_printf(isc->sc_dev, "operation timed out\n");
			break;
		}
	}

	/* Disable functional and interface clocks for the TLL and HOST modules */
	ti_prcm_clk_disable(USBTLL_CLK);
	ti_prcm_clk_disable(USBHSHOST_CLK);

	device_printf(isc->sc_dev, "Clock to USB host has been disabled\n");

}

/**
 *	omap_ehci_suspend - suspends the bus
 *	@dev: omap ehci device
 *
 *	Effectively boilerplate EHCI suspend code.
 *
 *	TODO: There is a lot more we could do here - i.e. force the controller into
 *	idle mode and disable all the clocks for start.
 *
 *	LOCKING:
 *	none
 *
 *	RETURNS:
 *	0 on success or a positive error code
 */
static int
omap_ehci_suspend(device_t dev)
{
	int err;

	err = bus_generic_suspend(dev);
	if (err)
		return (err);
	return (0);
}

/**
 *	omap_ehci_resume - resumes a suspended bus
 *	@dev: omap ehci device
 *
 *	Effectively boilerplate EHCI resume code.
 *
 *	LOCKING:
 *	none
 *
 *	RETURNS:
 *	0 on success or a positive error code on failure
 */
static int
omap_ehci_resume(device_t dev)
{

	bus_generic_resume(dev);

	return (0);
}

/**
 *	omap_ehci_shutdown - starts the given command
 *	@dev:
 *
 *	Effectively boilerplate EHCI shutdown code.
 *
 *	LOCKING:
 *	none.
 *
 *	RETURNS:
 *	0 on success or a positive error code on failure
 */
static int
omap_ehci_shutdown(device_t dev)
{
	int err;

	err = bus_generic_shutdown(dev);
	if (err)
		return (err);

	return (0);
}

/**
 *	omap_ehci_probe - starts the given command
 *	@dev:
 *
 *	Effectively boilerplate EHCI resume code.
 *
 *	LOCKING:
 *	Caller should be holding the OMAP3_MMC lock.
 *
 *	RETURNS:
 *	EH_HANDLED or EH_NOT_HANDLED
 */
static int
omap_ehci_probe(device_t dev)
{

	if (!ofw_bus_status_okay(dev))
		return (ENXIO);

	if (!ofw_bus_is_compatible(dev, "ti,usb-ehci"))
		return (ENXIO);

	device_set_desc(dev, OMAP_EHCI_HC_DEVSTR);

	return (BUS_PROBE_DEFAULT);
}

/**
 *	omap_ehci_attach - driver entry point, sets up the ECHI controller/driver
 *	@dev: the new device handle
 *
 *	Sets up bus spaces, interrupt handles, etc for the EHCI controller.  It also
 *	parses the resource hints and calls omap_ehci_init() to initialise the
 *	H/W.
 *
 *	LOCKING:
 *	none
 *
 *	RETURNS:
 *	0 on success or a positive error code on failure.
 */
static int
omap_ehci_attach(device_t dev)
{
	struct omap_ehci_softc *isc = device_get_softc(dev);
	phandle_t node;
	/* 3 ports with 3 cells per port */
	pcell_t phyconf[3 * 3];
	pcell_t *phyconf_ptr;
	ehci_softc_t *sc = &isc->base;
	int err;
	int rid;
	int len, tuple_size;
	int i;

	/* initialise some bus fields */
	sc->sc_bus.parent = dev;
	sc->sc_bus.devices = sc->sc_devices;
	sc->sc_bus.devices_max = EHCI_MAX_DEVICES;
	sc->sc_bus.dma_bits = 32;

	/* save the device */
	isc->sc_dev = dev;

	/* get all DMA memory */
	if (usb_bus_mem_alloc_all(&sc->sc_bus, USB_GET_DMA_TAG(dev),
	                          &ehci_iterate_hw_softc)) {
		return (ENOMEM);
	}

	/* When the EHCI driver is added to the tree it is expected that 3
	 * memory resources and 1 interrupt resource is assigned. The memory
	 * resources should be:
	 *   0 => EHCI register range
	 *   1 => UHH register range
	 *   2 => TLL register range
	 *
	 * The interrupt resource is just the single interupt for the controller.
	 */

	/* Allocate resource for the EHCI register set */
	rid = 0;
	sc->sc_io_res = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &rid, RF_ACTIVE);
	if (!sc->sc_io_res) {
		device_printf(dev, "Error: Could not map EHCI memory\n");
		goto error;
	}
	/* Request an interrupt resource */
	rid = 0;
	sc->sc_irq_res = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid, RF_ACTIVE);
	if (sc->sc_irq_res == NULL) {
		device_printf(dev, "Error: could not allocate irq\n");
		goto error;
	}

	/* Allocate resource for the UHH register set */
	rid = 1;
	isc->uhh_mem_res = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &rid, RF_ACTIVE);
	if (!isc->uhh_mem_res) {
		device_printf(dev, "Error: Could not map UHH memory\n");
		goto error;
	}
	/* Allocate resource for the TLL register set */
	rid = 2;
	isc->tll_mem_res = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &rid, RF_ACTIVE);
	if (!isc->tll_mem_res) {
		device_printf(dev, "Error: Could not map TLL memory\n");
		goto error;
	}

	/* Add this device as a child of the USBus device */
	sc->sc_bus.bdev = device_add_child(dev, "usbus", -1);
	if (!sc->sc_bus.bdev) {
		device_printf(dev, "Error: could not add USB device\n");
		goto error;
	}

	device_set_ivars(sc->sc_bus.bdev, &sc->sc_bus);
	device_set_desc(sc->sc_bus.bdev, OMAP_EHCI_HC_DEVSTR);

	/* Set the vendor name */
	sprintf(sc->sc_vendor, "Texas Instruments");

	/* Get the GPIO device, we may need this if the driver needs to toggle
	 * some pins for external PHY resets.
	 */
	isc->sc_gpio_dev = devclass_get_device(devclass_find("gpio"), 0);
	if (isc->sc_gpio_dev == NULL) {
		device_printf(dev, "Error: failed to get the GPIO device\n");
		goto error;
	}

	/* Set the defaults for the hints */
	for (i = 0; i < 3; i++) {
		isc->phy_reset[i] = 0;
		isc->port_mode[i] = EHCI_HCD_OMAP_MODE_UNKNOWN;
		isc->reset_gpio_pin[i] = -1;
	}

	tuple_size = sizeof(pcell_t) * 3;
	node = ofw_bus_get_node(dev);
	len = OF_getprop(node, "phy-config", phyconf, sizeof(phyconf));
	if (len > 0) {
		if (len % tuple_size)
			goto error;
		if ((len / tuple_size) != 3)
			goto error;

		phyconf_ptr = phyconf;
		for (i = 0; i < 3; i++) {
			isc->port_mode[i] = fdt32_to_cpu(*phyconf_ptr);
			isc->phy_reset[i] = fdt32_to_cpu(*(phyconf_ptr + 1));
			isc->reset_gpio_pin[i] = fdt32_to_cpu(*(phyconf_ptr + 2));

			phyconf_ptr += 3;
		}
	}

	/* Initialise the ECHI registers */
	err = omap_ehci_init(isc);
	if (err) {
		device_printf(dev, "Error: could not setup OMAP EHCI, %d\n", err);
		goto error;
	}

	/* Set the tag and size of the register set in the EHCI context */
	sc->sc_io_hdl = rman_get_bushandle(sc->sc_io_res);
	sc->sc_io_tag = rman_get_bustag(sc->sc_io_res);
	sc->sc_io_size = rman_get_size(sc->sc_io_res);

	/* Setup the interrupt */
	err = bus_setup_intr(dev, sc->sc_irq_res, INTR_TYPE_BIO | INTR_MPSAFE,
						 NULL, (driver_intr_t *)ehci_interrupt, sc, &sc->sc_intr_hdl);
	if (err) {
		device_printf(dev, "Error: could not setup irq, %d\n", err);
		sc->sc_intr_hdl = NULL;
		goto error;
	}

	/* Finally we are ready to kick off the ECHI host controller */
	err = ehci_init(sc);
	if (err == 0) {
		err = device_probe_and_attach(sc->sc_bus.bdev);
	}
	if (err) {
		device_printf(dev, "Error: USB init failed err=%d\n", err);
		goto error;
	}

	return (0);

error:
	omap_ehci_detach(dev);
	return (ENXIO);
}

/**
 *	omap_ehci_detach - detach the device and cleanup the driver
 *	@dev: device handle
 *
 *	Clean-up routine where everything initialised in omap_ehci_attach is
 *	freed and cleaned up.  This function calls omap_ehci_fini() to shutdown
 *	the on-chip module.
 *
 *	LOCKING:
 *	none
 *
 *	RETURNS:
 *	Always returns 0 (success).
 */
static int
omap_ehci_detach(device_t dev)
{
	struct omap_ehci_softc *isc = device_get_softc(dev);
	ehci_softc_t *sc = &isc->base;
	device_t bdev;
	int err;

	if (sc->sc_bus.bdev) {
		bdev = sc->sc_bus.bdev;
		device_detach(bdev);
		device_delete_child(dev, bdev);
	}

	/* during module unload there are lots of children leftover */
	device_delete_children(dev);

	/*
	 * disable interrupts that might have been switched on in ehci_init
	 */
	if (sc->sc_io_res) {
		EWRITE4(sc, EHCI_USBINTR, 0);
	}

	if (sc->sc_irq_res && sc->sc_intr_hdl) {
		/*
		 * only call ehci_detach() after ehci_init()
		 */
		ehci_detach(sc);

		err = bus_teardown_intr(dev, sc->sc_irq_res, sc->sc_intr_hdl);
		if (err)
			device_printf(dev, "Error: could not tear down irq, %d\n", err);
		sc->sc_intr_hdl = NULL;
	}

	/* Free the resources stored in the base EHCI handler */
	if (sc->sc_irq_res) {
		bus_release_resource(dev, SYS_RES_IRQ, 0, sc->sc_irq_res);
		sc->sc_irq_res = NULL;
	}
	if (sc->sc_io_res) {
		bus_release_resource(dev, SYS_RES_MEMORY, 0, sc->sc_io_res);
		sc->sc_io_res = NULL;
	}

	/* Release the other register set memory maps */
	if (isc->tll_mem_res) {
		bus_release_resource(dev, SYS_RES_MEMORY, 0, isc->tll_mem_res);
		isc->tll_mem_res = NULL;
	}
	if (isc->uhh_mem_res) {
		bus_release_resource(dev, SYS_RES_MEMORY, 0, isc->uhh_mem_res);
		isc->uhh_mem_res = NULL;
	}

	usb_bus_mem_free_all(&sc->sc_bus, &ehci_iterate_hw_softc);

	omap_ehci_fini(isc);

	return (0);
}

static device_method_t ehci_methods[] = {
	/* Device interface */
	DEVMETHOD(device_probe, omap_ehci_probe),
	DEVMETHOD(device_attach, omap_ehci_attach),
	DEVMETHOD(device_detach, omap_ehci_detach),
	DEVMETHOD(device_suspend, omap_ehci_suspend),
	DEVMETHOD(device_resume, omap_ehci_resume),
	DEVMETHOD(device_shutdown, omap_ehci_shutdown),

	/* Bus interface */
	DEVMETHOD(bus_print_child, bus_generic_print_child),

	{0, 0}
};

static driver_t ehci_driver = {
	"ehci",
	ehci_methods,
	sizeof(struct omap_ehci_softc),
};

static devclass_t ehci_devclass;

DRIVER_MODULE(ehci, simplebus, ehci_driver, ehci_devclass, 0, 0);


text:
SYNONYM

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

#### Published in
null

#### Original name
Urocystis bolivarii Bubák & Gonz. Frag., 1922

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
title: Blog
---

# Blog

#### Example

Red Clay School District Moving Forward with Priority Schools Plans

Check out this webinar archive to learn about the early challenges in implementing personalized mastery as a school improvement approach in a small-town middle school with a large achievement gap.

Red Clay School District Moving Forward with Priority Schools Plans

Check out this webinar archive to learn about the early challenges in implementing personalized mastery as a school improvement approach in a small-town middle school with a large achievement gap.

#### Code
```
<div class="row">
  <div class="col-md-3">
    <img src="http://placehold.it/170x170" />
  </div>
  <div class="col-md-9">
      <h3><a href="#">Red Clay School District Moving Forward with Priority Schools Plans</a></h3>
      <p>Check out this webinar archive to learn about the early challenges in implementing personalized mastery as a school improvement approach in a small-town middle school with a large achievement gap.</p>
  </div>
</div>
<div class="row">
  <div class="col-md-3">
    <img src="http://placehold.it/170x170" />
  </div>
  <div class="col-md-9">
      <h3><a href="#">Red Clay School District Moving Forward with Priority Schools Plans</a></h3>
      <p>Check out this webinar archive to learn about the early challenges in implementing personalized mastery as a school improvement approach in a small-town middle school with a large achievement gap.</p>
  </div>
</div>
```


text:
var Recorder = exports.Recorder = function (records) {
  this.records = records || [];
};

Recorder.prototype.in = function (event, data) {
  this.push('in', event, data);
};

Recorder.prototype.out = function (event, data) {
  this.push('out', event, data);
};

Recorder.prototype.push = function (direction, event, data) {
  this.records.push({
    event: event,
    data: data,
    direction: direction
  });
};

// build rules from records
//
// * create new rule for each 'in'
// * pair 'out' to last 'in' if not paired
// * otherwise it is ignored
//
// note states are not supported
Recorder.prototype.buildRules = function () {
  // temporary unpaired pair
  var pair;
  return this.records.reduce(function (soFar, record) {
    if (record.direction === 'in') {
      if (pair) {
        console.warn('unpaired conversation: ' + JSON.stringify(pair));
      }
      pair = {
        in: record
      };
      soFar.push(pair);
    } else if (record.direction === 'out') {
      if (pair) {
        pair.out = record;
        pair = undefined;
      } else {
        console.warn('unpaired out record: ' + JSON.stringify(record));
      }
    } else {
      console.warn('invalid direction: ' + record.direction);
    }
    return soFar;
  }, []);
};


text:
$(document).ready(function(){

	$("#create-file").dropzone({
		maxFilesize: 2,
		acceptedFiles:'image/*,video/*'
	});

});


text:
device_choice() {
clear
# Devices available
#
# Samsung Core 2
device_variants_1="SM-G355H SM-G355HN SM-G355M" device_defconfig_1="cyanogenmod_kanas_defconfig" device_name_1="Samsung-Core2"
# Menu
echo "${x} | ${color_green}Device choice${color_stock}"
echo
echo "1 | ${device_variants_1} | ${device_name_1}"
defconfig_updater ${device_name_1}
echo
echo "* | Any other key to Exit"
echo
read -p "  | Choice | " -n 1 -s x
case "${x}" in
	1) device_defconfig=${device_defconfig_1} device_name=${device_name_1};;
	a)
		if [ -f .config ]
		then
			echo "${x} | Working on ${device_name} defconfig!"
			make -j${build_cpu_usage}${kernel_build_output_enable} ARCH="${ARCH}" CROSS_COMPILE="${kernel_build_ccache}${CROSS_COMPILE}" savedefconfig
			mv defconfig arch/${ARCH}/configs/${device_defconfig}
		fi;;
	b)
		if [ -f .config ]
		then
			cp .config arch/${ARCH}/configs/${device_defconfig}
		fi;;
esac
if ! [ "${device_defconfig}" == "" ]
then
	echo "${x} | Working on ${device_name} defconfig!"
	make -j${build_cpu_usage}${kernel_build_output_enable} ARCH="${ARCH}" CROSS_COMPILE="${kernel_build_ccache}${CROSS_COMPILE}" ${device_defconfig}
	sleep 2
fi
}

# Toolchain Choice
toolchain_choice() {
echo "${x} | Toolchain choice"
echo
if [ -f ../android_prebuilt_toolchains/aptess.sh ]
then
	. ../android_prebuilt_toolchains/aptess.sh
else
	if [ -d ../android_prebuilt_toolchains ]
	then
		echo "  | You not have APTESS Script in Android Prebuilt Toolchain folder"
		echo "  | Check the folder"
		echo "  | We will use Manual Method now"
	else
		echo "  | You don't have TeamVee Prebuilt Toolchains"
	fi
	echo
	echo "  | Please specify a location"
	echo "  | and the prefix of the chosen toolchain at the end"
	echo "  | GCC 4.6 ex. ../arm-eabi-4.6/bin/arm-eabi-"
	echo
	echo "  | Stay blank if you want to exit"
	echo
	read -p "  | Place | " CROSS_COMPILE
	if ! [ "${CROSS_COMPILE}" == "" ]
	then
		ToolchainCompile="${CROSS_COMPILE}"
	fi
fi
}

# Kernel Build Process
kernel_build() {
if [ "${CROSS_COMPILE}" == "" ]
then
	wrong_choice
	unset CROSS_COMPILE ToolchainCompile
elif [ "${ToolchainCompile}" == "" ]
then
	wrong_choice
	unset CROSS_COMPILE ToolchainCompile
elif [ "${device_defconfig}" == "" ]
then
	wrong_choice
	unset device_name device_defconfig
elif [ "${device_name}" == "" ]
then
	wrong_choice
	unset device_name device_defconfig
elif [ ! -f .config ]
then
	wrong_choice
	unset device_name device_defconfig
else
	echo "${x} | Building ${builder} ${custom_kernel} ${custom_kernel_branch}"

	if [ $(which ccache) ]
	then
		export kernel_build_ccache="ccache "
		echo "  | ${color_blue}Using CCache to build${color_stock}"
	else
		echo "  | ${color_blue}CCache not enabled${color_stock}"
	fi

	echo "  | ${color_blue}Using ${build_cpu_usage} jobs at once${color_stock}"

	start_build_time=$(date +"%s")
	make -j${build_cpu_usage}${kernel_build_output_enable} ARCH="${ARCH}" CROSS_COMPILE="${kernel_build_ccache}${CROSS_COMPILE}"
	if ! [ "$?" == "0" ]
	then
		echo "  | ${color_red}Build Failed! Exiting...${color_stock}"
		break
	fi
	sleep 2
	build_time=$(($(date +"%s") - ${start_build_time}))
	build_time_minutes=$((${build_time} / 60))
fi
}

# Zip Packer Process
zip_packer() {
if ! [ "${device_defconfig}" == "" ]
then
	if [ -f arch/${ARCH}/boot/zImage ]
	then
		echo "${x} | Ziping ${builder} ${custom_kernel} ${custom_kernel_branch}"

		# Make base of zip
		original_dir=$(pwd)
		zip_out="/tmp/zip-creator_out"
		rm -rf ${zip_out}
		mkdir -p ${zip_out}/META-INF/com/google/android/

		# Copy core files
		cp zip-creator/base/update-binary ${zip_out}/META-INF/com/google/android/
		cp zip-creator/base/mkbootimg ${zip_out}/
		cp zip-creator/base/unpackbootimg ${zip_out}/
		cp arch/${ARCH}/boot/zImage ${zip_out}/

		# Set device
		echo "${builder}" >> ${zip_out}/device.prop
		echo "${custom_kernel} ${custom_kernel_branch}" >> ${zip_out}/device.prop
		echo "${device_name}" >> ${zip_out}/device.prop
		echo "Release ${release}" >> ${zip_out}/device.prop

		# Pack zip
		cd ${zip_out}
		zip -r ${zipfile} * -x .gitignore &> /dev/null
		cd ${original_dir}

		# Copy the zip created
		cp ${zip_out}/${zipfile} zip-creator/
		rm -rf ${zip_out}
	else
		wrong_choice
	fi
else
	wrong_choice
fi
}

# Updater of defconfigs
defconfig_updater() {
if [ -f .config ]
then
	if [[ "${device_defconfig}" == "${1}" || "${device_name}" == "${1}" ]]
	then
		echo "  | Update defconfig to:"
		echo "a | Default Linux Kernel format  | Small"
		echo "b | Usual copy of .config format | Complete"
		echo
	fi
fi
}

# Copy zip's via ADB
zip_copy_adb() {
if [ -f zip-creator/${zipfile} ]
then
	echo "${x} | Coping ${builder} ${custom_kernel} ${custom_kernel_branch}"
	echo
	adb shell rm -rf /data/media/0/${zipfile} &> /dev/null
	adb push zip-creator/${zipfile} /data/media/0/${zipfile} &> /dev/null
	if ! [ "$?" == "0" ]
	then
		echo "  | Copy failed!"
		if [ ! "$(which adb)" ]
		then
			echo "  | ADB not installed!"
		else
			echo "  | Check connection!"
		fi
		sleep 2
	fi
else
	wrong_choice
fi
}

# Wrong choice
wrong_choice() {
echo "${x} | This option is not available! | Something is wrong! | Check ${color_green}Choice Menu${color_stock}!"; sleep 2
}

if [ ! "${BASH_VERSION}" ]
then
	echo "  | Please do not use ${0} to run this script, just use '. build.sh'"
elif [ -e build.sh ]
then
	# Stock Color
	color_stock=$(tput sgr0)
	# Bold Colors
	color_red=$(tput bold)$(tput setaf 1)
	color_green=$(tput bold)$(tput setaf 2)
	color_yellow=$(tput bold)$(tput setaf 3)
	color_blue=$(tput bold)$(tput setaf 4)
	# Main Variables
	custom_kernel=OMKernel
	builder=TeamVee-Kanas
	custom_kernel_branch=KK
	export ARCH=arm

	while true
	do
		# Kernel OutPut
		if [ "${kernel_build_output}" == "(OFF)" ]
		then
			export kernel_build_output_enable=" -s"
		else
			kernel_build_output="(${color_green}ON${color_stock})"
			unset kernel_build_output_enable
		fi
		# Build Time
		if ! [ "${build_time}" == "" ]
		then
			if [ "${build_time_minutes}" == "" ]
			then
				menu_build_time="(${color_green}$((${build_time} % 60))s${color_stock})"
			else
				menu_build_time="(${color_green}${build_time_minutes}m$((${build_time} % 60))s${color_stock})"
			fi
		fi
		export build_cpu_usage=$(($(grep -c ^processor /proc/cpuinfo) + 1))
		# Variable's
		k_version=$(cat Makefile | grep VERSION | cut -c 11- | head -1)
		k_patch_level=$(cat Makefile | grep PATCHLEVEL | cut -c 14- | head -1)
		k_sub_level=$(cat Makefile | grep SUBLEVEL | cut -c 12- | head -1)
		kernel_base="${k_version}.${k_patch_level}.${k_sub_level}"
		release=$(date +%d""%m""%Y)
		if ! [ -f .version ]
		then
			echo "0" > .version
		fi
		build=$(cat .version)
		export zipfile="${custom_kernel}-${custom_kernel_branch}-${device_name}-${release}-${build}.zip"
		# Check ZIP
		if [ -f zip-creator/${zipfile} ]
		then
			menu_zipfile="(${color_green}zip-creator/${zipfile}${color_stock})"
		else
			unset menu_zipfile
		fi
		# Menu
		clear
		echo "  | Simple Linux Kernel ${kernel_base} Build Script ($(date +%d"/"%m"/"%Y))"
		echo "  | ${builder} ${custom_kernel} ${custom_kernel_branch} Release $(date +%d"/"%m"/"%Y) Build #${build}"
		echo
		echo "  | ${color_red}Clean Menu${color_stock}"
		echo "1 | Clean Zip Folder"
		echo "2 | Clean Kernel"
		echo "  | ${color_green}Choice Menu${color_stock}"
		echo "3 | Set Device Defconfig ${color_green}${device_name}${color_stock}"
		echo "4 | Set Toolchain        ${color_green}${ToolchainCompile}${color_stock}"
		echo "5 | Toggle Build Output  ${kernel_build_output}"
		echo "  | ${color_yellow}Build Menu${color_stock}"
		echo "6 | Build Kernel         ${menu_build_time}"
		echo "7 | Build Zip Package    ${menu_zipfile}"
		echo "8 | Copy Zip to '/data/media/0' of Device"
		echo "e | Exit"
		echo
		read -n 1 -p "  | Choice | " -s x
		case ${x} in
			1) rm -rf zip-creator/*.zip;;
			2)
				echo "${x} | Cleaning Kernel"
				make -j${build_cpu_usage}${kernel_build_output_enable} ARCH="${ARCH}" CROSS_COMPILE="${kernel_build_ccache}${CROSS_COMPILE}" clean mrproper
				unset device_name device_defconfig build_time;;
			3) device_choice;;
			4) toolchain_choice;;
			5)
				if [ "${kernel_build_output}" == "(OFF)" ]
				then
					unset kernel_build_output
				else
					kernel_build_output="(OFF)"
				fi;;
			6) kernel_build;;
			7) zip_packer;;
			8) zip_copy_adb;;
			q|e) echo "${x} | Ok, Bye!"; break;;
			*) wrong_choice;;
		esac
	done
else
	echo
	echo "  | Ensure you run this file from the SAME folder as where it was,"
	echo "  | otherwise the script will have problems running the commands."
	echo "  | After you 'cd' to the correct folder, start the build script"
	echo "  | with the . build.sh command, NOT with any other command!"
	echo
fi


text:
import os
from setuptools import find_packages, setup

# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))

setup(
    name='baroque',
    version='0.0.3',
    packages=find_packages(),
    include_package_data=True,
    install_requires=[
        'jsonschema==2.6.0,<3.0',
        'pytz==2016.10',
        'PyYAML==3.12,<4.0',
        'requests==2.9.1,<3.0'
    ],
    test_suite='tests',
    license='MIT License',
    description='Baroque is an event brokering framework with a honey-sweet '
                'interface.',
    url='https://github.com/baroquehq/baroque',
    author='Claudio Sparpaglione',
    author_email='csparpa@gmail.com',
    classifiers=[
      "License :: OSI Approved :: MIT License",
      'Programming Language :: Python :: 3 :: Only',
      "Natural Language :: English",
      "Operating System :: OS Independent",
      "Development Status :: 3 - Alpha",
      "Intended Audience :: Developers",
      "Topic :: Software Development :: Libraries",
      "Topic :: Communications"],
)


text:
module HealthSeven::V2_3
class Rxa < ::HealthSeven::Segment
  # Give Sub-ID Counter
  attribute :give_sub_id_counter, Id, position: "RXA.1", require: true
  # Administration Sub-ID Counter
  attribute :administration_sub_id_counter, Nm, position: "RXA.2", require: true
  # Date/Time Start of Administration
  attribute :date_time_start_of_administration, Ts, position: "RXA.3", require: true
  # Date/Time End of Administration
  attribute :date_time_end_of_administration, Ts, position: "RXA.4", require: true
  # Administered Code
  attribute :administered_code, Ce, position: "RXA.5", require: true
  # Administered Amount
  attribute :administered_amount, Nm, position: "RXA.6", require: true
  # Administered Units
  attribute :administered_units, Ce, position: "RXA.7"
  # Administered Dosage Form
  attribute :administered_dosage_form, Ce, position: "RXA.8"
  # Administration Notes
  attribute :administration_notes, Array[Ce], position: "RXA.9", multiple: true
  # Administering Provider
  attribute :administering_provider, Xcn, position: "RXA.10"
  # Administered-at Location
  attribute :administered_at_location, CmLa1, position: "RXA.11"
  # Administered Per (Time Unit)
  attribute :administered_per_time_unit, St, position: "RXA.12"
  # Administered Strength
  attribute :administered_strength, Nm, position: "RXA.13"
  # Administered Strength Units
  attribute :administered_strength_units, Ce, position: "RXA.14"
  # Substance Lot Number
  attribute :substance_lot_numbers, Array[St], position: "RXA.15", multiple: true
  # Substance Expiration Date
  attribute :substance_expiration_dates, Array[Ts], position: "RXA.16", multiple: true
  # Substance Manufacturer Name
  attribute :substance_manufacturer_names, Array[Ce], position: "RXA.17", multiple: true
  # Substance Refusal Reason
  attribute :substance_refusal_reasons, Array[Ce], position: "RXA.18", multiple: true
  # Indication
  attribute :indications, Array[Ce], position: "RXA.19", multiple: true
  # Completion Status
  attribute :completion_status, Id, position: "RXA.20"
  # Action Code-RXA
  attribute :action_code_rxa, Id, position: "RXA.21"
  # System Entry Date/Time
  attribute :system_entry_date_time, Ts, position: "RXA.22"
end
end


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.codingkapoor.problemsolving</groupId>
	<artifactId>java-problem-solving</artifactId>
	<version>1.0-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>Java Problem Solving</name>
	<url>http://codingkapoor.github.io/</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

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

</project>


text:
package org.bouncycastle.openpgp.examples;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.Security;

import org.bouncycastle.bcpg.ArmoredOutputStream;
import org.bouncycastle.bcpg.CompressionAlgorithmTags;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openpgp.PGPCompressedData;
import org.bouncycastle.openpgp.PGPEncryptedData;
import org.bouncycastle.openpgp.PGPEncryptedDataGenerator;
import org.bouncycastle.openpgp.PGPEncryptedDataList;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPLiteralData;
import org.bouncycastle.openpgp.PGPPBEEncryptedData;
import org.bouncycastle.openpgp.PGPUtil;
import org.bouncycastle.openpgp.jcajce.JcaPGPObjectFactory;
import org.bouncycastle.openpgp.operator.jcajce.JcaPGPDigestCalculatorProviderBuilder;
import org.bouncycastle.openpgp.operator.jcajce.JcePBEDataDecryptorFactoryBuilder;
import org.bouncycastle.openpgp.operator.jcajce.JcePBEKeyEncryptionMethodGenerator;
import org.bouncycastle.openpgp.operator.jcajce.JcePGPDataEncryptorBuilder;
import org.bouncycastle.util.io.Streams;

/**
 * A simple utility class that encrypts/decrypts password based
 * encryption files.
 *

 * To encrypt a file: PBEFileProcessor -e [-ai] fileName passPhrase.

 * If -a is specified the output file will be "ascii-armored".

 * If -i is specified the output file will be "integrity protected".
 *

 * To decrypt: PBEFileProcessor -d fileName passPhrase.
 *

 * Note: this example will silently overwrite files, nor does it pay any attention to
 * the specification of "_CONSOLE" in the filename. It also expects that a single pass phrase
 * will have been used.
 */
public class PBEFileProcessor
{
    private static void decryptFile(String inputFileName, char[] passPhrase)
        throws IOException, NoSuchProviderException, PGPException
    {
        InputStream in = new BufferedInputStream(new FileInputStream(inputFileName));
        decryptFile(in, passPhrase);
        in.close();
    }

    /*
     * decrypt the passed in message stream
     */
    private static void decryptFile(
        InputStream    in,
        char[]         passPhrase)
        throws IOException, NoSuchProviderException, PGPException
    {
        in = PGPUtil.getDecoderStream(in);

        JcaPGPObjectFactory        pgpF = new JcaPGPObjectFactory(in);
        PGPEncryptedDataList    enc;
        Object                  o = pgpF.nextObject();

        //
        // the first object might be a PGP marker packet.
        //
        if (o instanceof PGPEncryptedDataList)
        {
            enc = (PGPEncryptedDataList)o;
        }
        else
        {
            enc = (PGPEncryptedDataList)pgpF.nextObject();
        }

        PGPPBEEncryptedData     pbe = (PGPPBEEncryptedData)enc.get(0);

        InputStream clear = pbe.getDataStream(new JcePBEDataDecryptorFactoryBuilder(new JcaPGPDigestCalculatorProviderBuilder().setProvider("BC").build()).setProvider("BC").build(passPhrase));

        JcaPGPObjectFactory        pgpFact = new JcaPGPObjectFactory(clear);

        //
        // if we're trying to read a file generated by someone other than us
        // the data might not be compressed, so we check the return type from
        // the factory and behave accordingly.
        //
        o = pgpFact.nextObject();
        if (o instanceof PGPCompressedData)
        {
            PGPCompressedData   cData = (PGPCompressedData)o;

            pgpFact = new JcaPGPObjectFactory(cData.getDataStream());

            o = pgpFact.nextObject();
        }

        PGPLiteralData ld = (PGPLiteralData)o;
        InputStream unc = ld.getInputStream();

        OutputStream fOut = new BufferedOutputStream(new FileOutputStream(ld.getFileName()));

        Streams.pipeAll(unc, fOut);

        fOut.close();

        if (pbe.isIntegrityProtected())
        {
            if (!pbe.verify())
            {
                System.err.println("message failed integrity check");
            }
            else
            {
                System.err.println("message integrity check passed");
            }
        }
        else
        {
            System.err.println("no message integrity check");
        }
    }

    private static void encryptFile(
        String          outputFileName,
        String          inputFileName,
        char[]          passPhrase,
        boolean         armor,
        boolean         withIntegrityCheck)
        throws IOException, NoSuchProviderException
    {
        OutputStream out = new BufferedOutputStream(new FileOutputStream(outputFileName));
        encryptFile(out, inputFileName, passPhrase, armor, withIntegrityCheck);
        out.close();
    }

    private static void encryptFile(
        OutputStream    out,
        String          fileName,
        char[]          passPhrase,
        boolean         armor,
        boolean         withIntegrityCheck)
        throws IOException, NoSuchProviderException
    {
        if (armor)
        {
            out = new ArmoredOutputStream(out);
        }

        try
        {
            byte[] compressedData = PGPExampleUtil.compressFile(fileName, CompressionAlgorithmTags.ZIP);

            PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(new JcePGPDataEncryptorBuilder(PGPEncryptedData.CAST5)
                .setWithIntegrityPacket(withIntegrityCheck).setSecureRandom(new SecureRandom()).setProvider("BC"));

            encGen.addMethod(new JcePBEKeyEncryptionMethodGenerator(passPhrase).setProvider("BC"));

            OutputStream encOut = encGen.open(out, compressedData.length);

            encOut.write(compressedData);
            encOut.close();

            if (armor)
            {
                out.close();
            }
        }
        catch (PGPException e)
        {
            System.err.println(e);
            if (e.getUnderlyingException() != null)
            {
                e.getUnderlyingException().printStackTrace();
            }
        }
    }

    public static void main(
        String[] args)
        throws Exception
    {
        Security.addProvider(new BouncyCastleProvider());

        if (args[0].equals("-e"))
        {
            if (args[1].equals("-a") || args[1].equals("-ai") || args[1].equals("-ia"))
            {
                encryptFile(args[2] + ".asc", args[2], args[3].toCharArray(), true, (args[1].indexOf('i') > 0));
            }
            else if (args[1].equals("-i"))
            {
                encryptFile(args[2] + ".bpg", args[2], args[3].toCharArray(), false, true);
            }
            else
            {
                encryptFile(args[1] + ".bpg", args[1], args[2].toCharArray(), false, false);
            }
        }
        else if (args[0].equals("-d"))
        {
            decryptFile(args[1], args[2].toCharArray());
        }
        else
        {
            System.err.println("usage: PBEFileProcessor -e [-ai]|-d file passPhrase");
        }
    }
}


text:
package com.knight.designpatterns.creational.singleton;

public class SingletonPatternDemo {

	public static void main(String[] args) {
		// illegal construct
		// Compile Time Error: The constructor SingleObject() is not visible
		// SingleObject object = new SingleObject();
		// Get the only object available
		SingleObject object = SingleObject.getInstance();

		// show the message
		object.showMessage();
	}
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
<title>gem5: Stats::SparseHistStor Class Reference</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">

Main Page

Modules

Namespaces

Classes

Files

Related Pages

      <form action="search.php" method="get">

             Search for
            <input type="text" name="query" value="" size="20" accesskey="s"/>

      </form>

Alphabetical List

Class List

Class Hierarchy

Class Members

Stats::SparseHistStor

Stats::SparseHistStor Class Reference

["Statistic Types"]

Templatized storage and interface for a sparse histogram stat.
More...

#include <statistics.hh>

List of all members.

Public Member Functions

 	SparseHistStor (Info *info)

void 	sample (Counter val, int number)

 	Add a value to the distribution for the given number of times.

size_type 	size () const

 	Return the number of buckets in this distribution.

bool 	zero () const

 	Returns true if any calls to sample have been made.

void 	prepare (Info *info, SparseHistData &data)

void 	reset (Info *info)

 	Reset stat value to default.

Private Attributes

Counter 	samples

 	Counter for number of samples.

MCounter 	cmap

 	Counter for each bucket.

Classes

struct  	Params

 	The parameters for a sparse histogram stat.  More...

Detailed Description

Templatized storage and interface for a sparse histogram stat.

Definition at line 2782 of file statistics.hh.

Constructor & Destructor Documentation

          Stats::SparseHistStor::SparseHistStor
          (
          Info *
           info
           )
           [inline]

Definition at line 2798 of file statistics.hh.

References reset().

Member Function Documentation

          void Stats::SparseHistStor::prepare
          (
          Info *
           info,

          SparseHistData &
           data

          )
          		 [inline]

Definition at line 2832 of file statistics.hh.

References cmap, Stats::SparseHistData::cmap, samples, and Stats::SparseHistData::samples.

Referenced by Stats::SparseHistBase< Stats::SparseHistogram, Stats::SparseHistStor >::prepare().

          void Stats::SparseHistStor::reset
          (
          Info *
           info
           )
           [inline]

Reset stat value to default.

Definition at line 2847 of file statistics.hh.

References cmap, and samples.

Referenced by Stats::SparseHistBase< Stats::SparseHistogram, Stats::SparseHistStor >::reset(), and SparseHistStor().

          void Stats::SparseHistStor::sample
          (
          Counter
           val,

          int
           number

          )
          		 [inline]

Add a value to the distribution for the given number of times.

Parameters:

	val 	The value to add.

	number 	The number of times to add the value.

Definition at line 2809 of file statistics.hh.

References cmap, and samples.

Referenced by Stats::SparseHistBase< Stats::SparseHistogram, Stats::SparseHistStor >::sample().

          size_type Stats::SparseHistStor::size
          (

           )
           const [inline]

Return the number of buckets in this distribution.

Returns:

the number of buckets.

Definition at line 2819 of file statistics.hh.

References cmap.

Referenced by Stats::SparseHistBase< Stats::SparseHistogram, Stats::SparseHistStor >::size().

          bool Stats::SparseHistStor::zero
          (

           )
           const [inline]

Returns true if any calls to sample have been made.

Returns:

True if any values have been sampled.

Definition at line 2826 of file statistics.hh.

References samples.

Referenced by Stats::SparseHistBase< Stats::SparseHistogram, Stats::SparseHistStor >::zero().

Member Data Documentation

          MCounter Stats::SparseHistStor::cmap [private]

Counter for each bucket.

Definition at line 2795 of file statistics.hh.

Referenced by prepare(), reset(), sample(), and size().

          Counter Stats::SparseHistStor::samples [private]

Counter for number of samples.

Definition at line 2793 of file statistics.hh.

Referenced by prepare(), reset(), sample(), and zero().

The documentation for this class was generated from the following file:

base/statistics.hh

<address style="align: right;">
Generated on Fri Apr 17 12:41:52 2015 for gem5 by  doxygen 1.4.7</address>


text: {% include base_path %}


text:
package mekanism.generators.client.model;

import net.minecraft.client.model.ModelBase;
import net.minecraft.client.model.ModelRenderer;

public class ModelWindTurbine extends ModelBase
{
	ModelRenderer Base;
	ModelRenderer TowerFront;
	ModelRenderer TowerLeft;
	ModelRenderer TowerBack;
	ModelRenderer TowerRight;
	ModelRenderer TowerMoterFront;
	ModelRenderer TowerBaseMotor;
	ModelRenderer TowerBaseMotorBack;
	ModelRenderer TowerMotor;
	ModelRenderer Rotor;
	ModelRenderer RotorCover;
	ModelRenderer BladeBaseC;
	ModelRenderer BladeBaseB;
	ModelRenderer BladeBaseA;

	public ModelWindTurbine()
	{
		textureWidth = 128;
		textureHeight = 64;

		Base = new ModelRenderer(this, 0, 0);
		Base.addBox(-8F, 0F, -8F, 16, 6, 16);
		Base.setRotationPoint(0F, 18F, 0F);
		Base.setTextureSize(128, 64);
		Base.mirror = true;
		setRotation(Base, 0F, 0F, 0F);
		TowerFront = new ModelRenderer(this, 104, 0);
		TowerFront.addBox(-5F, -62F, -7F, 10, 63, 2);
		TowerFront.setRotationPoint(0F, 19F, 0F);
		TowerFront.setTextureSize(128, 64);
		TowerFront.mirror = true;
		setRotation(TowerFront, -0.0872665F, 0F, 0F);
		TowerLeft = new ModelRenderer(this, 104, 0);
		TowerLeft.addBox(-5F, -62F, 5F, 10, 63, 2);
		TowerLeft.setRotationPoint(0F, 19F, 0F);
		TowerLeft.setTextureSize(128, 64);
		TowerLeft.mirror = true;
		setRotation(TowerLeft, 0.0872665F, 1.570796F, 0F);
		TowerBack = new ModelRenderer(this, 104, 0);
		TowerBack.addBox(-5F, -62F, 5F, 10, 63, 2);
		TowerBack.setRotationPoint(0F, 19F, 0F);
		TowerBack.setTextureSize(128, 64);
		TowerBack.mirror = true;
		setRotation(TowerBack, 0.0872665F, 0F, 0F);
		TowerRight = new ModelRenderer(this, 104, 0);
		TowerRight.addBox(-5F, -62F, 5F, 10, 63, 2);
		TowerRight.setRotationPoint(0F, 19F, 0F);
		TowerRight.setTextureSize(128, 64);
		TowerRight.mirror = true;
		setRotation(TowerRight, 0.0872665F, -1.570796F, 0F);
		TowerMoterFront = new ModelRenderer(this, 40, 38);
		TowerMoterFront.addBox(-6F, -7.3F, -5F, 12, 9, 6);
		TowerMoterFront.setRotationPoint(0F, -45F, -1F);
		TowerMoterFront.setTextureSize(128, 64);
		TowerMoterFront.mirror = true;
		setRotation(TowerMoterFront, 0F, 0F, 0F);
		TowerBaseMotor = new ModelRenderer(this, 65, 0);
		TowerBaseMotor.addBox(-6F, -0.3F, 0F, 12, 2, 7);
		TowerBaseMotor.setRotationPoint(0F, -45F, 0F);
		TowerBaseMotor.setTextureSize(128, 64);
		TowerBaseMotor.mirror = true;
		setRotation(TowerBaseMotor, 0F, 0F, 0F);
		TowerBaseMotorBack = new ModelRenderer(this, 65, 30);
		TowerBaseMotorBack.addBox(-4F, -3.3F, 7F, 8, 4, 3);
		TowerBaseMotorBack.setRotationPoint(0F, -45F, 0F);
		TowerBaseMotorBack.setTextureSize(128, 64);
		TowerBaseMotorBack.mirror = true;
		setRotation(TowerBaseMotorBack, 0F, 0F, 0F);
		TowerMotor = new ModelRenderer(this, 65, 15);
		TowerMotor.addBox(-4F, -6.3F, 0F, 8, 6, 7);
		TowerMotor.setRotationPoint(0F, -45F, 0F);
		TowerMotor.setTextureSize(128, 64);
		TowerMotor.mirror = true;
		setRotation(TowerMotor, 0F, 0F, 0F);
		Rotor = new ModelRenderer(this, 88, 30);
		Rotor.addBox(-0.5F, -0.5F, 0F, 1, 1, 3);
		Rotor.setRotationPoint(0F, -48F, -8F);
		Rotor.setTextureSize(128, 64);
		Rotor.mirror = true;
		setRotation(Rotor, 0F, 0F, 0F);
		RotorCover = new ModelRenderer(this, 88, 35);
		RotorCover.addBox(-2F, -2F, -1F, 4, 4, 1);
		RotorCover.setRotationPoint(0F, -48F, -8F);
		RotorCover.setTextureSize(128, 64);
		RotorCover.mirror = true;
		setRotation(RotorCover, 0F, 0F, 0F);
		BladeBaseC = new ModelRenderer(this, 0, 54);
		BladeBaseC.addBox(1F, -1F, 0F, 32, 2, 1);
		BladeBaseC.setRotationPoint(0F, -48F, -8F);
		BladeBaseC.setTextureSize(128, 64);
		BladeBaseC.mirror = true;
		setRotation(BladeBaseC, 0F, 0F, getRotation(120));
		BladeBaseB = new ModelRenderer(this, 0, 54);
		BladeBaseB.addBox(1F, -1F, 0F, 32, 2, 1);
		BladeBaseB.setRotationPoint(0F, -48F, -8F);
		BladeBaseB.setTextureSize(128, 64);
		BladeBaseB.mirror = true;
		setRotation(BladeBaseB, 0F, 0F, 0F);
		BladeBaseA = new ModelRenderer(this, 0, 54);
		BladeBaseA.addBox(1F, -1F, 0F, 32, 2, 1);
		BladeBaseA.setRotationPoint(0F, -48F, -8F);
		BladeBaseA.setTextureSize(128, 64);
		BladeBaseA.mirror = true;
		setRotation(BladeBaseA, 0F, 0F, getRotation(240));
	}

	public void render(float size, double angle)
	{
		Base.render(size);
		TowerFront.render(size);
		TowerLeft.render(size);
		TowerBack.render(size);
		TowerRight.render(size);
		TowerMoterFront.render(size);
		TowerBaseMotor.render(size);
		TowerBaseMotorBack.render(size);
		TowerMotor.render(size);
		Rotor.render(size);
		RotorCover.render(size);
		setRotation(BladeBaseC, 0.0F, 0.0F, getRotation(getAbsoluteAngle(120 + angle)));
		BladeBaseC.render(size);
		setRotation(BladeBaseB, 0.0F, 0.0F, getRotation(getAbsoluteAngle(angle)));
		BladeBaseB.render(size);
		setRotation(BladeBaseA, 0.0F, 0.0F, getRotation(getAbsoluteAngle(240 + angle)));
		BladeBaseA.render(size);
	}

	public float getRotation(double angle)
	{
		return ((float)angle/(float)180)*(float)Math.PI;
	}

	public double getAbsoluteAngle(double angle)
	{
		return angle % 360;
	}

	private void setRotation(ModelRenderer model, float x, float y, float z)
	{
		model.rotateAngleX = x;
		model.rotateAngleY = y;
		model.rotateAngleZ = z;
	}
}


text:
package rapture.common;

/**
 * Note that this class is referenced in types.api - any changes to this file should be reflected there.
**/

public class PluginVersion {
    private int major;

    private int minor;

    private int release;

    private long timestamp;

    public PluginVersion() {
        this(0, 0, 0, 0);
    }
    public PluginVersion(int major, int minor, int release, long timestamp) {
        this.major = major;
        this.minor = minor;
        this.release = release;
        this.timestamp = timestamp;
    }

    public int getMajor() {
        return major;
    }

    public int getMinor() {
        return minor;
    }

    public int getRelease() {
        return release;
    }

    public long getTimestamp() {
        return timestamp;
    }

    public void setMajor(int major) {
        this.major = major;
    }

    public void setMinor(int minor) {
        this.minor = minor;
    }

    public void setRelease(int release) {
        this.release = release;
    }

    public void setTimestamp(long timestamp) {
        this.timestamp = timestamp;
    }

    public boolean sameAs(PluginVersion version) {
        return version.major == major && version.minor == minor && version.release == release && version.timestamp == timestamp;
    }

    public static PluginVersion makeVersion(int major, int minor, int release, long timestamp) {
        PluginVersion version = new PluginVersion();
        version.major = major;
        version.minor = minor;
        version.release = release;
        version.timestamp = timestamp;
        return version;
    }

    public boolean earlierThan(PluginVersion version) {
        if (major < version.major) {
            return true;
        } else if (major > version.major) {
            return false;
        }
        if (minor < version.minor) {
            return true;
        } else if (minor > version.minor) {
            return false;
        }
        if (release < version.release) {
            return true;
        } else if (release > version.release) {
            return false;
        }
        if (timestamp < version.timestamp) {
            return true;
        } else if (timestamp > version.timestamp) {
            return false;
        }
        // Same = no
        return false;
    }

    public String toString() {
        return "" + major + "." + minor + "." + release + "." + timestamp;
    }
}


text:
<?xml version="1.0"?>
<manuscript>
  <url/>
  <title>Fragment of a Lectionary</title>
  <shelfmark>Lewis E 144</shelfmark>
  <quire n="1">
    <leaf n="" conjoin="7" position="1" opposite="8"/>
    <leaf n="1" mode="original" single="false" folio_number="1" conjoin="6" position="2" opposite="7"/>
    <leaf n="2" mode="original" single="false" folio_number="2" conjoin="5" position="3" opposite="6"/>
    <leaf n="3" mode="original" single="false" folio_number="3" conjoin="4" position="4" opposite="5"/>
    <leaf n="4" mode="original" single="false" folio_number="4" conjoin="3" position="5" opposite="4"/>
    <leaf n="5" mode="original" single="false" folio_number="5" conjoin="2" position="6" opposite="3"/>
    <leaf n="6" mode="original" single="false" folio_number="6" conjoin="1" position="7" opposite="2"/>
    <leaf n="7" mode="original" single="true" folio_number="7" conjoin="" position="8" opposite="1"/>
  </quire>
  <quire n="2">
    <leaf n="1" mode="original" single="false" folio_number="8" conjoin="8" position="1" opposite="8"/>
    <leaf n="2" mode="original" single="false" folio_number="9" conjoin="7" position="2" opposite="7"/>
    <leaf n="3" mode="original" single="false" folio_number="10" conjoin="6" position="3" opposite="6"/>
    <leaf n="4" mode="original" single="false" folio_number="11" conjoin="5" position="4" opposite="5"/>
    <leaf n="5" mode="original" single="false" folio_number="12" conjoin="4" position="5" opposite="4"/>
    <leaf n="6" mode="original" single="false" folio_number="13" conjoin="3" position="6" opposite="3"/>
    <leaf n="7" mode="original" single="false" folio_number="14" conjoin="2" position="7" opposite="2"/>
    <leaf n="8" mode="original" single="false" folio_number="15" conjoin="1" position="8" opposite="1"/>
  </quire>
  <quire n="3">
    <leaf n="" conjoin="9" position="1" opposite="10"/>
    <leaf n="1" mode="original" single="false" folio_number="16" conjoin="8" position="2" opposite="9"/>
    <leaf n="2" mode="original" single="false" folio_number="17" conjoin="7" position="3" opposite="8"/>
    <leaf n="3" mode="original" single="false" folio_number="18" conjoin="6" position="4" opposite="7"/>
    <leaf n="4" mode="original" single="false" folio_number="19" conjoin="5" position="5" opposite="6"/>
    <leaf n="5" mode="original" single="false" folio_number="20" conjoin="4" position="6" opposite="5"/>
    <leaf n="6" mode="original" single="false" folio_number="21" conjoin="3" position="7" opposite="4"/>
    <leaf n="7" mode="original" single="false" folio_number="22" conjoin="2" position="8" opposite="3"/>
    <leaf n="8" mode="original" single="false" folio_number="23" conjoin="1" position="9" opposite="2"/>
    <leaf n="9" mode="original" single="true" folio_number="24" conjoin="" position="10" opposite="1"/>
  </quire>
</manuscript>


text:
//
//  IFADynamicPagingContainerViewControllerDataSource.h
//  Gusty
//
//  Created by Marcelo Schroeder on 12/11/11.
//  Copyright (c) 2011 InfoAccent Pty Limited. All rights reserved.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//

#import "IFACoreUiConstants.h"

@protocol IFADynamicPagingContainerViewControllerDataSource <NSObject>

@required

/*
 This method is called so the container view controller can obtain an instance of a child view controller for each page.
 The method is called once for each page represented in the IFAScrollPage enum.
 The child view controller for the centre page (i.e. IFAScrollPageCentre) is always obtained first. That way the child view controller for the other pages can have their model
    data generated relative to the centre page's child view controller.
 To indicate the left or right boundaries just return a nil value;
 */
-(UITableViewController*)childViewControlerForPage:(IFAScrollPage)a_page;

@optional

/*
 This method is called so the container view controller can obtain the title for each page.
 The method is called once for each page represented in the IFAScrollPage enum, with the exception of IFAScrollPageLeftFar and IFAScrollPageRightFar.
 Those pages never fully appear so their titles do not appear either.
 */
-(NSString*)titleForPage:(IFAScrollPage)a_page;

@end


text:
@interface ERNResourceFactoryTest : NSObject
+(void)testResourceFactory:(id<ERNResourceFactory>)resourceFactory;
@end


text:
package me.ramswaroop.jbot.core.slack;

import me.ramswaroop.jbot.core.common.EventType;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

/**
 *
 */
public class EventTypeTest {

    /**
     * Number of events in {@link EventType} should be
     * equal to the number of events supported by slack
     * (including 3 added by JBot) plus number of events
     * supported in fb bot.
     */
    @Test
    public void numberOfEventsType() {
        EventType[] events = EventType.values();
        assertEquals(87, events.length);
    }

}


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

<module xmlns="urn:jboss:module:1.1" name="org.aopalliance">

  <resources>
    <resource-root path="aopalliance.jar"/>
  </resources>

</module>


text:
ArtistView::ArtistView(int arid, QWidget* parent, QString qmlfile) :
    AlbumView(qmlfile, parent)
{
    addAlbums(db->getArtistAlbums(arid));
}


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 circleland.Quests;

import circleland.*;

/**
 *
 * @author Jeff
 */
public abstract class Quest {

    protected boolean completed;
    public boolean completed(){return completed;}
    public void completed(boolean l){completed = l;}

    public Quest(){
        completed = false;
    }
    public abstract void update(CircleClass player,CircleMap cM);
}


text:
package org.technbolts.asciitech.parser.ast;

import java.util.ArrayList;
import java.util.List;

/**
 * @author @aloyer
 */
public class Values {
    private List<String> values = new ArrayList<String>();

    public boolean append(String value) {
        values.add(value);
        return true;
    }

    public boolean ok() {
        return true;
    }

    public double[] toDoubles() {
        double[] doubles = new double[values.size()];
        for (int i = 0; i < values.size(); i++) {
            String value = values.get(i);
            doubles[i] = Double.parseDouble(value.trim());
        }
        return doubles;
    }

    @Override
    public String toString() {
        return "Values[" + values + ']';
    }
}


text:
using System;
using System.Reflection;
using System.Text;
using Mono.Cecil.Cil;

public static class ExceptionExtensions
{
    public static void LogException(this ILogger logger,  Exception exception)
    {
        var exceptionType = exception.GetType();
        if (exceptionType.Name == "WeavingException")
        {
            var point = GetSequencePoint(exception);
            if (point == null)
            {
                logger.LogError(exception.Message);
            }
            else
            {
                logger.LogError(exception.Message, point.Document.Url, point.StartLine, point.StartColumn, point.EndLine, point.EndColumn);
            }
        }
        else
        {
            logger.LogError(exception.ToFriendlyString());
        }
    }

    static SequencePoint GetSequencePoint(Exception exception)
    {
        var exceptionType = exception.GetType();
        var sequencePointProperty = exceptionType.GetProperty("SequencePoint", BindingFlags.Public | BindingFlags.Instance);
        var sequencePoint = (SequencePoint) sequencePointProperty?.GetValue(exception, null);
        if (sequencePoint != null)
        {
            return sequencePoint;
        }
        var sequencePointField = exceptionType.GetField("SequencePoint", BindingFlags.Public|BindingFlags.Instance);
        return (SequencePoint) sequencePointField?.GetValue(exception);
    }

    public static string ToFriendlyString(this Exception exception)
    {

        var stringBuilder = new StringBuilder();
		stringBuilder.Append("An unhandled exception occurred:");
        stringBuilder.Append(Environment.NewLine);
        stringBuilder.Append("Exception:");
        stringBuilder.Append(Environment.NewLine);
        while (exception != null)
        {
            stringBuilder.Append(exception.Message);
            stringBuilder.Append(Environment.NewLine);

            foreach (var i in exception.Data)
            {
                stringBuilder.Append("Data :");
                stringBuilder.Append(i);
                stringBuilder.Append(Environment.NewLine);
            }

            if (exception.StackTrace != null)
            {
                stringBuilder.Append("StackTrace:");
                stringBuilder.Append(Environment.NewLine);
                stringBuilder.Append(exception.StackTrace);
                stringBuilder.Append(Environment.NewLine);
            }

            if (exception.Source != null)
            {
                stringBuilder.Append("Source:");
                stringBuilder.Append(Environment.NewLine);
                stringBuilder.Append(exception.Source);
                stringBuilder.Append(Environment.NewLine);
            }

            if (exception.TargetSite != null)
            {
                stringBuilder.Append("TargetSite:");
                stringBuilder.Append(Environment.NewLine);
                stringBuilder.Append(exception.TargetSite);
                stringBuilder.Append(Environment.NewLine);
            }

            exception = exception.InnerException;
        }

        return stringBuilder.ToString();
    }
}


text:
package twilightforest.client.renderer.entity;

import net.minecraft.block.Block;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.client.renderer.entity.Render;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.entity.Entity;
import net.minecraft.util.MathHelper;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World;
import org.lwjgl.opengl.GL11;
import twilightforest.entity.boss.EntityTFIceBomb;

public class RenderTFThrownIce
  extends Render
{
  private final RenderBlocks renderBlocks = new RenderBlocks();

  public RenderTFThrownIce() {}

  public void func_76986_a(Entity var1, double var2, double var4, double var6, float var8, float var9) { doRender((EntityTFIceBomb)var1, var2, var4, var6, var8, var9); }

  public void doRender(EntityTFIceBomb entity, double x, double y, double z, float p_147918_8_, float p_147918_9_)
  {
    World world = field_70170_p;
    Block block = entity.getBlock();
    int i = MathHelper.func_76128_c(field_70165_t);
    int j = MathHelper.func_76128_c(field_70163_u);
    int k = MathHelper.func_76128_c(field_70161_v);

    if ((block != null) && (block != world.func_147439_a(i, j, k)))
    {
      GL11.glPushMatrix();
      GL11.glTranslatef((float)x, (float)y, (float)z);
      func_110777_b(entity);
      GL11.glDisable(2896);

      renderBlocks.func_147775_a(block);
      renderBlocks.func_147749_a(block, world, i, j, k, 0);

      GL11.glEnable(2896);
      GL11.glPopMatrix();
    }
  }

  protected ResourceLocation func_110775_a(Entity var1)
  {
    return TextureMap.field_110575_b;
  }
}


text:
#import "APCFormTextField.h"

static CGFloat const kButtonWidth = 25.0f;

@implementation APCFormTextField

#pragma mark - Init

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self sharedInit];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self sharedInit];
    }
    return self;
}

- (void)sharedInit
{
    _validationButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_validationButton addTarget:self action:@selector(validButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
    [_validationButton.imageView setContentMode:UIViewContentModeScaleAspectFit];
    _validationButton.transform = CGAffineTransformMakeScale(0, 0);
    [self addSubview:_validationButton];
}

- (void)layoutSubviews
{
    [super layoutSubviews];

    [self.validationButton setFrame:CGRectMake(CGRectGetMaxX(self.bounds) - kButtonWidth, 0, kButtonWidth, CGRectGetHeight(self.bounds))];
}

#pragma mark -Overrider UITextField Methods

- (CGRect)textRectForBounds:(CGRect)bounds
{
    return UIEdgeInsetsInsetRect([super textRectForBounds:bounds], UIEdgeInsetsMake(0, 0, 0, 27));
}

- (CGRect)editingRectForBounds:(CGRect)bounds
{
    return [self textRectForBounds:bounds];
}

#pragma mark - Button Actions

- (void)validButtonTapped:(UIButton *) __unused sender
{
    if (!self.valid) {
        if ([self.validationDelegate respondsToSelector:@selector(formTextFieldDidTapValidButton:)]) {
            [self.validationDelegate formTextFieldDidTapValidButton:self];
        }
    }
}

#pragma mark - Public Methods

- (void)setValid:(BOOL)valid
{
    if (valid) {
        [self.validationButton setImage:[UIImage imageNamed:@"valid_icon"] forState:UIControlStateNormal];
    } else {
        [self.validationButton setImage:[UIImage imageNamed:@"invalid_icon"] forState:UIControlStateNormal];
    }

    [UIView animateWithDuration:0.2 animations:^{
        self.validationButton.transform = CGAffineTransformMakeScale(1, 1);
    }];

    _valid = valid;
}

@end


text:
package uuid

import (
	"fmt"
	"math/big"
	"regexp"

	"github.com/google/uuid"
)

var valid = regexp.MustCompile(
	"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")

// Valid can be used to define a valid Valid.
func Valid(s string) error {
	if !valid.MatchString(string(s)) {
		return fmt.Errorf("invalid UUID %q", s)
	}
	return nil
}

// Parse decodes s into a UUID or returns an error. Both the standard UUID forms
// of xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx and
// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx are decoded as well as the
// Microsoft encoding {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} and the raw hex
// encoding: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.
func Parse(s string) (string, error) {
	x, err := uuid.Parse(s)
	return string(x.String()), err
}

// String represents a 128-bit UUID value as a string.
func ToString(x string) string {
	return string(x)
}

// URN reports the canonical URN of a UUID.
func URN(x string) (string, error) {
	u, err := uuid.Parse(string(x))
	if err != nil {
		return "", err
	}
	return u.URN(), nil
}

// FromInt creates a UUID from an integer.
//
//    DNS:  uuid.FromInt(0x6ba7b810_9dad_11d1_80b4_00c04fd430c8)
//
func FromInt(i *big.Int) (string, error) {
	// must be uint128
	var buf [16]byte
	b := i.Bytes()
	if len(b) < 16 {
		copy(buf[16-len(b):], b)
		b = buf[:]
	}
	u, err := uuid.FromBytes(b)
	return string(u.String()), err
}

// ToInt represents a UUID string as a 128-bit value.
func ToInt(x string) *big.Int {
	var i big.Int
	i.SetBytes([]byte(x[:]))
	return &i
}

// Variant reports the UUID variant.
func Variant(x string) (int, error) {
	u, err := uuid.Parse(string(x))
	if err != nil {
		return 0, err
	}
	return int(u.Variant()), nil
}

// Version reports the UUID version.
func Version(x string) (int, error) {
	u, err := uuid.Parse(string(x))
	if err != nil {
		return 0, err
	}
	return int(u.Version()), nil
}

// SHA1 generates a version 5 UUID based on the supplied name space and data.
func SHA1(space string, data []byte) (string, error) {
	u, err := uuid.Parse(string(space))
	if err != nil {
		return "", err
	}
	return string(uuid.NewSHA1(u, data).String()), nil
}

// MD5 generates a version 3 UUID based on the supplied name space and data.
// Use SHA1 instead if you can.
func MD5(space string, data []byte) (string, error) {
	u, err := uuid.Parse(string(space))
	if err != nil {
		return "", err
	}
	return string(uuid.NewMD5(u, data).String()), nil
}


text:
export default {
  "textLink.primary.default.fontColor": {
    value: {
      ref: "basics.colors.textLink.primary.againstDark",
    },
  },
};


text:
package io.github.kimkr.presentation.view.auth;

import android.content.Context;
import android.databinding.BindingConversion;

import javax.inject.Inject;

import io.github.kimkr.data.injection.ActivityScope;
import io.github.kimkr.presentation.R;

/**
 * Created by kkr on 2017. 10. 26..
 */

@ActivityScope
public class AuthViewBinding {

    private static Context context;

    @Inject
    public AuthViewBinding(Context context) {
        this.context = context;
    }

    @BindingConversion
    public static String convertViewModeToString(ViewMode viewMode) {
        if (viewMode == null) {
            return "";
        }
        switch (viewMode) {
            case SIGNIN:
                return context.getString(R.string.auth_sign_in_title);
            case SIGNUP:
                return context.getString(R.string.auth_sign_up_title);
            case FINDPWD:
                return context.getString(R.string.auth_find_pwd_title);
            case CHANGEPWD:
                return context.getString(R.string.auth_change_pwd_title);
            case POLICY:
                return context.getString(R.string.auth_policy_title);
            default:
                return "";
        }
    }
}


text:
from flask import jsonify, request, Flask, send_from_directory
from functools import wraps
import os
from panoptes_aggregation import reducers
from panoptes_aggregation import extractors

application = Flask(__name__,
                    instance_relative_config=True,
                    static_url_path='',
                    static_folder='docs/build/html')

def request_wrapper(name):
    def decorator(func):
        @wraps(func)
        def wrapper():
            if request.method == 'GET':
                return jsonify(name)
            else:
                resp = jsonify(func(request))
                resp.status_code = 200
                return resp
        return wrapper
    return decorator

'''
Example use of process_wrapper:
@application.route('/path', method=['POST', 'GET'])
@process_wrapper('string returned on a GET request')
def func(request):
    return

this is the same as:
application.route('/path', methods=['POST', 'GET'])(process_wrapper('string returned on a GET request')(func))
'''

@application.route('/')
def index():
    return jsonify('Python extractors and reducers for panoptes aggregation.')

for route, route_function in reducers.reducers.items():
    application.route('/reducers/{0}'.format(route), methods=['POST', 'GET'])(request_wrapper(route)(route_function))

for route, route_function in extractors.extractors.items():
    application.route('/extractors/{0}'.format(route), methods=['POST', 'GET'])(request_wrapper(route)(route_function))

@application.route('/docs')
def web_docs():
    return application.send_static_file('index.html')

if __name__ == "__main__":
    application.run(debug=True, host='0.0.0.0')


text:
layout: post
title: "n00b"
date: 2011-08-25 18:17
categories:
- blog
---

It's been a long time since I've spent significant time to learn an
entirely new technology. And I've had a blast digging into ruby, rails,
sinatra, padrino, javascript (okay, I really mean jQuery), and tons of
other related frameworks. In spite of some of the excellent, and
not-so-excellent, documentation out there, it can be an incredibly
frustrating experience. Especially when trying to learn something new --
like something *really new* -- not just new to me. Expect to see posts
here related to what I'm learning, that make as few assumptions as
possible about what you already know.

For example, I recently worked on getting a test environment set up for
my app that involves sinatra, mongoid, and twilio APIs. It was an
interesting experience. I'm sure seasoned ruby devs wouldn't have had
the same issues, but I'm a firm believer in "you're not alone" so I'll
be posting about the process to hopefully help someone else in my shoes.


text:
import { computed, observable } from 'mobx';
import { generateId } from 'utils/generate-id';

import { Operator } from 'core/models/operator';
import { range } from 'lodash';

import { Dimensions } from 'core/interfaces';
import { Envelope } from 'core/models/envelope';
import { InputPort, OutputPort } from 'core/models/graph/port';
import { Position } from 'core/primitives/position';
import { Snip } from 'core/models/snip';

import { getInputPosition, getOutputPosition } from 'features/GraphEditor/helpers/layout';

export type Data = Envelope | null;

export const DEFAULT_NODE_DIMENSIONS: Dimensions = {
  width: 100,
  height: 30,
};

export abstract class Node {
  id = generateId();
  abstract output: Data;
  label: string;

  nInputs: number;
  nOutputs: number;

  private inputMap = observable.map<number, Node>();
  private outputMap = observable.map<number, Node>();

  @computed
  get inputs(): (Node | null)[] {
    return [...this.inputMap.keys()].sort().map(key => {
      return this.inputMap.get(key) || null;
    });
  }

  @computed
  get outputs(): (Node | null)[] {
    return [...this.inputMap.keys()].sort().map(key => {
      return this.inputMap.get(key) || null;
    });
  }

  @computed
  get inputPorts(): InputPort[] {
    return range(this.nInputs).map(index => {
      const input = this.inputMap.get(index);
      const port = new InputPort(this, index, input);
      const position = getInputPosition(this, index);
      port.position.set(position);
      return port;
    });
  }

  @computed
  get outputPorts(): OutputPort[] {
    return range(this.nOutputs).map(index => {
      const output = this.outputMap.get(index);
      const port = new OutputPort(this, index, output);
      const position = getOutputPosition(index);
      port.position.set(position);
      return port;
    });
  }

  position = new Position();
  @observable
  dimensions: Dimensions = {
    ...DEFAULT_NODE_DIMENSIONS,
  };

  setInput(other: Node, index: number) {
    this.inputMap.set(index, other);
  }

  removeInput(index: number) {
    this.inputMap.delete(index);
  }

  setOutput(other: Node, index: number) {
    this.outputMap.set(index, other);
  }

  removeOutput(index: number) {
    this.outputMap.delete(index);
  }
}

export class EmptyNode extends Node {
  label = 'empty';

  @computed
  get output() {
    return null;
  }
}

export class OutputNode extends Node {
  label = 'output';

  @observable
  nInputs = 1;
  @observable
  nOutputs = 0;

  @computed
  get output() {
    const input = this.inputs[0];
    return input ? input.output : null;
  }
}

export class DataNode extends Node {
  @observable
  nInputs = 0;
  @observable
  nOutputs = 1;

  @computed
  get output() {
    return this.data;
  }

  @observable
  data: Data;
}

export class SnipNode extends Node {
  @observable
  nInputs = 0;
  @observable
  nOutputs = 1;

  get label() {
    return this.snip.data instanceof Envelope ? 'envelope' : 'snip';
  }

  @computed
  get output() {
    return this.snip.data;
  }

  @observable
  snip: Snip;

  constructor(snip: Snip) {
    super();
    this.snip = snip;
  }
}

export class OperatorNode extends Node {
  get nInputs() {
    return this.operator.nInputs || 1;
  }

  get nOutputs() {
    return this.operator.nOutputs || 1;
  }

  @computed
  get label() {
    return this.operator.label;
  }

  @computed
  get output() {
    const inputData = this.inputs.map(inputNode => (inputNode ? inputNode.output : null));
    return this.operator.operate(inputData);
  }

  @observable
  operator: Operator;

  constructor(operator: Operator) {
    super();
    this.operator = operator;
  }
}


text:
package com.ibm.watson.apis.conversation_enhanced.rest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.lang.Integer;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.google.gson.Gson;
import com.ibm.watson.apis.conversation_enhanced.payload.DocumentPayload;
import com.ibm.watson.apis.conversation_enhanced.payload.TransactionPayload;
import com.ibm.watson.apis.conversation_enhanced.retrieve_and_rank.Client;
import com.ibm.watson.apis.conversation_enhanced.utils.Logging;
import com.ibm.watson.apis.conversation_enhanced.utils.Messages;
import com.ibm.watson.developer_cloud.conversation.v1_experimental.ConversationService;
import com.ibm.watson.developer_cloud.conversation.v1_experimental.model.MessageRequest;
import com.ibm.watson.developer_cloud.conversation.v1_experimental.model.MessageResponse;
import com.ibm.watson.developer_cloud.service.exception.UnauthorizedException;
import com.ibm.watson.developer_cloud.util.GsonSingleton;

import com.ibm.watson.apis.conversation_enhanced.transaction.Transactions;
import com.ibm.watson.apis.conversation_enhanced.utils.DayHelper;

@Path("conversation/api/v1/workspaces")
public class ProxyResource {
  private static final Logger logger = LogManager.getLogger(ProxyResource.class.getName());

  private static String API_VERSION;
  private static String PASSWORD;
  private static String URL;
  private static String USERNAME;

  private static boolean LOGGING_ENABLED = Boolean.parseBoolean(System.getenv("LOGGING_ENABLED"));

  public static void setConversationAPIVersion(String version) {
    API_VERSION = version;
  }

  public static void setCredentials(String username, String password, String url) {
    USERNAME = username;
    PASSWORD = password;
    URL = url;
  }

  private MessageRequest buildMessageFromPayload(InputStream body) {
    StringBuilder sbuilder = null;
    BufferedReader reader = null;
    try {
      reader = new BufferedReader(new InputStreamReader(body, "UTF-8"));
      sbuilder = new StringBuilder();
      String str = reader.readLine();
      while (str != null) {
        sbuilder.append(str);
        str = reader.readLine();
        if (str != null) {
          sbuilder.append("\n");
        }
      }
      return GsonSingleton.getGson().fromJson(sbuilder.toString(), MessageRequest.class);
    } catch (IOException e) {
      logger.error(Messages.getString("ProxyResource.JSON_READ"), e);
    } finally {
      try {
        reader.close();
      } catch (IOException e) {
        logger.error(Messages.getString("ProxyResource.STREAM_CLOSE"), e);
      }
    }
    return null;
  }
  private String getDate(String dayUtterence)
  {
	  DayHelper dh = new DayHelper() ;
	  String dayDate = dh.getDate(dayUtterence) ;
	  return dayDate ;
  }

  /**
   * This method is responsible for sending the query the user types into the UI to the Watson
   * services. The code demonstrates how the conversation service is called, how the response is
   * evaluated, and how the response is then sent to the retrieve and rank service if necessary.
   *
   * @param request The full query the user asked of Watson
   * @param id The ID of the conversational workspace
   * @return The response from Watson. The response will always contain the conversation service's
   *         response. If the intent confidence is high or the intent is out_of_scope, the response
   *         will also contain information from the retrieve and rank service
   */
  private MessageResponse getWatsonResponse(MessageRequest request, String id) throws Exception {

    // Configure the Watson Developer Cloud SDK to make a call to the appropriate conversation
    // service. Specific information is obtained from the VCAP_SERVICES environment variable
    ConversationService service =
        new ConversationService(API_VERSION != null ? API_VERSION : ConversationService.VERSION_DATE_2016_05_19);
    if (USERNAME != null || PASSWORD != null) {
      service.setUsernameAndPassword(USERNAME, PASSWORD);
    }
    if (URL != null) {
      service.setEndPoint(URL);
    }

    // Use the previously configured service object to make a call to the conversational service
    MessageResponse response = service.message(id, request).execute();

    // Determine if conversation's response is sufficient to answer the user's question or if we
    // should call the retrieve and rank service to obtain better answers

    Map<String, Object> output = response.getOutput();

    if (output == null) {
      output = new HashMap<String, Object>();
      response.setOutput(output);
    }

    if (response.getContext().containsKey("loanType")) {
    	// EMI loan example to demonstrate how multiple entities are handled.
    	//Write code here to connect to DB or any other service to fetch data

    	String loanType = (String)(response.getContext().get("loanType")) ;

    	 String amt="" ;
    	 String dt="" ;
    	 if ( (response.getContext().containsKey("amt"))&&((boolean)(response.getContext().get("amt"))) )
    	 {
    		 amt="amount: $5000 " ;
    		 response.getContext().remove("amt") ;
    	 }
    	 if ((response.getContext().containsKey("dt"))&&((boolean)(response.getContext().get("dt"))) )
    	 {
    		 dt="date: 03/05/2019 " ;
    		 response.getContext().remove("dt") ;
    	 }
   	  	 	response.getContext().remove("loanType") ;
   	  	output.put("text", "Required EMI details for "+loanType+" loan are "+amt+dt);
    }
    else if (response.getContext().containsKey("RTT")&&response.getContext().containsKey("transNum")) {

    	// If there is a Retail transaction type and Number of transaction specfied, fetch the details from the DB

    	int transNo = Integer.parseInt((String)(response.getContext().get("transNum"))) ;
    	  String customerId = (String)(response.getContext().get("customerId")) ;

    	  String RTT = (String)(response.getContext().get("RTT")) ;
    	  Transactions trClient = new Transactions() ;
    	  List<TransactionPayload> docs = trClient.getTransactions(transNo,RTT,customerId) ;
    	  output.put("transPayload", docs);
    	  response.setOutput(output);

    	  //Delete context variables, alternately, you may want to keep them incase you want to do further context related processing.
    	  response.getContext().remove("RTT") ;
    	  response.getContext().remove("transNum") ;
      }
      else if (response.getContext().containsKey("dayAsked"))
      {
    	  // Example to show how days (today, tomorrow, day after tomorrow can be returned as 'day of the week and date' in the response)

    	  String dayAsked = (String)(response.getContext().get("dayAsked")) ;
    	  if (!dayAsked.equals("none") )
    	  {
    		  List<String> strList = new ArrayList<String>();
    		  dayAsked = getDate(dayAsked) ;

        	  response.getContext().remove("dayAsked") ;
        	  response.getContext().remove("isHoliday") ;
        	  String botResponse=dayAsked.concat(" is holiday.You can take a look at the holiday list here...") ;
        	  strList.add(botResponse) ;
    		  output.put("text", strList);
    	  }
      }

 /* else if (response.getContext().containsKey("callRetrieveAndRank")) {
      String query = response.getInputText();

      // Extract the user's original query from the conversational response
      if (query != null && !query.isEmpty()) {
        Client retrieveAndRankClient = new Client();

        // For this app, both the original conversation response and the retrieve and rank response
        // are sent to the UI. Extract and add the conversational response to the ultimate response
        // we will send to the user. The UI will process this response and show the top 5 retrieve
        // and rank answers to the user in the main UI. The JSON response section of the UI will
        // show information from the calls to both services.
      //  Map<String, Object> output = response.getOutput();
        if (output == null) {
          output = new HashMap<String, Object>();
          response.setOutput(output);
        }

        // Send the user's question to the retrieve and rank service
        List<DocumentPayload> docs = retrieveAndRankClient.getDocuments(query);

        // Append the retrieve and rank answers to the output object that will be sent to the UI
        output.put("CEPayload", docs); //$NON-NLS-1$
      }
    }*/

    // Log User input and output from Watson
    if (Boolean.TRUE.equals(LOGGING_ENABLED)) {
      logResponse(response);
    }

    return response;
  }

  @POST @Path("{id}/message") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response postMessage(
      @PathParam("id") String id, InputStream body) {

    HashMap<String, Object> errorsOutput = new HashMap<String, Object>();
    MessageRequest request = buildMessageFromPayload(body);

    if (request == null) {
      throw new IllegalArgumentException(Messages.getString("ProxyResource.NO_REQUEST"));
    }

    MessageResponse response = null;

    try {
      response = getWatsonResponse(request, id);

    } catch (Exception e) {
      if (e instanceof UnauthorizedException) {
        errorsOutput.put("error", Messages.getString("ProxyResource.INVALID_CONVERSATION_CREDS")); //$NON-NLS-1$
      } else if (e instanceof IllegalArgumentException) {
        errorsOutput.put("error", e.getMessage());
      } else if (e instanceof MalformedURLException) {
        errorsOutput.put("error", Messages.getString("ProxyResource.MALFORMED_URL")); //$NON-NLS-1$
      } else if (e.getMessage().contains("URL workspaceid parameter is not a valid GUID.")) {
        errorsOutput.put("error", Messages.getString("ProxyResource.INVALID_WORKSPACEID")); //$NON-NLS-1$
      } else if (e.getMessage().contains("/fcselect.")) {
        errorsOutput.put("error", Messages.getString("ProxyResource.INVALID_COLLECTION_NAME")); //$NON-NLS-1$
      } else if (e.getMessage().contains("is not authorized for cluster") && e.getMessage().contains("and ranker")) {
        errorsOutput.put("error", Messages.getString("ProxyResource.INVALID_RANKER_ID")); //$NON-NLS-1$
      } else {
        errorsOutput.put("error", Messages.getString("ProxyResource.GENERIC_ERROR")); //$NON-NLS-1$
      }
      logger.error(Messages.getString("ProxyResource.SOLR_QUERY_EXCEPTION") + e.getMessage()); //$NON-NLS-1$
      return Response.ok(new Gson().toJson(errorsOutput, HashMap.class)).type(MediaType.APPLICATION_JSON).build();
    }
    return Response.ok(new Gson().toJson(response, MessageResponse.class)).type(MediaType.APPLICATION_JSON).build();
  }

  /**
   *
   * This method takes in the response object and sends in to the cloudant logging class
   *
   * @param response
   * @throws Exception
   */
  private void logResponse(MessageResponse response) throws Exception {
    Logging cloudantLogging = new Logging();
    String intent = "<no intent>";
    String confidence = "<no confidence>";
    if (!response.getIntents().isEmpty() && response.getIntents().get(0) != null) {
      intent = response.getIntents().get(0).getIntent();
      confidence = response.getIntents().get(0).getConfidence().toString();
    }
    String entity = response.getEntities().size() > 0 ? "Entity: " + response.getEntities().get(0).getEntity()
        + " Value:" + response.getEntities().get(0).getValue() : "<no entity>";
    String convoOutput = (String) (response.getOutput().get("text") != null
        ? response.getOutput().get("text").toString() : "<no response>");
    String convoId = (String) (response.getContext().get("conversation_id") != null
        ? (response.getContext().get("conversation_id")).toString() : "<no conversation id>");
    String retrieveAndRankOutput = (String) (response.getOutput().get("CEPayload") != null
        ? response.getOutput().get("CEPayload").toString() : "<no payload>");

    cloudantLogging.log(response.getInputText(), intent, confidence, entity, convoOutput, convoId,
        retrieveAndRankOutput);
  }

}


text:
.class public interface abstract Lorg/apache/http/params/CoreProtocolPNames;
.super Ljava/lang/Object;
.source "CoreProtocolPNames.java"

# static fields
.field public static final HTTP_CONTENT_CHARSET:Ljava/lang/String; = "http.protocol.content-charset"

.field public static final HTTP_ELEMENT_CHARSET:Ljava/lang/String; = "http.protocol.element-charset"

.field public static final ORIGIN_SERVER:Ljava/lang/String; = "http.origin-server"

.field public static final PROTOCOL_VERSION:Ljava/lang/String; = "http.protocol.version"

.field public static final STRICT_TRANSFER_ENCODING:Ljava/lang/String; = "http.protocol.strict-transfer-encoding"

.field public static final USER_AGENT:Ljava/lang/String; = "http.useragent"

.field public static final USE_EXPECT_CONTINUE:Ljava/lang/String; = "http.protocol.expect-continue"

.field public static final WAIT_FOR_CONTINUE:Ljava/lang/String; = "http.protocol.wait-for-continue"