text:
/*****************************************************************************/
/**
*
* @file xspips.c
* @addtogroup spips_v3_1
* @{
*
* Contains implements the interface functions of the XSpiPs driver.
* See xspips.h for a detailed description of the device and driver.
*
*

* MODIFICATION HISTORY:
*
* Ver   Who    Date     Changes
* ----- ------ -------- -----------------------------------------------
* 1.00  drg/jz 01/25/10 First release
* 1.01	sg     03/07/12 Updated the code to always clear the relevant bits
*			before writing to config register.
*			Always clear the slave select bits before write and
*			clear the bits to no slave at the end of transfer
*			Modified the Polled transfer transmit/receive logic.
*			Tx should wait on TXOW Interrupt and Rx on RXNEMTY.
* 1.03	sg     09/21/12 Added memory barrier dmb in polled transfer and
*			interrupt handler to overcome the clock domain
*			crossing issue in the controller. For CR #679252.
* 1.04a	sg     01/30/13 Changed SPI transfer logic for polled and interrupt
*			modes to be based on filled tx fifo count and receive
*			based on it. RXNEMPTY interrupt is not used.
*			SetSlaveSelect API logic is modified to drive the bit
*			position low based on the slave select value
*			requested. GetSlaveSelect API will return the value
*			based on bit position that is low.
* 1.06a hk     08/22/13 Changed GetSlaveSelect function. CR# 727866.
*                       Added masking ConfigReg before writing in SetSlaveSel
*                       Added extended slave select support - CR#722569.
*                       Added check for MODF in polled transfer function.
* 3.00  kvn    02/13/15 Modified code for MISRA-C:2012 compliance.
* 3.02  raw    11/23/15 Updated XSpiPs_Abort() to read all RXFIFO entries.
* 			This change is to tackle CR#910231.
* 3.1	tjs    04/12/18 InputClockHz parameter copied in instance for use in
* 						application. CR#998910
*
*

*
******************************************************************************/

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

#include "xspips.h"

/************************** Constant Definitions *****************************/

/**************************** Type Definitions *******************************/

/***************** Macros (Inline Functions) Definitions *********************/

/****************************************************************************/
/*
*
* Send one byte to the currently selected slave. A byte of data is written to
* transmit FIFO/register.
*
* @param	BaseAddress is the  base address of the device
*
* @return	None.
*
* @note		C-Style signature:
*		void XSpiPs_SendByte(u32 BaseAddress, u8 Data);
*
*****************************************************************************/
#define XSpiPs_SendByte(BaseAddress, Data) \
        XSpiPs_Out32((BaseAddress) + (u32)XSPIPS_TXD_OFFSET, (u32)(Data))

/****************************************************************************/
/*
*
* Receive one byte from the device's receive FIFO/register. It is assumed
* that the byte is already available.
*
* @param	BaseAddress is the  base address of the device
*
* @return	The byte retrieved from the receive FIFO/register.
*
* @note		C-Style signature:
*		u8 XSpiPs_RecvByte(u32 BaseAddress);
*
*****************************************************************************/
#define XSpiPs_RecvByte(BaseAddress) \
		XSpiPs_In32((u32)((BaseAddress) + (u32)XSPIPS_RXD_OFFSET))

/************************** Function Prototypes ******************************/

static void StubStatusHandler(void *CallBackRef, u32 StatusEvent,
				u32 ByteCount);

/************************** Variable Definitions *****************************/

/*****************************************************************************/
/**
*
* Initializes a specific XSpiPs instance such that the driver is ready to use.
*
* The state of the device after initialization is:
*   - Device is disabled
*   - Slave mode
*   - Active high clock polarity
*   - Clock phase 0
*
* @param	InstancePtr is a pointer to the XSpiPs instance.
* @param	ConfigPtr is a reference to a structure containing information
*		about a specific SPI device. This function initializes an
*		InstancePtr object for a specific device specified by the
*		contents of Config. This function can initialize multiple
*		instance objects with the use of multiple calls giving different
*		Config information on each call.
* @param	EffectiveAddr is the device base address in the virtual memory
*		address space. The caller is responsible for keeping the address
*		mapping from EffectiveAddr to the device physical base address
*		unchanged once this function is invoked. Unexpected errors may
*		occur if the address mapping changes after this function is
*		called. If address translation is not used, use
*		ConfigPtr->Config.BaseAddress for this device.
*
* @return
*		- XST_SUCCESS if successful.
*		- XST_DEVICE_IS_STARTED if the device is already started.
*		It must be stopped to re-initialize.
*
* @note		None.
*
******************************************************************************/
s32 XSpiPs_CfgInitialize(XSpiPs *InstancePtr, XSpiPs_Config *ConfigPtr,
				u32 EffectiveAddr)
{
	s32 Status;
	Xil_AssertNonvoid(InstancePtr != NULL);
	Xil_AssertNonvoid(ConfigPtr != NULL);

	/*
	 * If the device is busy, disallow the initialize and return a status
	 * indicating it is already started. This allows the user to stop the
	 * device and re-initialize, but prevents a user from inadvertently
	 * initializing. This assumes the busy flag is cleared at startup.
	 */
	if (InstancePtr->IsBusy == TRUE) {
		Status = (s32)XST_DEVICE_IS_STARTED;
	} else {

		/*
		 * Set some default values.
		 */
		InstancePtr->IsBusy = FALSE;

		InstancePtr->Config.BaseAddress = EffectiveAddr;
		InstancePtr->Config.InputClockHz = ConfigPtr->InputClockHz;
		InstancePtr->StatusHandler = StubStatusHandler;

		InstancePtr->SendBufferPtr = NULL;
		InstancePtr->RecvBufferPtr = NULL;
		InstancePtr->RequestedBytes = 0U;
		InstancePtr->RemainingBytes = 0U;
		InstancePtr->IsReady = XIL_COMPONENT_IS_READY;

		/*
		 * Reset the SPI device to get it into its initial state. It is
		 * expected that device configuration will take place after this
		 * initialization is done, but before the device is started.
		 */
		XSpiPs_Reset(InstancePtr);
		Status = (s32)XST_SUCCESS;
	}

	return Status;
}

/*****************************************************************************/
/**
*
* Resets the SPI device. Reset must only be called after the driver has been
* initialized. The configuration of the device after reset is the same as its
* configuration after initialization.  Any data transfer that is in progress
* is aborted.
*
* The upper layer software is responsible for re-configuring (if necessary)
* and restarting the SPI device after the reset.
*
* @param	InstancePtr is a pointer to the XSpiPs instance.
*
* @return	None.
*
* @note		None.
*
******************************************************************************/
void XSpiPs_Reset(XSpiPs *InstancePtr)
{
	Xil_AssertVoid(InstancePtr != NULL);
	Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);

	/*
	 * Abort any transfer that is in progress
	 */
	XSpiPs_Abort(InstancePtr);

        /*
         * Reset any values that are not reset by the hardware reset such that
         * the software state matches the hardware device
         */
        XSpiPs_WriteReg(InstancePtr->Config.BaseAddress, XSPIPS_CR_OFFSET,
                        XSPIPS_CR_RESET_STATE);

}

/*****************************************************************************/
/**
*
* Transfers specified data on the SPI bus. If the SPI device is configured as
* a master, this function initiates bus communication and sends/receives the
* data to/from the selected SPI slave. If the SPI device is configured as a
* slave, this function prepares the buffers to be sent/received when selected
* by a master. For every byte sent, a byte is received. This function should
* be used to perform interrupt based transfers.
*
* The caller has the option of providing two different buffers for send and
* receive, or one buffer for both send and receive, or no buffer for receive.
* The receive buffer must be at least as big as the send buffer to prevent
* unwanted memory writes. This implies that the byte count passed in as an
* argument must be the smaller of the two buffers if they differ in size.
* Here are some sample usages:
*

*   XSpiPs_Transfer(InstancePtr, SendBuf, RecvBuf, ByteCount)
*	The caller wishes to send and receive, and provides two different
*	buffers for send and receive.
*
*   XSpiPs_Transfer(InstancePtr, SendBuf, NULL, ByteCount)
*	The caller wishes only to send and does not care about the received
*	data. The driver ignores the received data in this case.
*
*   XSpiPs_Transfer(InstancePtr, SendBuf, SendBuf, ByteCount)
*	The caller wishes to send and receive, but provides the same buffer
*	for doing both. The driver sends the data and overwrites the send
*	buffer with received data as it transfers the data.
*
*   XSpiPs_Transfer(InstancePtr, RecvBuf, RecvBuf, ByteCount)
*	The caller wishes to only receive and does not care about sending
*	data.  In this case, the caller must still provide a send buffer, but
*	it can be the same as the receive buffer if the caller does not care
*	what it sends.  The device must send N bytes of data if it wishes to
*	receive N bytes of data.
*

* Although this function takes entire buffers as arguments, the driver can only
* transfer a limited number of bytes at a time, limited by the size of the
* FIFO. A call to this function only starts the transfer, then subsequent
* transfers of the data is performed by the interrupt service routine until
* the entire buffer has been transferred. The status callback function is
* called when the entire buffer has been sent/received.
*
* This function is non-blocking. As a master, the SetSlaveSelect function must
* be called prior to this function.
*
* @param	InstancePtr is a pointer to the XSpiPs instance.
* @param	SendBufPtr is a pointer to a buffer of data for sending.
*		This buffer must not be NULL.
* @param	RecvBufPtr is a pointer to a buffer for received data.
*		This argument can be NULL if do not care about receiving.
* @param	ByteCount contains the number of bytes to send/receive.
*		The number of bytes received always equals the number of bytes
*		sent.
*
* @return
*		- XST_SUCCESS if the buffers are successfully handed off to the
*		device for transfer.
*		- XST_DEVICE_BUSY indicates that a data transfer is already in
*		progress. This is determined by the driver.
*
* @note
*
* This function is not thread-safe.  The higher layer software must ensure that
* no two threads are transferring data on the SPI bus at the same time.
*
******************************************************************************/
s32 XSpiPs_Transfer(XSpiPs *InstancePtr, u8 *SendBufPtr,
			u8 *RecvBufPtr, u32 ByteCount)
{
	u32 ConfigReg;
	u8 TransCount = 0U;
	s32 StatusTransfer;

	/*
	 * The RecvBufPtr argument can be null
	 */
	Xil_AssertNonvoid(InstancePtr != NULL);
	Xil_AssertNonvoid(SendBufPtr != NULL);
	Xil_AssertNonvoid(ByteCount > 0U);
	Xil_AssertNonvoid(InstancePtr->IsReady == (u32)XIL_COMPONENT_IS_READY);

	/*
	 * Check whether there is another transfer in progress. Not thread-safe.
	 */
	if (InstancePtr->IsBusy == TRUE) {
		StatusTransfer = (s32)XST_DEVICE_BUSY;
	} else {

		/*
		 * Set the busy flag, which will be cleared in the ISR when the
		 * transfer is entirely done.
		 */
		InstancePtr->IsBusy = TRUE;

		/*
		 * Set up buffer pointers.
		 */
		InstancePtr->SendBufferPtr = SendBufPtr;
		InstancePtr->RecvBufferPtr = RecvBufPtr;

		InstancePtr->RequestedBytes = ByteCount;
		InstancePtr->RemainingBytes = ByteCount;

	/*
	 * If manual chip select mode, initialize the slave select value.
	 */
	if (XSpiPs_IsManualChipSelect(InstancePtr) != FALSE) {
		ConfigReg = XSpiPs_ReadReg(InstancePtr->Config.BaseAddress,
					 XSPIPS_CR_OFFSET);
		/*
		 * Set the slave select value.
		 */
		ConfigReg &= (u32)(~XSPIPS_CR_SSCTRL_MASK);
		ConfigReg |= InstancePtr->SlaveSelect;
		XSpiPs_WriteReg(InstancePtr->Config.BaseAddress,
				 XSPIPS_CR_OFFSET, ConfigReg);
	}

		/*
		 * Enable the device.
		 */
		XSpiPs_Enable(InstancePtr);

		/*
		 * Clear all the interrrupts.
		 */
		XSpiPs_WriteReg(InstancePtr->Config.BaseAddress, XSPIPS_SR_OFFSET,
				XSPIPS_IXR_WR_TO_CLR_MASK);

		/*
		 * Fill the TXFIFO with as many bytes as it will take (or as many as
		 * we have to send).
		 */
		while ((InstancePtr->RemainingBytes > 0U) &&
			(TransCount < XSPIPS_FIFO_DEPTH)) {
			XSpiPs_SendByte(InstancePtr->Config.BaseAddress,
				  *InstancePtr->SendBufferPtr);
                  InstancePtr->SendBufferPtr += 1;
			InstancePtr->RemainingBytes--;
			TransCount++;
		}

		/*
		 * Enable interrupts (connecting to the interrupt controller and
		 * enabling interrupts should have been done by the caller).
		 */
		XSpiPs_WriteReg(InstancePtr->Config.BaseAddress,
				XSPIPS_IER_OFFSET, XSPIPS_IXR_DFLT_MASK);

		/*
		 * If master mode and manual start mode, issue manual start command
		 * to start the transfer.
		 */
	     if ((XSpiPs_IsManualStart(InstancePtr) == TRUE)
		&& (XSpiPs_IsMaster(InstancePtr) == TRUE)) {
			ConfigReg = XSpiPs_ReadReg(InstancePtr->Config.BaseAddress,
						   XSPIPS_CR_OFFSET);
				ConfigReg |= XSPIPS_CR_MANSTRT_MASK;
			XSpiPs_WriteReg(InstancePtr->Config.BaseAddress,
					 XSPIPS_CR_OFFSET, ConfigReg);
		 }
		StatusTransfer = (s32)XST_SUCCESS;
	}
	return StatusTransfer;
}

