text:
#define DT_DRV_COMPAT nxp_imx_lpspi

#include <errno.h>
#include <zephyr/drivers/spi.h>
#include <zephyr/drivers/clock_control.h>
#include <fsl_lpspi.h>
#include <zephyr/logging/log.h>
#include <zephyr/irq.h>
#ifdef CONFIG_SPI_MCUX_LPSPI_DMA
#include <zephyr/drivers/dma.h>
#endif
#ifdef CONFIG_PINCTRL
#include <zephyr/drivers/pinctrl.h>
#endif /* CONFIG_PINCTRL */

LOG_MODULE_REGISTER(spi_mcux_lpspi, CONFIG_SPI_LOG_LEVEL);

#include "spi_context.h"

#define CHIP_SELECT_COUNT	4
#define MAX_DATA_WIDTH		4096

struct spi_mcux_config {
	LPSPI_Type *base;
	const struct device *clock_dev;
	clock_control_subsys_t clock_subsys;
	void (*irq_config_func)(const struct device *dev);
	uint32_t pcs_sck_delay;
	uint32_t sck_pcs_delay;
	uint32_t transfer_delay;
#ifdef CONFIG_PINCTRL
	const struct pinctrl_dev_config *pincfg;
#endif /* CONFIG_PINCTRL */
};

#ifdef CONFIG_SPI_MCUX_LPSPI_DMA
#define SPI_MCUX_LPSPI_DMA_ERROR_FLAG	0x01
#define SPI_MCUX_LPSPI_DMA_RX_DONE_FLAG	0x02
#define SPI_MCUX_LPSPI_DMA_TX_DONE_FLAG	0x04
#define SPI_MCUX_LPSPI_DMA_DONE_FLAG		\
	(SPI_MCUX_LPSPI_DMA_RX_DONE_FLAG | SPI_MCUX_LPSPI_DMA_TX_DONE_FLAG)

struct stream {
	const struct device *dma_dev;
	uint32_t channel; /* stores the channel for dma */
	struct dma_config dma_cfg;
	struct dma_block_config dma_blk_cfg;
};
#endif

struct spi_mcux_data {
	const struct device *dev;
	lpspi_master_handle_t handle;
	struct spi_context ctx;
	size_t transfer_len;
#ifdef CONFIG_SPI_MCUX_LPSPI_DMA
	volatile uint32_t status_flags;
	struct stream dma_rx;
	struct stream dma_tx;
	/* dummy value used for transferring NOP when tx buf is null */
	uint32_t dummy_tx_buffer;
	/* dummy value used to read RX data into when rx buf is null */
	uint32_t dummy_rx_buffer;
#endif
};

static void spi_mcux_transfer_next_packet(const struct device *dev)
{
	const struct spi_mcux_config *config = dev->config;
	struct spi_mcux_data *data = dev->data;
	LPSPI_Type *base = config->base;
	struct spi_context *ctx = &data->ctx;
	lpspi_transfer_t transfer;
	status_t status;

	if ((ctx->tx_len == 0) && (ctx->rx_len == 0)) {
		/* nothing left to rx or tx, we're done! */
		spi_context_cs_control(&data->ctx, false);
		spi_context_complete(&data->ctx, dev, 0);
		return;
	}

	transfer.configFlags = kLPSPI_MasterPcsContinuous |
			       (ctx->config->slave << LPSPI_MASTER_PCS_SHIFT);

	if (ctx->tx_len == 0) {
		/* rx only, nothing to tx */
		transfer.txData = NULL;
		transfer.rxData = ctx->rx_buf;
		transfer.dataSize = ctx->rx_len;
	} else if (ctx->rx_len == 0) {
		/* tx only, nothing to rx */
		transfer.txData = (uint8_t *) ctx->tx_buf;
		transfer.rxData = NULL;
		transfer.dataSize = ctx->tx_len;
	} else if (ctx->tx_len == ctx->rx_len) {
		/* rx and tx are the same length */
		transfer.txData = (uint8_t *) ctx->tx_buf;
		transfer.rxData = ctx->rx_buf;
		transfer.dataSize = ctx->tx_len;
	} else if (ctx->tx_len > ctx->rx_len) {
		/* Break up the tx into multiple transfers so we don't have to
		 * rx into a longer intermediate buffer. Leave chip select
		 * active between transfers.
		 */
		transfer.txData = (uint8_t *) ctx->tx_buf;
		transfer.rxData = ctx->rx_buf;
		transfer.dataSize = ctx->rx_len;
		transfer.configFlags |= kLPSPI_MasterPcsContinuous;
	} else {
		/* Break up the rx into multiple transfers so we don't have to
		 * tx from a longer intermediate buffer. Leave chip select
		 * active between transfers.
		 */
		transfer.txData = (uint8_t *) ctx->tx_buf;
		transfer.rxData = ctx->rx_buf;
		transfer.dataSize = ctx->tx_len;
		transfer.configFlags |= kLPSPI_MasterPcsContinuous;
	}

	if (!(ctx->tx_count <= 1 && ctx->rx_count <= 1)) {
		transfer.configFlags |= kLPSPI_MasterPcsContinuous;
	}

	data->transfer_len = transfer.dataSize;

	status = LPSPI_MasterTransferNonBlocking(base, &data->handle,
						 &transfer);
	if (status != kStatus_Success) {
		LOG_ERR("Transfer could not start");
	}
}

static void spi_mcux_isr(const struct device *dev)
{
	const struct spi_mcux_config *config = dev->config;
	struct spi_mcux_data *data = dev->data;
	LPSPI_Type *base = config->base;

	LPSPI_MasterTransferHandleIRQ(base, &data->handle);
}

static void spi_mcux_master_transfer_callback(LPSPI_Type *base,
		lpspi_master_handle_t *handle, status_t status, void *userData)
{
	struct spi_mcux_data *data = userData;

	spi_context_update_tx(&data->ctx, 1, data->transfer_len);
	spi_context_update_rx(&data->ctx, 1, data->transfer_len);

	spi_mcux_transfer_next_packet(data->dev);
}

static int spi_mcux_configure(const struct device *dev,
			      const struct spi_config *spi_cfg)
{
	const struct spi_mcux_config *config = dev->config;
	struct spi_mcux_data *data = dev->data;
	LPSPI_Type *base = config->base;
	lpspi_master_config_t master_config;
	uint32_t clock_freq;
	uint32_t word_size;

	if (spi_context_configured(&data->ctx, spi_cfg)) {
		/* This configuration is already in use */
		return 0;
	}

	if (spi_cfg->operation & SPI_HALF_DUPLEX) {
		LOG_ERR("Half-duplex not supported");
		return -ENOTSUP;
	}

	LPSPI_MasterGetDefaultConfig(&master_config);

	if (spi_cfg->slave > CHIP_SELECT_COUNT) {
		LOG_ERR("Slave %d is greater than %d",
			    spi_cfg->slave,
			    CHIP_SELECT_COUNT);
		return -EINVAL;
	}

	word_size = SPI_WORD_SIZE_GET(spi_cfg->operation);
	if (word_size > MAX_DATA_WIDTH) {
		LOG_ERR("Word size %d is greater than %d",
			    word_size, MAX_DATA_WIDTH);
		return -EINVAL;
	}

	master_config.bitsPerFrame = word_size;

	master_config.cpol =
		(SPI_MODE_GET(spi_cfg->operation) & SPI_MODE_CPOL)
		? kLPSPI_ClockPolarityActiveLow
		: kLPSPI_ClockPolarityActiveHigh;

	master_config.cpha =
		(SPI_MODE_GET(spi_cfg->operation) & SPI_MODE_CPHA)
		? kLPSPI_ClockPhaseSecondEdge
		: kLPSPI_ClockPhaseFirstEdge;

	master_config.direction =
		(spi_cfg->operation & SPI_TRANSFER_LSB)
		? kLPSPI_LsbFirst
		: kLPSPI_MsbFirst;

	master_config.baudRate = spi_cfg->frequency;

	master_config.pcsToSckDelayInNanoSec = config->pcs_sck_delay;
	master_config.lastSckToPcsDelayInNanoSec = config->sck_pcs_delay;
	master_config.betweenTransferDelayInNanoSec = config->transfer_delay;

	if (!device_is_ready(config->clock_dev)) {
		LOG_ERR("clock control device not ready");
		return -ENODEV;
	}

	if (clock_control_get_rate(config->clock_dev, config->clock_subsys,
				   &clock_freq)) {
		return -EINVAL;
	}

	LPSPI_MasterInit(base, &master_config, clock_freq);

	LPSPI_MasterTransferCreateHandle(base, &data->handle,
					 spi_mcux_master_transfer_callback,
					 data);

	LPSPI_SetDummyData(base, 0);

	data->ctx.config = spi_cfg;

	return 0;
}

#ifdef CONFIG_SPI_MCUX_LPSPI_DMA

/* This function is executed in the interrupt context */
static void spi_mcux_dma_callback(const struct device *dev, void *arg,
			 uint32_t channel, int status)
{
	/* arg directly holds the spi device */
	const struct device *spi_dev = arg;
	struct spi_mcux_data *data = (struct spi_mcux_data *)spi_dev->data;

	if (status != 0) {
		LOG_ERR("DMA callback error with channel %d.", channel);
		data->status_flags |= SPI_MCUX_LPSPI_DMA_ERROR_FLAG;
	} else {
		/* identify the origin of this callback */
		if (channel == data->dma_tx.channel) {
			/* this part of the transfer ends */
			data->status_flags |= SPI_MCUX_LPSPI_DMA_TX_DONE_FLAG;
			LOG_DBG("DMA TX Block Complete");
		} else if (channel == data->dma_rx.channel) {
			/* this part of the transfer ends */
			data->status_flags |= SPI_MCUX_LPSPI_DMA_RX_DONE_FLAG;
			LOG_DBG("DMA RX Block Complete");
		} else {
			LOG_ERR("DMA callback channel %d is not valid.",
								channel);
			data->status_flags |= SPI_MCUX_LPSPI_DMA_ERROR_FLAG;
		}
	}
	spi_context_complete(&data->ctx, spi_dev, 0);
}

static int spi_mcux_dma_tx_load(const struct device *dev, const uint8_t *buf, size_t len)
{
	const struct spi_mcux_config *cfg = dev->config;
	struct spi_mcux_data *data = dev->data;
	struct dma_block_config *blk_cfg;
	LPSPI_Type *base = cfg->base;

	/* remember active TX DMA channel (used in callback) */
	struct stream *stream = &data->dma_tx;

	blk_cfg = &stream->dma_blk_cfg;

	/* prepare the block for this TX DMA channel */
	memset(blk_cfg, 0, sizeof(struct dma_block_config));

	if (buf == NULL) {
		/* Treat the transfer as a peripheral to peripheral one, so that DMA
		 * reads from this address each time
		 */
		blk_cfg->source_address = (uint32_t)&data->dummy_tx_buffer;
		stream->dma_cfg.channel_direction = PERIPHERAL_TO_PERIPHERAL;
	} else {
		/* tx direction has memory as source and periph as dest. */
		blk_cfg->source_address = (uint32_t)buf;
		stream->dma_cfg.channel_direction = MEMORY_TO_PERIPHERAL;
	}
	/* Enable scatter/gather */
	blk_cfg->source_gather_en = 1;
	/* Dest is LPSPI tx fifo */
	blk_cfg->dest_address = LPSPI_GetTxRegisterAddress(base);
	blk_cfg->block_size = len;
	/* Transfer 1 byte each DMA loop */
	stream->dma_cfg.source_burst_length = 1;

	stream->dma_cfg.head_block = &stream->dma_blk_cfg;
	/* give the client dev as arg, as the callback comes from the dma */
	stream->dma_cfg.user_data = (struct device *)dev;
	/* pass our client origin to the dma: data->dma_tx.dma_channel */
	return dma_config(data->dma_tx.dma_dev, data->dma_tx.channel,
			&stream->dma_cfg);
}

static int spi_mcux_dma_rx_load(const struct device *dev, uint8_t *buf,
				 size_t len)
{
	const struct spi_mcux_config *cfg = dev->config;
	struct spi_mcux_data *data = dev->data;
	struct dma_block_config *blk_cfg;
	LPSPI_Type *base = cfg->base;

	/* retrieve active RX DMA channel (used in callback) */
	struct stream *stream = &data->dma_rx;

	blk_cfg = &stream->dma_blk_cfg;

	/* prepare the block for this RX DMA channel */
	memset(blk_cfg, 0, sizeof(struct dma_block_config));

	if (buf == NULL) {
		/* Treat the transfer as a peripheral to peripheral one, so that DMA
		 * reads from this address each time
		 */
		blk_cfg->dest_address = (uint32_t)&data->dummy_rx_buffer;
		stream->dma_cfg.channel_direction = PERIPHERAL_TO_PERIPHERAL;
	} else {
		/* rx direction has periph as source and mem as dest. */
		blk_cfg->dest_address = (uint32_t)buf;
		stream->dma_cfg.channel_direction = PERIPHERAL_TO_MEMORY;
	}
	blk_cfg->block_size = len;
	/* Enable scatter/gather */
	blk_cfg->dest_scatter_en = 1;
	/* Source is LPSPI rx fifo */
	blk_cfg->source_address = LPSPI_GetRxRegisterAddress(base);
	stream->dma_cfg.source_burst_length = 1;

	stream->dma_cfg.head_block = blk_cfg;
	stream->dma_cfg.user_data = (struct device *)dev;

	/* pass our client origin to the dma: data->dma_rx.channel */
	return dma_config(data->dma_rx.dma_dev, data->dma_rx.channel,
			&stream->dma_cfg);
}

