text:
#include <linux/pci.h>
#include <linux/io.h>
#include <linux/delay.h>
#include <linux/vmalloc.h>
#include <linux/aer.h>
#include <linux/module.h>

#include "hfi.h"
#include "chip_registers.h"

/* link speed vector for Gen3 speed - not in Linux headers */
#define GEN1_SPEED_VECTOR 0x1
#define GEN2_SPEED_VECTOR 0x2
#define GEN3_SPEED_VECTOR 0x3

/*
 * This file contains PCIe utility routines.
 */

/*
 * Code to adjust PCIe capabilities.
 */
static void tune_pcie_caps(struct hfi1_devdata *);

/*
 * Do all the common PCIe setup and initialization.
 * devdata is not yet allocated, and is not allocated until after this
 * routine returns success.  Therefore dd_dev_err() can't be used for error
 * printing.
 */
int hfi1_pcie_init(struct pci_dev *pdev, const struct pci_device_id *ent)
{
	int ret;

	ret = pci_enable_device(pdev);
	if (ret) {
		/*
		 * This can happen (in theory) iff:
		 * We did a chip reset, and then failed to reprogram the
		 * BAR, or the chip reset due to an internal error.  We then
		 * unloaded the driver and reloaded it.
		 *
		 * Both reset cases set the BAR back to initial state.  For
		 * the latter case, the AER sticky error bit at offset 0x718
		 * should be set, but the Linux kernel doesn't yet know
		 * about that, it appears.  If the original BAR was retained
		 * in the kernel data structures, this may be OK.
		 */
		hfi1_early_err(&pdev->dev, "pci enable failed: error %d\n",
			       -ret);
		goto done;
	}

	ret = pci_request_regions(pdev, DRIVER_NAME);
	if (ret) {
		hfi1_early_err(&pdev->dev,
			       "pci_request_regions fails: err %d\n", -ret);
		goto bail;
	}

	ret = pci_set_dma_mask(pdev, DMA_BIT_MASK(64));
	if (ret) {
		/*
		 * If the 64 bit setup fails, try 32 bit.  Some systems
		 * do not setup 64 bit maps on systems with 2GB or less
		 * memory installed.
		 */
		ret = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
		if (ret) {
			hfi1_early_err(&pdev->dev,
				       "Unable to set DMA mask: %d\n", ret);
			goto bail;
		}
		ret = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32));
	} else
		ret = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(64));
	if (ret) {
		hfi1_early_err(&pdev->dev,
			       "Unable to set DMA consistent mask: %d\n", ret);
		goto bail;
	}

	pci_set_master(pdev);
	ret = pci_enable_pcie_error_reporting(pdev);
	if (ret) {
		hfi1_early_err(&pdev->dev,
			       "Unable to enable pcie error reporting: %d\n",
			      ret);
		ret = 0;
	}
	goto done;

bail:
	hfi1_pcie_cleanup(pdev);
done:
	return ret;
}

/*
 * Clean what was done in hfi1_pcie_init()
 */
void hfi1_pcie_cleanup(struct pci_dev *pdev)
{
	pci_disable_device(pdev);
	/*
	 * Release regions should be called after the disable. OK to
	 * call if request regions has not been called or failed.
	 */
	pci_release_regions(pdev);
}

/*
 * Do remaining PCIe setup, once dd is allocated, and save away
 * fields required to re-initialize after a chip reset, or for
 * various other purposes
 */
int hfi1_pcie_ddinit(struct hfi1_devdata *dd, struct pci_dev *pdev,
		     const struct pci_device_id *ent)
{
	unsigned long len;
	resource_size_t addr;

	dd->pcidev = pdev;
	pci_set_drvdata(pdev, dd);

	addr = pci_resource_start(pdev, 0);
	len = pci_resource_len(pdev, 0);

	/*
	 * The TXE PIO buffers are at the tail end of the chip space.
	 * Cut them off and map them separately.
	 */

	/* sanity check vs expectations */
	if (len != TXE_PIO_SEND + TXE_PIO_SIZE) {
		dd_dev_err(dd, "chip PIO range does not match\n");
		return -EINVAL;
	}

	dd->kregbase = ioremap_nocache(addr, TXE_PIO_SEND);
	if (!dd->kregbase)
		return -ENOMEM;

	dd->piobase = ioremap_wc(addr + TXE_PIO_SEND, TXE_PIO_SIZE);
	if (!dd->piobase) {
		iounmap(dd->kregbase);
		return -ENOMEM;
	}

	dd->flags |= HFI1_PRESENT;	/* now register routines work */

	dd->kregend = dd->kregbase + TXE_PIO_SEND;
	dd->physaddr = addr;        /* used for io_remap, etc. */

	/*
	 * Re-map the chip's RcvArray as write-combining to allow us
	 * to write an entire cacheline worth of entries in one shot.
	 * If this re-map fails, just continue - the RcvArray programming
	 * function will handle both cases.
	 */
	dd->chip_rcv_array_count = read_csr(dd, RCV_ARRAY_CNT);
	dd->rcvarray_wc = ioremap_wc(addr + RCV_ARRAY,
				     dd->chip_rcv_array_count * 8);
	dd_dev_info(dd, "WC Remapped RcvArray: %p\n", dd->rcvarray_wc);
	/*
	 * Save BARs and command to rewrite after device reset.
	 */
	dd->pcibar0 = addr;
	dd->pcibar1 = addr >> 32;
	pci_read_config_dword(dd->pcidev, PCI_ROM_ADDRESS, &dd->pci_rom);
	pci_read_config_word(dd->pcidev, PCI_COMMAND, &dd->pci_command);
	pcie_capability_read_word(dd->pcidev, PCI_EXP_DEVCTL, &dd->pcie_devctl);
	pcie_capability_read_word(dd->pcidev, PCI_EXP_LNKCTL, &dd->pcie_lnkctl);
	pcie_capability_read_word(dd->pcidev, PCI_EXP_DEVCTL2,
							&dd->pcie_devctl2);
	pci_read_config_dword(dd->pcidev, PCI_CFG_MSIX0, &dd->pci_msix0);
	pci_read_config_dword(dd->pcidev, PCIE_CFG_SPCIE1,
							&dd->pci_lnkctl3);
	pci_read_config_dword(dd->pcidev, PCIE_CFG_TPH2, &dd->pci_tph2);

	return 0;
}

/*
 * Do PCIe cleanup related to dd, after chip-specific cleanup, etc.  Just prior
 * to releasing the dd memory.
 * Void because all of the core pcie cleanup functions are void.
 */
void hfi1_pcie_ddcleanup(struct hfi1_devdata *dd)
{
	u64 __iomem *base = (void __iomem *) dd->kregbase;

	dd->flags &= ~HFI1_PRESENT;
	dd->kregbase = NULL;
	iounmap(base);
	if (dd->rcvarray_wc)
		iounmap(dd->rcvarray_wc);
	if (dd->piobase)
		iounmap(dd->piobase);

	pci_set_drvdata(dd->pcidev, NULL);
}

/*
 * Do a Function Level Reset (FLR) on the device.
 * Based on static function drivers/pci/pci.c:pcie_flr().
 */
void hfi1_pcie_flr(struct hfi1_devdata *dd)
{
	int i;
	u16 status;

	/* no need to check for the capability - we know the device has it */

	/* wait for Transaction Pending bit to clear, at most a few ms */
	for (i = 0; i < 4; i++) {
		if (i)
			msleep((1 << (i - 1)) * 100);

		pcie_capability_read_word(dd->pcidev, PCI_EXP_DEVSTA, &status);
		if (!(status & PCI_EXP_DEVSTA_TRPND))
			goto clear;
	}

	dd_dev_err(dd, "Transaction Pending bit is not clearing, proceeding with reset anyway\n");

clear:
	pcie_capability_set_word(dd->pcidev, PCI_EXP_DEVCTL,
						PCI_EXP_DEVCTL_BCR_FLR);
	/* PCIe spec requires the function to be back within 100ms */
	msleep(100);
}

static void msix_setup(struct hfi1_devdata *dd, int pos, u32 *msixcnt,
		       struct hfi1_msix_entry *hfi1_msix_entry)
{
	int ret;
	int nvec = *msixcnt;
	struct msix_entry *msix_entry;
	int i;

	/* We can't pass hfi1_msix_entry array to msix_setup
	 * so use a dummy msix_entry array and copy the allocated
	 * irq back to the hfi1_msix_entry array. */
	msix_entry = kmalloc_array(nvec, sizeof(*msix_entry), GFP_KERNEL);
	if (!msix_entry) {
		ret = -ENOMEM;
		goto do_intx;
	}

	for (i = 0; i < nvec; i++)
		msix_entry[i] = hfi1_msix_entry[i].msix;

	ret = pci_enable_msix_range(dd->pcidev, msix_entry, 1, nvec);
	if (ret < 0)
		goto free_msix_entry;
	nvec = ret;

	for (i = 0; i < nvec; i++)
		hfi1_msix_entry[i].msix = msix_entry[i];

	kfree(msix_entry);
	*msixcnt = nvec;
	return;

free_msix_entry:
	kfree(msix_entry);

do_intx:
	dd_dev_err(dd, "pci_enable_msix_range %d vectors failed: %d, falling back to INTx\n",
		   nvec, ret);
	*msixcnt = 0;
	hfi1_enable_intx(dd->pcidev);

}

/* return the PCIe link speed from the given link status */
static u32 extract_speed(u16 linkstat)
{
	u32 speed;

	switch (linkstat & PCI_EXP_LNKSTA_CLS) {
	default: /* not defined, assume Gen1 */
	case PCI_EXP_LNKSTA_CLS_2_5GB:
		speed = 2500; /* Gen 1, 2.5GHz */
		break;
	case PCI_EXP_LNKSTA_CLS_5_0GB:
		speed = 5000; /* Gen 2, 5GHz */
		break;
	case GEN3_SPEED_VECTOR:
		speed = 8000; /* Gen 3, 8GHz */
		break;
	}
	return speed;
}

/* return the PCIe link speed from the given link status */
static u32 extract_width(u16 linkstat)
{
	return (linkstat & PCI_EXP_LNKSTA_NLW) >> PCI_EXP_LNKSTA_NLW_SHIFT;
}

/* read the link status and set dd->{lbus_width,lbus_speed,lbus_info} */
static void update_lbus_info(struct hfi1_devdata *dd)
{
	u16 linkstat;

	pcie_capability_read_word(dd->pcidev, PCI_EXP_LNKSTA, &linkstat);
	dd->lbus_width = extract_width(linkstat);
	dd->lbus_speed = extract_speed(linkstat);
	snprintf(dd->lbus_info, sizeof(dd->lbus_info),
		 "PCIe,%uMHz,x%u", dd->lbus_speed, dd->lbus_width);
}

/*
 * Read in the current PCIe link width and speed.  Find if the link is
 * Gen3 capable.
 */
int pcie_speeds(struct hfi1_devdata *dd)
{
	u32 linkcap;

	if (!pci_is_pcie(dd->pcidev)) {
		dd_dev_err(dd, "Can't find PCI Express capability!\n");
		return -EINVAL;
	}

	/* find if our max speed is Gen3 and parent supports Gen3 speeds */
	dd->link_gen3_capable = 1;

	pcie_capability_read_dword(dd->pcidev, PCI_EXP_LNKCAP, &linkcap);
	if ((linkcap & PCI_EXP_LNKCAP_SLS) != GEN3_SPEED_VECTOR) {
		dd_dev_info(dd,
			"This HFI is not Gen3 capable, max speed 0x%x, need 0x3\n",
			linkcap & PCI_EXP_LNKCAP_SLS);
		dd->link_gen3_capable = 0;
	}

	/*
	 * bus->max_bus_speed is set from the bridge's linkcap Max Link Speed
	 */
	if (dd->pcidev->bus->max_bus_speed != PCIE_SPEED_8_0GT) {
		dd_dev_info(dd, "Parent PCIe bridge does not support Gen3\n");
		dd->link_gen3_capable = 0;
	}

	/* obtain the link width and current speed */
	update_lbus_info(dd);

	/* check against expected pcie width and complain if "wrong" */
	if (dd->lbus_width < 16)
		dd_dev_err(dd, "PCIe width %u (x16 HFI)\n", dd->lbus_width);

	return 0;
}

/*
 * Returns in *nent:
 *	- actual number of interrupts allocated
 *	- 0 if fell back to INTx.
 */
void request_msix(struct hfi1_devdata *dd, u32 *nent,
		  struct hfi1_msix_entry *entry)
{
	int pos;

	pos = dd->pcidev->msix_cap;
	if (*nent && pos) {
		msix_setup(dd, pos, nent, entry);
		/* did it, either MSI-X or INTx */
	} else {
		*nent = 0;
		hfi1_enable_intx(dd->pcidev);
	}

	tune_pcie_caps(dd);
}

void hfi1_enable_intx(struct pci_dev *pdev)
{
	/* first, turn on INTx */
	pci_intx(pdev, 1);
	/* then turn off MSI-X */
	pci_disable_msix(pdev);
}