/*****************************************************************************/
/**
* Transfers specified data on the SPI bus in polled mode.
*
* The caller has the option of providing two different buffers for send and
* receive, or one buffer for both send and receive, or no buffer for receive.
* The receive buffer must be at least as big as the send buffer to prevent
* unwanted memory writes. This implies that the byte count passed in as an
* argument must be the smaller of the two buffers if they differ in size.
* Here are some sample usages:
*

*   XSpiPs_PolledTransfer(InstancePtr, SendBuf, RecvBuf, ByteCount)
*	The caller wishes to send and receive, and provides two different
*	buffers for send and receive.
*
*   XSpiPs_PolledTransfer(InstancePtr, SendBuf, NULL, ByteCount)
*	The caller wishes only to send and does not care about the received
*	data. The driver ignores the received data in this case.
*
*   XSpiPs_PolledTransfer(InstancePtr, SendBuf, SendBuf, ByteCount)
*	The caller wishes to send and receive, but provides the same buffer
*	for doing both. The driver sends the data and overwrites the send
*	buffer with received data as it transfers the data.
*
*   XSpiPs_PolledTransfer(InstancePtr, RecvBuf, RecvBuf, ByteCount)
*	The caller wishes to only receive and does not care about sending
*	data.  In this case, the caller must still provide a send buffer, but
*	it can be the same as the receive buffer if the caller does not care
*	what it sends.  The device must send N bytes of data if it wishes to
*	receive N bytes of data.
*
*

*
* @param	InstancePtr is a pointer to the XSpiPs instance.
* @param	SendBufPtr is a pointer to a buffer of data for sending.
*		This buffer must not be NULL.
* @param	RecvBufPtr is a pointer to a buffer for received data.
*		This argument can be NULL if do not care about receiving.
* @param	ByteCount contains the number of bytes to send/receive.
*		The number of bytes received always equals the number of bytes
*		sent.

* @return
*		- XST_SUCCESS if the buffers are successfully handed off to the
*		device for transfer.
*		- XST_DEVICE_BUSY indicates that a data transfer is already in
*		progress. This is determined by the driver.
*
* @note
*
* This function is not thread-safe.  The higher layer software must ensure that
* no two threads are transferring data on the SPI bus at the same time.
*
******************************************************************************/
s32 XSpiPs_PolledTransfer(XSpiPs *InstancePtr, u8 *SendBufPtr,
				u8 *RecvBufPtr, u32 ByteCount)
{
	u32 StatusReg;
	u32 ConfigReg;
	u32 TransCount;
	u32 CheckTransfer;
	s32 Status_Polled;
	u8 TempData;

	/*
	 * The RecvBufPtr argument can be NULL.
	 */
	Xil_AssertNonvoid(InstancePtr != NULL);
	Xil_AssertNonvoid(SendBufPtr != NULL);
	Xil_AssertNonvoid(ByteCount > 0U);
	Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);

	/*
	 * Check whether there is another transfer in progress. Not thread-safe.
	 */
	if (InstancePtr->IsBusy == TRUE) {
		Status_Polled = (s32)XST_DEVICE_BUSY;
	} else {

		/*
		 * Set the busy flag, which will be cleared when the transfer is
		 * entirely done.
		 */
		InstancePtr->IsBusy = TRUE;

		/*
		 * Set up buffer pointers.
		 */
		InstancePtr->SendBufferPtr = SendBufPtr;
		InstancePtr->RecvBufferPtr = RecvBufPtr;

		InstancePtr->RequestedBytes = ByteCount;
		InstancePtr->RemainingBytes = ByteCount;

		/*
		 * If manual chip select mode, initialize the slave select value.
		 */
	     if (XSpiPs_IsManualChipSelect(InstancePtr) == TRUE) {
			ConfigReg = XSpiPs_ReadReg(InstancePtr->Config.BaseAddress,
						 XSPIPS_CR_OFFSET);
			/*
			 * Set the slave select value.
			 */
			ConfigReg &= (u32)(~XSPIPS_CR_SSCTRL_MASK);
			ConfigReg |= InstancePtr->SlaveSelect;
			XSpiPs_WriteReg(InstancePtr->Config.BaseAddress,
					 XSPIPS_CR_OFFSET, ConfigReg);
		}

		/*
		 * Enable the device.
		 */
		XSpiPs_Enable(InstancePtr);

		while((InstancePtr->RemainingBytes > (u32)0U) ||
			(InstancePtr->RequestedBytes > (u32)0U)) {
			TransCount = 0U;
			/*
			 * Fill the TXFIFO with as many bytes as it will take (or as
			 * many as we have to send).
			 */
			while ((InstancePtr->RemainingBytes > (u32)0U) &&
				((u32)TransCount < (u32)XSPIPS_FIFO_DEPTH)) {
				XSpiPs_SendByte(InstancePtr->Config.BaseAddress,
						*InstancePtr->SendBufferPtr);
				InstancePtr->SendBufferPtr += 1;
				InstancePtr->RemainingBytes--;
				++TransCount;
			}

			/*
			 * If master mode and manual start mode, issue manual start
			 * command to start the transfer.
			 */
			if ((XSpiPs_IsManualStart(InstancePtr) == TRUE)
				&& (XSpiPs_IsMaster(InstancePtr) == TRUE)) {
				ConfigReg = XSpiPs_ReadReg(
						InstancePtr->Config.BaseAddress,
						 XSPIPS_CR_OFFSET);
				ConfigReg |= XSPIPS_CR_MANSTRT_MASK;
				XSpiPs_WriteReg(InstancePtr->Config.BaseAddress,
						 XSPIPS_CR_OFFSET, ConfigReg);
			}

			/*
			 * Wait for the transfer to finish by polling Tx fifo status.
			 */
	        CheckTransfer = (u32)0U;
	        while (CheckTransfer == 0U){
			StatusReg = XSpiPs_ReadReg(
					        InstancePtr->Config.BaseAddress,
						        XSPIPS_SR_OFFSET);
				if ( (StatusReg & XSPIPS_IXR_MODF_MASK) != 0U) {
					/*
					 * Clear the mode fail bit
					 */
					XSpiPs_WriteReg(
						InstancePtr->Config.BaseAddress,
						XSPIPS_SR_OFFSET,
						XSPIPS_IXR_MODF_MASK);
					return (s32)XST_SEND_ERROR;
				}
		        CheckTransfer = (StatusReg &
							XSPIPS_IXR_TXOW_MASK);
		    }

			/*
			 * A transmit has just completed. Process received data and
			 * check for more data to transmit.
			 * First get the data received as a result of the transmit
			 * that just completed. Receive data based on the
			 * count obtained while filling tx fifo. Always get the
			 * received data, but only fill the receive buffer if it
			 * points to something (the upper layer software may not
			 * care to receive data).
			 */
			while (TransCount != (u32)0U) {
				TempData = (u8)XSpiPs_RecvByte(
					InstancePtr->Config.BaseAddress);
				if (InstancePtr->RecvBufferPtr != NULL) {
					*(InstancePtr->RecvBufferPtr) = TempData;
					InstancePtr->RecvBufferPtr += 1;
				}
				InstancePtr->RequestedBytes--;
				--TransCount;
			}
		}

		/*
		 * Clear the slave selects now, before terminating the transfer.
		 */
		if (XSpiPs_IsManualChipSelect(InstancePtr) == TRUE) {
			ConfigReg = XSpiPs_ReadReg(InstancePtr->Config.BaseAddress,
						XSPIPS_CR_OFFSET);
			ConfigReg |= XSPIPS_CR_SSCTRL_MASK;
			XSpiPs_WriteReg(InstancePtr->Config.BaseAddress,
					 XSPIPS_CR_OFFSET, ConfigReg);
		}

		/*
		 * Clear the busy flag.
		 */
		InstancePtr->IsBusy = FALSE;

		/*
		 * Disable the device.
		 */
		XSpiPs_Disable(InstancePtr);
		Status_Polled = (s32)XST_SUCCESS;
	}
	return Status_Polled;
}