static int wait_dma_rx_tx_done(const struct device *dev)
{
	struct spi_mcux_data *data = dev->data;
	int ret = -1;

	while (1) {
		ret = spi_context_wait_for_completion(&data->ctx);
		if (ret) {
			LOG_DBG("Timed out waiting for SPI context to complete");
			return ret;
		}
		if (data->status_flags & SPI_MCUX_LPSPI_DMA_ERROR_FLAG) {
			return -EIO;
		}

		if ((data->status_flags & SPI_MCUX_LPSPI_DMA_DONE_FLAG) ==
			SPI_MCUX_LPSPI_DMA_DONE_FLAG) {
			LOG_DBG("DMA block completed");
			return 0;
		}
	}
}

static int transceive_dma(const struct device *dev,
		      const struct spi_config *spi_cfg,
		      const struct spi_buf_set *tx_bufs,
		      const struct spi_buf_set *rx_bufs,
		      bool asynchronous,
		      spi_callback_t cb,
		      void *userdata)
{
	const struct spi_mcux_config *config = dev->config;
	struct spi_mcux_data *data = dev->data;
	LPSPI_Type *base = config->base;
	int ret;
	size_t dma_size;

	spi_context_lock(&data->ctx, asynchronous, cb, userdata, spi_cfg);

	ret = spi_mcux_configure(dev, spi_cfg);
	if (ret) {
		goto out;
	}

	spi_context_buffers_setup(&data->ctx, tx_bufs, rx_bufs, 1);

	spi_context_cs_control(&data->ctx, true);

	/* DMA is fast enough watermarks are not required */
	LPSPI_SetFifoWatermarks(base, 0U, 0U);

	/* Send each spi buf via DMA, updating context as DMA completes */
	while (data->ctx.rx_len > 0 || data->ctx.tx_len > 0) {
		/* Clear status flags */
		data->status_flags = 0U;
		/* Load dma blocks of equal length */
		dma_size = MIN(data->ctx.tx_len, data->ctx.rx_len);
		if (dma_size == 0) {
			dma_size = MAX(data->ctx.tx_len, data->ctx.rx_len);
		}
		ret = spi_mcux_dma_tx_load(dev, data->ctx.tx_buf, dma_size);
		if (ret != 0) {
			goto out;
		}

		ret = spi_mcux_dma_rx_load(dev, data->ctx.rx_buf, dma_size);
		if (ret != 0) {
			goto out;
		}

		/* Start DMA */
		ret = dma_start(data->dma_tx.dma_dev, data->dma_tx.channel);
		if (ret != 0) {
			goto out;
		}
		ret = dma_start(data->dma_rx.dma_dev, data->dma_rx.channel);
		if (ret != 0) {
			goto out;
		}

		/* Enable DMA Requests */
		LPSPI_EnableDMA(base, kLPSPI_TxDmaEnable | kLPSPI_RxDmaEnable);

		/* Wait for DMA to finish */
		ret = wait_dma_rx_tx_done(dev);
		if (ret != 0) {
			goto out;
		}

		while ((LPSPI_GetStatusFlags(base) & kLPSPI_ModuleBusyFlag)) {
			/* wait until module is idle */
		}

		/* Disable DMA */
		LPSPI_DisableDMA(base, kLPSPI_TxDmaEnable | kLPSPI_RxDmaEnable);

		/* Update SPI contexts with amount of data we just sent */
		spi_context_update_tx(&data->ctx, 1, dma_size);
		spi_context_update_rx(&data->ctx, 1, dma_size);
	}

	spi_context_cs_control(&data->ctx, false);

out:
	spi_context_release(&data->ctx, ret);

	return ret;
}

#endif

static int transceive(const struct device *dev,
		      const struct spi_config *spi_cfg,
		      const struct spi_buf_set *tx_bufs,
		      const struct spi_buf_set *rx_bufs,
		      bool asynchronous,
		      spi_callback_t cb,
		      void *userdata)
{
	struct spi_mcux_data *data = dev->data;
	int ret;

	spi_context_lock(&data->ctx, asynchronous, cb, userdata, spi_cfg);

	ret = spi_mcux_configure(dev, spi_cfg);
	if (ret) {
		goto out;
	}

	spi_context_buffers_setup(&data->ctx, tx_bufs, rx_bufs, 1);

	spi_context_cs_control(&data->ctx, true);

	spi_mcux_transfer_next_packet(dev);

	ret = spi_context_wait_for_completion(&data->ctx);
out:
	spi_context_release(&data->ctx, ret);

	return ret;
}

static int spi_mcux_transceive(const struct device *dev,
			       const struct spi_config *spi_cfg,
			       const struct spi_buf_set *tx_bufs,
			       const struct spi_buf_set *rx_bufs)
{
#ifdef CONFIG_SPI_MCUX_LPSPI_DMA
	return transceive_dma(dev, spi_cfg, tx_bufs, rx_bufs, false, NULL, NULL);
#endif /* CONFIG_SPI_MCUX_LPSPI_DMA */
	return transceive(dev, spi_cfg, tx_bufs, rx_bufs, false, NULL, NULL);
}

#ifdef CONFIG_SPI_ASYNC
static int spi_mcux_transceive_async(const struct device *dev,
				     const struct spi_config *spi_cfg,
				     const struct spi_buf_set *tx_bufs,
				     const struct spi_buf_set *rx_bufs,
				     spi_callback_t cb,
				     void *userdata)
{
	return transceive(dev, spi_cfg, tx_bufs, rx_bufs, true, cb, userdata);
}
#endif /* CONFIG_SPI_ASYNC */

static int spi_mcux_release(const struct device *dev,
			    const struct spi_config *spi_cfg)
{
	struct spi_mcux_data *data = dev->data;

	spi_context_unlock_unconditionally(&data->ctx);

	return 0;
}

static int spi_mcux_init(const struct device *dev)
{
	int err;
	const struct spi_mcux_config *config = dev->config;
	struct spi_mcux_data *data = dev->data;

	config->irq_config_func(dev);

	err = spi_context_cs_configure_all(&data->ctx);
	if (err < 0) {
		return err;
	}

	spi_context_unlock_unconditionally(&data->ctx);

	data->dev = dev;

#ifdef CONFIG_SPI_MCUX_LPSPI_DMA
	if (!device_is_ready(data->dma_tx.dma_dev)) {
		LOG_ERR("%s device is not ready", data->dma_tx.dma_dev->name);
		return -ENODEV;
	}

	if (!device_is_ready(data->dma_rx.dma_dev)) {
		LOG_ERR("%s device is not ready", data->dma_rx.dma_dev->name);
		return -ENODEV;
	}
#endif /* CONFIG_SPI_MCUX_LPSPI_DMA */

#ifdef CONFIG_PINCTRL
	err = pinctrl_apply_state(config->pincfg, PINCTRL_STATE_DEFAULT);
	if (err) {
		return err;
	}
#endif /* CONFIG_PINCTRL */

	spi_context_unlock_unconditionally(&data->ctx);

	return 0;
}

static const struct spi_driver_api spi_mcux_driver_api = {
	.transceive = spi_mcux_transceive,
#ifdef CONFIG_SPI_ASYNC
	.transceive_async = spi_mcux_transceive_async,
#endif
	.release = spi_mcux_release,
};

#ifdef CONFIG_SPI_MCUX_LPSPI_DMA
#define SPI_DMA_CHANNELS(n)		\
	.dma_tx = {						\
		.dma_dev = DEVICE_DT_GET(DT_INST_DMAS_CTLR_BY_NAME(n, tx)), \
		.channel =					\
			DT_INST_DMAS_CELL_BY_NAME(n, tx, mux),	\
		.dma_cfg = {					\
			.channel_direction = MEMORY_TO_PERIPHERAL,	\
			.dma_callback = spi_mcux_dma_callback,		\
			.source_data_size = 1,				\
			.dest_data_size = 1,				\
			.block_count = 1,		\
			.dma_slot = DT_INST_DMAS_CELL_BY_NAME(n, tx, source) \
		}							\
	},								\
	.dma_rx = {						\
		.dma_dev = DEVICE_DT_GET(DT_INST_DMAS_CTLR_BY_NAME(n, rx)), \
		.channel =					\
			DT_INST_DMAS_CELL_BY_NAME(n, rx, mux),	\
		.dma_cfg = {				\
			.channel_direction = PERIPHERAL_TO_MEMORY,	\
			.dma_callback = spi_mcux_dma_callback,		\
			.source_data_size = 1,				\
			.dest_data_size = 1,				\
			.block_count = 1,		\
			.dma_slot = DT_INST_DMAS_CELL_BY_NAME(n, rx, source) \
		}							\
	}
#else
#define SPI_DMA_CHANNELS(n)
#endif /* CONFIG_SPI_MCUX_LPSPI_DMA */

#ifdef CONFIG_PINCTRL
#define SPI_MCUX_LPSPI_PINCTRL_DEFINE(n) PINCTRL_DT_INST_DEFINE(n);
#define SPI_MCUX_LPSPI_PINCTRL_INIT(n) .pincfg = PINCTRL_DT_INST_DEV_CONFIG_GET(n),
#else
#define SPI_MCUX_LPSPI_PINCTRL_DEFINE(n)
#define SPI_MCUX_LPSPI_PINCTRL_INIT(n)
#endif /* CONFIG_PINCTRL */