/* restore command and BARs after a reset has wiped them out */
void restore_pci_variables(struct hfi1_devdata *dd)
{
	pci_write_config_word(dd->pcidev, PCI_COMMAND, dd->pci_command);
	pci_write_config_dword(dd->pcidev,
				PCI_BASE_ADDRESS_0, dd->pcibar0);
	pci_write_config_dword(dd->pcidev,
				PCI_BASE_ADDRESS_1, dd->pcibar1);
	pci_write_config_dword(dd->pcidev,
				PCI_ROM_ADDRESS, dd->pci_rom);
	pcie_capability_write_word(dd->pcidev, PCI_EXP_DEVCTL, dd->pcie_devctl);
	pcie_capability_write_word(dd->pcidev, PCI_EXP_LNKCTL, dd->pcie_lnkctl);
	pcie_capability_write_word(dd->pcidev, PCI_EXP_DEVCTL2,
							dd->pcie_devctl2);
	pci_write_config_dword(dd->pcidev, PCI_CFG_MSIX0, dd->pci_msix0);
	pci_write_config_dword(dd->pcidev, PCIE_CFG_SPCIE1,
							dd->pci_lnkctl3);
	pci_write_config_dword(dd->pcidev, PCIE_CFG_TPH2, dd->pci_tph2);
}

/*
 * BIOS may not set PCIe bus-utilization parameters for best performance.
 * Check and optionally adjust them to maximize our throughput.
 */
static int hfi1_pcie_caps;
module_param_named(pcie_caps, hfi1_pcie_caps, int, S_IRUGO);
MODULE_PARM_DESC(pcie_caps, "Max PCIe tuning: Payload (0..3), ReadReq (4..7)");

static void tune_pcie_caps(struct hfi1_devdata *dd)
{
	struct pci_dev *parent;
	u16 rc_mpss, rc_mps, ep_mpss, ep_mps;
	u16 rc_mrrs, ep_mrrs, max_mrrs, ectl;

	/*
	 * Turn on extended tags in DevCtl in case the BIOS has turned it off
	 * to improve WFR SDMA bandwidth
	 */
	pcie_capability_read_word(dd->pcidev, PCI_EXP_DEVCTL, &ectl);
	if (!(ectl & PCI_EXP_DEVCTL_EXT_TAG)) {
		dd_dev_info(dd, "Enabling PCIe extended tags\n");
		ectl |= PCI_EXP_DEVCTL_EXT_TAG;
		pcie_capability_write_word(dd->pcidev, PCI_EXP_DEVCTL, ectl);
	}
	/* Find out supported and configured values for parent (root) */
	parent = dd->pcidev->bus->self;
	if (!pci_is_root_bus(parent->bus)) {
		dd_dev_info(dd, "Parent not root\n");
		return;
	}

	if (!pci_is_pcie(parent) || !pci_is_pcie(dd->pcidev))
		return;
	rc_mpss = parent->pcie_mpss;
	rc_mps = ffs(pcie_get_mps(parent)) - 8;
	/* Find out supported and configured values for endpoint (us) */
	ep_mpss = dd->pcidev->pcie_mpss;
	ep_mps = ffs(pcie_get_mps(dd->pcidev)) - 8;

	/* Find max payload supported by root, endpoint */
	if (rc_mpss > ep_mpss)
		rc_mpss = ep_mpss;

	/* If Supported greater than limit in module param, limit it */
	if (rc_mpss > (hfi1_pcie_caps & 7))
		rc_mpss = hfi1_pcie_caps & 7;
	/* If less than (allowed, supported), bump root payload */
	if (rc_mpss > rc_mps) {
		rc_mps = rc_mpss;
		pcie_set_mps(parent, 128 << rc_mps);
	}
	/* If less than (allowed, supported), bump endpoint payload */
	if (rc_mpss > ep_mps) {
		ep_mps = rc_mpss;
		pcie_set_mps(dd->pcidev, 128 << ep_mps);
	}

	/*
	 * Now the Read Request size.
	 * No field for max supported, but PCIe spec limits it to 4096,
	 * which is code '5' (log2(4096) - 7)
	 */
	max_mrrs = 5;
	if (max_mrrs > ((hfi1_pcie_caps >> 4) & 7))
		max_mrrs = (hfi1_pcie_caps >> 4) & 7;

	max_mrrs = 128 << max_mrrs;
	rc_mrrs = pcie_get_readrq(parent);
	ep_mrrs = pcie_get_readrq(dd->pcidev);

	if (max_mrrs > rc_mrrs) {
		rc_mrrs = max_mrrs;
		pcie_set_readrq(parent, rc_mrrs);
	}
	if (max_mrrs > ep_mrrs) {
		ep_mrrs = max_mrrs;
		pcie_set_readrq(dd->pcidev, ep_mrrs);
	}
}
/* End of PCIe capability tuning */

/*
 * From here through hfi1_pci_err_handler definition is invoked via
 * PCI error infrastructure, registered via pci
 */
static pci_ers_result_t
pci_error_detected(struct pci_dev *pdev, pci_channel_state_t state)
{
	struct hfi1_devdata *dd = pci_get_drvdata(pdev);
	pci_ers_result_t ret = PCI_ERS_RESULT_RECOVERED;

	switch (state) {
	case pci_channel_io_normal:
		dd_dev_info(dd, "State Normal, ignoring\n");
		break;

	case pci_channel_io_frozen:
		dd_dev_info(dd, "State Frozen, requesting reset\n");
		pci_disable_device(pdev);
		ret = PCI_ERS_RESULT_NEED_RESET;
		break;

	case pci_channel_io_perm_failure:
		if (dd) {
			dd_dev_info(dd, "State Permanent Failure, disabling\n");
			/* no more register accesses! */
			dd->flags &= ~HFI1_PRESENT;
			hfi1_disable_after_error(dd);
		}
		 /* else early, or other problem */
		ret =  PCI_ERS_RESULT_DISCONNECT;
		break;

	default: /* shouldn't happen */
		dd_dev_info(dd, "HFI1 PCI errors detected (state %d)\n",
			    state);
		break;
	}
	return ret;
}

static pci_ers_result_t
pci_mmio_enabled(struct pci_dev *pdev)
{
	u64 words = 0U;
	struct hfi1_devdata *dd = pci_get_drvdata(pdev);
	pci_ers_result_t ret = PCI_ERS_RESULT_RECOVERED;

	if (dd && dd->pport) {
		words = read_port_cntr(dd->pport, C_RX_WORDS, CNTR_INVALID_VL);
		if (words == ~0ULL)
			ret = PCI_ERS_RESULT_NEED_RESET;
		dd_dev_info(dd,
			    "HFI1 mmio_enabled function called, read wordscntr %Lx, returning %d\n",
			    words, ret);
	}
	return  ret;
}

static pci_ers_result_t
pci_slot_reset(struct pci_dev *pdev)
{
	struct hfi1_devdata *dd = pci_get_drvdata(pdev);

	dd_dev_info(dd, "HFI1 slot_reset function called, ignored\n");
	return PCI_ERS_RESULT_CAN_RECOVER;
}

static pci_ers_result_t
pci_link_reset(struct pci_dev *pdev)
{
	struct hfi1_devdata *dd = pci_get_drvdata(pdev);

	dd_dev_info(dd, "HFI1 link_reset function called, ignored\n");
	return PCI_ERS_RESULT_CAN_RECOVER;
}

static void
pci_resume(struct pci_dev *pdev)
{
	struct hfi1_devdata *dd = pci_get_drvdata(pdev);

	dd_dev_info(dd, "HFI1 resume function called\n");
	pci_cleanup_aer_uncorrect_error_status(pdev);
	/*
	 * Running jobs will fail, since it's asynchronous
	 * unlike sysfs-requested reset.   Better than
	 * doing nothing.
	 */
	hfi1_init(dd, 1); /* same as re-init after reset */
}

const struct pci_error_handlers hfi1_pci_err_handler = {
	.error_detected = pci_error_detected,
	.mmio_enabled = pci_mmio_enabled,
	.link_reset = pci_link_reset,
	.slot_reset = pci_slot_reset,
	.resume = pci_resume,
};

/*============================================================================*/
/* PCIe Gen3 support */

/*
 * This code is separated out because it is expected to be removed in the
 * final shipping product.  If not, then it will be revisited and items
 * will be moved to more standard locations.
 */

/* ASIC_PCI_SD_HOST_STATUS.FW_DNLD_STS field values */
#define DL_STATUS_HFI0 0x1	/* hfi0 firmware download complete */
#define DL_STATUS_HFI1 0x2	/* hfi1 firmware download complete */
#define DL_STATUS_BOTH 0x3	/* hfi0 and hfi1 firmware download complete */

/* ASIC_PCI_SD_HOST_STATUS.FW_DNLD_ERR field values */
#define DL_ERR_NONE		0x0	/* no error */
#define DL_ERR_SWAP_PARITY	0x1	/* parity error in SerDes interrupt */
					/*   or response data */
#define DL_ERR_DISABLED	0x2	/* hfi disabled */
#define DL_ERR_SECURITY	0x3	/* security check failed */
#define DL_ERR_SBUS		0x4	/* SBus status error */
#define DL_ERR_XFR_PARITY	0x5	/* parity error during ROM transfer*/

/* gasket block secondary bus reset delay */
#define SBR_DELAY_US 200000	/* 200ms */

/* mask for PCIe capability register lnkctl2 target link speed */
#define LNKCTL2_TARGET_LINK_SPEED_MASK 0xf

static uint pcie_target = 3;
module_param(pcie_target, uint, S_IRUGO);
MODULE_PARM_DESC(pcie_target, "PCIe target speed (0 skip, 1-3 Gen1-3)");

static uint pcie_force;
module_param(pcie_force, uint, S_IRUGO);
MODULE_PARM_DESC(pcie_force, "Force driver to do a PCIe firmware download even if already at target speed");

static uint pcie_retry = 5;
module_param(pcie_retry, uint, S_IRUGO);
MODULE_PARM_DESC(pcie_retry, "Driver will try this many times to reach requested speed");

#define UNSET_PSET 255
#define DEFAULT_DISCRETE_PSET 2	/* discrete HFI */
#define DEFAULT_MCP_PSET 4	/* MCP HFI */
static uint pcie_pset = UNSET_PSET;
module_param(pcie_pset, uint, S_IRUGO);
MODULE_PARM_DESC(pcie_pset, "PCIe Eq Pset value to use, range is 0-10");

/* equalization columns */
#define PREC 0
#define ATTN 1
#define POST 2

/* discrete silicon preliminary equalization values */
static const u8 discrete_preliminary_eq[11][3] = {
	/* prec   attn   post */
	{  0x00,  0x00,  0x12 },	/* p0 */
	{  0x00,  0x00,  0x0c },	/* p1 */
	{  0x00,  0x00,  0x0f },	/* p2 */
	{  0x00,  0x00,  0x09 },	/* p3 */
	{  0x00,  0x00,  0x00 },	/* p4 */
	{  0x06,  0x00,  0x00 },	/* p5 */
	{  0x09,  0x00,  0x00 },	/* p6 */
	{  0x06,  0x00,  0x0f },	/* p7 */
	{  0x09,  0x00,  0x09 },	/* p8 */
	{  0x0c,  0x00,  0x00 },	/* p9 */
	{  0x00,  0x00,  0x18 },	/* p10 */
};

/* integrated silicon preliminary equalization values */
static const u8 integrated_preliminary_eq[11][3] = {
	/* prec   attn   post */
	{  0x00,  0x1e,  0x07 },	/* p0 */
	{  0x00,  0x1e,  0x05 },	/* p1 */
	{  0x00,  0x1e,  0x06 },	/* p2 */
	{  0x00,  0x1e,  0x04 },	/* p3 */
	{  0x00,  0x1e,  0x00 },	/* p4 */
	{  0x03,  0x1e,  0x00 },	/* p5 */
	{  0x04,  0x1e,  0x00 },	/* p6 */
	{  0x03,  0x1e,  0x06 },	/* p7 */
	{  0x03,  0x1e,  0x04 },	/* p8 */
	{  0x05,  0x1e,  0x00 },	/* p9 */
	{  0x00,  0x1e,  0x0a },	/* p10 */
};

/* helper to format the value to write to hardware */
#define eq_value(pre, curr, post) \
	((((u32)(pre)) << \
			PCIE_CFG_REG_PL102_GEN3_EQ_PRE_CURSOR_PSET_SHIFT) \
	| (((u32)(curr)) << PCIE_CFG_REG_PL102_GEN3_EQ_CURSOR_PSET_SHIFT) \
	| (((u32)(post)) << \
		PCIE_CFG_REG_PL102_GEN3_EQ_POST_CURSOR_PSET_SHIFT))

/*
 * Load the given EQ preset table into the PCIe hardware.
 */