/*****************************************************************************/
/**
*
* Selects or deselect the slave with which the master communicates. This setting
* affects the SPI_ss_outN signals. The behavior depends on the setting of the
* CR_SSDECEN bit. If CR_SSDECEN is 0, the SPI_ss_outN bits will be output with a
* single signal low. If CR_SSDECEN is 1, the SPI_ss_outN bits will reflect the
* value set.
*
* The user is not allowed to deselect the slave while a transfer is in progress.
* If no transfer is in progress, the user can select a new slave, which
* implicitly deselects the current slave. In order to explicitly deselect the
* current slave, a value of all 1's, 0x0F can be passed in as the argument to
* the function.
*
* @param	InstancePtr is a pointer to the XSpiPs instance.
* @param	SlaveSel is the slave number to be selected.
* 		Normally, 3 slaves can be selected with values 0-2.
* 		In case, 3-8 decode option is set, then upto 8 slaves
* 		can be selected. Only one slave can be selected at a time.
*
* @return
*		- XST_SUCCESS if the slave is selected or deselected
*		successfully.
*		- XST_DEVICE_BUSY if a transfer is in progress, slave cannot be
*		changed.
*
* @note
*
* This function only sets the slave which will be selected when a transfer
* occurs. The slave is not selected when the SPI is idle. The slave select
* has no affect when the device is configured as a slave.
*
******************************************************************************/
s32 XSpiPs_SetSlaveSelect(XSpiPs *InstancePtr, u8 SlaveSel)
{
	u32 ConfigReg;
	s32 Status_Slave;
	Xil_AssertNonvoid(InstancePtr != NULL);
	Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);
	Xil_AssertNonvoid(SlaveSel <= XSPIPS_CR_SSCTRL_MAXIMUM);

	/*
	 * Do not allow the slave select to change while a transfer is in
	 * progress. Not thread-safe.
	 */
	if (InstancePtr->IsBusy == TRUE) {
		Status_Slave = (s32)XST_DEVICE_BUSY;
	} else {
		/*
		 * If decode slave select option is set,
		 * then set slave select value directly.
		 * Update the Instance structure member.
		 */
		if ( XSpiPs_IsDecodeSSelect( InstancePtr ) == TRUE) {
			InstancePtr->SlaveSelect = ((u32)SlaveSel) << XSPIPS_CR_SSCTRL_SHIFT;
		}
		else {
		/*
		 * Set the bit position to low using SlaveSel. Update the Instance
		 * structure member.
		 */
			InstancePtr->SlaveSelect = ((~(1U << SlaveSel)) & \
				XSPIPS_CR_SSCTRL_MAXIMUM) << XSPIPS_CR_SSCTRL_SHIFT;
		}

		/*
		 * Read the config register, update the slave select value and write
		 * back to config register.
		 */
		ConfigReg = XSpiPs_ReadReg(InstancePtr->Config.BaseAddress,
				 XSPIPS_CR_OFFSET);
		ConfigReg &= (u32)(~XSPIPS_CR_SSCTRL_MASK);
		ConfigReg |= InstancePtr->SlaveSelect;
		XSpiPs_WriteReg(InstancePtr->Config.BaseAddress, XSPIPS_CR_OFFSET,
				 ConfigReg);
	    Status_Slave = (s32)XST_SUCCESS;
	}
	return Status_Slave;
}

/*****************************************************************************/
/**
*
* Gets the current slave select setting for the SPI device.
*
* @param	InstancePtr is a pointer to the XSpiPs instance.
*
* @return	The slave number selected (starting from 0).
*
* @note		None.
*
******************************************************************************/
u8 XSpiPs_GetSlaveSelect(XSpiPs *InstancePtr)
{
	u32 ConfigReg;
	u32 SlaveSel;

	Xil_AssertNonvoid(InstancePtr != NULL);
	Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);

	ConfigReg = InstancePtr->SlaveSelect;
	ConfigReg &= XSPIPS_CR_SSCTRL_MASK;
	ConfigReg >>= XSPIPS_CR_SSCTRL_SHIFT;
	ConfigReg &= XSPIPS_CR_SSCTRL_MAXIMUM;

	/*
	 * If decode slave select option is set, then read value directly.
	 */
	if ( XSpiPs_IsDecodeSSelect( InstancePtr ) == TRUE) {
		SlaveSel = ConfigReg;
	}
	else {

		/*
		 * Get the slave select value
		 */
		if(ConfigReg == 0x0FU) {
			/*
			 * No slave selected
			 */
			SlaveSel = 0xFU;
		}else {
			/*
			 * Get selected slave number (0,1 or 2)
			 */
			SlaveSel = ((~ConfigReg) & XSPIPS_CR_SSCTRL_MAXIMUM)/2;
		}
	}
	return (u8)SlaveSel;
}

/*****************************************************************************/
/**
*
* Sets the status callback function, the status handler, which the driver
* calls when it encounters conditions that should be reported to upper
* layer software. The handler executes in an interrupt context, so it must
* minimize the amount of processing performed. One of the following status
* events is passed to the status handler.
*
*

* XST_SPI_MODE_FAULT		A mode fault error occurred, meaning the device
*				is selected as slave while being a master.
*
* XST_SPI_TRANSFER_DONE		The requested data transfer is done
*
* XST_SPI_TRANSMIT_UNDERRUN	As a slave device, the master clocked data
*				but there were none available in the transmit
*				register/FIFO. This typically means the slave
*				application did not issue a transfer request
*				fast enough, or the processor/driver could not
*				fill the transmit register/FIFO fast enough.
*
* XST_SPI_RECEIVE_OVERRUN	The SPI device lost data. Data was received
*				but the receive data register/FIFO was full.
*
* XST_SPI_SLAVE_MODE_FAULT	A slave SPI device was selected as a slave
*				while it was disabled. This indicates the
*				master is already transferring data (which is
*				being dropped until the slave application
*				issues a transfer).
*

* @param	InstancePtr is a pointer to the XSpiPs instance.
* @param	CallBackRef is the upper layer callback reference passed back
*		when the callback function is invoked.
* @param	FunctionPtr is the pointer to the callback function.
*
* @return	None.
*
* @note
*
* The handler is called within interrupt context, so it should do its work
* quickly and queue potentially time-consuming work to a task-level thread.
*
******************************************************************************/
void XSpiPs_SetStatusHandler(XSpiPs *InstancePtr, void *CallBackRef,
				XSpiPs_StatusHandler FunctionPtr)
{
	Xil_AssertVoid(InstancePtr != NULL);
	Xil_AssertVoid(FunctionPtr != NULL);
	Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY);

	InstancePtr->StatusHandler = FunctionPtr;
	InstancePtr->StatusRef = CallBackRef;
}

/*****************************************************************************/
/**
*
* This is a stub for the status callback. The stub is here in case the upper
* layers forget to set the handler.
*
* @param	CallBackRef is a pointer to the upper layer callback reference
* @param	StatusEvent is the event that just occurred.
* @param	ByteCount is the number of bytes transferred up until the event
*		occurred.
*
* @return	None.
*
* @note		None.
*
******************************************************************************/
static void StubStatusHandler(void *CallBackRef, u32 StatusEvent,
				u32 ByteCount)
{
	(void) CallBackRef;
	(void) StatusEvent;
	(void) ByteCount;

	Xil_AssertVoidAlways();
}