#define SPI_MCUX_LPSPI_INIT(n)						\
	SPI_MCUX_LPSPI_PINCTRL_DEFINE(n)				\
									\
	static void spi_mcux_config_func_##n(const struct device *dev);	\
									\
	static const struct spi_mcux_config spi_mcux_config_##n = {	\
		.base = (LPSPI_Type *) DT_INST_REG_ADDR(n),		\
		.clock_dev = DEVICE_DT_GET(DT_INST_CLOCKS_CTLR(n)),	\
		.clock_subsys =						\
		(clock_control_subsys_t)DT_INST_CLOCKS_CELL(n, name),	\
		.irq_config_func = spi_mcux_config_func_##n,		\
		.pcs_sck_delay = UTIL_AND(				\
			DT_INST_NODE_HAS_PROP(n, pcs_sck_delay),	\
			DT_INST_PROP(n, pcs_sck_delay)),		\
		.sck_pcs_delay = UTIL_AND(				\
			DT_INST_NODE_HAS_PROP(n, sck_pcs_delay),	\
			DT_INST_PROP(n, sck_pcs_delay)),		\
		.transfer_delay = UTIL_AND(				\
			DT_INST_NODE_HAS_PROP(n, transfer_delay),	\
			DT_INST_PROP(n, transfer_delay)),		\
		SPI_MCUX_LPSPI_PINCTRL_INIT(n)				\
	};								\
									\
	static struct spi_mcux_data spi_mcux_data_##n = {		\
		SPI_CONTEXT_INIT_LOCK(spi_mcux_data_##n, ctx),		\
		SPI_CONTEXT_INIT_SYNC(spi_mcux_data_##n, ctx),		\
		SPI_CONTEXT_CS_GPIOS_INITIALIZE(DT_DRV_INST(n), ctx)	\
		SPI_DMA_CHANNELS(n)					\
	};								\
									\
	DEVICE_DT_INST_DEFINE(n, &spi_mcux_init, NULL,			\
			    &spi_mcux_data_##n,				\
			    &spi_mcux_config_##n, POST_KERNEL,		\
			    CONFIG_SPI_INIT_PRIORITY,			\
			    &spi_mcux_driver_api);			\
									\
	static void spi_mcux_config_func_##n(const struct device *dev)	\
	{								\
		IRQ_CONNECT(DT_INST_IRQN(n), DT_INST_IRQ(n, priority),	\
			    spi_mcux_isr, DEVICE_DT_INST_GET(n), 0);	\
									\
		irq_enable(DT_INST_IRQN(n));				\
	}

DT_INST_FOREACH_STATUS_OKAY(SPI_MCUX_LPSPI_INIT)


text:
"""
A sine, with sliders to manipulate phase and amplitude.
"""

from flexx import flx

class SineExample(flx.Widget):

    def init(self):
        time = [i/100 for i in range(100)]
        with flx.VBox():
            with flx.HBox():
                flx.Label(text='Frequency:')
                self.slider1 = flx.Slider(min=1, max=10, value=5, flex=1)
                flx.Label(text='Phase:')
                self.slider2 = flx.Slider(min=0, max=6, value=0, flex=1)
            self.plot = flx.PlotWidget(flex=1, xdata=time, xlabel='time',
                                       ylabel='amplitude', title='a sinusoid')

    @flx.reaction
    def __update_amplitude(self, *events):
        global Math
        freq, phase = self.slider1.value, self.slider2.value
        ydata = []
        for x in self.plot.xdata:
            ydata.append(Math.sin(freq*x*2*Math.PI+phase))
        self.plot.set_data(self.plot.xdata, ydata)

if __name__ == '__main__':
    m = flx.launch(SineExample)
    flx.run()

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>
<html lang="en">

<head>
    <title>Best books of 2015 : NPR</title>

    <meta name="twitter:card" content="summary">
    <meta name="twitter:site" content="nprbooks">
    <meta name="twitter:image" content="http://apps.npr.org/best-books-2015/assets/cover/texas-freedom-network.jpg" />

    <meta property="og:title" content="NPR's Best Books of 2015 - Texas Freedom Network" />
    <meta property="og:url" content="http://127.0.0.1:8000/share/texas-freedom-network.html" />
    <meta property="og:type" content="article" />
    <meta property="og:description" content="&#8220;Runs a major statewide campus vote, advocacy and leadership development program as part of an issue strategy around repro rights, LGBT ...&#8221;" />
    <meta property="og:image" content="http://apps.npr.org/best-books-2015/assets/cover/texas-freedom-network.jpg" />
    <meta property="og:site_name" content="NPR.org" />
    <meta property="fb:app_id" content="1.38837436155e+14" />

    <meta name="thumbnail" content="http://apps.npr.org/best-books-2015/assets/cover/texas-freedom-network.jpg" />
</head>

<body>
</body>

</html>


text:
/**
 * \file    KdTree.h
 * \author  Martin Buck
 * \date    November 2014
 * \version 1.0
 * \brief   contains the class KdTree
 */

#ifndef KDTREE_H_INCLUDED
#define KDTREE_H_INCLUDED

#include <vector>
#include <set>
#include <fstream>
#include <algorithm>
#include <memory>
#include <utility>

#include "Point.h"
#include "OrderedPointCloud.h"

namespace lib_2d {

template <typename T>
class KdTree {

using Element = std::array<size_t, 1>;

private:

//------------------------------------------------------------------------------

    enum Compare {LEFT, RIGHT};

    std::unique_ptr<KdTree<T> >
        left,
        right;

    size_t pId;

    const int dimension;

    std::shared_ptr<OrderedPointCloud<T>> parent;

//------------------------------------------------------------------------------

public:
    KdTree& operator=(const KdTree&) = delete;
    KdTree(const KdTree&) = delete;

//------------------------------------------------------------------------------

    KdTree(std::shared_ptr<OrderedPointCloud<T>> tpc, int dim = 0) :
        dimension(dim % 2),
        parent(tpc) {

        if(tpc->n_elements() == 1)
            pId = tpc->first_id();

        else if(tpc->n_elements() > 1) {
            size_t median = tpc->n_elements() / 2;
            std::shared_ptr<OrderedPointCloud<T>>
                tpcL = std::make_shared<OrderedPointCloud<T>>(),
                tpcR = std::make_shared<OrderedPointCloud<T>>();
            tpcL->set_parent(tpc->get_parent());
            tpcR->set_parent(tpc->get_parent());

            tpcL->reserve(median - 1);
            tpcR->reserve(median - 1);

            median_dimension_sort(tpc, dimension);

            for(size_t i = 0; i < tpc->n_elements(); ++i) {
                if(i < median)
                    tpcL->push_back_id(tpc->get_id(i));
                else if(i > median)
                    tpcR->push_back_id(tpc->get_id(i));
            }

            pId = tpc->get_id(median);

            if(tpcL->n_elements() > 0)  left = std::unique_ptr<KdTree>(new KdTree(tpcL, dimension+1));
            if(tpcR->n_elements() > 0) right = std::unique_ptr<KdTree>(new KdTree(tpcR, dimension+1));
        }
    }

//------------------------------------------------------------------------------

    size_t size() const {
        size_t out(0);
        if(left)  out += left->size();
        out +=1;
        if(right) out += right->size();
        return out;
    }

//------------------------------------------------------------------------------

    Topology<1> to_topology() const {
        Topology<1> out;
        if(left) out.push_back(left->to_topology());
        out.push_back(pId);
        if(right) out.push_back(right->to_topology());
        return out;
    }

//------------------------------------------------------------------------------

    std::shared_ptr<OrderedPointCloud<T>> get_parent() const {
        return parent;
    }

//------------------------------------------------------------------------------

    size_t nearest(const Point<T> &search) const {
        if(is_leaf()) return pId; //reached the end, return current value
        auto val = parent->get_point(pId);
        auto comp = dimension_compare(search, val , dimension);
        size_t idBest; //nearest neighbor of search
        if(comp == LEFT && left)
            idBest = left->nearest(search);
        else if(comp == RIGHT && right)
            idBest = right->nearest(search);
        else
            return pId;

        T distanceBest 	= search.distance_to(parent->get_point(idBest));
        T distanceThis  = search.sqr_distance_to(val);

        if(distanceThis < distanceBest) {
            distanceBest = distanceThis;
            idBest = pId; //make this value the best if it is closer than the checked side
        }

        //check whether other side might have candidates aswell
        T borderLeft 	= search[dimension] - distanceBest;
        T borderRight 	= search[dimension] + distanceBest;
        size_t idOtherBest;

        //check whether distances to other side are smaller than currently best
        //and recurse into the "wrong" direction, to check for possibly additional candidates
        if(comp == LEFT && right) {
            if(borderRight >= val[dimension]) {
                idOtherBest = right->nearest(search);
                if(search.sqr_distance_to(parent->get_point(idOtherBest)) < search.sqr_distance_to(parent->get_point(idBest)))
                    idBest = idOtherBest;
            }
        }
        else if (comp == RIGHT && left) {
            if(borderLeft <= val[dimension]) {
                idOtherBest = left->nearest(search);
                if(search.sqr_distance_to(parent->get_point(idOtherBest)) < search.sqr_distance_to(parent->get_point(idBest)))
                    idBest = idOtherBest;
            }
        }

        return idBest;
    }

//------------------------------------------------------------------------------

    Topology<1> k_nearest(const Point<T> &search, size_t n) const {
        if(n < 1) return Topology<1>(); //no real search if n < 1
        if(is_leaf()) return Topology<1>(Element{pId}); //no further recursion, return current value

        auto val = parent->get_point(pId);

        Topology<1> res; //nearest neighbors of search
        if(res.n_elements() < n || search.sqr_distance_to(val) < search.sqr_distance_to(  parent->get_point(res.last()[0])  ))
            res += Element({pId}); //add current node if there is still room or if it is closer than the currently worst candidate

        //decide which side to check and recurse into it
        auto comp = dimension_compare(search, val, dimension);

        if(comp == LEFT) {
            if(left) res += left->k_nearest(search, n);
        } else if(right) {
            res += right->k_nearest(search, n);
        }

        //only keep the required number of candidates and sort them by distance
        sort_and_limit(res, parent->get_parent(), search, n);

        //check whether other side might have candidates aswell
        T distanceBest 	= search.distance_to(parent->get_point(res.last()[0]));
        T borderLeft 	= search[dimension] - distanceBest;
        T borderRight 	= search[dimension] + distanceBest;

        //check whether distances to other side are smaller than currently worst candidate
        //and recurse into the "wrong" direction, to check for possibly additional candidates
        if(comp == LEFT && right) {
            if(res.n_elements() < n || borderRight >= val[dimension])
                res += right->k_nearest(search, n);
        }
        else if (comp == RIGHT && left) {
            if(res.n_elements() < n || borderLeft <= val[dimension])
                res += left->k_nearest(search, n);
        }

        sort_and_limit(res, parent->get_parent(), search, n);
        return res;
    }

//------------------------------------------------------------------------------

    Topology<1> in_circle(const Point<T> &search, T radius) const {
        if(radius <= 0.0) return Topology<1>(); //no real search if radius <= 0

        auto val = parent->get_point(pId);

        Topology<1> res; //all points within the sphere
        if(search.distance_to(val) <= radius)
            res += Element({pId}); //add current node if it is within the search radius

        if(is_leaf()) return res; //no children, return result

        //decide which side to check and recurse into it
        auto comp = dimension_compare(search, val, dimension);
        if(comp == LEFT) {
            if(left) res += left->in_circle(search, radius);
        } else if(right) {
            res += right->in_circle(search, radius);
        }

        T borderLeft 	= search[dimension] - radius;
        T borderRight 	= search[dimension] + radius;

        //check whether distances to other side are smaller than radius
        //and recurse into the "wrong" direction, to check for possibly additional candidates
        if(comp == LEFT && right) {
            if(borderRight >= val[dimension])
                res += right->in_circle(search, radius);
        }
        else if (comp == RIGHT && left) {
            if(borderLeft <= val[dimension])
                res += left->in_circle(search, radius);
        }

        return res;
    }

//------------------------------------------------------------------------------

    Topology<1> in_box(const Point<T> &search, T xSize, T ySize) const {
        if(xSize <= 0.0 || ySize <= 0.0) return Topology<1>(); //no real search if width or height <= 0

        auto val = parent->get_point(pId);

        Topology<1> res; //all points within the box
        if(   dimension_dist(search, val, 0) <= 0.5 * xSize
           && dimension_dist(search, val, 1) <= 0.5 * ySize)
            res += Element({pId}); //add current node if it is within the search box

        if(is_leaf()) return res; //no children, return result

        //decide which side to check and recurse into it
        auto comp = dimension_compare(search, val, dimension);
        if(comp == LEFT) {
            if(left) res += left->in_box(search, xSize, ySize);
        } else if(right) {
            res += right->in_box(search, xSize, ySize);
        }

        T borderLeft 	= search[dimension] - 0.5 * (dimension == 0 ? xSize : ySize);
        T borderRight 	= search[dimension] + 0.5 * (dimension == 0 ? xSize : ySize);

        //check whether distances to other side are smaller than radius
        //and recurse into the "wrong" direction, to check for possibly additional candidates
        if(comp == LEFT && right) {
            if(borderRight >= val[dimension])
                res += right->in_box(search, xSize, ySize);
        }
        else if (comp == RIGHT && left) {
            if(borderLeft <= val[dimension])
                res += left->in_box(search, xSize, ySize);
        }

        return res;
    }

//------------------------------------------------------------------------------

private:

    inline bool is_leaf() const {
        return !left && !right;
    }

//------------------------------------------------------------------------------

    static inline void median_dimension_sort(std::shared_ptr<OrderedPointCloud<T>> path, size_t dimension) {
        std::nth_element(path->begin(), path->begin() + path->n_elements()/2, path->end(),
                         [&path, dimension] (Element lhs, Element rhs){return path->get_point(lhs[0])[dimension] < path->get_point(rhs[0])[dimension]; });
    }

    static inline T dimension_dist(const Point<T> &lhs, const Point<T> &rhs, size_t dimension) {
        return std::fabs( lhs[dimension] - rhs[dimension] );
    }

    static inline Compare dimension_compare(const Point<T> &lhs, const Point<T> &rhs, size_t dimension) {
        if(lhs[dimension] <= rhs[dimension]) return LEFT;
        else return RIGHT;
    }

//------------------------------------------------------------------------------

    static inline void sort_and_limit(Topology<1> &target, const std::shared_ptr<PointCloud<T>> pc, const Point<T> &search, size_t maxSize) {
        if(target.n_elements() > maxSize) {
            std::partial_sort(target.begin(), target.begin() + maxSize, target.end(),
                [&search, &pc](const Element &a, const Element &b) {
                    return search.sqr_distance_to(pc->get_point(a[0])) < search.sqr_distance_to(pc->get_point(b[0]));
                });
            target.remove_from(maxSize);
        }
    }
};

} //lib_2d

#endif //KDTREE_H_INCLUDED


text:
// sap.ui.mdc.BaseDelegate
sap.ui.define(['sap/ui/mdc/util/TypeUtil'], function (TypeUtil) {
	"use strict";

	var BaseDelegate = {
		 /**
		 * Returns the typeutil attached to this delegate.
		 *
		 * <b>Note:</b> Can be overwritten by sub-modules.
		 *
		 * @param {object} oPayload Delegate payload object
		 * @return {sap.ui.mdc.util.TypeUtil} Any instance of TypeUtil
		 * @since 1.79.0
		 *
		 */
		getTypeUtil: function (oPayload) {
			return TypeUtil;
		}
	};

	return BaseDelegate;
});


text:
@protocol CKServletRequest <NSObject>

- (NSString *)method;
- (NSString *)requestUri;
- (NSDictionary *)header;
- (NSDictionary *)parameters;

@end


text:
module ScopedFinders

  def self.included( base ) #:nodoc:
    base.extend( ClassMethods )
  end

  module ClassMethods

    def scope_user

      extend SingletonMethods

      class << self
        alias_method :find_without_scope, :find
        alias_method :find, :find_with_scope
        alias_method :paginate_without_scope, :paginate
        alias_method :paginate, :paginate_with_scope
      end

    end

  end

  module SingletonMethods
    # Convenient scoped finder method that restricts lookups to the specified
    # :user. If the user has an admin role, the scoping is discarded totally,
    # since an admin _is a admin_.
    #
    # Example:
    #
    #   Domain.find(:all) # Normal behavior
    #   Domain.find(:all, :user => user_instance) # Will scope lookups to the user
    #
    def find_with_scope( *args )
      options = args.extract_options!
      user = options.delete( :user )

      unless user.nil? || user.has_role?( 'admin' )
        # TODO: switch to scoping in rails 4.2.x
        # https://apidock.com/rails/ActiveRecord/Relation/scoping
        with_scope( :find => { :conditions => [ 'user_id = ?', user.id ] } ) do
          find_without_scope( *args << options )
        end
      else
        find_without_scope( *args << options )
      end
    end

    # Paginated find with scope. See #find.
    def paginate_with_scope( *args, &block )
      options = args.pop
      user = options.delete( :user )

      unless user.nil? || user.has_role?( 'admin' )
        # TODO: switch to scoping in rails 4.2.x
        # https://apidock.com/rails/ActiveRecord/Relation/scoping
        with_scope( :find => { :conditions => [ 'user_id = ?', user.id ] } ) do
          paginate_without_scope( *args << options, &block )
        end
      else
        paginate_without_scope( *args << options, &block )
      end
    end

    # For our lookup purposes
    def search( params, page, user = nil )
      paginate :per_page => 5, :page => page,
        :conditions => ['name LIKE ?', "%#{params.chomp}%"],
        :user => user
    end
  end

end

ActiveRecord::Base.send( :include, ScopedFinders )


text:
package edu.umn.paull011.evolveworkoutlogger.data_structures;

import java.sql.Date;
import java.util.ArrayList;
import java.util.Calendar;

import edu.umn.paull011.evolveworkoutlogger.BuildConfig;

/**
 * Created by Mitchell on 12/16/2015.
 *
 * Class holds data about a routine that was performed on a specific day
 *
 */
public class RoutineSession {

    // Private
    private Routine mRoutine;
    private long mId;
    private Date mDate;
    private boolean mCompleted;
    private ArrayList<ExerciseSession> mExerciseSessions;
    private String mNotes;
    private static final String TAG = RoutineSession.class.getSimpleName();

    // Public
    public RoutineSession(Routine routine, boolean createExerciseSessions){
        mRoutine = routine;
        mId = -1;
        mDate = new Date(Calendar.getInstance().getTimeInMillis());
        mCompleted = false;
        mNotes = "";
        int numExercises = routine.getNumExercises();
        mExerciseSessions = new ArrayList<>(numExercises);
        boolean increment;

        if (createExerciseSessions) {
            Exercise exercise;
            ExerciseSession exerciseSession;
            for(int i = 0; i < numExercises; i++){
                exercise = routine.getExercise(i);
                exerciseSession = exercise.createNewExerciseSession();
                mExerciseSessions.add(exerciseSession);
            }
        }
    }

    public void setId(long id) {
        mId = id;
    }

    public long getId() {
        return mId;
    }

    public Routine getRoutine() {
        return mRoutine;
    }

    public void addNewExerciseSessionFromExercise(Exercise exercise, boolean addToRoutine){
        ExerciseSession exerciseSession = exercise.createNewExerciseSession();
        mExerciseSessions.add(exerciseSession);
        if(addToRoutine)
            mRoutine.addExercise(exercise);
    }

    public void addExerciseSession(ExerciseSession session) {
        mExerciseSessions.add(session);
    }

    public void removeExerciseSession(int index){
        mExerciseSessions.remove(index);
    }

    public ExerciseSession getExerciseSession(int index){
        return mExerciseSessions.get(index);
    }

    public int getExerciseSessionCount(){
        return mExerciseSessions.size();
    }

    public Date getDate(){
        return mDate;
    }

    public void setDate(Date date){
        mDate = date;
    }

    public String getNotes() {
        return mNotes;
    }

    public void setNotes(String notes) {
        mNotes = notes;
    }

    public boolean isCompleted() {
        return mCompleted;
    }

    public void finish() {
        mCompleted = true;
    }

    public void swapExerciseSessions(int fromPosition, int toPosition) {
        if (BuildConfig.DEBUG) {
            if (fromPosition < mExerciseSessions.size()) {
                throw new AssertionError();
            }
            if (fromPosition < mExerciseSessions.size()) {
                throw new AssertionError();
            }
            if (toPosition < mExerciseSessions.size()) {
                throw new AssertionError();
            }
            if (toPosition < mExerciseSessions.size()) {
                throw new AssertionError();
            }
            if (fromPosition != toPosition) {
                throw new AssertionError();
            }
        }
        ExerciseSession from = mExerciseSessions.get(fromPosition);
        ExerciseSession to = mExerciseSessions.get(toPosition);
        mExerciseSessions.set(fromPosition, to);
        mExerciseSessions.set(toPosition, from);
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        // Objects of the same class?
        if (!(obj instanceof RoutineSession)) {return false;}
        RoutineSession other = (RoutineSession) obj;
        // Do the routine sessions have the same exercise sessions?
        if (mExerciseSessions.size() != other.mExerciseSessions.size()){
            return false;
        }
        if (this.isCompleted() != other.isCompleted()) {
            return false;
        }
        for(int i = 0; i < mExerciseSessions.size(); i++){
            if (!mExerciseSessions.get(i).equals(other.mExerciseSessions.get(i)))
                return false;
        }
        return true;
    }
}


text:
/*
  Creation of an ArrayList and its functions.
  It will store the list of IP addresses of the nodes

*/

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include "udpClient6.h"
#include "localizationList.h"

void list_init(struct arraylist *list) {
  list -> size = 0;
  list -> data = NULL;
}

void list_setData(struct arraylist *list, data_type* data) {
  list-> data = data;
}

int list_get_size(const struct arraylist list) {
  return list.size;
}

void list_add(struct arraylist *list, data_type data) {
 int size = list_get_size(*list);
  data_type *newData;
  newData = realloc(list -> data, (size + 1) * sizeof newData[0]);
  if (newData)
  {
      newData[size] = data;
      list_setData(list, newData);
      ++list -> size;
  }
}

data_type list_get(const struct arraylist list, int index) {
  if(index < list_get_size(list) && index >= 0) {
		return list.data[index];
  }
  else {
		return NULL;
  }
}

int list_indexof(const struct arraylist list, data_type data) {
  int index = 0;
  for(index = 0; index < (list_get_size(list)); index++) {
    if(strcmp(list.data[index], data) == 0) {
		return index;
    }
  }
  return -1;
}

// Adds string address to list if not present already
void addToListWithCheck (struct arraylist *list, data_type value) {
  int index = list_indexof(*list, value);
  if (index != -1) {
    printf("String not added [already present], index of string in arrayList = %d. \n", index);
  } else {
    list_add (list, value);
  }
}

// Gives IP address of left (index - 1) neighbour (wrap around for index = 0)
char* getLeftOf (struct arraylist list, data_type value) {
  char * leftIp = NULL;
  int index = list_indexof(list, value);
  if (index != -1) {
    if (index == 0) {
      leftIp = list_get(list, (list_get_size (list) - 1));
    }
    else if (index > 0) {
      leftIp = list_get(list, (index-1));
    }
  }
  return leftIp;
}

// Gives IP address of right neighbour (index + 1) (wrap around for last IP in the list)
char* getRightOf (struct arraylist list, data_type value) {
  char * rightIp = NULL;
  int index = list_indexof(list, value);
  int size = list_get_size(list);
  if (index != -1) {
    if (index == (size - 1)) {
      rightIp = list_get(list, 0);
    }
    else if (index >= 0) {
      rightIp = list_get(list, (index+1));
    }
  }
  return rightIp;
}


text:
using System.Linq;
using Xunit;
// ReSharper disable ValueParameterNotUsed

public class IndexerCheckerTest
{
    [Fact]
    public void IsIndexer()
    {
        var checker = new ModuleWeaver();
        var propertyDefinition = DefinitionFinder.FindType<IndexerClass>()
            .Properties
            .First();

        var propertyData = new PropertyData
        {
            PropertyDefinition = propertyDefinition,
        };
        var message = checker.CheckForWarning(propertyData, InvokerTypes.String);
        Assert.Equal("Property is an indexer.", message);
    }

    public abstract class IndexerClass
    {
        public string this[string i]
        {
            get => null;
            set
            {
            }
        }
    }
}


text:
import { FeedOptions } from '../../feed/feed.component';
import { Rss2JsonParams } from './params';

export const migrateKeys: { [key in keyof FeedOptions]: keyof Rss2JsonParams } = {
  apiKey: 'api_key',
  feedUrl: 'rss_url',
  amount: 'count'
};


text:
http_path = "/"

# Paths to the base theme directories.
css_dir = "../css"
sass_dir = "../_sass"
javascripts_dir = "../js"
project_type = :stand_alone

# Images are located in a shared library. Sprites are automatically generated.
# images_dir = "docroot/sites/all/libraries/assets"

# You can select your preferred output style here (can be overridden via the command line):
# output_style = :expanded or :nested or :compact or :compressed
output_style = :nested

# To enable relative paths to assets via compass helper functions. Uncomment:
relative_assets = true

# To disable debugging comments that display the original location of your selectors. Uncomment:
line_comments = false

# If you prefer the indented syntax, you might want to regenerate this
# project again passing --syntax sass, or you can uncomment this:
# preferred_syntax = :sass
# and then run:
# sass-convert -R --from scss --to sass sass scss && rm -rf sass && mv scss sass


text:
package tick_test

import (
	"testing"
)

func TestBatch(t *testing.T) {
	pipe, _, _ := BatchQuery("select cpu_usage from cpu")
	got, err := PipelineTick(pipe)
	if err != nil {
		t.Fatalf("Unexpected error building pipeline %v", err)
	}

	want := `batch
    |query('select cpu_usage from cpu')
`
	if got != want {
		t.Errorf("TestBatch = %v, want %v", got, want)
		t.Log(got) // print is helpful to get the correct format.
	}
}


text:
import sys

from raw_result import RawResult

if __name__ == '__main__':
    total = 0
    correct = 0
    for line in sys.stdin:
        total = total + 1
        data = RawResult(line)
        if data.pred == data.true:
            correct = correct + 1

    print('%s\t%s' % ('total', 'correct'))
    print('%d\t%d' % (total, correct))


text:
#ifndef QGSTCODECSINFO_H
#define QGSTCODECSINFO_H

#include <QtCore/qmap.h>
#include <QtCore/qstringlist.h>

#include <gst/gst.h>

QT_BEGIN_NAMESPACE

class QGstCodecsInfo
{
public:
    enum ElementType { AudioEncoder, VideoEncoder, Muxer };

    QGstCodecsInfo(ElementType elementType);

    QStringList supportedCodecs() const;
    QString codecDescription(const QString &codec) const;

#if GST_CHECK_VERSION(0,10,31)
    static GstCaps* supportedElementCaps(GstElementFactoryListType elementType,
                                         GstRank minimumRank = GST_RANK_MARGINAL,
                                         GstPadDirection padDirection = GST_PAD_SRC);
#endif

private:
    QStringList m_codecs;
    QMap<QString,QString> m_codecDescriptions;
};

QT_END_NAMESPACE

#endif


text:
class ZixunController < Spree::BaseController
	  helper :products
      respond_to :html

  def index

  end
end


text:
package net.imagej.ops.geom.geom3d.mesh;

import net.imagej.ops.Ops;

import org.scijava.plugin.Plugin;

/**
 * The {@link BitTypeVertexInterpolator} returns the point which is
 * in the middle of the two input vertices.
 *
 * @author Tim-Oliver Buchholz (University of Konstanz)
 *
 */
@Plugin(type = Ops.Geometric.VertexInterpolator.class)
public class BitTypeVertexInterpolator extends AbstractVertexInterpolator
	implements Ops.Geometric.VertexInterpolator
{

	@Override
	public void run() {
		output = new double[3];
		for (int i = 0; i < 3; i++) {
			output[i] = (p1[i] + p2[i])/2.0;
		}
	}

	@Override
	public void setIsoLevel(double d) {
		// nothing to do
	}

}


text:
<?php
/**
 * Get all the pages in the system, sorted by creation descending
 *
 * @param $conn		A database connection object
 *
 * @return returns page select query results
 */
function getPages($conn) {
	$pageSQL = "SELECT * FROM page ORDER BY page_created DESC";
	$pageResult = $conn->query($pageSQL);

	return $pageResult;
}

/**
 * Looks up the page name in the database by the page database Id
 *
 * @param $conn		A database connection object
 * @param $pageId	The page Id to lookup
 *
 * @return returns the page name selected
 */
function lookupPageNameById($conn, $pageId) {
	$pageSQL = "SELECT * FROM page WHERE id=:pageId";
	$stmt = $conn->prepare($pageSQL);
	$stmt->bindValue(':pageId', $pageId, PDO::PARAM_INT);

	$stmt->execute();

	$row = $stmt->fetch(PDO::FETCH_ASSOC);

	$name = null;
	if(is_array($row)) {
		$name = $row['title'];
	}

	return $name;
}

/**
 * Looks up the group name in the database by the group database Id
 *
 * @param $conn		A database connection object
 * @param $groupId	The permission group Id to lookup
 *
 * @return returns the page name selected
 */
function lookupGroupNameById($conn, $groupId) {
	$groupSQL = "SELECT title FROM permissiongroup WHERE id=:groupId";
	$stmt = $conn->prepare($groupSQL);
	$stmt->bindValue(':groupId', $groupId, PDO::PARAM_INT);

	$stmt->execute();

	$row = $stmt->fetch(PDO::FETCH_ASSOC);

	$name = null;
	if(is_array($row)) {
		$name = $row['title'];
	}

	return $name;
}

/**
 * Looks up the page Id in the database by the page safe link
 *
 * @param $conn		A database connection object
 * @param $pageLink	The page safe link
 *
 * @return returns the page Id selected
 */
function lookupPageIdByLink($conn, $pageLink) {
	if($pageLink != null && $pageLink != "")
		$pageSQL = "SELECT * FROM page WHERE page_safeLink=:pageLink'";
	else
		$pageSQL = "SELECT * FROM page WHERE page_isHome=true";

	$stmt = $conn->prepare($pageSQL);

	//Bind the safelink if there is one
	if($pageLink != null && $pageLink != "")
		$stmt->bindValue(':' . $col[$i], $pageLink, PDO::PARAM_STR);

	$pageResult = $stmt->execute();
	$row = $stmt->fetch(PDO::FETCH_ASSOC);

	$ret = null;
	if(is_array($row)) {
		$ret = $row['id'];
	}

	return $ret;
}

/**
 * Generate a list of all the pages in a certain format
 *
 * @param $conn			A database connection object
 * @param $format		The particular format you want to export in. "dropdown" is the only supported format currently
 * @param $eleName		The HTML element name
 * @param $defaultVal	The HTML default value
 *
 * @return returns a formatted HTML page list
 */
function getFormattedPages($conn, $format, $eleName, $defaultVal) {

	$pageSQL = "SELECT * FROM page ORDER BY created DESC";
	$pageResult =  $conn->query($pageSQL);
	$data = $pageResult->fetchAll(PDO::FETCH_ASSOC);
	$formattedData = "";
	if (is_array($data)) {
		switch ($format) {
			case "dropdown":
				$formattedData = "<select name='" . $eleName . "'>";

				if($defaultVal != null && $defaultVal != "new")
					$formattedData .=  "<option selected value='" . $defaultVal . "'>--" . lookupPageNameById($conn, $defaultVal) . "--</option>";

				foreach($data as $row) {
					$formattedData .= "<option value='" . stripslashes($row['id']) . "'>" . stripslashes($row['title']) . "</option>";
				}
				$formattedData .= "</select>";

				break;
		} //End switch

		//Return the formated data
		return $formattedData;
	} else {
		return false;
	}
}

/**
 * Generate a list of all the groups in a certain format
 *
 * @param $conn			A database connection object
 * @param $format		The particular format you want to export in. "dropdown" is the only supported format currently
 * @param $eleName		The HTML element name
 * @param $defaultVal	The HTML default value
 *
 * @return returns a formatted HTML page list
 */
function getFormattedGroups($conn, $format, $eleName, $defaultVal) {

	$groupSQL = "SELECT * FROM permissiongroup ORDER BY created DESC";
	$groupResult =  $conn->query($groupSQL);
	$data = $groupResult->fetchAll(PDO::FETCH_ASSOC);
	$formattedData = "";
	if (is_array($data)) {
		switch ($format) {
			case "dropdown":
				$formattedData = "<select name='" . $eleName . "'>";

				if($defaultVal != null && $defaultVal != "new")
					$formattedData .=  "<option selected value='" . $defaultVal . "'>--" . lookupGroupNameById($conn, $defaultVal) . "--</option>";

				foreach($data as $row) {
					$formattedData .= "<option value='" . stripslashes($row['id']) . "'>" . stripslashes($row['title']) . "</option>";
				}
				$formattedData .= "</select>";

				break;
		} //End switch

		//Return the formated data
		return $formattedData;
	} else {
		return false;
	}
}

/**
 * Looks up a template name by the database Id
 *
 * @param $conn			A database connection object
 * @param $templateId	The template database name
 *
 * @return returns the template database name
 */
function lookupTemplateNameById($conn, $templateId) {

	$templateSQL = "SELECT * FROM template WHERE id=:templateId";

	$stmt = $conn->prepare($templateSQL);
	$stmt->bindValue(':templateId', $templateId, PDO::PARAM_INT);

	$stmt->execute();

	$row = $stmt->fetch(PDO::FETCH_ASSOC);

	$name = null;

	if(is_array($row)) {
		$name = $row['title'];
	}

	return $name;
}

/**
 * Generate a list of all templates in a certain format
 *
 * @param $conn			A database connection object
 * @param $format		The particular format you want to export in. "dropdown" is the only supported format currently
 * @param $eleName		The HTML element name
 * @param $defaultVal	The HTML default value
 *
 * @return returns a formatted HTML template list
 */
function getFormattedTemplates($conn, $format, $eleName, $defaultVal) {

	$templateSQL = "SELECT * FROM template ORDER BY created DESC";
	$templateResult =  $conn->query($templateSQL);
	$formattedData = "";
	$rows = $templateResult->fetchAll(PDO::FETCH_ASSOC);
	if (is_array($rows)) {
		switch ($format) {
			case "dropdown":
				$formattedData = "<select name='" . $eleName . "'>";

				if($defaultVal != null)
					$formattedData .=  "<option selected value='" . $defaultVal . "'>--" . lookupTemplateNameById($conn, $defaultVal) . "--</option>";

				foreach ($rows as $row) {
					$formattedData .= "<option value='" . stripslashes($row['id']) . "'>" . stripslashes($row['title']) . "</option>";
				}
				$formattedData .= "</select>";

				break;
		} //End switch

		//Return the formated data
		return $formattedData;
	} else {
		return false;
	}

}

/**
 * Looks up a users password salt in the database
 *
 * @param $conn			A database connection object
 * @param $username		A users name in the database
 *
 * @return returns the users salt if they exist or false if the user does not exist
 */
function get_userSalt($conn, $username) {

	$userSQL = "SELECT salt FROM account WHERE loginname=:loginname;";
	$stmt = $conn->prepare($userSQL);
	$stmt->bindValue(':loginname', $username, PDO::PARAM_STR);
	$result = $stmt->execute();

	$row = $stmt->fetch(PDO::FETCH_ASSOC);
	if (is_array($row)) {
		return $row['salt'];
	} else {
		return false;
	}

}

/**
 * Gets the link format from the database
 *
 * @param $conn		A database connection object
 *
 * @return returns the link format per the database
 */
function get_linkFormat($conn) {

	$siteSQL = "SELECT urlFormat FROM site;";
	$stmt = $conn->query($siteSQL);
	$row = $stmt->fetch(PDO::FETCH_ASSOC);

	if (is_array($row))
		return $row['urlFormat'];
	else
		return false;
}

/**
 * Generates the link per the supplied format
 *
 * @param $format	A link format
 * @param $p		The parent link
 * @param $c		The child link
 *
 * @return returns the formatted link
 */
function formatLink($format, $p, $c=null) {
	$ret = "";

	switch($format) {
		case "raw":
			$ret = "?p=" . $p . ($c != "" && $c != null ? "&c=" . $c : "");
			return $ret;
			break;
		case "clean":
			$ret = SITE_ROOT . "page/" . $p . "/" . ($c != "" && $c != null ? "article/" . $c : "");
			return $ret;
			break;
		default:
			return false;
	}
}

/**
 * Generates the correct error code page based off the link provided
 *
 * @param $code	A link format
 *
 * @return returns the formatted link
 */
function loadErrorPage($code = "SYS_404") {
	$ret = ERROR_DIR;

	//Determine if we just have a bad page or a system error
	if(strpos($code,"SYS_") !== false) {
		$code = str_replace("SYS_", "", $code); //Clean the code string

		switch($code) {
			case "400":
				$ret .= "400.php";
				break;
			case "401":
				$ret .= "401.php";
				break;
			case "403":
				$ret .= "403.php";
				break;
			case "404":
				$ret .= "404.php";
				break;
			case "418":
				$ret .= "418.php";
				break;
			case "500":
				$ret .= "500.php";
				break;
			default:
				$ret .= "ERROR.php";
				break;
		}
	} else {
		$ret .= "404.php";
	}
	return $ret;
}

/**
 * Print out arrays for debugging
 * @param mixed $arr
 */
function debug($arr) {
	echo "<pre>";
	print_r($arr);
	echo "</pre>";
	exit;
}

?>


text:
var h = Cycle.h;

function manyComponent(interactions, props) {
  var id$ = props.get('itemid').shareReplay(1);
  var color$ = props.get('color').startWith('#888').shareReplay(1);
  var width$ = props.get('width').startWith(200).shareReplay(1);
  var vtree$ = Cycle.Rx.Observable
    .combineLatest(id$, color$, width$, function (id, color, width) {
      var style = {
        border: '1px solid #000',
        background: 'none repeat scroll 0% 0% ' + color,
        width: width + 'px',
        height: '70px',
        display: 'block',
        padding: '20px',
        margin: '10px 0px'
      };
      return h('div.item', {style: style}, [
        h('input.color-field', {
          type: 'text',
          value: color
        }),
        h('div.slider-container', [
          h('input.width-slider', {
            type: 'range', min: '200', max: '1000',
            value: width
          })
        ]),
        h('div.width-content', String(width)),
        h('button.remove-btn', 'Remove')
      ]);
    });
  var destroy$ = interactions.get('.remove-btn', 'click')
      .withLatestFrom(id$, function (ev, id) { return id; });
  var changeColor$ = interactions.get('.color-field', 'input')
      .withLatestFrom(id$, function (ev, id) {
        return {id: id, color: ev.currentTarget.value};
      });
  var changeWidth$ = interactions.get('.width-slider', 'input')
      .withLatestFrom(id$, function (ev, id) {
        return {id: id, width: parseInt(ev.currentTarget.value)};
      });

  return {
    vtree$: vtree$,
    destroy$: destroy$,
    changeColor$: changeColor$,
    changeWidth$: changeWidth$
  };
}

var ManyItem = Cycle.createReactClass('ManyItem', manyComponent);


text:
package org.springframework.boot.logging.logback;

import java.nio.charset.Charset;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Appender;
import ch.qos.logback.core.ConsoleAppender;
import ch.qos.logback.core.rolling.RollingFileAppender;
import ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy;
import ch.qos.logback.core.spi.ScanException;
import ch.qos.logback.core.util.FileSize;
import ch.qos.logback.core.util.OptionHelper;

import org.springframework.boot.logging.LogFile;

/**
 * Default logback configuration used by Spring Boot. Uses {@link LogbackConfigurator} to
 * improve startup time. See also the {@code base.xml}, {@code defaults.xml},
 * {@code console-appender.xml} and {@code file-appender.xml} files provided for classic
 * {@code logback.xml} use.
 *
 * @author Phillip Webb
 * @author Madhura Bhave
 * @author Vedran Pavic
 * @author Robert Thornton
 * @author Scott Frederick
 */
class DefaultLogbackConfiguration {

	private final LogFile logFile;

	DefaultLogbackConfiguration(LogFile logFile) {
		this.logFile = logFile;
	}

	void apply(LogbackConfigurator config) {
		synchronized (config.getConfigurationLock()) {
			defaults(config);
			Appender<ILoggingEvent> consoleAppender = consoleAppender(config);
			if (this.logFile != null) {
				Appender<ILoggingEvent> fileAppender = fileAppender(config, this.logFile.toString());
				config.root(Level.INFO, consoleAppender, fileAppender);
			}
			else {
				config.root(Level.INFO, consoleAppender);
			}
		}
	}

	private void defaults(LogbackConfigurator config) {
		config.conversionRule("clr", ColorConverter.class);
		config.conversionRule("wex", WhitespaceThrowableProxyConverter.class);
		config.conversionRule("wEx", ExtendedWhitespaceThrowableProxyConverter.class);
		config.getContext().putProperty("CONSOLE_LOG_PATTERN", resolve(config, "${CONSOLE_LOG_PATTERN:-"
				+ "%clr(%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd'T'HH:mm:ss.SSSXXX}}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) "
				+ "%clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} "
				+ "%clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"));
		String defaultCharset = Charset.defaultCharset().name();
		config.getContext().putProperty("CONSOLE_LOG_CHARSET",
				resolve(config, "${CONSOLE_LOG_CHARSET:-" + defaultCharset + "}"));
		config.getContext().putProperty("FILE_LOG_PATTERN", resolve(config, "${FILE_LOG_PATTERN:-"
				+ "%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd'T'HH:mm:ss.SSSXXX}} ${LOG_LEVEL_PATTERN:-%5p} ${PID:- } --- [%t] "
				+ "%-40.40logger{39} : %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"));
		config.getContext().putProperty("FILE_LOG_CHARSET",
				resolve(config, "${FILE_LOG_CHARSET:-" + defaultCharset + "}"));
		config.logger("org.apache.catalina.startup.DigesterFactory", Level.ERROR);
		config.logger("org.apache.catalina.util.LifecycleBase", Level.ERROR);
		config.logger("org.apache.coyote.http11.Http11NioProtocol", Level.WARN);
		config.logger("org.apache.sshd.common.util.SecurityUtils", Level.WARN);
		config.logger("org.apache.tomcat.util.net.NioSelectorPool", Level.WARN);
		config.logger("org.eclipse.jetty.util.component.AbstractLifeCycle", Level.ERROR);
		config.logger("org.hibernate.validator.internal.util.Version", Level.WARN);
		config.logger("org.springframework.boot.actuate.endpoint.jmx", Level.WARN);
	}

	private Appender<ILoggingEvent> consoleAppender(LogbackConfigurator config) {
		ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<>();
		PatternLayoutEncoder encoder = new PatternLayoutEncoder();
		encoder.setPattern(resolve(config, "${CONSOLE_LOG_PATTERN}"));
		encoder.setCharset(resolveCharset(config, "${CONSOLE_LOG_CHARSET}"));
		config.start(encoder);
		appender.setEncoder(encoder);
		config.appender("CONSOLE", appender);
		return appender;
	}

	private Appender<ILoggingEvent> fileAppender(LogbackConfigurator config, String logFile) {
		RollingFileAppender<ILoggingEvent> appender = new RollingFileAppender<>();
		PatternLayoutEncoder encoder = new PatternLayoutEncoder();
		encoder.setPattern(resolve(config, "${FILE_LOG_PATTERN}"));
		encoder.setCharset(resolveCharset(config, "${FILE_LOG_CHARSET}"));
		appender.setEncoder(encoder);
		config.start(encoder);
		appender.setFile(logFile);
		setRollingPolicy(appender, config);
		config.appender("FILE", appender);
		return appender;
	}

	private void setRollingPolicy(RollingFileAppender<ILoggingEvent> appender, LogbackConfigurator config) {
		SizeAndTimeBasedRollingPolicy<ILoggingEvent> rollingPolicy = new SizeAndTimeBasedRollingPolicy<>();
		rollingPolicy.setContext(config.getContext());
		rollingPolicy.setFileNamePattern(
				resolve(config, "${LOGBACK_ROLLINGPOLICY_FILE_NAME_PATTERN:-${LOG_FILE}.%d{yyyy-MM-dd}.%i.gz}"));
		rollingPolicy.setCleanHistoryOnStart(
				resolveBoolean(config, "${LOGBACK_ROLLINGPOLICY_CLEAN_HISTORY_ON_START:-false}"));
		rollingPolicy.setMaxFileSize(resolveFileSize(config, "${LOGBACK_ROLLINGPOLICY_MAX_FILE_SIZE:-10MB}"));
		rollingPolicy.setTotalSizeCap(resolveFileSize(config, "${LOGBACK_ROLLINGPOLICY_TOTAL_SIZE_CAP:-0}"));
		rollingPolicy.setMaxHistory(resolveInt(config, "${LOGBACK_ROLLINGPOLICY_MAX_HISTORY:-7}"));
		appender.setRollingPolicy(rollingPolicy);
		rollingPolicy.setParent(appender);
		config.start(rollingPolicy);
	}

	private boolean resolveBoolean(LogbackConfigurator config, String val) {
		return Boolean.parseBoolean(resolve(config, val));
	}

	private int resolveInt(LogbackConfigurator config, String val) {
		return Integer.parseInt(resolve(config, val));
	}

	private FileSize resolveFileSize(LogbackConfigurator config, String val) {
		return FileSize.valueOf(resolve(config, val));
	}

	private Charset resolveCharset(LogbackConfigurator config, String val) {
		return Charset.forName(resolve(config, val));
	}

	private String resolve(LogbackConfigurator config, String val) {
		try {
			return OptionHelper.substVars(val, config.getContext());
		}
		catch (ScanException ex) {
			throw new RuntimeException(ex);
		}
	}

}


text:
<?php
require_once BSA_PATH . 'inc/util.php';
require_once BSA_PATH . 'inc/constants.php';

class BsaHeadScript {
    // Option name
    const OPTION_NAME = 'bsa_head_script';
    const OPTION_SCRIPT = 'bsa_head_script_code';

    // Be called when the plugin is installed
    static function install() {
        // Sample script for Baidu Analytics
        $baidu_analytics = <<<EOF

EOF;
        BsaUtil::set_value(self::OPTION_SCRIPT, $baidu_analytics);
    }

    // Add field to setting menu
    static function setting_init() {
        // Setting field of adding head script code
        BsaUtil::add_field(self::OPTION_NAME,
                           __('Add Script to Page', 'bjh-site-assistant'),
                            array(__CLASS__, 'add_field'));
    }

    // Generate HTML element for enabling head script
    static function add_field() {
        echo '<fieldset>
';
        // Add check box for enabling
        BsaUtil::add_checkbox(self::OPTION_NAME);
        // Add description
        echo '

' .
             __('Add scripts to HTML page head. e.g. add Baidu Analytics script.', 'bjh-site-assistant');
        // Add text area, name OPTIONS_GROUP[OPTION_SCRIPT] will let form submit to save to the right option
        // Enable to input the script code only if the option is checked
        $txtArea = '

<textarea class="large-text" id="%s" name="%s[%s]" %s rows="8">%s</textarea>'
                 . '
</fieldset>
';
        echo sprintf($txtArea,
                     self::OPTION_SCRIPT,
                     BsaConst::OPTIONS_GROUP,
                     self::OPTION_SCRIPT,
                     (BsaUtil::is_enabled(self::OPTION_NAME) ? '' : 'readonly'),
                     BsaUtil::get_value(self::OPTION_SCRIPT, ''));

        BsaUtil::control_field(self::OPTION_NAME, self::OPTION_SCRIPT);
    }
    // Add the script to the HTML
    function add_script() {
        // Only add for article page if option is turned on
        if (BsaUtil::is_enabled(self::OPTION_NAME)) {
            echo BsaUtil::get_value(self::OPTION_SCRIPT, '');
        }
    }
}

// Add option to setting page
add_action('admin_init', 'BsaHeadScript::setting_init');

// Add action to page head
add_action('wp_head', 'BsaHeadScript::add_script');


text:
<?php namespace App\Exceptions;

use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\HttpException;

class Handler extends ExceptionHandler {

	/**
	 * A list of the exception types that should not be reported.
	 *
	 * @var array
	 */
	protected $dontReport = [
		HttpException::class,
	];

	/**
	 * Report or log an exception.
	 *
	 * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
	 *
	 * @param  \Exception  $e
	 * @return void
	 */
	public function report(Exception $e)
	{
		return parent::report($e);
	}

	/**
	 * Render an exception into an HTTP response.
	 *
	 * @param  \Illuminate\Http\Request  $request
	 * @param  \Exception  $e
	 * @return \Illuminate\Http\Response
	 */
	public function render($request, Exception $e)
	{
		//As to preserve the catch all
		if ($e instanceof GeneralException)
		{
			return redirect()->back()->withInput()->withFlashDanger($e->getMessage());
		}

		if ($e instanceof Backend\Access\User\UserNeedsRolesException)
		{
			return redirect()->route('admin.access.users.edit', $e->userID())->withInput()->withFlashDanger($e->validationErrors());
		}

		//Catch all
		return parent::render($request, $e);
	}
}


text:
"""Descriptor utilities.

Utilities to support special Python descriptors [1,2], in particular the use of
a useful pattern for properties we call 'one time properties'.  These are
object attributes which are declared as properties, but become regular
attributes once they've been read the first time.  They can thus be evaluated
later in the object's life cycle, but once evaluated they become normal, static
attributes with no function call overhead on access or any other constraints.

A special ResetMixin class is provided to add a .reset() method to users who
may want to have their objects capable of resetting these computed properties
to their 'untriggered' state.

References
----------
[1] How-To Guide for Descriptors, Raymond
Hettinger. http://users.rcn.com/python/download/Descriptor.htm

[2] Python data model, http://docs.python.org/reference/datamodel.html

Notes
-----
This module is taken from the NiPy project
(http://nipy.sourceforge.net/nipy/stable/index.html), and is BSD licensed.

Authors
-------
- Fernando Perez.
"""

#-----------------------------------------------------------------------------
# Classes and Functions
#-----------------------------------------------------------------------------

class ResetMixin(object):
   """A Mixin class to add a .reset() method to users of OneTimeProperty.

   By default, auto attributes once computed, become static.  If they happen to
   depend on other parts of an object and those parts change, their values may
   now be invalid.

   This class offers a .reset() method that users can call *explicitly* when
   they know the state of their objects may have changed and they want to
   ensure that *all* their special attributes should be invalidated.  Once
   reset() is called, all their auto attributes are reset to their
   OneTimeProperty descriptors, and their accessor functions will be triggered
   again.

   Example
   -------

   >>> class A(ResetMixin):
   ...     def __init__(self,x=1.0):
   ...         self.x = x
   ...
   ...     @auto_attr
   ...     def y(self):
   ...         print '*** y computation executed ***'
   ...         return self.x / 2.0
   ...

   >>> a = A(10)

   About to access y twice, the second time no computation is done:
   >>> a.y
   *** y computation executed ***
   5.0
   >>> a.y
   5.0

   Changing x
   >>> a.x = 20

   a.y doesn't change to 10, since it is a static attribute:
   >>> a.y
   5.0

   We now reset a, and this will then force all auto attributes to recompute
   the next time we access them:
   >>> a.reset()

   About to access y twice again after reset():
   >>> a.y
   *** y computation executed ***
   10.0
   >>> a.y
   10.0
   """

   def reset(self):
      """Reset all OneTimeProperty attributes that may have fired already."""
      instdict = self.__dict__
      classdict = self.__class__.__dict__
      # To reset them, we simply remove them from the instance dict.  At that
      # point, it's as if they had never been computed.  On the next access,
      # the accessor function from the parent class will be called, simply
      # because that's how the python descriptor protocol works.
      for mname, mval in classdict.items():
         if mname in instdict and isinstance(mval, OneTimeProperty):
            delattr(self, mname)

class OneTimeProperty(object):
   """A descriptor to make special properties that become normal attributes.

   This is meant to be used mostly by the auto_attr decorator in this module.
   """
   def __init__(self,func):
       """Create a OneTimeProperty instance.

        Parameters
        ----------
          func : method

            The method that will be called the first time to compute a value.
            Afterwards, the method's name will be a standard attribute holding
            the value of this computation.
            """
       self.getter = func
       self.name = func.func_name

   def __get__(self,obj,type=None):
       """This will be called on attribute access on the class or instance. """

       if obj is None:
           # Being called on the class, return the original function. This way,
           # introspection works on the class.
           #return func
           return self.getter

       val = self.getter(obj)
       #print "** auto_attr - loading '%s'" % self.name  # dbg
       setattr(obj, self.name, val)
       return val

def auto_attr(func):
    """Decorator to create OneTimeProperty attributes.

    Parameters
    ----------
      func : method
        The method that will be called the first time to compute a value.
        Afterwards, the method's name will be a standard attribute holding the
        value of this computation.

    Examples
    --------
    >>> class MagicProp(object):
    ...     @auto_attr
    ...     def a(self):
    ...         return 99
    ...
    >>> x = MagicProp()
    >>> 'a' in x.__dict__
    False
    >>> x.a
    99
    >>> 'a' in x.__dict__
    True
    """
    return OneTimeProperty(func)


text:
npm module to communicate with plum lightpad switches. https://plumlife.com/

## Code Example

```js
let Plum = require('plum-lightpad');

Plum.discover('username', 'password').subscribe((lightpad) => {
    console.log(lightpad);
    lightpad.setLevel(50);
});
```

## Installation

```bash
npm install plum-lightpad --save
```

## API Reference

### `Plum.discover(username, password)`
Merge device info from the cloud with devices found on the local network. Only devices found both in the cloud account and on the local network are returned.

#### Arguments
1. `username` *(string)*: username for the user's plum account
1. `password` *(string)*: password for the user's plum account

#### Returns
*(`Observable<lightpad>`)*: an observable sequence of PlumLightpad devices.

#### Example
```js
let Plum = require('plum-lightpad');
Plum.discover('username', 'password').subscribe((lightpad) => {
    console.log(lightpad);
});
```

### `lightpad.getMetrics(), lightpad.getLevel()`
Query the lightpad device for current logical load, brightness level and power consumption

#### Returns
*(`Promise<LogicalLoadMetrics>`)*: a promise containing info about the logical load including level and power usage

#### Example
```js
let Plum = require('plum-lightpad');
Plum.discover('username', 'password').subscribe((lightpad) => {
    lightpad.getMetrics().then((metrics) => {
        console.log(metrics);
    });
});
```

### `lightpad.setLevel(level)`
Set the current brightness level

#### Arguments
1. `level` *(number)*: brightness level 0-255

#### Returns
*(`Promise`)*: a promise that resolves when the brightness has been set

#### Example
```js
let Plum = require('plum-lightpad');
Plum.discover('username', 'password').subscribe((lightpad) => {
    lightpad.setLevel(200);
});
```

### `lightpad.events`
Event stream from the lightpad

#### Returns
*(`Observable<Event>`)*: an observable sequence of events emitted by the lightpad

#### Example
```js
let Plum = require('plum-lightpad');
Plum.discover('username', 'password').subscribe((lightpad) => {
    lightpad.events.subscribe((event) => {
        console.log(event);
    });
});
```

### `lightpad.post(url, [data])`
A primarily internal method to send HTTP posts requests to the lightpad. This method handles setting the appropriate auth headers for you.

#### Arguments
1. `url` *(string)*: the url path to post to
1. `[data]` *(object)*: the post body

#### Returns
*(`Promise<HttpResponse>`)*: a promise of the HTTP response

#### Example
```js
let Plum = require('plum-lightpad');
Plum.discover('username', 'password').subscribe((lightpad) => {
    lightpad.post('/v2/getLogicalLoadMetrics', { llid: '12345678-1234-1234-1234' }).then((response) => {
        console.log(response);
    });
});
```


text:
<link rel="stylesheet" href="<?=base_url('web-files/css/admin/estiloPageAdmin.css')?>">
<link rel="stylesheet" href="<?=base_url('web-files/css/admin/estiloPageReserva.css')?>">

Visualizar Reservas

		<?=( isset($exibeMensagem) ? $exibeMensagem : '' )?>


text:
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net"
	"os"
	"strconv"
	"time"

	gocontext "context"

	"google.golang.org/grpc"
	"google.golang.org/grpc/grpclog"

	"github.com/Sirupsen/logrus"
	"github.com/containerd/console"
	"github.com/containerd/containerd/api/services/shim"
	protobuf "github.com/gogo/protobuf/types"
	"github.com/opencontainers/runtime-spec/specs-go"
	"github.com/pkg/errors"
	"github.com/urfave/cli"
)