static int load_eq_table(struct hfi1_devdata *dd, const u8 eq[11][3], u8 fs,
			 u8 div)
{
	struct pci_dev *pdev = dd->pcidev;
	u32 hit_error = 0;
	u32 violation;
	u32 i;
	u8 c_minus1, c0, c_plus1;

	for (i = 0; i < 11; i++) {
		/* set index */
		pci_write_config_dword(pdev, PCIE_CFG_REG_PL103, i);
		/* write the value */
		c_minus1 = eq[i][PREC] / div;
		c0 = fs - (eq[i][PREC] / div) - (eq[i][POST] / div);
		c_plus1 = eq[i][POST] / div;
		pci_write_config_dword(pdev, PCIE_CFG_REG_PL102,
			eq_value(c_minus1, c0, c_plus1));
		/* check if these coefficients violate EQ rules */
		pci_read_config_dword(dd->pcidev, PCIE_CFG_REG_PL105,
								&violation);
		if (violation
		    & PCIE_CFG_REG_PL105_GEN3_EQ_VIOLATE_COEF_RULES_SMASK){
			if (hit_error == 0) {
				dd_dev_err(dd,
					"Gen3 EQ Table Coefficient rule violations\n");
				dd_dev_err(dd, "         prec   attn   post\n");
			}
			dd_dev_err(dd, "   p%02d:   %02x     %02x     %02x\n",
				i, (u32)eq[i][0], (u32)eq[i][1], (u32)eq[i][2]);
			dd_dev_err(dd, "            %02x     %02x     %02x\n",
				(u32)c_minus1, (u32)c0, (u32)c_plus1);
			hit_error = 1;
		}
	}
	if (hit_error)
		return -EINVAL;
	return 0;
}

/*
 * Steps to be done after the PCIe firmware is downloaded and
 * before the SBR for the Pcie Gen3.
 * The hardware mutex is already being held.
 */
static void pcie_post_steps(struct hfi1_devdata *dd)
{
	int i;

	set_sbus_fast_mode(dd);
	/*
	 * Write to the PCIe PCSes to set the G3_LOCKED_NEXT bits to 1.
	 * This avoids a spurious framing error that can otherwise be
	 * generated by the MAC layer.
	 *
	 * Use individual addresses since no broadcast is set up.
	 */
	for (i = 0; i < NUM_PCIE_SERDES; i++) {
		sbus_request(dd, pcie_pcs_addrs[dd->hfi1_id][i],
			     0x03, WRITE_SBUS_RECEIVER, 0x00022132);
	}

	clear_sbus_fast_mode(dd);
}

/*
 * Trigger a secondary bus reset (SBR) on ourselves using our parent.
 *
 * Based on pci_parent_bus_reset() which is not exported by the
 * kernel core.
 */
static int trigger_sbr(struct hfi1_devdata *dd)
{
	struct pci_dev *dev = dd->pcidev;
	struct pci_dev *pdev;

	/* need a parent */
	if (!dev->bus->self) {
		dd_dev_err(dd, "%s: no parent device\n", __func__);
		return -ENOTTY;
	}

	/* should not be anyone else on the bus */
	list_for_each_entry(pdev, &dev->bus->devices, bus_list)
		if (pdev != dev) {
			dd_dev_err(dd,
				"%s: another device is on the same bus\n",
				__func__);
			return -ENOTTY;
		}

	/*
	 * A secondary bus reset (SBR) issues a hot reset to our device.
	 * The following routine does a 1s wait after the reset is dropped
	 * per PCI Trhfa (recovery time).  PCIe 3.0 section 6.6.1 -
	 * Conventional Reset, paragraph 3, line 35 also says that a 1s
	 * delay after a reset is required.  Per spec requirements,
	 * the link is either working or not after that point.
	 */
	pci_reset_bridge_secondary_bus(dev->bus->self);

	return 0;
}

/*
 * Write the given gasket interrupt register.
 */
static void write_gasket_interrupt(struct hfi1_devdata *dd, int index,
				   u16 code, u16 data)
{
	write_csr(dd, ASIC_PCIE_SD_INTRPT_LIST + (index * 8),
	    (((u64)code << ASIC_PCIE_SD_INTRPT_LIST_INTRPT_CODE_SHIFT)
	    |((u64)data << ASIC_PCIE_SD_INTRPT_LIST_INTRPT_DATA_SHIFT)));
}

/*
 * Tell the gasket logic how to react to the reset.
 */
static void arm_gasket_logic(struct hfi1_devdata *dd)
{
	u64 reg;

	reg = (((u64)1 << dd->hfi1_id)
			<< ASIC_PCIE_SD_HOST_CMD_INTRPT_CMD_SHIFT)
		| ((u64)pcie_serdes_broadcast[dd->hfi1_id]
			<< ASIC_PCIE_SD_HOST_CMD_SBUS_RCVR_ADDR_SHIFT
		| ASIC_PCIE_SD_HOST_CMD_SBR_MODE_SMASK
		| ((u64)SBR_DELAY_US & ASIC_PCIE_SD_HOST_CMD_TIMER_MASK)
			<< ASIC_PCIE_SD_HOST_CMD_TIMER_SHIFT
		);
	write_csr(dd, ASIC_PCIE_SD_HOST_CMD, reg);
	/* read back to push the write */
	read_csr(dd, ASIC_PCIE_SD_HOST_CMD);
}

/*
 * Do all the steps needed to transition the PCIe link to Gen3 speed.
 */
int do_pcie_gen3_transition(struct hfi1_devdata *dd)
{
	struct pci_dev *parent;
	u64 fw_ctrl;
	u64 reg, therm;
	u32 reg32, fs, lf;
	u32 status, err;
	int ret;
	int do_retry, retry_count = 0;
	uint default_pset;
	u16 target_vector, target_speed;
	u16 lnkctl, lnkctl2, vendor;
	u8 nsbr = 1;
	u8 div;
	const u8 (*eq)[3];
	int return_error = 0;

	/* PCIe Gen3 is for the ASIC only */
	if (dd->icode != ICODE_RTL_SILICON)
		return 0;

	if (pcie_target == 1) {			/* target Gen1 */
		target_vector = GEN1_SPEED_VECTOR;
		target_speed = 2500;
	} else if (pcie_target == 2) {		/* target Gen2 */
		target_vector = GEN2_SPEED_VECTOR;
		target_speed = 5000;
	} else if (pcie_target == 3) {		/* target Gen3 */
		target_vector = GEN3_SPEED_VECTOR;
		target_speed = 8000;
	} else {
		/* off or invalid target - skip */
		dd_dev_info(dd, "%s: Skipping PCIe transition\n", __func__);
		return 0;
	}

	/* if already at target speed, done (unless forced) */
	if (dd->lbus_speed == target_speed) {
		dd_dev_info(dd, "%s: PCIe already at gen%d, %s\n", __func__,
			pcie_target,
			pcie_force ? "re-doing anyway" : "skipping");
		if (!pcie_force)
			return 0;
	}

	/*
	 * A0 needs an additional SBR
	 */
	if (is_ax(dd))
		nsbr++;

	/*
	 * Do the Gen3 transition.  Steps are those of the PCIe Gen3
	 * recipe.
	 */

	/* step 1: pcie link working in gen1/gen2 */

	/* step 2: if either side is not capable of Gen3, done */
	if (pcie_target == 3 && !dd->link_gen3_capable) {
		dd_dev_err(dd, "The PCIe link is not Gen3 capable\n");
		ret = -ENOSYS;
		goto done_no_mutex;
	}

	/* hold the HW mutex across the firmware download and SBR */
	ret = acquire_hw_mutex(dd);
	if (ret)
		return ret;

	/* make sure thermal polling is not causing interrupts */
	therm = read_csr(dd, ASIC_CFG_THERM_POLL_EN);
	if (therm) {
		write_csr(dd, ASIC_CFG_THERM_POLL_EN, 0x0);
		msleep(100);
		dd_dev_info(dd, "%s: Disabled therm polling\n",
			    __func__);
	}

retry:
	/* the SBus download will reset the spico for thermal */

	/* step 3: download SBus Master firmware */
	/* step 4: download PCIe Gen3 SerDes firmware */
	dd_dev_info(dd, "%s: downloading firmware\n", __func__);
	ret = load_pcie_firmware(dd);
	if (ret)
		goto done;

	/* step 5: set up device parameter settings */
	dd_dev_info(dd, "%s: setting PCIe registers\n", __func__);

	/*
	 * PcieCfgSpcie1 - Link Control 3
	 * Leave at reset value.  No need to set PerfEq - link equalization
	 * will be performed automatically after the SBR when the target
	 * speed is 8GT/s.
	 */

	/* clear all 16 per-lane error bits (PCIe: Lane Error Status) */
	pci_write_config_dword(dd->pcidev, PCIE_CFG_SPCIE2, 0xffff);

	/* step 5a: Set Synopsys Port Logic registers */

	/*
	 * PcieCfgRegPl2 - Port Force Link
	 *
	 * Set the low power field to 0x10 to avoid unnecessary power
	 * management messages.  All other fields are zero.
	 */
	reg32 = 0x10ul << PCIE_CFG_REG_PL2_LOW_PWR_ENT_CNT_SHIFT;
	pci_write_config_dword(dd->pcidev, PCIE_CFG_REG_PL2, reg32);

	/*
	 * PcieCfgRegPl100 - Gen3 Control
	 *
	 * turn off PcieCfgRegPl100.Gen3ZRxDcNonCompl
	 * turn on PcieCfgRegPl100.EqEieosCnt (erratum)
	 * Everything else zero.
	 */
	reg32 = PCIE_CFG_REG_PL100_EQ_EIEOS_CNT_SMASK;
	pci_write_config_dword(dd->pcidev, PCIE_CFG_REG_PL100, reg32);

	/*
	 * PcieCfgRegPl101 - Gen3 EQ FS and LF
	 * PcieCfgRegPl102 - Gen3 EQ Presets to Coefficients Mapping
	 * PcieCfgRegPl103 - Gen3 EQ Preset Index
	 * PcieCfgRegPl105 - Gen3 EQ Status
	 *
	 * Give initial EQ settings.
	 */
	if (dd->pcidev->device == PCI_DEVICE_ID_INTEL0) { /* discrete */
		/* 1000mV, FS=24, LF = 8 */
		fs = 24;
		lf = 8;
		div = 3;
		eq = discrete_preliminary_eq;
		default_pset = DEFAULT_DISCRETE_PSET;
	} else {
		/* 400mV, FS=29, LF = 9 */
		fs = 29;
		lf = 9;
		div = 1;
		eq = integrated_preliminary_eq;
		default_pset = DEFAULT_MCP_PSET;
	}
	pci_write_config_dword(dd->pcidev, PCIE_CFG_REG_PL101,
		(fs << PCIE_CFG_REG_PL101_GEN3_EQ_LOCAL_FS_SHIFT)
		| (lf << PCIE_CFG_REG_PL101_GEN3_EQ_LOCAL_LF_SHIFT));
	ret = load_eq_table(dd, eq, fs, div);
	if (ret)
		goto done;

	/*
	 * PcieCfgRegPl106 - Gen3 EQ Control
	 *
	 * Set Gen3EqPsetReqVec, leave other fields 0.
	 */
	if (pcie_pset == UNSET_PSET)
		pcie_pset = default_pset;
	if (pcie_pset > 10) {	/* valid range is 0-10, inclusive */
		dd_dev_err(dd, "%s: Invalid Eq Pset %u, setting to %d\n",
			__func__, pcie_pset, default_pset);
		pcie_pset = default_pset;
	}
	dd_dev_info(dd, "%s: using EQ Pset %u\n", __func__, pcie_pset);
	pci_write_config_dword(dd->pcidev, PCIE_CFG_REG_PL106,
		((1 << pcie_pset)
			<< PCIE_CFG_REG_PL106_GEN3_EQ_PSET_REQ_VEC_SHIFT)
		| PCIE_CFG_REG_PL106_GEN3_EQ_EVAL2MS_DISABLE_SMASK
		| PCIE_CFG_REG_PL106_GEN3_EQ_PHASE23_EXIT_MODE_SMASK);

	/*
	 * step 5b: Do post firmware download steps via SBus
	 */
	dd_dev_info(dd, "%s: doing pcie post steps\n", __func__);
	pcie_post_steps(dd);

	/*
	 * step 5c: Program gasket interrupts
	 */
	/* set the Rx Bit Rate to REFCLK ratio */
	write_gasket_interrupt(dd, 0, 0x0006, 0x0050);
	/* disable pCal for PCIe Gen3 RX equalization */
	write_gasket_interrupt(dd, 1, 0x0026, 0x5b01);
	/*
	 * Enable iCal for PCIe Gen3 RX equalization, and set which
	 * evaluation of RX_EQ_EVAL will launch the iCal procedure.
	 */
	write_gasket_interrupt(dd, 2, 0x0026, 0x5202);
	/* terminate list */
	write_gasket_interrupt(dd, 3, 0x0000, 0x0000);

	/*
	 * step 5d: program XMT margin
	 * Right now, leave the default alone.  To change, do a
	 * read-modify-write of:
	 *	CcePcieCtrl.XmtMargin
	 *	CcePcieCtrl.XmitMarginOverwriteEnable
	 */

	/* step 5e: disable active state power management (ASPM) */
	dd_dev_info(dd, "%s: clearing ASPM\n", __func__);
	pcie_capability_read_word(dd->pcidev, PCI_EXP_LNKCTL, &lnkctl);
	lnkctl &= ~PCI_EXP_LNKCTL_ASPMC;
	pcie_capability_write_word(dd->pcidev, PCI_EXP_LNKCTL, lnkctl);

	/*
	 * step 5f: clear DirectSpeedChange
	 * PcieCfgRegPl67.DirectSpeedChange must be zero to prevent the
	 * change in the speed target from starting before we are ready.
	 * This field defaults to 0 and we are not changing it, so nothing
	 * needs to be done.
	 */

	/* step 5g: Set target link speed */
	/*
	 * Set target link speed to be target on both device and parent.
	 * On setting the parent: Some system BIOSs "helpfully" set the
	 * parent target speed to Gen2 to match the ASIC's initial speed.
	 * We can set the target Gen3 because we have already checked
	 * that it is Gen3 capable earlier.
	 */
	dd_dev_info(dd, "%s: setting parent target link speed\n", __func__);
	parent = dd->pcidev->bus->self;
	pcie_capability_read_word(parent, PCI_EXP_LNKCTL2, &lnkctl2);
	dd_dev_info(dd, "%s: ..old link control2: 0x%x\n", __func__,
		(u32)lnkctl2);
	/* only write to parent if target is not as high as ours */
	if ((lnkctl2 & LNKCTL2_TARGET_LINK_SPEED_MASK) < target_vector) {
		lnkctl2 &= ~LNKCTL2_TARGET_LINK_SPEED_MASK;
		lnkctl2 |= target_vector;
		dd_dev_info(dd, "%s: ..new link control2: 0x%x\n", __func__,
			(u32)lnkctl2);
		pcie_capability_write_word(parent, PCI_EXP_LNKCTL2, lnkctl2);
	} else {
		dd_dev_info(dd, "%s: ..target speed is OK\n", __func__);
	}

	dd_dev_info(dd, "%s: setting target link speed\n", __func__);
	pcie_capability_read_word(dd->pcidev, PCI_EXP_LNKCTL2, &lnkctl2);
	dd_dev_info(dd, "%s: ..old link control2: 0x%x\n", __func__,
		(u32)lnkctl2);
	lnkctl2 &= ~LNKCTL2_TARGET_LINK_SPEED_MASK;
	lnkctl2 |= target_vector;
	dd_dev_info(dd, "%s: ..new link control2: 0x%x\n", __func__,
		(u32)lnkctl2);
	pcie_capability_write_word(dd->pcidev, PCI_EXP_LNKCTL2, lnkctl2);

	/* step 5h: arm gasket logic */
	/* hold DC in reset across the SBR */
	write_csr(dd, CCE_DC_CTRL, CCE_DC_CTRL_DC_RESET_SMASK);
	(void) read_csr(dd, CCE_DC_CTRL); /* DC reset hold */
	/* save firmware control across the SBR */
	fw_ctrl = read_csr(dd, MISC_CFG_FW_CTRL);

	dd_dev_info(dd, "%s: arming gasket logic\n", __func__);
	arm_gasket_logic(dd);

	/*
	 * step 6: quiesce PCIe link
	 * The chip has already been reset, so there will be no traffic
	 * from the chip.  Linux has no easy way to enforce that it will
	 * not try to access the device, so we just need to hope it doesn't
	 * do it while we are doing the reset.
	 */

	/*
	 * step 7: initiate the secondary bus reset (SBR)
	 * step 8: hardware brings the links back up
	 * step 9: wait for link speed transition to be complete
	 */
	dd_dev_info(dd, "%s: calling trigger_sbr\n", __func__);
	ret = trigger_sbr(dd);
	if (ret)
		goto done;

	/* step 10: decide what to do next */

	/* check if we can read PCI space */
	ret = pci_read_config_word(dd->pcidev, PCI_VENDOR_ID, &vendor);
	if (ret) {
		dd_dev_info(dd,
			"%s: read of VendorID failed after SBR, err %d\n",
			__func__, ret);
		return_error = 1;
		goto done;
	}
	if (vendor == 0xffff) {
		dd_dev_info(dd, "%s: VendorID is all 1s after SBR\n", __func__);
		return_error = 1;
		ret = -EIO;
		goto done;
	}

	/* restore PCI space registers we know were reset */
	dd_dev_info(dd, "%s: calling restore_pci_variables\n", __func__);
	restore_pci_variables(dd);
	/* restore firmware control */
	write_csr(dd, MISC_CFG_FW_CTRL, fw_ctrl);

	/*
	 * Check the gasket block status.
	 *
	 * This is the first CSR read after the SBR.  If the read returns
	 * all 1s (fails), the link did not make it back.
	 *
	 * Once we're sure we can read and write, clear the DC reset after
	 * the SBR.  Then check for any per-lane errors. Then look over
	 * the status.
	 */
	reg = read_csr(dd, ASIC_PCIE_SD_HOST_STATUS);
	dd_dev_info(dd, "%s: gasket block status: 0x%llx\n", __func__, reg);
	if (reg == ~0ull) {	/* PCIe read failed/timeout */
		dd_dev_err(dd, "SBR failed - unable to read from device\n");
		return_error = 1;
		ret = -ENOSYS;
		goto done;
	}

	/* clear the DC reset */
	write_csr(dd, CCE_DC_CTRL, 0);

	/* Set the LED off */
	if (is_ax(dd))
		setextled(dd, 0);

	/* check for any per-lane errors */
	pci_read_config_dword(dd->pcidev, PCIE_CFG_SPCIE2, &reg32);
	dd_dev_info(dd, "%s: per-lane errors: 0x%x\n", __func__, reg32);

	/* extract status, look for our HFI */
	status = (reg >> ASIC_PCIE_SD_HOST_STATUS_FW_DNLD_STS_SHIFT)
			& ASIC_PCIE_SD_HOST_STATUS_FW_DNLD_STS_MASK;
	if ((status & (1 << dd->hfi1_id)) == 0) {
		dd_dev_err(dd,
			"%s: gasket status 0x%x, expecting 0x%x\n",
			__func__, status, 1 << dd->hfi1_id);
		ret = -EIO;
		goto done;
	}

	/* extract error */
	err = (reg >> ASIC_PCIE_SD_HOST_STATUS_FW_DNLD_ERR_SHIFT)
		& ASIC_PCIE_SD_HOST_STATUS_FW_DNLD_ERR_MASK;
	if (err) {
		dd_dev_err(dd, "%s: gasket error %d\n", __func__, err);
		ret = -EIO;
		goto done;
	}

	/* update our link information cache */
	update_lbus_info(dd);
	dd_dev_info(dd, "%s: new speed and width: %s\n", __func__,
		dd->lbus_info);

	if (dd->lbus_speed != target_speed) { /* not target */
		/* maybe retry */
		do_retry = retry_count < pcie_retry;
		dd_dev_err(dd, "PCIe link speed did not switch to Gen%d%s\n",
			pcie_target, do_retry ? ", retrying" : "");
		retry_count++;
		if (do_retry) {
			msleep(100); /* allow time to settle */
			goto retry;
		}
		ret = -EIO;
	}

done:
	if (therm) {
		write_csr(dd, ASIC_CFG_THERM_POLL_EN, 0x1);
		msleep(100);
		dd_dev_info(dd, "%s: Re-enable therm polling\n",
			    __func__);
	}
	release_hw_mutex(dd);
done_no_mutex:
	/* return no error if it is OK to be at current speed */
	if (ret && !return_error) {
		dd_dev_err(dd, "Proceeding at current speed PCIe speed\n");
		ret = 0;
	}

	dd_dev_info(dd, "%s: done\n", __func__);
	return ret;
}