/*****************************************************************************/
/**
*
* The interrupt handler for SPI interrupts. This function must be connected
* by the user to an interrupt controller.
*
* The interrupts that are handled are:
*
* - Mode Fault Error. This interrupt is generated if this device is selected
*   as a slave when it is configured as a master. The driver aborts any data
*   transfer that is in progress by resetting FIFOs (if present) and resetting
*   its buffer pointers. The upper layer software is informed of the error.
*
* - Data Transmit Register (FIFO) Empty. This interrupt is generated when the
*   transmit register or FIFO is empty. The driver uses this interrupt during a
*   transmission to continually send/receive data until the transfer is done.
*
* - Data Transmit Register (FIFO) Underflow. This interrupt is generated when
*   the SPI device, when configured as a slave, attempts to read an empty
*   DTR/FIFO.  An empty DTR/FIFO usually means that software is not giving the
*   device data in a timely manner. No action is taken by the driver other than
*   to inform the upper layer software of the error.
*
* - Data Receive Register (FIFO) Overflow. This interrupt is generated when the
*   SPI device attempts to write a received byte to an already full DRR/FIFO.
*   A full DRR/FIFO usually means software is not emptying the data in a timely
*   manner.  No action is taken by the driver other than to inform the upper
*   layer software of the error.
*
* - Slave Mode Fault Error. This interrupt is generated if a slave device is
*   selected as a slave while it is disabled. No action is taken by the driver
*   other than to inform the upper layer software of the error.
*
* @param	InstancePtr is a pointer to the XSpiPs instance.
*
* @return	None.
*
* @note
*
* The slave select register is being set to deselect the slave when a transfer
* is complete.  This is being done regardless of whether it is a slave or a
* master since the hardware does not drive the slave select as a slave.
*
******************************************************************************/
void XSpiPs_InterruptHandler(XSpiPs *InstancePtr)
{
	XSpiPs *SpiPtr = InstancePtr;
	u32 IntrStatus;
	u32 ConfigReg;
	u32 BytesDone; /* Number of bytes done so far. */

	Xil_AssertVoid(InstancePtr != NULL);
	Xil_AssertVoid(SpiPtr->IsReady == XIL_COMPONENT_IS_READY);

	/*
	 * Immediately clear the interrupts in case the ISR causes another
	 * interrupt to be generated. If we clear at the end of the ISR,
	 * we may miss newly generated interrupts.
	 * Disable the TXOW interrupt because we transmit from within the ISR,
	 * which could potentially cause another TX_OW interrupt.
	 */
	IntrStatus =
		XSpiPs_ReadReg(SpiPtr->Config.BaseAddress, XSPIPS_SR_OFFSET);
	XSpiPs_WriteReg(SpiPtr->Config.BaseAddress, XSPIPS_SR_OFFSET,
			(IntrStatus & XSPIPS_IXR_WR_TO_CLR_MASK));
	XSpiPs_WriteReg(SpiPtr->Config.BaseAddress, XSPIPS_IDR_OFFSET,
			XSPIPS_IXR_TXOW_MASK);

	/*
	 * Check for mode fault error. We want to check for this error first,
	 * before checking for progress of a transfer, since this error needs
	 * to abort any operation in progress.
	 */
	if ((u32)XSPIPS_IXR_MODF_MASK == (u32)(IntrStatus & XSPIPS_IXR_MODF_MASK)) {
		BytesDone = SpiPtr->RequestedBytes - SpiPtr->RemainingBytes;

		/*
		 * Abort any operation currently in progress. This includes
		 * clearing the mode fault condition by reading the status
		 * register. Note that the status register should be read after
		 * the abort, since reading the status register clears the mode
		 * fault condition and would cause the device to restart any
		 * transfer that may be in progress.
		 */
		XSpiPs_Abort(SpiPtr);

		SpiPtr->StatusHandler(SpiPtr->StatusRef, XST_SPI_MODE_FAULT,
					BytesDone);

		return; /* Do not continue servicing other interrupts. */
	}

	if ((IntrStatus & XSPIPS_IXR_TXOW_MASK) != 0U) {
		u8 TempData;
		u32 TransCount;
		/*
		 * A transmit has just completed. Process received data and
		 * check for more data to transmit.
		 * First get the data received as a result of the transmit that
		 * just completed.  Always get the received data, but only fill
		 * the receive buffer if it is not null (it can be null when
		 * the device does not care to receive data).
		 * Initialize the TransCount based on the requested bytes.
		 * Loop on receive FIFO based on TransCount.
		 */
		TransCount = SpiPtr->RequestedBytes - SpiPtr->RemainingBytes;

		while (TransCount != 0U) {
			TempData = (u8)XSpiPs_RecvByte(SpiPtr->Config.BaseAddress);
			if (SpiPtr->RecvBufferPtr != NULL) {
				*SpiPtr->RecvBufferPtr = TempData;
				SpiPtr->RecvBufferPtr += 1;
			}
			SpiPtr->RequestedBytes--;
			--TransCount;
		}

		/*
		 * Fill the TXFIFO until data exists, otherwise fill upto
		 * FIFO depth.
		 */
		while ((SpiPtr->RemainingBytes > 0U) &&
			(TransCount < XSPIPS_FIFO_DEPTH)) {
			XSpiPs_SendByte(SpiPtr->Config.BaseAddress,
					 *SpiPtr->SendBufferPtr);
			SpiPtr->SendBufferPtr += 1;
			SpiPtr->RemainingBytes--;
			++TransCount;
		}

		if ((SpiPtr->RemainingBytes == 0U) &&
			(SpiPtr->RequestedBytes == 0U)) {
			/*
			 * No more data to send. Disable the interrupt and
			 * inform the upper layer software that the transfer
			 * is done. The interrupt will be re-enabled when
			 * another transfer is initiated.
			 */
			XSpiPs_WriteReg(SpiPtr->Config.BaseAddress,
				 XSPIPS_IDR_OFFSET, XSPIPS_IXR_DFLT_MASK);

			/*
			 * Disable slave select lines as the transfer
			 * is complete.
			 */
			if (XSpiPs_IsManualChipSelect(InstancePtr) == TRUE) {
				ConfigReg = XSpiPs_ReadReg(
					SpiPtr->Config.BaseAddress,
					 XSPIPS_CR_OFFSET);
				ConfigReg |= XSPIPS_CR_SSCTRL_MASK;
				XSpiPs_WriteReg(
					SpiPtr->Config.BaseAddress,
					 XSPIPS_CR_OFFSET, ConfigReg);
			}

			/*
			 * Clear the busy flag.
			 */
			SpiPtr->IsBusy = FALSE;

			/*
			 * Disable the device.
			 */
			XSpiPs_Disable(SpiPtr);

			/*
			 * Inform the Transfer done to upper layers.
			 */
			SpiPtr->StatusHandler(SpiPtr->StatusRef,
						XST_SPI_TRANSFER_DONE,
						SpiPtr->RequestedBytes);
		} else {
			/*
			 * Enable the TXOW interrupt.
			 */
			XSpiPs_WriteReg(SpiPtr->Config.BaseAddress,
				 XSPIPS_IER_OFFSET, XSPIPS_IXR_TXOW_MASK);
			/*
			 * Start the transfer by not inhibiting the transmitter
			 * any longer.
			 */
			if ((XSpiPs_IsManualStart(SpiPtr) == TRUE)
				&& (XSpiPs_IsMaster(SpiPtr) == TRUE)) {
				ConfigReg = XSpiPs_ReadReg(
					SpiPtr->Config.BaseAddress,
					 XSPIPS_CR_OFFSET);
				ConfigReg |= XSPIPS_CR_MANSTRT_MASK;
				XSpiPs_WriteReg(
					SpiPtr->Config.BaseAddress,
					 XSPIPS_CR_OFFSET, ConfigReg);
			}
		}
	}

	/*
	 * Check for overflow and underflow errors.
	 */
	if ((IntrStatus & XSPIPS_IXR_RXOVR_MASK) != 0U) {
		BytesDone = SpiPtr->RequestedBytes - SpiPtr->RemainingBytes;
		SpiPtr->IsBusy = FALSE;

		/*
		 * The Slave select lines are being manually controlled.
		 * Disable them because the transfer is complete.
		 */
		if (XSpiPs_IsManualChipSelect(SpiPtr) == TRUE) {
			ConfigReg = XSpiPs_ReadReg(
				SpiPtr->Config.BaseAddress,
				 XSPIPS_CR_OFFSET);
			ConfigReg |= XSPIPS_CR_SSCTRL_MASK;
			XSpiPs_WriteReg(
				SpiPtr->Config.BaseAddress,
				 XSPIPS_CR_OFFSET, ConfigReg);
		}

		SpiPtr->StatusHandler(SpiPtr->StatusRef,
			XST_SPI_RECEIVE_OVERRUN, BytesDone);
	}

	if ((IntrStatus & XSPIPS_IXR_TXUF_MASK) != 0U) {
		BytesDone = SpiPtr->RequestedBytes - SpiPtr->RemainingBytes;

		SpiPtr->IsBusy = FALSE;
		/*
		 * The Slave select lines are being manually controlled.
		 * Disable them because the transfer is complete.
		 */
		if (XSpiPs_IsManualChipSelect(SpiPtr) == TRUE) {
			ConfigReg = XSpiPs_ReadReg(
				SpiPtr->Config.BaseAddress,
				 XSPIPS_CR_OFFSET);
			ConfigReg |= XSPIPS_CR_SSCTRL_MASK;
			XSpiPs_WriteReg(
				SpiPtr->Config.BaseAddress,
				 XSPIPS_CR_OFFSET, ConfigReg);
		}

		SpiPtr->StatusHandler(SpiPtr->StatusRef,
			XST_SPI_TRANSMIT_UNDERRUN, BytesDone);
	}

}

/*****************************************************************************/
/**
*
* Aborts a transfer in progress by disabling the device and resetting the FIFOs
* if present. The byte counts are cleared, the busy flag is cleared, and mode
* fault is cleared.
*
* @param	InstancePtr is a pointer to the XSpiPs instance.
*
* @return	None.
*
* @note
*
* This function does a read/modify/write of the Config register. The user of
* this function needs to take care of critical sections.
*
******************************************************************************/
void XSpiPs_Abort(XSpiPs *InstancePtr)
{

	u8 Temp;
	u32 Check;
	u32 Count;
	XSpiPs_Disable(InstancePtr);

	/*
	 * Clear the RX FIFO and drop any data.
	 */
	Check = (XSpiPs_ReadReg(InstancePtr->Config.BaseAddress,
		XSPIPS_SR_OFFSET) & XSPIPS_IXR_RXNEMPTY_MASK);
	while (Check != (u32)0U) {
		Temp = (u8)XSpiPs_RecvByte(InstancePtr->Config.BaseAddress);
		if(Temp != (u8)0U){
		}
		Check = (XSpiPs_ReadReg(InstancePtr->Config.BaseAddress,
		XSPIPS_SR_OFFSET) & XSPIPS_IXR_RXNEMPTY_MASK);
	}

	/*
	 * Read all RX_FIFO entries
	 */
	for (Count = 0; Count < XSPIPS_FIFO_DEPTH; Count++) {
		(void)XSpiPs_ReadReg(InstancePtr->Config.BaseAddress,
			XSPIPS_RXD_OFFSET);
	}

	/*
	 * Clear mode fault condition.
	 */
	XSpiPs_WriteReg(InstancePtr->Config.BaseAddress,
			XSPIPS_SR_OFFSET,
			XSPIPS_IXR_MODF_MASK);

	InstancePtr->RemainingBytes = 0U;
	InstancePtr->RequestedBytes = 0U;
	InstancePtr->IsBusy = FALSE;
}

/** @} */


text:
package org.ehcache.clustered.server;

import java.util.Properties;
import org.ehcache.clustered.common.internal.messages.EhcacheEntityResponse;
import org.terracotta.entity.ActiveInvokeChannel;
import org.terracotta.entity.ActiveInvokeContext;
import org.terracotta.entity.ClientDescriptor;
import org.terracotta.entity.ClientSourceId;

import java.util.concurrent.atomic.AtomicLong;

public final class TestInvokeContext implements ActiveInvokeContext<EhcacheEntityResponse> {

  private final AtomicLong currentTransactionId = new AtomicLong();

  private final ClientDescriptor clientDescriptor = new TestClientDescriptor();

  public void incrementCurrentTransactionId() {
    currentTransactionId.incrementAndGet();
  }

  @Override
  public ClientDescriptor getClientDescriptor() {
    return clientDescriptor;
  }

  @Override
  public ActiveInvokeChannel<EhcacheEntityResponse> openInvokeChannel() {
    return null;
  }

  @Override
  public ClientSourceId getClientSource() {
    return clientDescriptor.getSourceId();
  }

  @Override
  public long getCurrentTransactionId() {
    return currentTransactionId.get();
  }

  @Override
  public long getOldestTransactionId() {
    return 1;
  }

  @Override
  public boolean isValidClientInformation() {
    return true;
  }

  @Override
  public ClientSourceId makeClientSourceId(long l) {
    return new TestClientSourceId(l);
  }

  @Override
  public int getConcurrencyKey() {
    return 1;
  }

  @Override
  public Properties getClientSourceProperties() {
    return new Properties();
  }
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

var grunt   = require('grunt');
var server  = require('../tasks/lib/server');

exports['livereload'] = {
  'start': function(test) {
    test.expect(2);

    server.start(function(err) {
      test.equal(null, err);

      server.start(function(err) {
        test.equal(true, !!err);
        test.done();
      });
    });
  }
};


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

    <parent>
        <groupId>de.javagl</groupId>
        <artifactId>flow-parent</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>

    <artifactId>flow-repository</artifactId>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>


text:
"use strict";

/**
 * @module Provider
 */

// Imports
var Provider = require('./provider.js');
var util = require('util');
var httpClient = require('http');
var querystring = require('querystring');

// Implementation
/**
 * @class Http
 * @extends Provider
 * @constructor
 * @param {String} ip
 */
function Http(ip) {
    Http['super_'].call(this);

    /**
     * @property options
     * @private
     * @type {{hostname: String, port: Number, path: String, method: String}}
     */
    this.options = {
        hostname: ip,
        port: 80,
        path: '/rpc',
        method: 'POST',
        headers: {
            'Content-Length': 0
        }
    };
}

util.inherits(Http, Provider);

/**
 * @method request
 * @param {Request} request
 * @param {Function} callback
 * @param {Error} callback.err
 * @param {String} callback.jsonData
 */
Http.prototype.request = function (request, callback) {
    var postData = querystring.stringify({
        RPC: JSON.stringify(request.getRequestJson())
    });

    this.options.headers['Content-Length'] = postData.length;

    var req = httpClient.request(this.options, function (res) {
        var data = '';

        if (res.statusCode !== 200) {
            return callback(new Error("Request Status Code !== 200 (" + res.statusCode + ")"));
        }
        res.setEncoding('utf8');

        res.on('data', function (chunk) {
            data = data + chunk;
        });

        res.on('end', function () {
            return callback(null, data);
        });
    });

    req.on('error', function (e) {
        return callback(e);
    });

    req.write(postData, "utf8");
    req.end();
};

module.exports = Http;


text:
package com.example.nasaproject;

import java.io.IOException;
import java.util.ArrayList;

import android.app.Activity;
import android.app.WallpaperManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.parser.ApodFeedItem;
import com.example.parser.BackgroundTask;
import com.example.parser.GetImageInBackground;
import com.example.parser.ReturnFromBackgroundTask;

public class MainActivity extends Activity implements ReturnFromBackgroundTask {