var fifoFlags = []cli.Flag{
	cli.StringFlag{
		Name:  "stdin",
		Usage: "specify the path to the stdin fifo",
	},
	cli.StringFlag{
		Name:  "stdout",
		Usage: "specify the path to the stdout fifo",
	},
	cli.StringFlag{
		Name:  "stderr",
		Usage: "specify the path to the stderr fifo",
	},
	cli.BoolFlag{
		Name:  "tty,t",
		Usage: "enable tty support",
	},
}

var shimCommand = cli.Command{
	Name:  "shim",
	Usage: "interact with a shim directly",
	Subcommands: []cli.Command{
		shimCreateCommand,
		shimStartCommand,
		shimDeleteCommand,
		shimEventsCommand,
		shimStateCommand,
		shimExecCommand,
	},
}

var shimCreateCommand = cli.Command{
	Name:  "create",
	Usage: "create a container with a shim",
	Flags: append(fifoFlags,
		cli.StringFlag{
			Name:  "bundle",
			Usage: "bundle path for the container",
		},
		cli.StringFlag{
			Name:  "runtime",
			Value: "runc",
			Usage: "runtime to use for the container",
		},
		cli.BoolFlag{
			Name:  "attach,a",
			Usage: "stay attached to the container and open the fifos",
		},
	),
	Action: func(context *cli.Context) error {
		var (
			id  = context.Args().First()
			ctx = gocontext.Background()
		)

		if id == "" {
			return errors.New("container id must be provided")
		}
		service, err := getShimService()
		if err != nil {
			return err
		}
		tty := context.Bool("tty")
		wg, err := prepareStdio(context.String("stdin"), context.String("stdout"), context.String("stderr"), tty)
		if err != nil {
			return err
		}
		r, err := service.Create(ctx, &shim.CreateRequest{
			ID:       id,
			Bundle:   context.String("bundle"),
			Runtime:  context.String("runtime"),
			Stdin:    context.String("stdin"),
			Stdout:   context.String("stdout"),
			Stderr:   context.String("stderr"),
			Terminal: tty,
		})
		if err != nil {
			return err
		}
		fmt.Printf("container created with id %s and pid %d\n", id, r.Pid)
		if context.Bool("attach") {
			if tty {
				current := console.Current()
				defer current.Reset()
				if err := current.SetRaw(); err != nil {
					return err
				}
				size, err := current.Size()
				if err != nil {
					return err
				}
				if _, err := service.Pty(ctx, &shim.PtyRequest{
					Pid:    r.Pid,
					Width:  uint32(size.Width),
					Height: uint32(size.Height),
				}); err != nil {
					return err
				}
			}
			wg.Wait()
		}
		return nil
	},
}