text:
package com.didi.virtualapk.internal;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityThread;
import android.app.LoadedApk;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.ResourcesImpl;
import android.content.res.ResourcesKey;
import android.os.Build;
import android.util.ArrayMap;
import android.util.DisplayMetrics;
import android.util.Log;

import com.didi.virtualapk.PluginManager;
import com.didi.virtualapk.utils.Reflector;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Created by renyugang on 16/8/9.
 */
class ResourcesManager {

    public static final String TAG = Constants.TAG_PREFIX + "LoadedPlugin";

    private static Configuration mDefaultConfiguration;

    public static synchronized Resources createResources(Context hostContext, String packageName, File apk) throws Exception {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return createResourcesForN(hostContext, packageName, apk);
        }

        Resources resources = ResourcesManager.createResourcesSimple(hostContext, apk.getAbsolutePath());
        ResourcesManager.hookResources(hostContext, resources);
        return resources;
    }

    private static Resources createResourcesSimple(Context hostContext, String apk) throws Exception {
        Resources hostResources = hostContext.getResources();
        Resources newResources = null;
        AssetManager assetManager;
        Reflector reflector = Reflector.on(AssetManager.class).method("addAssetPath", String.class);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            assetManager = AssetManager.class.newInstance();
            reflector.bind(assetManager);
            final int cookie1 = reflector.call(hostContext.getApplicationInfo().sourceDir);;
            if (cookie1 == 0) {
                throw new RuntimeException("createResources failed, can't addAssetPath for " + hostContext.getApplicationInfo().sourceDir);
            }
        } else {
            assetManager = hostResources.getAssets();
            reflector.bind(assetManager);
        }
        final int cookie2 = reflector.call(apk);
        if (cookie2 == 0) {
            throw new RuntimeException("createResources failed, can't addAssetPath for " + apk);
        }
        List<LoadedPlugin> pluginList = PluginManager.getInstance(hostContext).getAllLoadedPlugins();
        for (LoadedPlugin plugin : pluginList) {
            final int cookie3 = reflector.call(plugin.getLocation());
            if (cookie3 == 0) {
                throw new RuntimeException("createResources failed, can't addAssetPath for " + plugin.getLocation());
            }
        }
        if (isMiUi(hostResources)) {
            newResources = MiUiResourcesCompat.createResources(hostResources, assetManager);
        } else if (isVivo(hostResources)) {
            newResources = VivoResourcesCompat.createResources(hostContext, hostResources, assetManager);
        } else if (isNubia(hostResources)) {
            newResources = NubiaResourcesCompat.createResources(hostResources, assetManager);
        } else if (isNotRawResources(hostResources)) {
            newResources = AdaptationResourcesCompat.createResources(hostResources, assetManager);
        } else {
            // is raw android resources
            newResources = new Resources(assetManager, hostResources.getDisplayMetrics(), hostResources.getConfiguration());
        }
        // lastly, sync all LoadedPlugin to newResources
        for (LoadedPlugin plugin : pluginList) {
            plugin.updateResources(newResources);
        }

        return newResources;
    }

    public static void hookResources(Context base, Resources resources) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return;
        }
        try {
            Reflector reflector = Reflector.with(base);
            reflector.field("mResources").set(resources);
            Object loadedApk = reflector.field("mPackageInfo").get();
            Reflector.with(loadedApk).field("mResources").set(resources);

            Object activityThread = ActivityThread.currentActivityThread();
            Object resManager;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                resManager = android.app.ResourcesManager.getInstance();
            } else {
                resManager = Reflector.with(activityThread).field("mResourcesManager").get();
            }
            Map<Object, WeakReference<Resources>> map = Reflector.with(resManager).field("mActiveResources").get();
            Object key = map.keySet().iterator().next();
            map.put(key, new WeakReference<>(resources));
        } catch (Exception e) {
            Log.w(TAG, e);
        }
    }

    /**
     * Use System Apis to update all existing resources.
     *

     * 1. Update ApplicationInfo.splitSourceDirs and LoadedApk.mSplitResDirs
     *

     * 2. Replace all keys of ResourcesManager.mResourceImpls to new ResourcesKey
     *

     * 3. Use ResourcesManager.appendLibAssetForMainAssetPath(appInfo.publicSourceDir, "${packageName}.vastub") to update all existing resources.
     *

     *
     * see android.webkit.WebViewDelegate.addWebViewAssetPath(Context)
     */
    @TargetApi(Build.VERSION_CODES.N)
    private static Resources createResourcesForN(Context context, String packageName, File apk) throws Exception {
        long startTime = System.currentTimeMillis();
        String newAssetPath = apk.getAbsolutePath();
        ApplicationInfo info = context.getApplicationInfo();
        String baseResDir = info.publicSourceDir;

        info.splitSourceDirs = append(info.splitSourceDirs, newAssetPath);
        LoadedApk loadedApk = Reflector.with(context).field("mPackageInfo").get();

        Reflector rLoadedApk = Reflector.with(loadedApk).field("mSplitResDirs");
        String[] splitResDirs = rLoadedApk.get();
        rLoadedApk.set(append(splitResDirs, newAssetPath));

        final android.app.ResourcesManager resourcesManager = android.app.ResourcesManager.getInstance();
        ArrayMap<ResourcesKey, WeakReference<ResourcesImpl>> originalMap = Reflector.with(resourcesManager).field("mResourceImpls").get();

        synchronized (resourcesManager) {
            HashMap<ResourcesKey, WeakReference<ResourcesImpl>> resolvedMap = new HashMap<>();

            if (Build.VERSION.SDK_INT >= 28
                || (Build.VERSION.SDK_INT == 27 && Build.VERSION.PREVIEW_SDK_INT != 0)) { // P Preview
                ResourcesManagerCompatForP.resolveResourcesImplMap(originalMap, resolvedMap, context, loadedApk);

            } else {
                ResourcesManagerCompatForN.resolveResourcesImplMap(originalMap, resolvedMap, baseResDir, newAssetPath);
            }

            originalMap.clear();
            originalMap.putAll(resolvedMap);
        }

        android.app.ResourcesManager.getInstance().appendLibAssetForMainAssetPath(baseResDir, packageName + ".vastub");

        Resources newResources = context.getResources();

        // lastly, sync all LoadedPlugin to newResources
        for (LoadedPlugin plugin : PluginManager.getInstance(context).getAllLoadedPlugins()) {
            plugin.updateResources(newResources);
        }

        Log.d(TAG, "createResourcesForN cost time: +" + (System.currentTimeMillis() - startTime) + "ms");
        return newResources;
    }

    private static String[] append(String[] paths, String newPath) {
        if (contains(paths, newPath)) {
            return paths;
        }

        final int newPathsCount = 1 + (paths != null ? paths.length : 0);
        final String[] newPaths = new String[newPathsCount];
        if (paths != null) {
            System.arraycopy(paths, 0, newPaths, 0, paths.length);
        }
        newPaths[newPathsCount - 1] = newPath;
        return newPaths;
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    private static boolean contains(String[] array, String value) {
        if (array == null) {
            return false;
        }
        for (int i = 0; i < array.length; i++) {
            if (Objects.equals(array[i], value)) {
                return true;
            }
        }
        return false;
    }

    private static boolean isMiUi(Resources resources) {
        return resources.getClass().getName().equals("android.content.res.MiuiResources");
    }

    private static boolean isVivo(Resources resources) {
        return resources.getClass().getName().equals("android.content.res.VivoResources");
    }

    private static boolean isNubia(Resources resources) {
        return resources.getClass().getName().equals("android.content.res.NubiaResources");
    }

    private static boolean isNotRawResources(Resources resources) {
        return !resources.getClass().getName().equals("android.content.res.Resources");
    }

    private static final class MiUiResourcesCompat {
        private static Resources createResources(Resources hostResources, AssetManager assetManager) throws Exception {
            Reflector reflector = Reflector.on("android.content.res.MiuiResources");
            Resources newResources = reflector.constructor(AssetManager.class, DisplayMetrics.class, Configuration.class)
                .newInstance(assetManager, hostResources.getDisplayMetrics(), hostResources.getConfiguration());
            return newResources;
        }
    }

    private static final class VivoResourcesCompat {
        private static Resources createResources(Context hostContext, Resources hostResources, AssetManager assetManager) throws Exception {
            Reflector reflector = Reflector.on("android.content.res.VivoResources");
            Resources newResources = reflector.constructor(AssetManager.class, DisplayMetrics.class, Configuration.class)
                .newInstance(assetManager, hostResources.getDisplayMetrics(), hostResources.getConfiguration());
            reflector.method("init", String.class).callByCaller(newResources, hostContext.getPackageName());
            reflector.field("mThemeValues");
            reflector.set(newResources, reflector.get(hostResources));
            return newResources;
        }
    }

    private static final class NubiaResourcesCompat {
        private static Resources createResources(Resources hostResources, AssetManager assetManager) throws Exception {
            Reflector reflector = Reflector.on("android.content.res.NubiaResources");
            Resources newResources = reflector.constructor(AssetManager.class, DisplayMetrics.class, Configuration.class)
                .newInstance(assetManager, hostResources.getDisplayMetrics(), hostResources.getConfiguration());
            return newResources;
        }
    }

    private static final class AdaptationResourcesCompat {
        private static Resources createResources(Resources hostResources, AssetManager assetManager) throws Exception {
            Resources newResources;
            try {
                Reflector reflector = Reflector.with(hostResources);
                newResources = reflector.constructor(AssetManager.class, DisplayMetrics.class, Configuration.class)
                    .newInstance(assetManager, hostResources.getDisplayMetrics(), hostResources.getConfiguration());
            } catch (Exception e) {
                newResources = new Resources(assetManager, hostResources.getDisplayMetrics(), hostResources.getConfiguration());
            }

            return newResources;
        }
    }

    private static final class ResourcesManagerCompatForN {

        @TargetApi(Build.VERSION_CODES.KITKAT)
        public static void resolveResourcesImplMap(Map<ResourcesKey, WeakReference<ResourcesImpl>> originalMap, Map<ResourcesKey, WeakReference<ResourcesImpl>> resolvedMap, String baseResDir, String newAssetPath) throws Exception {
            for (Map.Entry<ResourcesKey, WeakReference<ResourcesImpl>> entry : originalMap.entrySet()) {
                ResourcesKey key = entry.getKey();
                if (Objects.equals(key.mResDir, baseResDir)) {
                    resolvedMap.put(new ResourcesKey(key.mResDir,
                        append(key.mSplitResDirs, newAssetPath),
                        key.mOverlayDirs,
                        key.mLibDirs,
                        key.mDisplayId,
                        key.mOverrideConfiguration,
                        key.mCompatInfo), entry.getValue());
                } else {
                    resolvedMap.put(key, entry.getValue());
                }
            }
        }
    }

    private static final class ResourcesManagerCompatForP {

        @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
        public static void resolveResourcesImplMap(Map<ResourcesKey, WeakReference<ResourcesImpl>> originalMap, Map<ResourcesKey, WeakReference<ResourcesImpl>> resolvedMap, Context context, LoadedApk loadedApk) throws Exception {
            HashMap<ResourcesImpl, Context> newResImplMap = new HashMap<>();
            Map<ResourcesImpl, ResourcesKey> resKeyMap = new HashMap<>();
            Resources newRes;

            // Recreate the resImpl of the context

            // See LoadedApk.getResources()
            if (mDefaultConfiguration == null) {
                mDefaultConfiguration = new Configuration();
            }
            newRes = context.createConfigurationContext(mDefaultConfiguration).getResources();
            newResImplMap.put(newRes.getImpl(), context);

            // Recreate the ResImpl of the activity
            for (WeakReference<Activity> ref : PluginManager.getInstance(context).getInstrumentation().getActivities()) {
                Activity activity = ref.get();
                if (activity != null) {
                    newRes = activity.createConfigurationContext(activity.getResources().getConfiguration()).getResources();
                    newResImplMap.put(newRes.getImpl(), activity);
                }
            }

            // Mapping all resKey and resImpl
            for (Map.Entry<ResourcesKey, WeakReference<ResourcesImpl>> entry : originalMap.entrySet()) {
                ResourcesImpl resImpl = entry.getValue().get();
                if (resImpl != null) {
                    resKeyMap.put(resImpl, entry.getKey());
                }
                resolvedMap.put(entry.getKey(), entry.getValue());
            }

            // Replace the resImpl to the new resKey and remove the origin resKey
            for (Map.Entry<ResourcesImpl, Context> entry : newResImplMap.entrySet()) {
                ResourcesKey newKey = resKeyMap.get(entry.getKey());
                ResourcesImpl originResImpl = entry.getValue().getResources().getImpl();

                resolvedMap.put(newKey, new WeakReference<>(originResImpl));
                resolvedMap.remove(resKeyMap.get(originResImpl));
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
[![Gem](https://img.shields.io/gem/v/reactssr-rails.svg?style=flat-square)](http://rubygems.org/gems/reactssr-rails)

* * *

# Reactssr::Rails

React SSR in Rails.

This gem is to solve one problem, that's `react-rails` will compile all React
components in one file.

This gem will works well with `webpackrails` to let you use commonjs feature,
and only evaluate js code as few as possible, and in production environment it
will use precompiled static file **instead of** compiling the files again and again.

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'reactssr-rails'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install reactssr-rails

## Usage

The SSR file is a js file whose name ends with `ssr.js` under base folder, and
base folder is the folder where you put all your SSR files at, the default base
folder name is `components`.

You can config the base folder, put this within your `config/application.rb` file,
`config.reactssr.assets_base = 'folder_name'`.

#### react server rendering

`react_ssr` is a view helper just like `react_component` in `react-rails`. Here is
an example how to use it:

```js
<%= react_ssr('IndexView', {props}) %>
```

So, suppose the current `controller_path` is `home`, then reactssr-rails will look
up a ssr file in components named `home.ssr.js`, just like below:

```js
// home.ssr.js

Components.IndexView = require('./IndexView.jsx');
```

### Make events work

Put this in your `application.js`: `//= require react_ssr` that below your Components.
This scripts will remount the component on client side so the event will be working.

According to React document, if remount the component on a markup that has been
mounted on the server side, the React will remount it in an efficient way on the
client side.

## Example

http://github.com/towry/reactssr-rails-example

## TODO

- [x] In production env, do not run `webpackrails`

## Development

After checking out the repo, run `bin/setup` to install dependencies. Then, run `bin/console` for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release` to create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).

## Contributing

1. Fork it ( https://github.com/towry/reactssr-rails/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request


text:
package com.geth1b.coding.design.patterns.behavioral.iterator;

import com.geth1b.coding.ds.ListNode;
import java.util.Iterator;

/**
 * @author geth1b
 */
public class IteratorPattern {

  public static void main(String[] args) {
    IteratorPattern obj = new IteratorPattern();
    IterableListNode t1 = obj.new IterableListNode(1);
    IterableListNode t2 = obj.new IterableListNode(2);
    IterableListNode t3 = obj.new IterableListNode(3);
    t1.next = t2;
    t2.next = t3;
    for (ListNode node : t1) {
      System.out.println(node.val);
    }
  }

  public class IterableListNode extends ListNode implements Iterable<ListNode> {

    public IterableListNode(int x) {
      super(x);
    }

    @Override public Iterator<ListNode> iterator() {
      return new ListNodeIterator();
    }

    // make it nested class; good oo
    private class ListNodeIterator implements Iterator<ListNode> {
      ListNode head = IterableListNode.this;
      @Override public boolean hasNext() {
        return head != null;
      }
      @Override public ListNode next() {
        ListNode node = head;
        head = head.next;
        return node;
      }
    }

  }

}


text:
var Y = require('yui').use('pnm-place');

module.exports = function placeLookup(rootPath) {
    return function (req, res) {
        var place     = new Y.PNM.Place(),
            placeText = req.url.split('/')[1];

        place.load({text: placeText}, function () {
            if (place.isNew()) {
                return res.send(404);
            }

            res.redirect(rootPath + place.get('id') + '/', 302);
        });
    };
};


text:
docker-machine ip default > dock
set /p DOCKER_IP= < dock
del dock
curl -X POST -d "{\"role\": \"serialize\", \"cmd\": \"write\", \"sensorId\": \"1\", \"temperature\": 32}" --header "Content-Type:application/json" http://%DOCKER_IP%:10000/act


text:
package eu.chargetime.ocpp.model.core;

import eu.chargetime.ocpp.PropertyConstraintException;
import eu.chargetime.ocpp.model.Request;
import eu.chargetime.ocpp.utilities.ModelUtil;
import eu.chargetime.ocpp.utilities.MoreObjects;
import java.util.Objects;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 * Sent by Central System to Charge Point.
 *
 * <p>It is RECOMMENDED that the content and meaning of the 'key' and 'value' fields is agreed upon
 * between Charge Point and Central System.
 */
@XmlRootElement
@XmlType(propOrder = {"key", "value"})
public class ChangeConfigurationRequest implements Request {

  private static final String ERROR_MESSAGE = "Exceeded limit of %s chars";
  private static final int KEY_MAX_LENGTH = 50;
  private static final int VALUE_MAX_LENGTH = 500;

  private String key;
  private String value;

  /**
   * @deprecated use {@link #ChangeConfigurationRequest(String, String)} to be sure to set required
   *     fields
   */
  @Deprecated
  public ChangeConfigurationRequest() {}

  /**
   * Handle required fields.
   *
   * @param key String, max 50 characters, case insensitive, see {@link #setKey(String)}
   * @param value String, max 500 characters, case insensitive, see {@link #setValue(String)}
   */
  public ChangeConfigurationRequest(String key, String value) {
    setKey(key);
    setValue(value);
  }

  private static String createErrorMessage(int valueMaxLength) {
    return String.format(ERROR_MESSAGE, valueMaxLength);
  }

  /**
   * The name of the configuration setting to change.
   *
   * @return Name of the configuration setting.
   */
  public String getKey() {
    return key;
  }

  /**
   * Required. The name of the configuration setting to change.
   *
   * @param key String, max 50 characters, case insensitive.
   */
  @XmlElement
  public void setKey(String key) {
    if (!isValidKey(key)) {
      throw new PropertyConstraintException(key.length(), createErrorMessage(KEY_MAX_LENGTH));
    }

    this.key = key;
  }

  private boolean isValidKey(String key) {
    return ModelUtil.validate(key, KEY_MAX_LENGTH);
  }

  /**
   * The new value as string for the setting.
   *
   * @return Value of the configuration setting.
   */
  public String getValue() {
    return value;
  }

  /**
   * Required. The new value as string for the setting.
   *
   * @param value String, max 500 characters, case insensitive.
   */
  @XmlElement
  public void setValue(String value) {
    if (!isValidValue(value)) {
      throw new PropertyConstraintException(value.length(), createErrorMessage(VALUE_MAX_LENGTH));
    }

    this.value = value;
  }

  private boolean isValidValue(String value) {
    return ModelUtil.validate(value, VALUE_MAX_LENGTH);
  }

  @Override
  public boolean validate() {
    return isValidKey(this.key) && isValidValue(this.value);
  }

  @Override
  public boolean transactionRelated() {
    return false;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    ChangeConfigurationRequest that = (ChangeConfigurationRequest) o;
    return Objects.equals(key, that.key) && Objects.equals(value, that.value);
  }

  @Override
  public int hashCode() {
    return Objects.hash(key, value);
  }

  @Override
  public String toString() {
    return MoreObjects.toStringHelper(this)
        .add("key", key)
        .add("value", value)
        .add("isValid", validate())
        .toString();
  }
}


text:
<!-- Do not edit this file. It is automatically generated by API Documenter. -->

[Home](./index.md) > [puppeteer](./puppeteer.md) > [Protocol](./puppeteer.protocol.md) > [Network](./puppeteer.protocol.network.md) > [Initiator](./puppeteer.protocol.network.initiator.md) > [stack](./puppeteer.protocol.network.initiator.stack.md)

## Protocol.Network.Initiator.stack property

Initiator JavaScript stack trace, set for Script only.

<b>Signature:</b>

```typescript
stack?: Runtime.StackTrace;
```


text:
  Murville est
       un village
       géographiquement positionné dans le département de Meurthe-et-Moselle en Lorraine. On dénombrait 257 habitants en 2008.

Le nombre de logements, à Murville, était réparti en 2011 en trois appartements et 100 maisons soit
 un marché relativement équilibré.

À coté de Murville sont localisées les villes de
Landres située à 2 km, 888 habitants,
Xivry-Circourt localisée à 5 km, 272 habitants,
Mairy-Mainville à 4 km, 536 habitants,
Tucquegnieux localisée à 5 km, 2 649 habitants,
Mercy-le-Haut localisée à 3 km, 245 habitants,
Mont-Bonvillers localisée à 1 km, 960 habitants,
 entre autres. De plus, Murville est située à seulement 24 km de Thionville.

Si vous pensez emmenager à Murville, vous pourrez facilement trouver une maison à acheter.


text:
angular
    .module(module.core)
    .service('BaseService', baseService);

baseService.$inject = ['$http', 'ActionService'];

function baseService($http, $actionService) {
    return {
        get: get,
        post: post
    };

    function get(url, success, error, data) {
        return $actionService.getInstance('GET', url, success, error, data);
    };

    function post(url, success, error, data) {
        return $actionService.getInstance('POST', url, success, error, data);
    };
};


text:
(function() {

  var app = angular.module('githubViewer', []);

  var MainController = function(
    $scope, github, $interval,
    $log, $anchorScroll, $location) {

    var onUserComplete = function(data) {
      $scope.user = data;
      github.getRepos($scope.user).then(onRepos, onError);
    };

    var onRepos = function(data) {
      $scope.repos = data;
      $location.hash("userDetails");
      $anchorScroll();
    };

    var onError = function(reason) {
      $scope.error = "Not fetched";
    };

    var decCount = function() {
      $scope.countdown -= 1;
      if ($scope.countdown < 1) {
        $scope.search($scope.username);
      };
    };

    var countdownInterval = null;
    var startCountdown = function() {
      countdownInterval = $interval(decCount, 1000, $scope.countdown);
    };

    $scope.search = function(username) {
      $log.info("searching for " + username);
      github.getUser(username).then(onUserComplete, onError);
      if (countdownInterval) {
        $interval.cancel(countdownInterval);
        $scope.countdown = null;
      };
    };

    $scope.username = "angular";
    $scope.repoSortOrder = "-stargazers_count";
    $scope.countdown = 5;
    startCountdown();

  };
  app.controller('MainController', MainController);
}());


text:
<?php
include('../header.php');
include('../vdaemon/vdaemon.php');
include('../html_header.php');
?>

                <?php echo \app\conf\App::$param['heroText']; ?>

                    <img src="<?php echo \app\conf\App::$param['loginLogo']; ?>" id="logo">

                <form id="Register" action="p" method="POST" runat="vdaemon" disablebuttons="all">

                                <vlsummary class="error" headertext="" displaymode="paragraph">

                            <vllabel validators="UserID" errclass="error"
                                     errtext="User name required" for="UserID">

                            </vllabel>
                            <vlvalidator name="UserID" type="required" control="UserID"/>
                            <vlvalidator name="UserIDExist" type="custom" control="UserID"
                                         errmsg="User name already exist"
                                         function="UserIDCheck"/>
                            <input name="UserID" type="text" class="form-control" id="UserID" placeholder="User name"/>

                            <vllabel errclass="error" validators="Email1,Email2" for="Email"
                                     errtext="Hmm, that does not look like an email">

                            </vllabel>

                            <input name="Email" type="TEXT" class="form-control" id="Email" size="15"
                                   placeholder="E-mail">
                            <vlvalidator type="required" format="email" name="Email1" control="Email"/>
                            <vlvalidator type="format" format="email" name="Email2" control="Email"/>

                            <vllabel errclass="error" validators="Password" for="Password"
                                     errtext="You must type a password">

                            </vllabel>
                            <input name="Password" type="password" class="form-control" id="Password"
                                   placeholder="Password"/>
                            <vlvalidator type="required" name="Password" control="Password"/>

                            <vllabel validators="Password,PassCmp" errclass="error" for="Password2"
                                     errtext="Both Password fields must be equal">

                            </vllabel>
                            <input name="Password2" type="PASSWORD" class="form-control last" id="Password2"
                                   placeholder="Confirm password">
                            <vlvalidator name="PassCmp" type="compare" control="Password" comparecontrol="Password2"
                                         operator="e" validtype="string">

                        <?php if (\app\conf\App::$param['domain']) { ?>

                                Choose between data center locations

                                    <input type="radio" name="Zone" value="us1" checked>
                                    North America

                                    <input type="radio" name="Zone" value="eu1">
                                    Europe

                        <?php } ?>

                            <input type="submit" class="btn btn-danger full-width" value="Create Account">

                                <input name="Agreement" type="checkbox" id="Agreement" value="1">
                                <vllabel errclass="error" validators="Agreement" for="Agreement"
                                         errtext="Agreement must be checked">
                                    I agree with the terms
                                        of service
                                </vllabel>

                            <vlvalidator type="required" name="Agreement" control="Agreement">

                </form>

<?php VDEnd(); ?>


text:
package io.github.hl7.bridge.handler;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ca.uhn.hl7v2.model.Message;
import io.github.hl7.bridge.MessageListener;
import io.github.hl7.bridge.MessageProcessDelegate;
import io.github.hl7.bridge.exchange.MessageExchangeImpl;

public class NotificationHandlerManager implements NotificationHandler{
	private static final NotificationHandler INSTANCE = new NotificationHandlerManager();
	private final ExecutorService executor = Executors.newFixedThreadPool(20);
	private final Logger log = LoggerFactory.getLogger(NotificationHandlerManager.class);

	private NotificationHandlerManager() {

	}

	@Override
	public void handle(Message message, List<MessageListener> listeners, MessageProcessDelegate delegate) {
		MessageExchangeImpl exchange = new MessageExchangeImpl();
		exchange.setIdentifier(UUID.randomUUID().toString());
		exchange.setMessage(message);

		sendAndAwait(exchange, listeners, delegate);
	}

	private void sendAndAwait(final MessageExchangeImpl exchange, final List<MessageListener> listeners, final MessageProcessDelegate delegate){

		executor.execute(new Runnable() {

			@Override
			public void run() {
				//Creates tasks to execute on background
				List<MessageListenerNotifierCallable> tasks = new ArrayList<>();
				for (MessageListener listener : listeners) {
					tasks.add( new MessageListenerNotifierCallable(exchange, listener) );
				}

				try {
					executor.invokeAll(tasks);
					delegate.completed(exchange);
				} catch (InterruptedException e) {
					log.error("Unable to dispatch message:", e);
				}
			}
		});

	}

	public static NotificationHandler getInstance(){
		return INSTANCE;
	}

}


text:
/**
 * @title AspectjUtil.java
 * @description TODO(这里用一句话描述这个文件的作用)
 * @package lm.pro.aop
 * @author mrluo735
 * @since JDK1.7
 * @date 2017年5月2日上午10:41:54
 * @version v1.0.0
 */
package lm.com.aop.util;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.reflect.CodeSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Description;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;

import lm.com.aop.model.AopClass;
import lm.com.aop.model.EnumClassType;
import lm.com.framework.JavaUtil;
import lm.com.framework.JsonUtil;
import lm.com.framework.ReflectUtil;

/**
 * Aspectj工具类
 *
 * @ClassName: AspectjUtil
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author mrluo735
 * @date 2017年5月2日 上午10:41:54
 *
 */
public class ClassUtil {
	private static final Logger logger = LoggerFactory.getLogger(ClassUtil.class);

	/**
	 * 获取拦截主体信息
	 *
	 * @param joinPoint
	 * @return
	 */
	public static AopClass getBody(JoinPoint joinPoint) {
		AopClass aopClass = new AopClass();
		try {
			Signature signature = joinPoint.getSignature();
			if (null != signature) {
				Class<?> clazz = signature.getDeclaringType();
				EnumClassType classType = getClassType(clazz);
				String packageName = clazz.getPackage().getName();
				String className = clazz.getSimpleName();
				String classDescription = getClassDescription(clazz);
				String methodFullName = signature.getDeclaringTypeName().concat(".").concat(signature.getName());
				String methodName = signature.getName();
				String methodParameter = getMethodParameter(joinPoint, signature);
				String methodDescription = getMethodDescription(clazz, methodName, classType);

				aopClass.setType(ReflectUtil.getTopSuperClass(clazz));
				aopClass.setClassType(classType);
				aopClass.setPackageName(packageName);
				aopClass.setClassName(className);
				aopClass.setClassDescription(classDescription);
				aopClass.setMethodFullName(methodFullName);
				aopClass.setMethodName(methodName);
				aopClass.setMethodParameter(methodParameter);
				aopClass.setMethodDescription(methodDescription);
			}
		} catch (Exception ex) {
			logger.error("AspectjUtil.getBody解析出错!错误原因:{}", ex.getMessage());
		}
		return aopClass;
	}

	/**
	 * 获取类类型
	 *
	 * @param clazz
	 * @return
	 */
	public static EnumClassType getClassType(Class<?> clazz) {
		// 获取类上所有注解
		Annotation[] annotations = clazz.getDeclaredAnnotations();
		if (null == annotations || annotations.length < 1) {
			return EnumClassType.Common;
		}

		for (Annotation item : annotations) {
			if (item.annotationType().equals(RestController.class))
				return EnumClassType.RestController;
			else if (item.annotationType().equals(Controller.class))
				return EnumClassType.Controller;
		}
		return EnumClassType.Common;
	}

	/**
	 * 获取类描述
	 *
	 * @param clazz
	 * @return
	 */
	public static String getClassDescription(Class<?> clazz) {
		try {
			// 获取类上所有注解
			Annotation[] annotations = clazz.getDeclaredAnnotations();
			if (null == annotations || annotations.length < 1) {
				return "";
			}

			for (Annotation item : annotations) {
				if (!item.annotationType().equals(Description.class))
					continue;

				Method valueMethod = item.annotationType().getMethod("value");
				if (null == valueMethod)
					return "";

				Object methodDesc = valueMethod.invoke(item);
				return null == methodDesc ? "" : methodDesc.toString();
			}
		} catch (NoSuchMethodException ex) {
		} catch (IllegalAccessException ex) {
		} catch (IllegalArgumentException ex) {
		} catch (InvocationTargetException ex) {
		} catch (Exception ex) {
		}
		return "";
	}

	/**
	 * 获取方法参数
	 *
	 * @param joinPoint
	 * @param signature
	 * @return
	 */
	public static String getMethodParameter(JoinPoint joinPoint, Signature signature) {
		CodeSignature codeSignature = (CodeSignature) signature;
		if (null == codeSignature)
			return "";

		String[] parameterNames = codeSignature.getParameterNames();
		if (null == parameterNames || parameterNames.length < 1)
			return "";

		Class<?>[] parameterTypes = codeSignature.getParameterTypes();
		Object[] parameterValues = joinPoint.getArgs();
		StringBuilder sb = new StringBuilder();
		sb.append("参数名称 = ".concat(JsonUtil.toJsonUseJackson(parameterNames)).concat(JavaUtil.getLineSeparator()));
		sb.append("参数类型 = ".concat(JsonUtil.toJsonUseJackson(parameterTypes)).concat(JavaUtil.getLineSeparator()));
		sb.append("参数值 = ".concat(JsonUtil.toJsonUseJackson(parameterValues)).concat(JavaUtil.getLineSeparator()));
		return sb.toString();
	}

	/**
	 * 获取方法描述
	 *
	 * @param clazz
	 * @param methodName
	 * @param classType
	 * @return
	 */
	public static String getMethodDescription(Class<?> clazz, String methodName, EnumClassType classType) {
		// 普通类里的方法不获取描述
		if (classType == EnumClassType.Common)
			return "";

		try {
			// 获取方法上的注解
			Method[] methods = clazz.getMethods();
			if (null == methods || methods.length < 1)
				return "";

			for (Method method : methods) {
				if (!method.getName().equals(methodName))
					continue;
				Annotation[] annotations = method.getAnnotations();
				for (Annotation item : annotations) {
					if (!item.annotationType().equals(Description.class))
						continue;
					Method valueMethod;
					valueMethod = item.annotationType().getMethod("value");

					if (null == valueMethod)
						return "";

					Object methodDesc = valueMethod.invoke(item);
					return null == methodDesc ? "" : methodDesc.toString();
				}
			}
		} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
				| InvocationTargetException ex) {
		}
		return "";
	}

	/**
	 * 获取ServletRequest
	 *
	 * @param joinPoint
	 * @return
	 */
	public static HttpServletRequest getServletRequest(JoinPoint joinPoint) {
		Signature signature = joinPoint.getSignature();
		if (signature == null || !(signature instanceof CodeSignature))
			return null;

		CodeSignature codeSignature = (CodeSignature) signature;

		String[] parameterNames = codeSignature.getParameterNames();
		if (null == parameterNames || parameterNames.length < 1)
			return null;

		// Class<?>[] parameterTypes = codeSignature.getParameterTypes();
		Object[] parameterValues = joinPoint.getArgs();
		for (Object parameterValue : parameterValues) {
			if (parameterValue instanceof HttpServletRequest) {
				HttpServletRequest request = (HttpServletRequest) parameterValue;
				return request;
			}
		}
		return null;
	}
}


text:
"use strict";
function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
var base_transform_walker_1 = require("./base-transform-walker");
exports.BaseTransformWalker = base_transform_walker_1.BaseTransformWalker;
var aot_transform_walker_1 = require("./aot-transform-walker");
exports.AotTransformWalker = aot_transform_walker_1.AotTransformWalker;
__export(require("./patching"));
//# sourceMappingURL=index.js.map


text:
package org.terasology.network.internal.pipelineFactory;

import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.handler.codec.compression.ZlibDecoder;
import org.jboss.netty.handler.codec.frame.LengthFieldBasedFrameDecoder;
import org.jboss.netty.handler.codec.protobuf.ProtobufDecoder;
import org.jboss.netty.handler.codec.protobuf.ProtobufEncoder;
import org.jboss.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import org.jboss.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import org.terasology.network.internal.ClientConnectionHandler;
import org.terasology.network.internal.ClientHandler;
import org.terasology.network.internal.ClientHandshakeHandler;
import org.terasology.network.internal.JoinStatusImpl;
import org.terasology.network.internal.MetricRecordingHandler;
import org.terasology.network.internal.NetworkSystemImpl;
import org.terasology.protobuf.NetData;

import static org.jboss.netty.channel.Channels.pipeline;

/**
 * Netty pipeline for Clients
 *
 * @author Immortius
 */
public class TerasologyClientPipelineFactory implements ChannelPipelineFactory {

    private NetworkSystemImpl networkSystem;

    public TerasologyClientPipelineFactory(NetworkSystemImpl networkSystem) {
        this.networkSystem = networkSystem;
    }

    @Override
    public ChannelPipeline getPipeline() throws Exception {
        JoinStatusImpl joinStatus = new JoinStatusImpl();
        ChannelPipeline p = pipeline();
        p.addLast(MetricRecordingHandler.NAME, new MetricRecordingHandler());

        p.addLast("lengthFrameDecoder", new LengthFieldBasedFrameDecoder(8388608, 0, 3, 0, 3));
        p.addLast("inflateDecoder", new ZlibDecoder());
        p.addLast("frameDecoder", new ProtobufVarint32FrameDecoder());
        p.addLast("protobufDecoder", new ProtobufDecoder(NetData.NetMessage.getDefaultInstance()));

        p.addLast("frameEncoder", new ProtobufVarint32LengthFieldPrepender());
        p.addLast("protobufEncoder", new ProtobufEncoder());
        p.addLast("authenticationHandler", new ClientHandshakeHandler(joinStatus));
        p.addLast("connectionHandler", new ClientConnectionHandler(joinStatus, networkSystem));
        p.addLast("handler", new ClientHandler(networkSystem));
        return p;
    }
}


text:
# define _actsize 1500
# define _memsize 3500
# define _nstates 400
# define _nterms 95
# define _nprod 250
# define _nnonterm 100
# define _tempsize 400
# define _cnamsz 2000
# define _lsetsize 200
# define _wsetsize 150

# define _tbitset 6

int tbitset;  /* size of lookahed sets */
int nolook 0; /* flag to suppress lookahead computations */
struct looksets { int lset[ _tbitset ]; } ;
struct item { int *pitem; } ;

/* this file contains the definitions for most externally known data */

int nstate 0;		/* number of states */
struct item *pstate[_nstates];	/* pointers to the descriptions of the states */
int apstate[_nstates];	/* index to the actions for the states */
int tystate[_nstates];	/* contains type information about the states */
int stsize _nstates;	/* maximum number of states, at present */
int memsiz _memsize;	/* maximum size for productions and states */
int mem0[_memsize] ; /* production storage */
int *mem mem0;
int amem[_actsize];  /* action table storage */
int actsiz _actsize; /* action table size */
int memact 0;		/* next free action table position */
int nprod 1;	/* number of productions */
int *prdptr[_nprod];	/* pointers to descriptions of productions */
int prdlim _nprod ;  /* the maximum number of productions */
	/* levprd - productions levels to break conflicts */
int levprd[_nprod] {0,0};
  /* last two bits code associativity:
       0 = no definition
       1 = left associative
       2 = binary
       3 = right associative
     bit 04 is 1 if the production has an action
     the high 13 bits have the production level
     */
int nterms 0;	/* number of terminals */
int tlim _nterms ; /* the maximum number of terminals */
/*	the ascii representations of the terminals	*/
int extval 0;  /* start of output values */
struct sxxx1 {char *name; int value;} trmset[_nterms];
char cnames[_cnamsz];
int cnamsz _cnamsz;
char *cnamp;
int maxtmp _tempsize;	/* the size of the temp1 array */
int temp1[_tempsize]; /* temporary storage, indexed by terms + nterms or states */
int temp2[_nnonterm]; /* temporary storage indexed by nonterminals */
int trmlev[_nterms];	/* vector with the precedence of the terminals */
  /* The levels are the same as for levprd, but bit 04 is always 0 */
/* the ascii representations of the nonterminals */
struct sxxx2 { char *name; } nontrst[_nnonterm];
int ntlim _nnonterm ; /* limit to the number of nonterminals */
int indgo[_nstates];		/* index to the stored goto table */
int ***pres; /* vector of pointers to the productions yielding each nonterminal */
struct looksets **pfirst; /* vector of pointers to first sets for each nonterminal */
int *pempty 0 ; /* table of nonterminals nontrivially deriving e */
int nnonter -1;	/* the number of nonterminals */
int lastred 0;	/* the number of the last reduction of a state */
int ftable;		/* y.tab.c file */
int foutput;		/* y.output file */
int arrndx; /* used in the output of arrays on y.tab.c */
int zzcwset 0;
int zzpairs 0;
int zzgoent 0;
int zzgobest 0;
int zzacent 0;
int zzacsave 0;
int zznsave 0;
int zzclose 0;
int zzsrconf 0;
int zzrrconf 0;
char *ctokn;
int lineno 1; /* current input line number */
int peekc -1; /* look-ahead character */
int tstates[ _nterms ]; /* states generated by terminal gotos */
int ntstates[ _nnonterm ]; /* states generated by nonterminal gotos */
int mstates[ _nstates ]; /* chain of overflows of term/nonterm generation lists  */

struct looksets clset;
struct looksets lkst [ _lsetsize ];
int nlset 0; /* next lookahead set index */
int lsetsz _lsetsize; /* number of lookahead sets */

struct wset { int *pitem, flag, ws[_tbitset]; } wsets[ _wsetsize ];
int cwset;
int wssize _wsetsize;

int numbval;  /* the value of an input number */
int rflag 0;  /* ratfor flag */
int oflag 0;  /* optimization flag */

int ndefout 3;  /* number of defined symbols output */
int nerrors 0;	/* number of errors */
int fatfl 1;  	/* if on, error is fatal */
int machine;   /* has a number describing the machine */


text:
using System;
using System.Drawing;
using System.Linq;
using MonoTouch.UIKit;
using MonoTouch.Dialog;
using System.Collections.Generic;

namespace Sample
{
	public partial class AppDelegate
	{
		public void DemoContainerStyle ()
		{
			var root = new RootElement ("Container Style") {
				new Section ("A") {
					new StringElement ("Another kind of"),
					new StringElement ("TableView, just by setting the"),
					new StringElement ("Style property"),
				},
				new Section ("C"){
					new StringElement ("Chaos"),
					new StringElement ("Corner"),
				},
				new Section ("Style"){
					from a in "Hello there, this is a long text that I would like to split in many different nodes for the sake of all of us".Split (' ')
						select (Element) new StringElement (a)
				}
			};
			var dvc = new DialogViewController (root, true) {
				Style = UITableViewStyle.Plain
			};
			navigation.PushViewController (dvc, true);
		}

	}
}


text:
import balanced

balanced.configure('ak-test-2eKlj1ZDfAcZSARMf3NMhBHywDej0avSY')

refund = balanced.Refund.fetch('/refunds/RF5OXw4w1a9g2GsPqQ2Hg9hj')


text:
package com.mebigfatguy.inventory.core;

import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;

import com.mebigfatguy.inventory.xml.InventoryNamespaceContext;

public class XMLScanner implements ArchiveScanner {

    private static DocumentBuilderFactory documentBuilderFactory;
    private static XPathExpression beanXPathExpression;

    private static XPathExpression servletXPathExpression;
    private static XPathExpression listenerXPathExpression;

    static {
        try {
            documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);

            XPathFactory xpf = XPathFactory.newInstance();
            XPath xpath = xpf.newXPath();
            xpath.setNamespaceContext(new InventoryNamespaceContext());

            beanXPathExpression = xpath.compile(InventoryNamespaceContext.springQualified("beans", "bean"));
            servletXPathExpression = xpath.compile(InventoryNamespaceContext.webXmlQualified("web-app", "servlet", "servlet-class") + "/text()");
            listenerXPathExpression = xpath.compile(InventoryNamespaceContext.webXmlQualified("web-app", "listener", "listener-class") + "/text()");
        } catch (XPathExpressionException e) {
            throw new Error(e);
        }
    }

    @Override
    public void scan(String name, Inventory inventory) throws IOException {
        try (InputStream is = inventory.getStream()) {
            DocumentBuilder db = documentBuilderFactory.newDocumentBuilder();
            Document document = db.parse(is);

            scanSpringBeans(document, name, inventory);
            scanWebXml(document, name, inventory);

        } catch (ParserConfigurationException | SAXException | XPathExpressionException e) {
            throw new IOException("Failed to parse xml file: " + name, e);
        }
    }

    private void scanSpringBeans(Document document, String name, Inventory inventory) throws XPathExpressionException {
        NodeList beans = (NodeList) beanXPathExpression.evaluate(document, XPathConstants.NODESET);
        for (int i = 0; i < beans.getLength(); i++) {
            Element bean = (Element) beans.item(i);
            String clsName = bean.getAttribute("class");
            if ((clsName != null) && !clsName.isEmpty()) {
                inventory.getEventFirer().fireClassUsed(clsName, name);
            }
        }
    }

    private void scanWebXml(Document document, String name, Inventory inventory) throws XPathExpressionException {
        NodeList servlets = (NodeList) servletXPathExpression.evaluate(document, XPathConstants.NODESET);
        for (int i = 0; i < servlets.getLength(); i++) {
            Text classNode = (Text) servlets.item(i);
            if (classNode != null) {
                String clsName = classNode.getTextContent();
                if (!clsName.isEmpty()) {
                    inventory.getEventFirer().fireClassUsed(clsName, name);
                }
            }
        }

        NodeList listeners = (NodeList) listenerXPathExpression.evaluate(document, XPathConstants.NODESET);
        for (int i = 0; i < listeners.getLength(); i++) {
            Text classNode = (Text) listeners.item(i);
            if (classNode != null) {
                String clsName = classNode.getTextContent();
                if (!clsName.isEmpty()) {
                    inventory.getEventFirer().fireClassUsed(clsName, name);
                }
            }
        }

    }
}


text:
@implementation ABI43_0_0AIRGMSMarker

@end

#endif


text:
ACCEPTED

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

#### Published in
Sydowia 50(1): 49 (1998)

#### Original name
Entosordaria deightonii Petr., 1952

### Remarks
null


text:
cask 'noisebuddy' do
  version '1.2'
  sha256 'e5497362319e111fb4a0c9ff9d479e21b75fda768a96ef3497c1fad7db2c7c38'

  url "https://github.com/insidegui/NoiseBuddy/releases/download/#{version}/NoiseBuddy_v#{version}.zip"
  appcast 'https://github.com/insidegui/NoiseBuddy/releases.atom'
  name 'NoiseBuddy'
  homepage 'https://github.com/insidegui/NoiseBuddy'

  depends_on macos: '>= :catalina'

  app 'NoiseBuddy.app'
end


text:
{% extends "nav.html" %}
{% block title %}
Introductory Project Results
{% endblock %}
{% block body %}

Introductory Project Results

    <form data-module="introductoryProject">

Introductory Members

                    <input class="form-control" type="text" placeholder="Quick Select" data-module="ipSearch" data-target="table.intro-project">

                                Name
                                Result

                            {% for f in intro_members %}

                                     {{f['name']}}

                                            {{f['freshman_project']}}

                                                 Passed

                                                 Pending

                                                 Failed

                            {% endfor %}

        <input type="submit" role="button" class="btn btn-raised btn-primary" style="width:100%;" value="Save Results"/>
    </form>

{% endblock %}


text:
package org.adligo.aws_client_tests;

import org.adligo.aws_client.WebSocketClientConfig;
import org.adligo.aws_client.WebSocketClientConfig.OUTPUT_FORMAT;
import org.adligo.aws_client.models.WebSocketProtocol;
import org.adligo.tests.ATest;

public class WebSocketClientConfigTests extends ATest {

	public void testConfig() {
		WebSocketClientConfig config = new WebSocketClientConfig(WebSocketProtocol.RFC6544);
		config.setOutputFormat(OUTPUT_FORMAT.UTF8_STRING);
		assertEquals(OUTPUT_FORMAT.UTF8_STRING, config.getOutputFormat());
	}
}


text:
//
//  VideoClipView.h
//  CutVideo
//
//  Created by 项羽 on 17/5/17.
//  Copyright © 2017年 项羽. All rights reserved.
//

#import <UIKit/UIKit.h>

typedef void(^CloseBtnBlock)();
typedef void(^ConfirmBtnBlock)();

@interface VideoClipView : UIView

/**
 关闭回调
 */
@property (nonatomic,copy)CloseBtnBlock closeHander;

/**
 确认回调
 */
@property (nonatomic,copy)ConfirmBtnBlock confirmHander;

/**
 缩略图数组
 */
@property (nonatomic,strong)NSMutableArray *imges;

@end

@interface ThumCell : UICollectionViewCell

@property (nonatomic,strong)UIImage *img;

@end


text:
<?php

class Mirasvit_SearchSphinx_Block_Adminhtml_Stopword_Edit_Form extends Mage_Adminhtml_Block_Widget_Form
{
    protected function _prepareForm()
    {
        $model = Mage::registry('current_model');

        $form = new Varien_Data_Form(array(
            'id'      => 'edit_form',
            'action'  => $this->getData('action'),
            'method'  => 'post',
            'enctype' => 'multipart/form-data',
        ));

        $general = $form->addFieldset('general', array('legend' => Mage::helper('searchsphinx')->__('General Information')));

        if ($model->getId()) {
            $general->addField('stopword_id', 'hidden', array(
                'name'  => 'stopword_id',
                'value' => $model->getId(),
            ));
        }

        $general->addField('word', 'text', array(
            'name'     => 'word',
            'label'    => Mage::helper('searchsphinx')->__('Stopword'),
            'required' => true,
            'value'    => $model->getWord(),
        ));

        $general->addField('store', 'select', array(
            'label'    => Mage::helper('searchsphinx')->__('Store View'),
            'required' => true,
            'name'     => 'store',
            'value'    => $model->getStore(),
            'values'   => Mage::getSingleton('adminhtml/system_store')->getStoreValuesForForm(false, false),
        ));

        $form->setAction($this->getUrl('*/*/save'));
        $form->setUseContainer(true);
        $this->setForm($form);

        return parent::_prepareForm();
    }

}


text:
{% assign posts = site.posts | where:"lang",page.lang %}
{% if page.lang == "en" and include.category_en %}
  {% assign posts = posts | where:"categories",include.category_en %}
  {% assign category = include.category_en | downcase %}
{% else %}
  {% assign posts = posts | where:"categories",include.category_fi" %}
  {% assign category = include.category_fi | downcase %}
{% endif %}

{% if posts.size == 1 %}
  {% assign posts_text = include.posts-singular %}
{% else %}
  {% assign posts_text = include.posts-plural %}
{% endif %}

{{ posts_size }} {{ site.t.news-amount-singular[page.lang] }}{{ site.t.news-amount-plural[page.lang] }}

{% for post in posts %}
  {% if post.title %}

{{ post.title }}

        create{% if page.lang == "en" %}{{ post.date | date: "%-m/%-d/%Y" }}{% else %}{{ post.date | date: "%-d.%-m.%Y" }}{% endif %}
{% for traffictype in post.traffictypes %}
{{ traffictype }}
{% endfor %}

{% for tag in post.tags %}
{{ tag }}
{% endfor %}

{{ post.excerpt }}

  {% endif %}
{% endfor %}

  {{ site.t.no-posts[page.lang] }}


text:
<?php

namespace Application\Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration,
    Doctrine\DBAL\Schema\Schema;

/**
 * Auto-generated Migration: Please modify to your need!
 */
class Version20130710161438 extends AbstractMigration
{
    public function up(Schema $schema)
    {
        $this->addSql("ALTER TABLE pic ADD created_at TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL");
        $this->addSql("ALTER TABLE login ADD created_at TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL");
    }

    public function down(Schema $schema)
    {
        $this->addSql("ALTER TABLE pic DROP created_at");
        $this->addSql("ALTER TABLE login DROP created_at");
    }
}


text:
import { isPlatformBrowser } from "@angular/common";
import { Inject, Injectable, Optional, PLATFORM_ID } from "@angular/core";
import { BehaviorSubject, Observable, of } from "rxjs";

import { loader } from "./load-script";
import { RECAPTCHA_BASE_URL, RECAPTCHA_LANGUAGE, RECAPTCHA_NONCE, RECAPTCHA_V3_SITE_KEY } from "./tokens";

@Injectable()
export class RecaptchaLoaderService {
  /**
   * @internal
   * @nocollapse
   */
  private static ready: BehaviorSubject<ReCaptchaV2.ReCaptcha> = null;

  public ready: Observable<ReCaptchaV2.ReCaptcha>;

  /** @internal */
  private language: string;
  /** @internal */
  private baseUrl: string;
  /** @internal */
  private nonce: string;
  /** @internal */
  private v3SiteKey: string;

  constructor(
    // eslint-disable-next-line @typescript-eslint/ban-types
    @Inject(PLATFORM_ID) private readonly platformId: Object,
    @Optional() @Inject(RECAPTCHA_LANGUAGE) language?: string,
    @Optional() @Inject(RECAPTCHA_BASE_URL) baseUrl?: string,
    @Optional() @Inject(RECAPTCHA_NONCE) nonce?: string,
    @Optional() @Inject(RECAPTCHA_V3_SITE_KEY) v3SiteKey?: string
  ) {
    this.language = language;
    this.baseUrl = baseUrl;
    this.nonce = nonce;
    this.v3SiteKey = v3SiteKey;
    this.init();
    this.ready = isPlatformBrowser(this.platformId) ? RecaptchaLoaderService.ready.asObservable() : of();
  }

  /** @internal */
  private init() {
    if (RecaptchaLoaderService.ready) {
      return;
    }
    if (isPlatformBrowser(this.platformId)) {
      const subject = new BehaviorSubject<ReCaptchaV2.ReCaptcha>(null);
      RecaptchaLoaderService.ready = subject;
      const langParam = this.language ? "&hl=" + this.language : "";

      const renderMode = this.v3SiteKey || "explicit";
      loader.loadScript(renderMode, (grecaptcha) => subject.next(grecaptcha), langParam, this.baseUrl, this.nonce);
    }
  }
}


text:
from abc import ABCMeta
from six import with_metaclass
from pixiedust.display.chart.renderers import PixiedustRenderer
from pixiedust.display.chart.renderers.baseChartDisplay import BaseChartDisplay, commonChartOptions

@PixiedustRenderer(rendererId="table")
class TableBaseDisplay(with_metaclass(ABCMeta, BaseChartDisplay)):

    def get_options_dialog_pixieapp(self):
            """
            Return the fully qualified path to a PixieApp used to display the dialog options
            PixieApp must inherit from pixiedust.display.chart.options.baseOptions.BaseOptions
            """
            return "pixiedust.display.chart.renderers.table.tableOptions.TableOptions"

    ## overrides empty method in baseChartDisplay
    def getExtraFields(self):
        fieldNames = self.getFieldNames()
        if len(fieldNames) == 0:
            return []
        tableFields = []
        tableFieldStr = self.options.get("tableFields")
        if tableFieldStr is None:
            return fieldNames
        else:
            tableFields = tableFieldStr.split(",")
            tableFields = [val for val in tableFields if val in fieldNames]
            table_row_value = self.options.get("table_row_value", None)
            if table_row_value is not None and table_row_value not in tableFields:
                tableFields.append(table_row_value)
        return tableFields

    def canRenderChart(self):
        return (True, None)

    def isTableRenderer(self):
        return True

    def supportsKeyFields(self, handlerId):
        return False

    def supportsKeyFieldLabels(self, handlerId):
        return False

    def supportsLegend(self, handlerId):
        return False

    def supportsAggregation(self, handlerId):
        return False

    @commonChartOptions
    def getChartOptions(self):
        return [
            {
                'name': 'table_noschema',
                'description': 'Hide Schema',
                'metadata': {
                    'type': 'checkbox',
                    'default': "false"
                }
            },
            {
                'name': 'table_nosearch',
                'description': 'Hide Search',
                'metadata': {
                    'type': 'checkbox',
                    'default': "false"
                }
            },
            {
                'name': 'table_nocount',
                'description': 'Hide Row Count',
                'metadata': {
                    'type': 'checkbox',
                    'default': "false"
                }
            },
            {
                'name': 'table_showrows',
                'description': 'Show Rows',
                'tooltip': 'Warning: this filter only applies to the sampled data and not the original data set',
                'metadata': {
                    'type': 'dropdown',
                    'values': ['All', 'Missing values', 'Not missing values'],
                    'default': "All"
                }
            }
        ]


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Haplographium graminum Cooke & Massee

### Remarks
null


text:
angular.module('angularAgilityDemo')
  .controller('notify', function ($scope, aaNotify, $timeout) {
    'use strict';
    $scope.trySuccess = function () {
      //the default notifyConfig sets the life to 4 seconds
      //you can tweak this globally or add your own default notifyConfig
      aaNotify.success('Example success message!');
    };

    $scope.tryInfo = function () {
      //configure to 1 second life here only
      aaNotify.info('Example info message!', { ttl: 1000 });
    };

    $scope.tryWarning = function () {
      var handle = aaNotify.warning('Example warning message!', { ttl: 999999999 });

      //whoops that message is going to be around a little *too* long with that ttl.
      //use the handle to remove it after only 4 seconds
      $timeout(function () {
        aaNotify.remove(handle);
      }, 4000);

    };

    $scope.tryDanger = function () {
      aaNotify.danger('Example danger message!

This text after some <br/>s',
        {
          //You can register many different templates and
          //*do whatever you want* for a notification, wherever/however you want!
          //(you aren't bound by this dev's idea of what a notification should look like)
          //if you like the sound of this keep scrolling to Advanced Mode below...

          //the default template has these options
          //*if you don't like them *easily* make your own template!*
          showClose: true,                            //close button
          iconClass: 'fa fa-exclamation-triangle',    //iconClass for a  style icon to use
          allowHtml: true,                            //allows HTML in the message to render as HTML

          //common to the framework as a whole
          ttl: 0  //time to live in ms
        });
    };

    $scope.notifyBuilder = function () {

      aaNotify[$scope.type]($scope.message, { ttl: $scope.ttl});

      $scope.message = null;
      $scope.type = null;
      $scope.ttl = null;
    };
  });


text:
set -e;

echo "starting to install dependencies"

sudo apt-get -qq update
echo "updated for the first time"
sudo apt-get install -y software-properties-common | grep -v "^[(Selecting)|(Preparing)|(Unpacking)]"
echo "installed"
sudo add-apt-repository -y ppa:ubuntu-toolchain-r/test
echo "added ubuntu-toolchain-r/test"
sudo apt-get -qq update
echo "updated for the second time"
sudo DEBIAN_FRONTEND=noninteractive apt-get -q install -y {{system_reqs}} | grep -v '^[(Get)|(Adding)|(Enabling)|(Selecting)|(Preparing)|(Unpacking)|(update)]';
echo "installed system packages"
sudo locale-gen en_US.UTF-8
echo "ran locale-gen"
LANG=en_US.UTF-8
echo "set LANG"
LANGUAGE=en_US:en
echo "set LANGUAGE"

echo "INSTALLING PIP"
sudo curl --silent --show-error --retry 5 https://bootstrap.pypa.io/get-pip.py | sudo -H python3

echo "INSTALL virtualenv"
sudo -H pip install virtualenv

sudo git clone https://github.com/DanielJDufour/safecast /safecast
cd /safecast
sudo make install
echo "installed safecast"