	private static final String mURL = "http://www.nasa.gov/rss/dyn/image_of_the_day.rss";
	final int DEFAULT_FEED_NUMBER = 0;
	int CURRENT_FEED_NUMBER = 0;
	ArrayList<ApodFeedItem> list = null;
	private TextView title;
	private TextView date;
	private ImageView image;
	private TextView description;
	private Button buttonSetWallpaper;
	private ProgressBar pb;
	private Bitmap backgroundImage;
	private ImageButton left,right;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		initializeUI();
		initilizeOnClickListener();

		pb.setVisibility(ProgressBar.VISIBLE);
		BackgroundTask t = new BackgroundTask(mURL);
		t.deligate = MainActivity.this;
		t.execute();
	}

	private void initializeUI(){

		title = (TextView) findViewById(R.id.imageTitle);
		date = (TextView) findViewById(R.id.imageDate);
		image = (ImageView) findViewById(R.id.imageDisplay);
		description = (TextView) findViewById(R.id.imageDesc);
		buttonSetWallpaper = (Button) findViewById(R.id.button_setAsWallpaper);
		pb = (ProgressBar) findViewById(R.id.progressBar1);
		left = (ImageButton) findViewById(R.id.imageButtonLeft);
		right = (ImageButton) findViewById(R.id.imageButtonRight);
	}

	private void initilizeOnClickListener() {

		buttonSetWallpaper.setVisibility(Button.INVISIBLE);

		left.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				pb.setVisibility(ProgressBar.VISIBLE);
				--CURRENT_FEED_NUMBER;
				refreshDisplay(list.get(CURRENT_FEED_NUMBER).getTitle(),
						list.get(CURRENT_FEED_NUMBER).getDate(),
						list.get(CURRENT_FEED_NUMBER).getImageUrl(),
						list.get(CURRENT_FEED_NUMBER).getDescription());
			}
		});
		right.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				pb.setVisibility(ProgressBar.VISIBLE);
				++CURRENT_FEED_NUMBER;
				refreshDisplay(list.get(CURRENT_FEED_NUMBER).getTitle(),
						list.get(CURRENT_FEED_NUMBER).getDate(),
						list.get(CURRENT_FEED_NUMBER).getImageUrl(),
						list.get(CURRENT_FEED_NUMBER).getDescription());
			}
		});
		buttonSetWallpaper.setOnClickListener(new  OnClickListener() {
			@Override
			public void onClick(View v) {
				Toast.makeText(MainActivity.this, "Wallpaper is set !!! ", Toast.LENGTH_LONG).show();
				WallpaperManager wm = WallpaperManager.getInstance(MainActivity.this);
				try {
					wm.setBitmap(backgroundImage);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});

	}

	@Override
	public void responseFromBackground(ArrayList<ApodFeedItem> response) {
		//all the content of rss feed in list call refreshDispaly in Main Activity

		list = response;

		CURRENT_FEED_NUMBER = DEFAULT_FEED_NUMBER;

		refreshDisplay(list.get(DEFAULT_FEED_NUMBER).getTitle(),
				list.get(DEFAULT_FEED_NUMBER).getDate(),
				list.get(DEFAULT_FEED_NUMBER).getImageUrl(),
				list.get(DEFAULT_FEED_NUMBER).getDescription());

	}

	public void refreshDisplay(String mTitle, String mDate,String mImageUrl, String mDescription){
//		title.setText(mTitle);
//		date.setText(mDate);
//		description.setText(mDescription);

		Log.i("Rahooool", "About to send request for image : "+mImageUrl);
		GetImageInBackground imageFromBackground = new GetImageInBackground(mImageUrl);
		imageFromBackground.deligate = this;
		imageFromBackground.execute();

	}

	@Override
	public void responseImageFromBackground(Bitmap response) {
		Log.i("Rahooool","Setting Image From Background ");
		pb.setVisibility(ProgressBar.INVISIBLE);
		buttonSetWallpaper.setVisibility(Button.VISIBLE);
		image.setImageBitmap(response);
		title.setText( list.get(CURRENT_FEED_NUMBER).getTitle() );
		date.setText( list.get(CURRENT_FEED_NUMBER).getDate() );
		description.setText( list.get(CURRENT_FEED_NUMBER).getDescription() );

		backgroundImage = response;
		if (CURRENT_FEED_NUMBER == 0) {
			left.setVisibility(ImageButton.INVISIBLE);
		}else {
			left.setVisibility(ImageButton.VISIBLE);
		}

		if (CURRENT_FEED_NUMBER == list.size()-1) {
			right.setVisibility(ImageButton.INVISIBLE);
		}else {
			right.setVisibility(ImageButton.VISIBLE);
		}

		//refreshDisplay(response.get(1).getTitle(), response.get(1).getDate(),response.get(1).getImageUrl(),response.get(1).getDescription());
	}
}


text:
package com.lightcrafts.ui.metadata;

import com.lightcrafts.image.metadata.ImageMetadataDirectory;

import java.util.*;

// Given a ImageMetaDirectory object, this class identifies a presentation
// filter for the directory's metadata and filters KeyValuePairs accordingly.

class MetaTagFilter {

    // Take an ArrayList of KeyValuePairs, filter them, and return the result:
    static ArrayList<KeyValuePair> filter(
        ImageMetadataDirectory dir, ArrayList<KeyValuePair> pairs
    ) {
        ArrayList<KeyValuePair> result = new ArrayList<KeyValuePair>(pairs);
        for (Iterator i=result.iterator(); i.hasNext(); ) {
            KeyValuePair pair = (KeyValuePair) i.next();
            Integer id = pair.getTagID();
            if (! dir.shouldDisplayTag(id)) {
                i.remove();
            }
        }
        return result;
    }
}


text:
using Aurora.EffectsEngine;
using Aurora.Profiles;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Controls;
using Aurora.Utils;
using System.ComponentModel;

namespace Aurora.Settings.Layers
{
    public enum ShortcutAssistantPresentationType
    {
        [Description("Show All Keys")]
        Default = 0,

        [Description("Progressive Suggestion")]
        ProgressiveSuggestion = 1
    }

    public class ShortcutAssistantLayerHandlerProperties : LayerHandlerProperties<ShortcutAssistantLayerHandlerProperties>
    {
        [Overrides.LogicOverridable("Dim Background")]
        public bool? _DimBackground { get; set; }

        [JsonIgnore]
        public bool DimBackground { get { return (Logic._DimBackground ?? _DimBackground) ?? false; } }

        [JsonIgnore]
        public bool? __MergeModifierKey { get; set; }

        public bool? _MergeModifierKey { get { return __MergeModifierKey; } set { __MergeModifierKey = value; ShortcutKeysInvalidated = true; } }

        [JsonIgnore]
        public bool MergeModifierKey { get { return (Logic._MergeModifierKey ?? _MergeModifierKey) ?? default(bool); } }

        [Overrides.LogicOverridable("Dim Color")]
        public Color? _DimColor { get; set; }

        [JsonIgnore]
        public Color DimColor { get { return (Logic._DimColor ?? _DimColor) ?? Color.Empty; } }

        [JsonIgnore]
        private Keybind[] __ShortcutKeys = new Keybind[] { };

        public Keybind[] _ShortcutKeys
        {
            get { return __ShortcutKeys; }
            set { __ShortcutKeys = value; ShortcutKeysInvalidated = true; }
        }

        [JsonIgnore]
        public Keybind[] ShortcutKeys { get { return _ShortcutKeys; } }

        [JsonIgnore]
        public bool ShortcutKeysInvalidated = true;

        [JsonIgnore]
        private Tree<Keys> _ShortcutKeysTree = new Tree<Keys>(Keys.None);

        [JsonIgnore]
        public Tree<Keys> ShortcutKeysTree
        {
            get
            {
                if (ShortcutKeysInvalidated)
                {
                    _ShortcutKeysTree = new Tree<Keys>(Keys.None);

                    foreach (Keybind keyb in ShortcutKeys)
                    {
                        Keys[] keys = keyb.ToArray();

                        if (MergeModifierKey)
                        {
                            for (int i = 0; i < keys.Length; i++)
                                keys[i] = KeyUtils.GetStandardKey(keys[i]);
                        }

                        _ShortcutKeysTree.AddBranch(keys);
                    }

                    ShortcutKeysInvalidated = false;
                }

                return _ShortcutKeysTree;
            }
        }

        public ShortcutAssistantPresentationType? _PresentationType { get; set; }

        [JsonIgnore]
        public ShortcutAssistantPresentationType PresentationType { get { return Logic._PresentationType ?? _PresentationType ?? ShortcutAssistantPresentationType.Default; } }

        public ShortcutAssistantLayerHandlerProperties() : base() { }

        public ShortcutAssistantLayerHandlerProperties(bool empty = false) : base(empty) { }

        public override void Default()
        {
            base.Default();
            _DimBackground = true;
            _DimColor = Color.FromArgb(169, 0, 0, 0);
            _PresentationType = ShortcutAssistantPresentationType.Default;
            _MergeModifierKey = false;
        }
    }

    public class ShortcutAssistantLayerHandler : LayerHandler<ShortcutAssistantLayerHandlerProperties>
    {
        protected override System.Windows.Controls.UserControl CreateControl()
        {
            return new Control_ShortcutAssistantLayer(this);
        }