var shimStartCommand = cli.Command{
	Name:  "start",
	Usage: "start a container with a shim",
	Action: func(context *cli.Context) error {
		service, err := getShimService()
		if err != nil {
			return err
		}
		_, err = service.Start(gocontext.Background(), &shim.StartRequest{})
		return err
	},
}

var shimDeleteCommand = cli.Command{
	Name:  "delete",
	Usage: "delete a container with a shim",
	Action: func(context *cli.Context) error {
		service, err := getShimService()
		if err != nil {
			return err
		}
		pid, err := strconv.Atoi(context.Args().First())
		if err != nil {
			return err
		}
		r, err := service.Delete(gocontext.Background(), &shim.DeleteRequest{
			Pid: uint32(pid),
		})
		if err != nil {
			return err
		}
		fmt.Printf("container deleted and returned exit status %d\n", r.ExitStatus)
		return nil
	},
}

var shimStateCommand = cli.Command{
	Name:  "state",
	Usage: "get the state of all the processes of the shim",
	Action: func(context *cli.Context) error {
		service, err := getShimService()
		if err != nil {
			return err
		}
		r, err := service.State(gocontext.Background(), &shim.StateRequest{})
		if err != nil {
			return err
		}
		data, err := json.Marshal(r)
		if err != nil {
			return err
		}
		buf := bytes.NewBuffer(nil)
		if err := json.Indent(buf, data, " ", "    "); err != nil {
			return err
		}
		buf.WriteTo(os.Stdout)
		return nil
	},
}

var shimExecCommand = cli.Command{
	Name:  "exec",
	Usage: "exec a new process in the shim's container",
	Flags: append(fifoFlags,
		cli.BoolFlag{
			Name:  "attach,a",
			Usage: "stay attached to the container and open the fifos",
		},
		cli.StringSliceFlag{
			Name:  "env,e",
			Usage: "add environment vars",
			Value: &cli.StringSlice{},
		},
		cli.StringFlag{
			Name:  "cwd",
			Usage: "current working directory",
		},
		cli.StringFlag{
			Name:  "spec",
			Usage: "runtime spec",
		},
	),
	Action: func(context *cli.Context) error {
		service, err := getShimService()
		ctx := gocontext.Background()
		if err != nil {
			return err
		}
		tty := context.Bool("tty")
		wg, err := prepareStdio(context.String("stdin"), context.String("stdout"), context.String("stderr"), tty)
		if err != nil {
			return err
		}

		// read spec file and extract Any object
		spec, err := ioutil.ReadFile(context.String("spec"))
		if err != nil {
			return err
		}

		rq := &shim.ExecRequest{
			Spec: &protobuf.Any{
				TypeUrl: specs.Version,
				Value:   spec,
			},
			Stdin:    context.String("stdin"),
			Stdout:   context.String("stdout"),
			Stderr:   context.String("stderr"),
			Terminal: tty,
		}
		r, err := service.Exec(ctx, rq)
		if err != nil {
			return err
		}
		fmt.Printf("exec running with pid %d\n", r.Pid)
		if context.Bool("attach") {
			logrus.Info("attaching")
			if tty {
				current := console.Current()
				defer current.Reset()
				if err := current.SetRaw(); err != nil {
					return err
				}
				size, err := current.Size()
				if err != nil {
					return err
				}
				if _, err := service.Pty(ctx, &shim.PtyRequest{
					Pid:    r.Pid,
					Width:  uint32(size.Width),
					Height: uint32(size.Height),
				}); err != nil {
					return err
				}
			}
			wg.Wait()
		}
		return nil
	},
}