        public override EffectLayer Render(IGameState gamestate)
        {
            EffectLayer sc_assistant_layer = new EffectLayer("Shortcut Assistant");

            Keys[] heldKeys = Global.InputEvents.PressedKeys;

            Tree<Keys> _childKeys = Properties.ShortcutKeysTree;
            foreach (var key in heldKeys)
            {
                if(_childKeys != null)
                    _childKeys = _childKeys.ContainsItem(Properties.MergeModifierKey ? KeyUtils.GetStandardKey(key) : key);
            }

            if(_childKeys != null && _childKeys.Item != Keys.None)
            {
                Keys[] shortcutKeys;

                if (Properties.PresentationType == ShortcutAssistantPresentationType.ProgressiveSuggestion)
                    shortcutKeys = _childKeys.GetChildren();
                else
                    shortcutKeys = _childKeys.GetAllChildren();

                if(shortcutKeys.Length > 0)
                {

                    Devices.DeviceKeys[] selectedKeys = Utils.KeyUtils.GetDeviceKeys(shortcutKeys, true, !Console.NumberLock)
                        .Concat(Utils.KeyUtils.GetDeviceKeys(heldKeys, true)).ToArray();

                    if (Properties.DimBackground)
                    {
                        Devices.DeviceKeys[] backgroundKeys = Utils.KeyUtils.GetDeviceAllKeys().Except(selectedKeys).ToArray();
                        sc_assistant_layer.Set(backgroundKeys, Properties.DimColor);
                        //sc_assistant_layer.Fill(Properties.DimColor);
                    }

                    sc_assistant_layer.Set(selectedKeys, Properties.PrimaryColor);

                }
            }

            return sc_assistant_layer;
        }
    }
}


text:
const schemas = require('./schemas'),
      Config = require('./config'),
      RaidenConfig = require('./raidenConfig');

const raidenConfig = new RaidenConfig('config.yml');

const envs = new Config(
    'envs.yml',
    schemas.envsSanitizeSchema,
    schemas.envsValidationSchema
);

const requests = new Config(
    raidenConfig.get('reqfile') || 'requests.yml',
    schemas.requestSanitizeSchema,
    schemas.requestValidationSchema
);

const userConfigs = {
    envs,
    requests
};

module.exports = userConfigs;


text:
import { assert, JSData } from '../../_setup'

describe('Container#getAdapters', function () {
  it('should be an instance method', function () {
    const Container = JSData.Container
    const store = new Container()
    assert.equal(typeof store.getAdapters, 'function')
    assert.strictEqual(store.getAdapters, Container.prototype.getAdapters)
  })
  it('should return the adapters of the container', function () {
    const Container = JSData.Container
    const container = new Container()
    assert.strictEqual(container.getAdapters(), container._adapters)
  })
})


text:
package com.harmazing.openbridge.paasos.resource.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.harmazing.framework.authorization.IUser;
import com.harmazing.framework.common.JsonResponse;
import com.harmazing.framework.util.StringUtil;
import com.harmazing.framework.util.WebUtil;
import com.harmazing.openbridge.paas.util.StorageUtil;
import com.harmazing.openbridge.paasos.resource.model.PaasRedis;
import com.harmazing.openbridge.paasos.resource.service.IPaasRedisService;
import com.harmazing.openbridge.paasos.utils.ConfigUtils;

@Controller
@RequestMapping("/resource/redis")
public class PaasRedisController extends PaasResourceBaseController {
	protected static final Log logger = LogFactory
			.getLog(PaasRedisController.class);

	@Autowired
	private IPaasRedisService redisService;

	@RequestMapping("/list")//首页的列表
	public String list(HttpServletRequest request, HttpServletResponse response){
		try{
			IUser user = WebUtil.getUserByRequest(request);
			Map<String, Object> params = new HashMap<String, Object>();
			int pageNo = StringUtil.getIntParam(request, "pageNo", 1);
			int pageSize = StringUtil.getIntParam(request, "pageSize", 10);
			String listType = request.getParameter("listType");
			params.put("pageNo", pageNo);
			params.put("pageSize", pageSize);
			/*if(!user.isAdministrator()){
				params.put("userId", user.getUserId());
			}*/
			if(listType != null && listType.equals("tenant")){
				params.put("tenantId", user.getTenantId());
			}else{
				params.put("userId", user.getUserId());
				params.put("tenantId", user.getTenantId());
			}
			List<PaasRedis> pageData = redisService.queryPaasRedissByParams(params);
			request.setAttribute("pageData", pageData);
			return getUrlPrefix()+"/list";
		}catch(Exception e){
			request.setAttribute("exception", e);
			logger.error("获取缓存列表信息出错");
			return forward(ERROR);
		}
	}

	@RequestMapping("/queryRedisStatusInfo")//实时rest请求查询redis实例的运行状态
	@ResponseBody
	public JsonResponse queryRedisInfo(HttpServletRequest request, HttpServletResponse response){
		try{
			IUser user = WebUtil.getUserByRequest(request);
			String resId = request.getParameter("resId");
			String paasOsUserId = user.getUserId();
			String paasOsTenantId = user.getTenantId();
			if(StringUtil.isNull(resId)){
				return JsonResponse.failure(403, "查询参数不正确");
			}
			JSONObject RedisObj = redisService.queryRedisInfo(resId, paasOsUserId, paasOsTenantId);
			String status = RedisObj.getString("status");
			switch(status){
			case "creating":
				status = "创建中";
				break;
			case "starting":
				status = "启动中";
				break;
			case "running":
				status = "运行中";
				break;
			case "stopped":
				status = "已停止";
				break;
			default:
				status ="";
			}
			JSONObject returnObj = new JSONObject();
			returnObj.put("status", status);
			if(RedisObj.containsKey("podInfo")){
				if(RedisObj.getJSONObject("podInfo")!=null){
					returnObj.put("podName", RedisObj.getJSONObject("podInfo").get("podName"));
					returnObj.put("namespace", RedisObj.getJSONObject("podInfo").get("namespace"));
				}
			}
			return JsonResponse.success(returnObj);
		}catch(Exception e){
			logger.error("查询redis运行状态失败"+e.getMessage());
			return JsonResponse.failure(500, "查询redis运行状态失败");
		}
	}

	@Override
	protected void setResourceLimit2Request(HttpServletRequest request){
		String userId = (String) request.getAttribute("userId");
		String tenantId = (String)request.getAttribute("tenantId");
		JSONObject RedisOptions = redisService.getPaasRedisOptions(userId, tenantId);
		if(RedisOptions!=null){
			request.setAttribute("options", RedisOptions);
		}
	}

	@RequestMapping("/options")//实时rest请求查询redis配额信息
	@ResponseBody
	public JsonResponse queryRedisOptions(HttpServletRequest request, HttpServletResponse response){
		try{
			IUser user = WebUtil.getUserByRequest(request);
			String userId = user.getUserId();
			String tenantId = user.getTenantId();
			JSONObject RedisOptions = redisService.getPaasRedisOptions(userId, tenantId);
			return JsonResponse.success(RedisOptions);
		}catch(Exception e){
			logger.error("查询redis配额信息失败"+e.getMessage());
			return JsonResponse.failure(500, "查询redis配额信息失败");
		}
	}

	@RequestMapping("/save")//保存redis实例的操作
	@ResponseBody
	public JsonResponse addRedisSave(HttpServletRequest request, HttpServletResponse response){
		try{
			IUser user = WebUtil.getUserByRequest(request);
			String userId = user.getUserId();
			String tenantId = user.getTenantId();
			String redisName = request.getParameter("instanceName");
			String version = request.getParameter("version");
			String memory = request.getParameter("memory");
			String projectId = request.getParameter("projectId");
			String envId = request.getParameter("envId");
			String envType = request.getParameter("envType");
			String desc = request.getParameter("resDesc");
			String applyType = request.getParameter("applyType");
			if(StringUtil.isNull(applyType) || !"api".equals(applyType)&&!"app".equals(applyType)){
				applyType="paasOS";
			}
			if(StringUtil.isNull(redisName)|| StringUtil.isNull(tenantId)){
				return JsonResponse.failure(400, "新建reids资源失败,实例名和租户不能为空");
			}
			JSONObject RedisConfig = new JSONObject();
			PaasRedis redis = new PaasRedis();
			RedisConfig.put("name", redisName);
			RedisConfig.put("memory", memory);

			redis.setMemory(StorageUtil.getMemory(memory));

			RedisConfig.put("version", version);
			JSONObject attributes = new JSONObject();
			attributes.put("envId", envId);
			attributes.put("projectId", projectId);
			attributes.put("envType", envType);
			RedisConfig.put("attributes", attributes);

			redis.setRedisId(StringUtil.getUUID());
			redis.setRedisName(redisName);
			redis.setApplyContent(RedisConfig.toJSONString());
			redis.setCreater(userId);
			Date now = new Date();
			redis.setCreateDate(now);
			redis.setUpdateDate(now);
			redis.setAllocateContent("");
			redis.setTenantId(tenantId);
			redis.setProjectId(projectId);
			redis.setEnvId(envId);
			redis.setEnvType(envType);
			redis.setOnReady(false);
			redis.setResDesc(desc);
			redis.setApplyType(applyType);
			redisService.addPaasRedisResource(redis);
			logger.debug("成功添加redis实例,"+redisName);
			return JsonResponse.success(redis.getRedisId());
		}catch(Exception e){

			logger.error("添加redis实例失败"+e.getMessage(),e);
			return JsonResponse.failure(500, "新建redis资源失败"+e.getMessage());
		}
	}

	@RequestMapping("/delete")//删除redis的操作
	@ResponseBody
	public JsonResponse deleteRedis(HttpServletRequest request, HttpServletResponse response){
		try{
			IUser user = WebUtil.getUserByRequest(request);
			String redisId = request.getParameter("resId");
			String userId = user.getUserId();
			String tenantId = user.getTenantId();
			if(StringUtil.isNull(redisId)||StringUtil.isNull(tenantId)||StringUtil.isNull(userId)){
				logger.error("删除redis资源出错,resId/userId/tenantId参数为空");
				return JsonResponse.failure(500, "删除redis资源失败,resId/userId/tenantId参数为空");
			}
			JSONObject res = redisService.deletePaasRedisById(redisId,userId, tenantId);
			if(res.containsKey("result") && res.getString("result").equals("success")){
				logger.debug("删除redis资源"+redisId);
				return JsonResponse.success(redisId);
			}else{
				logger.error("删除redis资源操作失败"+redisId);
				return JsonResponse.failure(500, "删除redis资源失败");
			}
		}catch(Exception e){
			logger.error("删除redis资源操作失败"+e.getMessage());
			return JsonResponse.failure(500, "删除redis资源失败"+e.getMessage());
		}
	}

	@RequestMapping("/info")//查看redis详情页面
	public String RedisInfo(HttpServletRequest request, HttpServletResponse response){
		String redisId = request.getParameter("redisId");
		PaasRedis redisInfo = redisService.getPaasRedisInfoById(redisId);
		request.setAttribute("redisInfo", redisInfo);
		ConfigUtils.setEnvType2Request(request);
		return getUrlPrefix()+"/info";
	}

	@RequestMapping("/startRedis")
	@ResponseBody
	public JsonResponse startPassRedis(HttpServletRequest request, HttpServletResponse response){
		try{
			IUser user = WebUtil.getUserByRequest(request);
			String resId = request.getParameter("resId");
			String userId = user.getUserId();
			String tenantId = user.getTenantId();
			if(StringUtil.isNull(resId)||StringUtil.isNull(tenantId)||StringUtil.isNull(userId)){
				logger.error("启动redis出错,resId/userId/tenantId参数为空");
				return JsonResponse.failure(500, "启动redis失败,resId/userId/tenantId参数为空");
			}
			JSONObject res = redisService.startPaasRedis(resId,userId, tenantId);
			if(res.containsKey("result") && res.getString("result").equals("success")){
				logger.debug("成功启动redis--"+resId);
				return JsonResponse.success();
			}else{
				logger.error("启动redis失败"+resId);
				return JsonResponse.failure(500, "启动redis失败");
			}
		}catch(Exception e){
			logger.error("启动redis失败"+e.getMessage());
			return JsonResponse.failure(500, e.getMessage());
		}
	}

	@RequestMapping("/stopRedis")
	@ResponseBody
	public JsonResponse stopPassRedis(HttpServletRequest request, HttpServletResponse response){
		try{
			IUser user = WebUtil.getUserByRequest(request);
			String resId = request.getParameter("resId");
			String userId = user.getUserId();
			String tenantId = user.getTenantId();
			if(StringUtil.isNull(resId)||StringUtil.isNull(tenantId)||StringUtil.isNull(userId)){
				logger.error("停止Redis出错,resId/userId/tenantId参数为空");
				return JsonResponse.failure(500, "停止Redis失败,resId/userId/tenantId参数为空");
			}
			JSONObject res = redisService.stopPaasRedis(resId,userId, tenantId);
			if(res.containsKey("result") && res.getString("result").equals("success")){
				logger.debug("成功停止Redis--"+resId);
				return JsonResponse.success();
			}else{
				logger.error("停止Redis失败"+resId);
				return JsonResponse.failure(500, "停止Redis失败");
			}
		}catch(Exception e){
			logger.error("停止Redis失败"+e.getMessage());
			return JsonResponse.failure(500, e.getMessage());
		}
	}

	@RequestMapping("/getConfig")
	@ResponseBody
	public JsonResponse getMysqlConfig(HttpServletRequest request, HttpServletResponse response){
		try{
			IUser user = WebUtil.getUserByRequest(request);
			String userId = user.getUserId();
			String tenantId = user.getTenantId();
			String resId = request.getParameter("resId");
			return JsonResponse.success(redisService.getPaasRedisConfig(resId));
		}catch(Exception e){
			logger.error("获取redis配置出错---getConfig--"+e.getMessage());
			return JsonResponse.failure(500, e.getMessage());
		}
	}

	@RequestMapping("/getInstances")
	@ResponseBody
	public JsonResponse getRedisInstance(HttpServletRequest request, HttpServletResponse response){
		try{
			IUser user = WebUtil.getUserByRequest(request);
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("start", 0);
			params.put("size", 999999);
			//params.put("userId", user.getUserId());
			params.put("byTenantId", "true");
			params.put("tenantId", user.getTenantId());
			StringBuilder sb = new StringBuilder();
			JSONObject mys = redisService.queryPaasRedisWithStatus(params,sb);
			if(logger.isDebugEnabled()){
				logger.debug("统计redis实例及运行状态"+sb.toString());
			}
			return JsonResponse.success(mys);
		}catch(Exception e){
			logger.error("统计redis实例及运行状态出错"+e.getMessage());
			return JsonResponse.failure(500, e.getMessage());
		}
	}

}


text:
      Navigation(管理者)

        Dashboard

        Department

        Member

        Contract

      Navigation(使用者)

        Dashboard

        Contract


text:
from dataclasses import dataclass
from typing import Any, Callable, Sequence, NamedTuple, Any

from absl.testing import absltest

from flax.core import Scope, Array, init, apply, unfreeze, nn
import jax
from jax import numpy as jnp, random

from jax.scipy.linalg import expm

Initializer = Any
Flow = Any

@dataclass
class DenseFlow:
  kernel_init: Initializer = nn.linear.default_kernel_init
  bias_init: Initializer = nn.initializers.zeros

  def params(self, scope: Scope, features: int):
    kernel = scope.param('kernel', self.kernel_init, (features, features))
    bias = scope.param('bias', self.bias_init, (features,))
    return kernel, bias

  def forward(self, scope: Scope, x: Array):
    kernel, bias = self.params(scope, x.shape[-1])
    return jnp.dot(
      x, expm(kernel)) + bias.reshape((1,) * (x.ndim - 1) + (-1,))

  def backward(self, scope: Scope, y: Array):
    kernel, bias = self.params(scope, y.shape[-1])
    return jnp.dot(
      y - bias.reshape((1,) * (y.ndim - 1) + (-1,)), expm(-kernel))

@dataclass
class StackFlow:
  flows: Sequence[Flow]

  def forward(self, scope: Scope, x: Array):
    for i, f in enumerate(self.flows):
      x = scope.child(f.forward, name=str(i))(x)
    return x

  def backward(self, scope: Scope, x: Array):
    for i, f in reversed(tuple(enumerate(self.flows))):
      x = scope.child(f.backward, name=str(i))(x)
    return x

class FlowTest(absltest.TestCase):

  def test_flow(self):
    x = jnp.ones((1, 3))
    flow = StackFlow((DenseFlow(),) * 3)
    y, variables = init(flow.forward)(random.PRNGKey(0), x)
    param_shapes = unfreeze(
        jax.tree_util.tree_map(jnp.shape, variables['params']))
    self.assertEqual(y.shape, (1, 3))
    self.assertEqual(param_shapes, {
        '0': {'kernel': (3, 3), 'bias': (3,)},
        '1': {'kernel': (3, 3), 'bias': (3,)},
        '2': {'kernel': (3, 3), 'bias': (3,)},
    })
    x_restored = apply(flow.backward)(variables, y)
    self.assertTrue(jnp.allclose(x, x_restored))

if __name__ == '__main__':
  absltest.main()