var shimEventsCommand = cli.Command{
	Name:  "events",
	Usage: "get events for a shim",
	Action: func(context *cli.Context) error {
		service, err := getShimService()
		if err != nil {
			return err
		}
		events, err := service.Events(gocontext.Background(), &shim.EventsRequest{})
		if err != nil {
			return err
		}
		for {
			e, err := events.Recv()
			if err != nil {
				return err
			}
			fmt.Printf("type=%s id=%s pid=%d status=%d\n", e.Type, e.ID, e.Pid, e.ExitStatus)
		}
	},
}

func getShimService() (shim.ShimClient, error) {
	bindSocket := "shim.sock"

	// reset the logger for grpc to log to dev/null so that it does not mess with our stdio
	grpclog.SetLogger(log.New(ioutil.Discard, "", log.LstdFlags))
	dialOpts := []grpc.DialOption{grpc.WithInsecure(), grpc.WithTimeout(100 * time.Second)}
	dialOpts = append(dialOpts,
		grpc.WithDialer(func(addr string, timeout time.Duration) (net.Conn, error) {
			return net.DialTimeout("unix", bindSocket, timeout)
		},
		))
	conn, err := grpc.Dial(fmt.Sprintf("unix://%s", bindSocket), dialOpts...)
	if err != nil {
		return nil, err
	}
	return shim.NewShimClient(conn), nil
}


text:
<?php
namespace Concrete\Core\Page;

use PageType;
use Core;

class Template
{
    public static function exportList($xml)
    {
        $nxml = $xml->addChild('pagetemplates');
        $list = static::getList();
        foreach ($list as $pt) {
            $pt->export($nxml);
        }
    }

    public static function getByHandle($pTemplateHandle)
    {
        $em = \ORM::entityManager();

        return $em->getRepository('\Concrete\Core\Entity\Page\Template')
            ->findOneBy(
                ['pTemplateHandle' => $pTemplateHandle]
            );
    }

    public static function getByID($pTemplateID)
    {
        if ($pTemplateID) {
            $em = \ORM::entityManager();

            return $em->find('\Concrete\Core\Entity\Page\Template', $pTemplateID);
        }
    }

    protected static function sort($list)
    {
        $wrapperList = [];
        foreach ($list as $item) {
            $wrapperList[] = ['item' => $item, 'text' => $item->getPageTemplateDisplayName('text')];
        }
        usort(
            $wrapperList,
            function ($a, $b) {
                return strcasecmp($a['text'], $b['text']);
            }
        );
        $result = [];
        foreach ($wrapperList as $array) {
            $result[] = $array['item'];
        }

        return $result;
    }

    public static function getListByPackage($pkg)
    {
        $em = \ORM::entityManager();
        $list = $em->getRepository('\Concrete\Core\Entity\Page\Template')
            ->findBy(
                ['pkgID' => $pkg->getPackageID()]
            );
        $list = self::sort($list);

        return $list;
    }

    public static function getList($includeInternal = false)
    {
        $em = \ORM::entityManager();
        $args = ['pTemplateIsInternal' => $includeInternal];
        $list = $em->getRepository('\Concrete\Core\Entity\Page\Template')->findBy(
            $args, ['pTemplateID' => 'asc']
        );
        $list = self::sort($list);

        return $list;
    }

    public static function add(
        $pTemplateHandle,
        $pTemplateName,
        $pTemplateIcon = FILENAME_PAGE_TEMPLATE_DEFAULT_ICON,
        $pkg = null,
        $pTemplateIsInternal = false
    ) {
        $pkgID = (!is_object($pkg)) ? 0 : $pkg->getPackageID();

        $template = new \Concrete\Core\Entity\Page\Template();
        $template->pTemplateHandle = $pTemplateHandle;
        $template->pTemplateName = $pTemplateName;
        $template->pTemplateIcon = $pTemplateIcon;
        $template->pkgID = $pkgID;
        $template->pTemplateIsInternal = (bool) $pTemplateIsInternal;

        $em = \ORM::entityManager();
        $em->persist($template);
        $em->flush();

        // now that we have added a template, we need to find any page types that can use this template (any page types that allow ALL page templates or all + a template not of this kind)
        // and we need to update them to have a reference to this template defaults
        $ptlist = PageType::getList();
        foreach ($ptlist as $pt) {
            $pt->rescanPageTypeComposerOutputControlObjects();
        }

        return $template;
    }

    public function getIcons()
    {
        $f = Core::make('helper/file');

        return $f->getDirectoryContents(DIR_FILES_PAGE_TEMPLATE_ICONS);
    }
}


text:
- Beam serarch decoder in the Attention-based models
- LAS(Listen, Attend, and Spell) model
- Add Gausian noise to inputs and weights when training
- Warp CTC loss training
- WFST decoder
- Sequence Training such as sMBR


text:
package edu.usc.corral.types;

import java.io.PrintStream;
import java.util.Date;

import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
import org.simpleframework.xml.stream.Format;
import org.simpleframework.xml.stream.HyphenStyle;
import org.simpleframework.xml.stream.Style;