text:
<?xml version="1.0"?>
<!--
  ~ Copyright (c) 2011-2014 The original author or authors
  ~
  ~  All rights reserved. This program and the accompanying materials
  ~  are made available under the terms of the Eclipse Public License v1.0
  ~  and Apache License v2.0 which accompanies this distribution.
  ~
  ~      The Eclipse Public License is available at
  ~      http://www.eclipse.org/legal/epl-v10.html
  ~
  ~      The Apache License v2.0 is available at
  ~      http://www.opensource.org/licenses/apache2.0.php
  ~
  ~  You may elect to redistribute this code under either of these licenses.
  -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>io.vertx</groupId>
    <artifactId>vertx-web-parent</artifactId>
    <version>4.4.0-SNAPSHOT</version>
  </parent>

  <artifactId>vertx-web-openapi</artifactId>

  <properties>
    <doc.skip>false</doc.skip>
    <junit5.version>5.7.0</junit5.version>
    <mockito.version>3.3.0</mockito.version>
    <assertj.version>3.15.0</assertj.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>io.vertx</groupId>
      <artifactId>vertx-web</artifactId>
    </dependency>
    <dependency>
      <groupId>io.vertx</groupId>
      <artifactId>vertx-web-validation</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>io.vertx</groupId>
      <artifactId>vertx-web-api-service</artifactId>
      <version>${project.version}</version>
      <scope>compile</scope>
      <optional>true</optional>
    </dependency>
    <dependency>
      <groupId>io.vertx</groupId>
      <artifactId>vertx-json-schema</artifactId>
    </dependency>
    <dependency>
      <groupId>org.yaml</groupId>
      <artifactId>snakeyaml</artifactId>
      <version>${snakeyaml.version}</version>
    </dependency>
    <!-- For docs -->
    <dependency>
      <groupId>io.vertx</groupId>
      <artifactId>vertx-auth-jwt</artifactId>
      <scope>provided</scope>
      <optional>true</optional>
    </dependency>
    <dependency>
      <groupId>io.vertx</groupId>
      <artifactId>vertx-auth-oauth2</artifactId>
      <scope>provided</scope>
      <optional>true</optional>
    </dependency>

    <!-- Testing dependencies -->
    <dependency>
      <groupId>io.vertx</groupId>
      <artifactId>vertx-web-validation</artifactId>
      <type>test-jar</type>
      <version>${project.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>io.vertx</groupId>
      <artifactId>vertx-web-client</artifactId>
      <version>${project.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>io.vertx</groupId>
      <artifactId>vertx-junit5</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter</artifactId>
      <version>${junit5.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.assertj</groupId>
      <artifactId>assertj-core</artifactId>
      <version>${assertj.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.7.21</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-core</artifactId>
      <version>${mockito.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-junit-jupiter</artifactId>
      <version>${mockito.version}</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
          <compilerArgument>-proc:none</compilerArgument>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.22.2</version>
        <configuration>
          <trimStackTrace>false</trimStackTrace>
          <additionalClasspathElements>
            <additionalClasspathElement>${basedir}/src/test/resources/jars/refs.jar</additionalClasspathElement>
            <additionalClasspathElement>${basedir}/src/test/resources/jars/specs.jar</additionalClasspathElement>
          </additionalClasspathElements>
        </configuration>
        <executions>
          <execution>
            <id>run-all-tests</id>
            <goals>
              <goal>test</goal>
            </goals>
          </execution>
          <execution>
            <id>run-all-tests-without-api-service</id>
            <goals>
              <goal>test</goal>
            </goals>
            <configuration>
              <excludes>
                <exclude>**/RouterBuilderApiServiceIntegrationTest.java</exclude>
              </excludes>
              <classpathDependencyExcludes>
                <exclude>io.vertx:vertx-web-api-service</exclude>
              </classpathDependencyExcludes>
            </configuration>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.bsc.maven</groupId>
        <artifactId>maven-processor-plugin</artifactId>
        <version>3.3.3</version>
        <executions>
          <execution>
            <id>generate-test-sources</id>
            <goals>
              <goal>process-test</goal>
            </goals>
            <phase>generate-test-sources</phase>
            <configuration>
              <processors>
                <processor>io.vertx.codegen.CodeGenProcessor</processor>
              </processors>
              <excludes>
                <exclude>**/*Test.java</exclude>
              </excludes>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>


text:
var utils = require('../util/utils'),
	dateUtils = require('../util/date-utils');

exports.login = function (req, res) {

	var message = utils.messageFactory(),
		params = {
			loginJSON : req.param('loginJSON')
		};

	if (!params.loginJSON) {
		utils.throwError(10, 'Missing login data.', res);
		return;
	}

	params.loginJSON = JSON.parse(params.loginJSON);

	var sql = "SELECT user.userToken, user.email, user.firstName, user.lastName, user.addDate," +
		"	preference.preferenceToken, preference.linkColumns, preference.tableWidth, preference.openLinkFrame," +
		"	preference.styleMask, preference.calendarWeeks, preference.aliasPage, preference.aliasPages," +
		"	preference.aliasCategory, preference.aliasCategories, preference.aliasLink, preference.aliasLinks\n" +
		"FROM user LEFT JOIN preference on user.user_id = preference.FK_user_id\n" +
		"WHERE user.email = '" + params.loginJSON.email + "'\n" +
		"	AND user.passwordMD5 = '" + params.loginJSON.passwordMD5 + "'";

	utils.connection.query(sql,
		function (error, rows) {
			if (error) {
				utils.throwError(10, 'Login Error: ' + error, res);
				return;
			}
			if (rows.length === 0) {
				utils.throwError(20, 'User not found in database.', res);
				return;
			}

			var user = {};
			rows.forEach(function (userRow) {
				user.userToken = userRow.userToken;
				user.sessionToken = utils.generateToken();
				user.email = userRow.email;
				user.firstName = userRow.firstName;
				user.lastName = userRow.lastName;
				user.addDate = userRow.addDate;
				user.prefs = {};
				user.prefs.alertViewDays = userRow.alertViewDays;
				user.prefs.aliasCategories = userRow.aliasCategories;
				user.prefs.aliasCategory = userRow.aliasCategory;
				user.prefs.aliasLink = userRow.aliasLink;
				user.prefs.aliasLinks = userRow.aliasLinks;
				user.prefs.aliasPage = userRow.aliasPage;
				user.prefs.aliasPages = userRow.aliasPages;
				user.prefs.calendarWeeks = userRow.calendarWeeks;
				user.prefs.linkColumns = userRow.linkColumns;
				user.prefs.openLinkFrame = userRow.openLinkFrame;
				user.prefs.searchCols = userRow.searchCols;
				user.prefs.searchEngines = userRow.searchEngines;
				user.prefs.showAlerts = userRow.showAlerts;
				user.prefs.showSearchLogos = userRow.showSearchLogos;
				user.prefs.styleMask = userRow.styleMask;
				user.prefs.tableWidth = userRow.tableWidth;
			});

			sql = "UPDATE user\n" +
				"SET sessionToken = '" + user.sessionToken + "'\n" +
				"WHERE userToken = '" + user.userToken + "'";

			utils.connection.query(sql,
				function (error) {
					if (error) {
						utils.throwError(30, 'Error: ' + error, res);
						return;
					} else {
						message.data = user;
						utils.jsonWriter(res, message);
					}
				}
			);
		}
	);
};

exports.getUserBySessionToken = function (req, res, routeCallback, sessionToken, callback) {

	var message = utils.messageFactory();

	if (req.param('sessionToken')) {
		sessionToken = req.param('sessionToken');
		console.log('sessionToken: ', sessionToken);
	}

	if (!sessionToken) {
		utils.throwError(40, 'Missing session token.', res);
		return;
	}

	var sql = "SELECT user.user_id, user.userToken, user.email, user.firstName, user.lastName, user.addDate," +
		"	preference.preferenceToken, preference.linkColumns, preference.tableWidth, preference.openLinkFrame," +
		"	preference.styleMask, preference.calendarWeeks, preference.aliasPage, preference.aliasPages," +
		"	preference.aliasCategory, preference.aliasCategories, preference.aliasLink, preference.aliasLinks\n" +
		"FROM user LEFT JOIN preference on user.user_id = preference.FK_user_id\n" +
		"WHERE user.sessionToken = '" + sessionToken + "'";

	utils.connection.query(sql,
		function (error, rows) {
			if (error) {
				utils.throwError(50, 'Get by session token Error: ' + error, res);
				return;
			}
			if (rows.length === 0) {
				utils.throwError(60, 'User not found by session token.', res);
				return;
			} else {
				var user = {};
				rows.forEach(function (userRow) {
					user.userID = userRow.user_id;
					user.userToken = userRow.userToken;
					user.sessionToken = utils.generateToken();
					user.email = userRow.email;
					user.firstName = userRow.firstName;
					user.lastName = userRow.lastName;
					user.addDate = userRow.addDate;
					user.prefs = {};
					user.prefs.alertViewDays = userRow.alertViewDays;
					user.prefs.aliasCategories = userRow.aliasCategories;
					user.prefs.aliasCategory = userRow.aliasCategory;
					user.prefs.aliasLink = userRow.aliasLink;
					user.prefs.aliasLinks = userRow.aliasLinks;
					user.prefs.aliasPage = userRow.aliasPage;
					user.prefs.aliasPages = userRow.aliasPages;
					user.prefs.calendarWeeks = userRow.calendarWeeks;
					user.prefs.linkColumns = userRow.linkColumns;
					user.prefs.openLinkFrame = userRow.openLinkFrame;
					user.prefs.searchCols = userRow.searchCols;
					user.prefs.searchEngines = userRow.searchEngines;
					user.prefs.showAlerts = userRow.showAlerts;
					user.prefs.showSearchLogos = userRow.showSearchLogos;
					user.prefs.styleMask = userRow.styleMask;
					user.prefs.tableWidth = userRow.tableWidth;
				});

				if (!!callback) {
					callback(user);
				} else {
					message.data = user;
					utils.jsonWriter(res, message);
				}
			}
		}
	);
};

exports.logout = function (req, res) {

	var message = utils.messageFactory(),
		params = {
			sessionToken : req.param('sessionToken')
		};

	if (!params.sessionToken) {
		utils.throwError(70, 'Missing session token.', res);
		return;
	}

	exports.getUserBySessionToken(req, res, null, params.sessionToken, function (user) {

		var sql = "UPDATE user\n" +
			"SET user.sessionToken = NULL\n" +
			"WHERE user.sessionToken = '" + params.sessionToken + "'";

		utils.connection.query(sql,
			function (error, rows) {
				if (error) {
					utils.throwError(80, 'Remove session token Error: ' + error, res);
					return;
				} else {
					message.data = '';
					utils.jsonWriter(res, message);
				}
			}
		);
	});
};

exports.prefsUpdate = function (req, res) {

	var message = utils.messageFactory(),
		sessionToken,
		params = {
			preferenceJSON : req.param('preferenceJSON')
		};

	if (!params.preferenceJSON) {
		utils.throwError(90, 'Missing session token or preferences JSON.', res);
		return;
	}
	var preference = JSON.parse(params.preferenceJSON);
	sessionToken = preference.sessionToken;

	exports.getUserBySessionToken(req, res, null, sessionToken, function (user) {

		user.editDate = dateUtils.formatDateForSQL(new Date());

		var sql = "UPDATE preference\n" +
			"SET \n" +
			"	preference.editDate = '" + user.editDate + "',\n" +
			"	preference.linkColumns = " + preference.linkColumns + ",\n" +
			"	preference.calendarWeeks = " + preference.calendarWeeks + "\n" +
			"WHERE preference.FK_user_id = " + user.userID + "";

		utils.connection.query(sql,
			function (error, rows) {
				if (error) {
					utils.throwError(80, 'Remove session token Error: ' + error, res);
					return;
				} else {
					message.data = 'Preferences updated.';
					utils.jsonWriter(res, message);
				}
			}
		);
	});
};


text:
<?php

namespace spec\Sylius\Bundle\OrderBundle\StateMachineCallback;

use PhpSpec\ObjectBehavior;
use Sylius\Component\Order\Model\OrderInterface;

class CompleteOrderCallbackSpec extends ObjectBehavior
{
    public function it_is_initializable()
    {
        $this->shouldHaveType('Sylius\Bundle\OrderBundle\StateMachineCallback\CompleteOrderCallback');
    }

    public function it_completes_order(OrderInterface $order)
    {
        $order->complete()->shouldBeCalled();

        $this->completeOrder($order);
    }
}


text:
import WarningIcon from '@mui/icons-material/Warning';
import CloseIcon from '@mui/icons-material/Close';
import * as React from 'react';
import Box from '@mui/joy/Box';
import Alert from '@mui/joy/Alert';
import IconButton from '@mui/joy/IconButton';
import Typography from '@mui/joy/Typography';
import Button from '@mui/joy/Button';

export default function AlertWithDangerState() {
  return (
    <Box sx={{ display: 'flex', gap: 2, width: '100%', flexDirection: 'column' }}>
      <Alert
        startDecorator={<WarningIcon sx={{ mx: 0.5 }} />}
        variant="soft"
        color="danger"
        endDecorator={
          <React.Fragment>
            <Button variant="soft" color="danger" sx={{ mr: 1 }}>
              Undo
            </Button>
            <IconButton variant="soft" size="sm" color="danger">
              <CloseIcon />
            </IconButton>
          </React.Fragment>
        }
      >
        <Typography color="danger" fontWeight="md">
          This file was successfully deleted
        </Typography>
      </Alert>
      <Alert
        startDecorator={<WarningIcon sx={{ mx: 0.5 }} />}
        variant="solid"
        color="danger"
        endDecorator={
          <React.Fragment>
            <Button variant="solid" color="danger" sx={{ mr: 1 }}>
              Undo
            </Button>
            <IconButton variant="solid" size="sm" color="danger">
              <CloseIcon />
            </IconButton>
          </React.Fragment>
        }
      >
        <Typography sx={{ color: 'white' }} fontWeight="md">
          This file was successfully deleted
        </Typography>
      </Alert>

      <Alert
        startDecorator={<WarningIcon sx={{ mx: 0.5 }} />}
        variant="outlined"
        color="danger"
        endDecorator={
          <React.Fragment>
            <Button variant="plain" color="danger" sx={{ mr: 1 }}>
              Undo
            </Button>
            <IconButton variant="soft" size="sm" color="danger">
              <CloseIcon />
            </IconButton>
          </React.Fragment>
        }
      >
        <Typography color="danger" fontWeight="md">
          This file was successfully deleted
        </Typography>
      </Alert>
    </Box>
  );
}


text:
// We only need to import the modules necessary for initial render
import CoreLayout from "../layouts/CoreLayout";
import Home from "./Home";
import AboutRoute from "./About";
import CounterRoute from "./Counter";
import LoginRoute from "./Login";
import ContactRoute from "./Contact";
import ResetPasswordRoute from "./ResetPassword";
import SignupRoute from "./Signup";
const _ = require('lodash')

const DEFAULT_LAYOUT = CoreLayout
const LAYOUT_MAP = _.mapKeys({
  login: null
}, (layout, path) => '/' + path);

export const createRoutes = (store) => {
  return {
    path: '/',
    getComponent(nextState, cb){
      const pathname = nextState.location.pathname
      const path = pathname.startsWith('/') ? pathname : '/' + pathname
      const Layout = LAYOUT_MAP[path] === undefined ? DEFAULT_LAYOUT : LAYOUT_MAP[path]
      cb(null, Layout)
    },
    indexRoute: Home(store),
    childRoutes: [
      AboutRoute(store),
      CounterRoute(store),
      LoginRoute(store),
      ContactRoute(store),
      ResetPasswordRoute(store),
      SignupRoute(store),
    ]
  }
}

/*  Note: childRoutes can be chunked or otherwise loaded programmatically
 using getChildRoutes with the following signature:

 getChildRoutes (location, cb) {
 require.ensure([], (require) => {
 cb(null, [
 // Remove imports!
 require('./Counter').default(store)
 ])
 })
 }

 However, this is not necessary for code-splitting! It simply provides
 an API for async route definitions. Your code splitting should occur
 inside the route `getComponent` function, since it is only invoked
 when the route exists and matches.
 */

export default createRoutes