public class Glidein extends CreateGlideinRequest implements Response {
	private @Attribute Integer id;
	private @Element String siteName;
	private @Element GlideinState state;
	private @Element String shortMessage;
	private @Element(required=false) String longMessage;
	private @Element Date created;
	private @Element Date lastUpdate;
	private @Element Integer submits;
	private @Element String subject;
	private @Element String localUsername;

	public Glidein() { }

	public Glidein(CreateGlideinRequest r) {
		this.siteId = r.siteId;
		this.condorHost = r.condorHost;
		this.count = r.count;
		this.hostCount = r.hostCount;
		this.wallTime = r.wallTime;
		this.numCpus = r.numCpus;
		this.condorConfig = r.condorConfig;
		this.gcbBroker = r.gcbBroker;
		this.highport = r.highport;
		this.lowport = r.lowport;
		this.ccbAddress = r.ccbAddress;
		this.idleTime = r.idleTime;
		this.condorDebug = r.condorDebug;
		this.resubmit = r.resubmit;
		this.until = r.until;
		this.resubmits = r.resubmits;
		this.rsl = r.rsl;
	}

	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public GlideinState getState() {
		return state;
	}
	public void setState(GlideinState state) {
		this.state = state;
	}
	public String getShortMessage() {
		return shortMessage;
	}
	public void setShortMessage(String shortMessage) {
		this.shortMessage = shortMessage;
	}
	public String getLongMessage() {
		return longMessage;
	}
	public void setLongMessage(String longMessage) {
		this.longMessage = longMessage;
	}
	public Date getCreated() {
		return created;
	}
	public void setCreated(Date created) {
		this.created = created;
	}
	public Date getLastUpdate() {
		return lastUpdate;
	}
	public void setLastUpdate(Date lastUpdate) {
		this.lastUpdate = lastUpdate;
	}
	public Integer getSubmits() {
		return submits;
	}
	public void setSubmits(Integer submits) {
		this.submits = submits;
	}
	public String getSubject() {
		return subject;
	}
	public void setSubject(String subject) {
		this.subject = subject;
	}
	public String getLocalUsername() {
		return localUsername;
	}
	public void setLocalUsername(String localUsername) {
		this.localUsername = localUsername;
	}
	public String getSiteName() {
		return siteName;
	}
	public void setSiteName(String siteName) {
		this.siteName = siteName;
	}

	public void print() {
		print(System.out);
	}

	public void print(PrintStream out) {
		out.printf("id = %d\n", getId());
		out.printf("site = %d\n", getSiteId());
		out.printf("site-name = %s\n", getSiteName());
		out.printf("condor-host = %s\n", getCondorHost());
		out.printf("count = %d\n", getCount());
		out.printf("host-count = %d\n", getHostCount());
		out.printf("num-cpus = %d\n", getNumCpus());
		out.printf("wall-time = %d\n", getWallTime());
		out.printf("idle-time = %d\n", getIdleTime());

		Date created = getCreated();
		if (created == null) {
			out.printf("created = null\n");
		} else {
			out.printf("created = %tc\n", created);
		}

		Date lastUpdate = getLastUpdate();
		if (lastUpdate == null) {
			out.printf("last-update = null\n");
		} else {
			out.printf("last-update = %tc\n", lastUpdate);
		}

		out.printf("state = %s\n", getState().toString());
		out.printf("short-message = %s\n", getShortMessage());
		String longMessage = getLongMessage();
		if (longMessage == null) {
			out.printf("long-message = null\n");
		} else {
			out.printf("long-message = <<END\n");
			out.printf(longMessage);
			out.printf("\nEND\n");
		}
		out.printf("condor-debug = %s\n", getCondorDebug());
		out.printf("gcb-broker = %s\n", getGcbBroker());
		out.printf("ccb-address = %s\n", getCcbAddress());
		out.printf("submits = %s\n", getSubmits());
		out.printf("resubmit = %s\n", getResubmit());
		out.printf("resubmits = %s\n", getResubmits());

		Date until = getUntil();
		if (until == null) {
			out.printf("until = null\n");
		} else {
			out.printf("until = %tc\n", until);
		}
		out.printf("rsl = %s\n", getRsl());
		out.printf("highport = %d\n", getHighport());
		out.printf("lowport = %d\n", getLowport());
		out.printf("subject = %s\n", getSubject());
		out.printf("local-username = %s\n", getLocalUsername());
	}

	public static void main(String[] args) throws Exception {
		Glidein req = new Glidein();
		req.setId(1000);
		req.setSiteName("foosite");
		req.setState(GlideinState.NEW);
		req.setShortMessage("short");
		req.setLongMessage("long");
		req.setCreated(new Date());
		req.setLastUpdate(new Date());
		req.setResubmits(0);
		req.setSubject("/gideon/juve");
		req.setLocalUsername("juve");

		req.setCount(1);
		req.setHostCount(1);
		req.setCondorHost("juve.isi.edu");
		req.setNumCpus(1);
		req.setSiteId(1);
		req.setWallTime(60);

		req.setHighport(100);
		req.setLowport(10);

		Style style = new HyphenStyle();
		Format format = new Format(style);
		Serializer serializer = new Persister(format);
		serializer.write(req, System.out);
	}
}


text:
package com.google.cloud.bigtable.hbase.adapters.read;

import com.google.api.core.InternalApi;
import com.google.cloud.bigtable.data.v2.models.Row;
import com.google.cloud.bigtable.hbase.adapters.ResponseAdapter;
import com.google.cloud.bigtable.hbase.util.ByteStringer;
import com.google.cloud.bigtable.hbase.util.TimestampConverter;
import java.util.SortedSet;
import java.util.TreeSet;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.util.Bytes;

/**
 * Adapt between a {@link Row} and an hbase client {@link Result}.
 *
 *
For internal use only - public for technical reasons.
 */
@InternalApi("For internal usage only")
public class RowAdapter implements ResponseAdapter<Row, Result> {
  /**
   * {@inheritDoc}
   *
   *
Convert a {@link Row} to a {@link Result}.
   */
  @Override
  public Result adaptResponse(Row response) {
    if (response == null) {
      return Result.EMPTY_RESULT;
    }

    SortedSet<Cell> hbaseCells = new TreeSet<>(KeyValue.COMPARATOR);
    byte[] rowKey = response.getKey().toByteArray();

    for (com.google.cloud.bigtable.data.v2.models.RowCell rowCell : response.getCells()) {

      byte[] familyNameBytes = Bytes.toBytes(rowCell.getFamily());
      byte[] columnQualifier = ByteStringer.extract(rowCell.getQualifier());

      // Bigtable timestamp has more granularity than HBase one. It is possible that Bigtable
      // cells are deduped unintentionally here. On the other hand, if we don't dedup them,
      // HBase will treat them as duplicates.
      long hbaseTimestamp = TimestampConverter.bigtable2hbase(rowCell.getTimestamp());
      RowCell keyValue =
          new RowCell(
              rowKey,
              familyNameBytes,
              columnQualifier,
              hbaseTimestamp,
              ByteStringer.extract(rowCell.getValue()));

      hbaseCells.add(keyValue);
    }

    return Result.create(hbaseCells.toArray(new Cell[hbaseCells.size()]));
  }
}


text:
import gulp from 'gulp';
import runSequence from 'run-sequence';

const svgTask = (cb) => {
  runSequence(
    [
      'svg-single',
      'svg-sprite',
    ],
    cb
  );
}

gulp.task('svg', svgTask);
module.exports = svgTask;


text:
[![Latest Version](https://poser.pugx.org/evelabs/oauth2-eveonline/v/stable)](https://packagist.org/packages/evelabs/oauth2-eveonline)
[![Software License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE.md)
[![Build Status](https://travis-ci.org/EvELabs/oauth2-eveonline.svg?branch=master)](https://travis-ci.org/EvELabs/oauth2-eveonline)
[![Code Coverage](https://scrutinizer-ci.com/g/EvELabs/oauth2-eveonline/badges/coverage.png?b=master)](https://scrutinizer-ci.com/g/EvELabs/oauth2-eveonline/?branch=master)
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/EvELabs/oauth2-eveonline/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/EvELabs/oauth2-eveonline/?branch=master)
[![Total Downloads](https://poser.pugx.org/evelabs/oauth2-eveonline/downloads)](https://packagist.org/packages/evelabs/oauth2-eveonline)

This package provides Eve Online OAuth 2.0 support for the PHP League's [OAuth 2.0 Client](https://github.com/thephpleague/oauth2-client).

## Installation

To install, use composer:

```
composer require evelabs/oauth2-eveonline
```

## Docs

[Eve Online CREST&SSO 3rd party documentation](http://eveonline-third-party-documentation.readthedocs.org/en/latest/crest/authentication/)

## Usage

Usage is the same as The League's OAuth client, using `\Evelabs\OAuth2\Client\Provider\EveOnline` as the provider.

See `example/example.php` for more insight.

### Authorization Code Flow

```php
$provider = new Evelabs\OAuth2\Client\Provider\EveOnline([
    'clientId'          => '{eveonline-client-id}',
    'clientSecret'      => '{eveonline-client-secret}',
    'redirectUri'       => 'https://example.com/callback-url',
]);

if (!isset($_GET['code'])) {

    // If we don't have an authorization code then get one
    $authUrl = $provider->getAuthorizationUrl();
    $_SESSION['oauth2state'] = $provider->getState();
    header('Location: '.$authUrl);
    exit;

// Check given state against previously stored one to mitigate CSRF attack
} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {

    unset($_SESSION['oauth2state']);
    exit('Invalid state');

} else {

    // Try to get an access token (using the authorization code grant)
    $token = $provider->getAccessToken('authorization_code', [
        'code' => $_GET['code']
    ]);

    // Optional: Now you have a token you can look up a users profile data
    try {

        // We got an access token, let's now get the user's details
        $user = $provider->getResourceOwner($token);

        // Use these details to create a new profile
        printf('Hello %s!', $user->getCharacterName());

    } catch (Exception $e) {

        // Failed to get user details
        exit('Oh dear...');
    }

    // Use this to interact with an API on the users behalf
    echo $token->getToken();
}
```

### Managing Scopes

When creating your EveOnline authorization URL, you can specify the scopes your application may authorize.

```php
$options = [
    'scope' => ['publicData','characterLocationRead'] // array or string
];

$authorizationUrl = $provider->getAuthorizationUrl($options);
```

### Refreshing access token

EVE Online Oauth server issues short-lived(around 20 minutes) access tokens so once it expires you have to obtain a new one using long-lived refresh token.

```php
$new_token = $provider->getAccessToken('refresh_token', [
    'refresh_token' => $old_token->getRefreshToken()
]);
```

### Calling CREST

Once you've obtained both (access & refresh) tokens you can start making requests.

#### Example GET

```php
$request = $provider->getAuthenticatedRequest(
    'GET',
    'https://crest-tq.eveonline.com/characters/{characterID}/',
    $accessToken->getToken()
);

$response = $provider->getResponse($request);
```

#### Example POST

```php
$request = $provider->getAuthenticatedRequest(
    'POST',
    'https://crest-tq.eveonline.com/characters/{characterID}/',
    $accessToken->getToken(),
    ['body' => 'some stuff']
);

$response = $provider->getResponse($request);
```

## Framework integration

Symfony 2

- [KnpUOAuth2ClientBundle](https://github.com/knpuniversity/oauth2-client-bundle)

## Testing

``` bash
$ ./vendor/bin/phpunit
```

## Contributing

Please see [CONTRIBUTING](https://github.com/thephpleague/oauth2-linkedin/blob/master/CONTRIBUTING.md) for details.

## Credits

- [Oleg Krasavin](https://github.com/okwinza)
- [All Contributors](https://github.com/evelabs/oauth2-eveonline/contributors)

## License

The MIT License (MIT). Please see [License File](https://github.com/evelabs/oauth2-eveonline/blob/master/LICENSE) for more information.


text:
                    <input type="text" name="search" ng-model="search" class="form-control" placeholder="Search">

{{options.tableTitle}}

                        <th vmf-table-header-renderer
                            style="width:{{column.width}}px !important"
                            ng-repeat="column in columns"
                            column="column"
                            field="{{column.field}}"
                            columns="columns"
                            class="header {{column.thClass}} unselectable"
                            ng-click="sortBy(column, $event);"
                            ng-if="column.visible === undefined || column.visible"
                            ng-class="{'sortable': column.sort,
                            'sort-desc': column.sorted == 'sort-desc',
                            'sort-asc': column.sorted == 'sort-asc',
                            'drag-accept':column.draggable === undefined || column.draggable}"
                            unselectable="on">

                        <td vmf-table-cell vmf-inline-editor
                            ng-attr-data-editable="{{ column.editable ? 'yes' : 'no' }}"
                            cell-renderers="cellRenderers"
                            selected-rows="selectedRows"
                            item="row"
                            tr-index="$parent.$index"
                            field="{{column.field}}"
                            column="column"
                            class="{{column.tdClass}}"
                            ng-if="column.visible === undefined || column.visible"
                            ng-repeat="column in columns">

              Total Records : {{totalRecords}}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Hafellner, Symb. bot. upsal. 32(no. 1): 64 (1997)

#### Original name
Brigantiaea praetermissa Hafellner & St. Clair

### Remarks
null