text:
#ifndef __CLOCK_540XX_H_
#define __CLOCK_540XX_H_

#ifdef __cplusplus
extern "C" {
#endif

/** @defgroup CLOCK_540XX CHIP: LPC540XX Clock Driver
 * @ingroup CHIP_540XX_Drivers
 * @{
 */

/* Internal oscillator frequency */
#define SYSCTL_IRC_FREQ     (12000000)
#define SYSCTL_WDTOSC_FREQ  (500000)
#define SYSCTL_RTC_FREQ     (32000)

/**
 * Clock sources for system PLLs
 */
typedef enum CHIP_SYSCTL_PLLCLKSRC {
	SYSCTL_PLLCLKSRC_IRC = 0,		/*!< Internal oscillator */
	SYSCTL_PLLCLKSRC_CLKIN, 		/*!< Crystal (system) oscillator */
	SYSCTL_PLLCLKSRC_WDTOSC, 		/*!< WDT oscillator */
	SYSCTL_PLLCLKSRC_RTC, 			/*!< RTC oscillator */
} CHIP_SYSCTL_PLLCLKSRC_T;

/**
 * System and peripheral clocks enum
 */
typedef enum CHIP_SYSCTL_CLOCK {
	/* Peripheral clock enables for SYSAHBCLKCTRL0 */
	SYSCTL_CLOCK_SYS = 0,				/*!< System clock */
	SYSCTL_CLOCK_ROM,					/*!< ROM clock */
	SYSCTL_CLOCK_SRAM1 = 3,				/*!< SRAM1 clock */
	SYSCTL_CLOCK_SRAM2,					/*!< SRAM2 clock */
	SYSCTL_CLOCK_FLASH = 7,				/*!< FLASH controller clock */
	SYSCTL_CLOCK_FMC, 				/*!< FMC clock */
	SYSCTL_CLOCK_MUX = 11,				/*!< Input mux clock */
	SYSCTL_CLOCK_IOCON = 13,		/*!< IOCON clock */
	SYSCTL_CLOCK_GPIO0,					/*!< GPIO0 clock */
	SYSCTL_CLOCK_GPIO1,					/*!< GPIO1 clock */
	SYSCTL_CLOCK_PININT = 18,			/*!< PININT clock */
	SYSCTL_CLOCK_GINT,					/*!< grouped pin interrupt block clock */
	SYSCTL_CLOCK_DMA,					/*!< DMA clock */
	SYSCTL_CLOCK_CRC,					/*!< CRC clock */
	SYSCTL_CLOCK_WWDT,				/*!< WDT clock */
	SYSCTL_CLOCK_RTC,					/*!< RTC clock */
	SYSCTL_CLOCK_MBOX = 26,				/*!< Mailbox clock */
	SYSCTL_CLOCK_ADC0,				/*!< ADC0 clock */

	/* Peripheral clock enables for SYSAHBCLKCTRL1 */
	SYSCTL_CLOCK_MRT = 32,				    /*!< multi-rate timer clock */
	SYSCTL_CLOCK_OSTIMER,					    /*!< OS timer clock */
	SYSCTL_CLOCK_SCT0,		            /*!< SCT0 clock */
	SYSCTL_CLOCK_VFIFO = 32 + 9,	    /*!< VFIFO clock */
	SYSCTL_CLOCK_UTICK,					      /*!< UTICK clock */
	SYSCTL_CLOCK_CTIMER2 = 32 + 22,	  /*!< CTIMER2 clock */
	SYSCTL_CLOCK_CTIMER3 = 32 + 26,		/*!< CTIMER3 clock */
	SYSCTL_CLOCK_CTIMER4,		          /*!< CTIMER4 clock */
	SYSCTL_CLOCK_PVT,					        /*!< PVT clock */
	SYSCTL_CLOCK_BODY_BIAS,					  /*!< Body Bias clock */
	SYSCTL_CLOCK_EZH_A,			          /*!< EZH_A clock */
	SYSCTL_CLOCK_EZH_B,			          /*!< EZH_B clock */
} CHIP_SYSCTL_CLOCK_T;

/**
 * System and peripheral clocks enum
 */
typedef enum CHIP_ASYNC_SYSCTL_CLOCK {
	/* Peripheral clock enables for SYSAHBCLKCTRL0 */
	ASYNC_SYSCTL_CLOCK_UART0 = 1,			/*!< UART0 clock */
	ASYNC_SYSCTL_CLOCK_UART1,					/*!< UART1 clock */
	ASYNC_SYSCTL_CLOCK_UART2,				  /*!< UART2 clock */
	ASYNC_SYSCTL_CLOCK_UART3,					/*!< UART3 clock */
	ASYNC_SYSCTL_CLOCK_I2C0,			 	  /*!< I2C0  clock */
	ASYNC_SYSCTL_CLOCK_I2C1, 				  /*!< I2C1  clock */
	ASYNC_SYSCTL_CLOCK_I2C2,				  /*!< I2C2  clock */
	ASYNC_SYSCTL_CLOCK_SPI0 = 9,			/*!< SPI0  clock */
	ASYNC_SYSCTL_CLOCK_SPI1,					/*!< SPI1  clock */
	ASYNC_SYSCTL_CLOCK_SPI2,			    /*!< SPI2  clock */
	ASYNC_SYSCTL_CLOCK_CTIMER0 = 13,	/*!< CTIMER0 clock */
	ASYNC_SYSCTL_CLOCK_CTIMER1,				/*!< CTIMER1 clock */
	ASYNC_SYSCTL_CLOCK_FRG,					  /*!< FRG clock */
} CHIP_ASYNC_SYSCTL_CLOCK_T;

/**
 * Clock sources for CLKOUT
 */
typedef enum CHIP_SYSCTL_CLKOUTSRC {
	SYSCTL_CLKOUTSRC_MAINSYSCLK = 0,	/*!< Main system clock for CLKOUT */
	SYSCTL_CLKOUTSRC_CLKIN,		  /*!< CLKIN for CLKOUT */
	SYSCTL_CLKOUTSRC_WDTOSC,		/*!< Watchdog oscillator for CLKOUT */
	SYSCTL_CLKOUTSRC_IRC,		    /*!< Internal oscillator for CLKOUT */
	SYSCTL_CLKOUTSRCA_OUTPUT,		  /*!< clkoutA output route to input of clkoutB */
	SYSCTL_CLKOUTSRC_RTC = 7				  /*!< RTC oscillator 32KHz output */
} CHIP_SYSCTL_CLKOUTSRC_T;

/* SYS PLL related bit fields */
#define SYS_PLL_BYPASS_PLL(d)    (d<<15)
#define SYS_PLL_BYPASS_FBDIV2(d) (d<<16)
#define SYS_PLL_LIMUPOFF(d) (d<<17)
#define SYS_PLL_BANDSEL(d)  (d<<18)
#define SYS_PLL_DIRECTI(d)  (d<<19)
#define SYS_PLL_DIRECTO(d)  (d<<20)
#define SYS_PLL_INSELR(d)   ((d&0xf)<<0)
#define SYS_PLL_INSELI(d)   ((d&0x3f)<<4)
#define SYS_PLL_INSELP(d)   ((d&0x1f)<<10)

/**
 * Clock source selections for only the main A system clock. The main A system
 * clock is used as an input into the main B system clock selector. Main clock A
 * only needs to be setup if the main clock A input is used in the main clock
 * system selector.
 */
typedef enum CHIP_SYSCTL_MAIN_A_CLKSRC {
	SYSCTL_MAIN_A_CLKSRC_IRC = 0,		/*!< Internal oscillator */
	SYSCTL_MAIN_A_CLKSRCA_CLKIN,		/*!< Crystal (main) oscillator in */
	SYSCTL_MAIN_A_CLKSRCA_WDTOSC,		/*!< Watchdog oscillator rate */
} CHIP_SYSCTL_MAIN_A_CLKSRC_T;

/**
 * @brief	Set main A system clock source
 * @param	src	: Clock source for main A
 * @return	Nothing
 * @note	This function only neesd to be setup if main clock A will be
 * selected in the Chip_Clock_GetMain_B_ClockRate() function.
 */
STATIC INLINE void Chip_Clock_SetMain_A_ClockSource(CHIP_SYSCTL_MAIN_A_CLKSRC_T src)
{
	LPC_SYSCTL->MAINCLKSELA = (uint32_t) src;
}

/**
 * @brief   Returns the main A clock source
 * @return	Returns which clock is used for the main A
 */
STATIC INLINE CHIP_SYSCTL_MAIN_A_CLKSRC_T Chip_Clock_GetMain_A_ClockSource(void)
{
	return (CHIP_SYSCTL_MAIN_A_CLKSRC_T) (LPC_SYSCTL->MAINCLKSELA);
}
/**
 * @brief	Return main A clock rate
 * @return	main A clock rate in Hz
 */
uint32_t Chip_Clock_GetMain_A_ClockRate(void);

/**
 * Clock sources for only main B system clock
 */
typedef enum CHIP_SYSCTL_MAIN_B_CLKSRC {
	SYSCTL_MAIN_B_CLKSRC_MAINCLKSELA = 0,	/*!< main clock A */
	SYSCTL_MAIN_B_CLKSRC_SYSPLLIN,			/*!< System PLL input */
	SYSCTL_MAIN_B_CLKSRC_SYSPLLOUT,			/*!< System PLL output */
	SYSCTL_MAIN_B_CLKSRC_RTC,				/*!< RTC oscillator 32KHz output */
} CHIP_SYSCTL_MAIN_B_CLKSRC_T;

/**
 * @brief	Set main B system clock source
 * @param	src	: Clock source for main B
 * @return	Nothing
 */
STATIC INLINE void Chip_Clock_SetMain_B_ClockSource(CHIP_SYSCTL_MAIN_B_CLKSRC_T src)
{
	LPC_SYSCTL->MAINCLKSELB = (uint32_t) src;
}

/**
 * @brief   Returns the main B clock source
 * @return	Returns which clock is used for the main B
 */
STATIC INLINE CHIP_SYSCTL_MAIN_B_CLKSRC_T Chip_Clock_GetMain_B_ClockSource(void)
{
	return (CHIP_SYSCTL_MAIN_B_CLKSRC_T) (LPC_SYSCTL->MAINCLKSELB);
}

/**
 * @brief	Return main B clock rate
 * @return	main B clock rate
 */
uint32_t Chip_Clock_GetMain_B_ClockRate(void);

/**
 * Clock source selections for the AsyncSyscon A system clock. The AsyncSyscon A system
 * clock is used as an input into the AsyncSyscon B system clock selector. AsyncSyscon clock A
 * only needs to be setup if the AsyncSyscon A input is used in the AsyncSyscon clock
 * system selector.
 */
typedef enum CHIP_ASYNC_SYSCTL_A_SRC {
	ASYNC_SYSCTL_IRC,		        /*!< IRC or RingOSC input (TBD) */
	ASYNC_SYSCTL_WDTOSC,		    /*!< external CLK input */
} CHIP_ASYNC_SYSCTL_A_SRC_T;

/**
 * @brief	Set AsyncSyscon A system clock source
 * @param	src	: Clock source for AsyncSyscon A
 * @return	Nothing
 * @note	This function only neesd to be setup if AsyncSyscon clock A will be
 * selected in the Chip_Clock_GetAsyncSyscon_B_ClockRate() function.
 */
STATIC INLINE void Chip_Clock_SetAsyncSyscon_A_ClockSource(CHIP_ASYNC_SYSCTL_A_SRC_T src)
{
	LPC_ASYNC_SYSCTL->ASYNCVPBCLKSELA = (uint32_t) src;
}

/**
 * @brief   Returns the AsyncSyscon A clock source
 * @return	Returns which clock is used for the AsyncSyscon A
 */
STATIC INLINE CHIP_ASYNC_SYSCTL_A_SRC_T Chip_Clock_GetAsyncSyscon_A_ClockSource(void)
{
	return (CHIP_ASYNC_SYSCTL_A_SRC_T) (LPC_ASYNC_SYSCTL->ASYNCVPBCLKSELA);
}
/**
 * @brief	Return AsyncSyscon A clock rate
 * @return	AsyncSyscon A clock rate in Hz
 */
uint32_t Chip_Clock_GetAsyncSyscon_A_ClockRate(void);

/**
 * Clock sources for only AsyncSyscon B system clock
 */
typedef enum CHIP_ASYNC_SYSCTL_B_SRC {
	ASYNC_SYSCTL_MAINCLK = 0,		/*!< Internal oscillator */
	ASYNC_SYSCTL_CLKIN,		      /*!< external CLK input */
	ASYNC_SYSCTL_PLLOUT,		    /*!< PLL output */
	ASYNC_SYSCTL_A_OUTPUT,		  /*!< output from ASYNC APBCLKSEL_A */
} CHIP_ASYNC_SYSCTL_B_SRC_T;

/**
 * @brief	Set AsyncSyscon B system clock source
 * @param	src	: Clock source for AsyncSyscon B
 * @return	Nothing
 */
STATIC INLINE void Chip_Clock_SetAsyncSyscon_B_ClockSource(CHIP_ASYNC_SYSCTL_B_SRC_T src)
{
	LPC_ASYNC_SYSCTL->ASYNCVPBCLKSELB = (uint32_t) src;
}

/**
 * @brief   Returns the AsyncSyscon B clock source
 * @return	Returns which clock is used for the AsyncSyscon B
 */
STATIC INLINE CHIP_ASYNC_SYSCTL_B_SRC_T Chip_Clock_GetAsyncSyscon_B_ClockSource(void)
{
	return (CHIP_ASYNC_SYSCTL_B_SRC_T) (LPC_ASYNC_SYSCTL->ASYNCVPBCLKSELB);
}

/**
 * @brief	Return main B clock rate
 * @return	main B clock rate
 */
uint32_t Chip_Clock_GetAsyncSyscon_B_ClockRate(void);

/**
 * Clock sources for ADC asynchronous clock source select
 */
typedef enum CHIP_SYSCTL_ADCASYNCCLKSRC {
	SYSCTL_ADCASYNCCLKSRC_MAINCLK = 0, 	  /*!< Main clock */
	SYSCTL_ADCASYNCCLKSRC_SYSPLLOUT,      /*!< PLL output */
	SYSCTL_ADCASYNCCLKSRC_IRC             /*!< Internal oscillator */
}
CHIP_SYSCTL_ADCASYNCCLKSRC_T;

/**
 * @brief	Set the ADC asynchronous clock source
 * @param	src	: ADC asynchronous clock source
 * @return	Nothing
 */
STATIC INLINE void Chip_Clock_SetADCASYNCSource(CHIP_SYSCTL_ADCASYNCCLKSRC_T src)
{
	LPC_SYSCTL->ADCASYNCCLKSEL = (uint32_t) src;
}

/**
 * @brief   Returns the ADC asynchronous clock source
 * @return	Returns which clock is used for the ADC asynchronous clock source
 */
STATIC INLINE CHIP_SYSCTL_ADCASYNCCLKSRC_T Chip_Clock_GetADCASYNCSource(void)
{
	return (CHIP_SYSCTL_ADCASYNCCLKSRC_T) (LPC_SYSCTL->ADCASYNCCLKSEL);
}

/**
 * @brief	Set the ADC asynchronous clock source
 * @param	src	: ADC asynchronous clock source
 * @return	Nothing
 */
STATIC INLINE void Chip_Clock_SetADCASYNCDivider(uint32_t div)
{
	LPC_SYSCTL->ADCASYNCCLKDIV = (uint32_t) div;
}

/**
 * @brief	Get the ADC asynchronous clock source
 * @param	src	: ADC asynchronous clock source
 * @return	Nothing
 */
STATIC INLINE uint32_t Chip_Clock_GetADCASYNCDivider(void)
{
	return (LPC_SYSCTL->ADCASYNCCLKDIV);
}

/**
 * @brief	Return ADC asynchronous clock rate
 * @return	ADC asynchronous clock rate
 */
uint32_t Chip_Clock_GetADCASYNCRate(void);

/**
 * Clock sources for main system clock. This is a mix of both main clock A
 * and B seelctions.
 */
typedef enum CHIP_SYSCTL_MAINCLKSRC {
	SYSCTL_MAINCLKSRC_IRC = 0,			/*!< Internal oscillator */
	SYSCTL_MAINCLKSRC_CLKIN,			  /*!< Crystal (main) oscillator in */
	SYSCTL_MAINCLKSRC_WDTOSC,			  /*!< Watchdog oscillator rate */
	SYSCTL_MAINCLKSRCA_OUTPUT,		  /*!< MainclkA output route to input of MainclkB */
	SYSCTL_MAINCLKSRC_PLLIN,		    /*!< System PLL input */
	SYSCTL_MAINCLKSRC_PLLOUT,		    /*!< System PLL output */
	SYSCTL_MAINCLKSRC_RTC,				  /*!< RTC oscillator 32KHz output */
} CHIP_SYSCTL_MAINCLKSRC_T;

/**
 * Clock sources for AsyncSyscon system clock. This is a mix of both AsyncSyscon clock A
 * and B seelctions.
 */
typedef enum CHIP_SYSCTL_ASYNCSYSCONCLKSRC {
	ASYNC_SYSCTL_CLOCK_MAINCLK = 0,		    /*!< MainclkA output route to input of AsyncSysconClkB */
	ASYNC_SYSCTL_CLOCK_CLKIN,		          /*!< CLKIN input */
	ASYNC_SYSCTL_CLOCK_PLLOUT,		        /*!< System PLL output */
	ASYNC_SYSCTL_CLOCK_A_OUTPUT,				  /*!< ASYNC SYSCTRL A OUTPUT to ASYNC SYSCTRL B INPUT */
	ASYNC_SYSCTL_CLOCK_IRC,		    	      /*!< Internal oscillator */
	ASYNC_SYSCTL_CLOCK_WDTOSC,			      /*!< WDT oscillator in */
} CHIP_SYSCTL_ASYNCSYSCONCLKSRC_T;

/**
 * @brief	Set system clock divider
 * @param	div	: divider for system clock
 * @return	Nothing
 * @note	Use 0 to disable, or a divider value of 1 to 255. The system clock
 * rate is the main system clock divided by this value.
 */
STATIC INLINE void Chip_Clock_SetSysClockDiv(uint32_t div)
{
	LPC_SYSCTL->SYSAHBCLKDIV  = div;
}

/**
 * @brief	Set UART divider clock
 * @param	div	: divider for UART clock
 * @return	Nothing
 * @note	Use 0 to disable, or a divider value of 1 to 255. The UART clock
 * rate is the main system clock divided by this value.
 */
STATIC INLINE void Chip_Clock_SetAsyncSysconClockDiv(uint32_t div)
{
	LPC_ASYNC_SYSCTL->ASYNCCLKDIV = div;
}

/**
 * @brief	Return UART divider
 * @return	divider for UART clock
 * @note	A value of 0 means the clock is disabled.
 */
STATIC INLINE uint32_t Chip_Clock_GetAsyncSysconClockDiv(void)
{
	return LPC_ASYNC_SYSCTL->ASYNCCLKDIV;
}

/**
 * @brief	Set The USART Fractional Generator Multiplier
 * @param   mult  :  An 8-bit value (0-255) U_PCLK = UARTCLKDIV/(1 + MULT/256)
 * @return	Nothing
 */
STATIC INLINE void Chip_SYSCTL_SetUSARTFRGCtrl(uint8_t mult, uint8_t div)
{
	LPC_ASYNC_SYSCTL->FRGCTRL = (uint32_t) ((mult<<8)|div);
}

/**
 * @brief	Get The USART Fractional Generator Multiplier
 * @return	Value of USART Fractional Generator Multiplier
 */
STATIC INLINE uint32_t Chip_SYSCTL_GetUSARTFRGCtrl(void)
{
	return LPC_ASYNC_SYSCTL->FRGCTRL;
}

/**
 * @brief	Returns the internal oscillator (IRC) clock rate
 * @return	internal oscillator (IRC) clock rate
 */
STATIC INLINE uint32_t Chip_Clock_GetIntOscRate(void)
{
	return SYSCTL_IRC_FREQ;
}

/**
 * @brief	Returns the external clock input rate
 * @return	External clock input rate
 */
STATIC INLINE uint32_t Chip_Clock_GetExtClockInRate(void)
{
	return ExtClockIn;
}

/**
 * @brief	Enable the RTC 32KHz output
 * @return	Nothing
 * @note	This clock can be used for the main clock directly, but
 *			do not use this clock with the system PLL.
 */
STATIC INLINE void Chip_Clock_EnableRTCOsc(void)
{
	LPC_SYSCTL->RTCOSCCTRL  = 1;
}

/**
 * @brief	Disable the RTC 32KHz output
 * @return	Nothing
 */
STATIC INLINE void Chip_Clock_DisableRTCOsc(void)
{
	LPC_SYSCTL->RTCOSCCTRL  = 0;
}

/**
 * @brief	Set System PLL clock source
 * @param	src	: Clock source for system PLL
 * @return	Nothing
 * @note	This function will also toggle the clock source update register
 * to update the clock source
 */
void Chip_Clock_SetSystemPLLSource(CHIP_SYSCTL_PLLCLKSRC_T src);

/**
 * @brief	Set main system clock source
 * @param	src	: Clock source for main system
 * @return	Nothing
 * @note	This function will also toggle the clock source update register
 * to update the clock source
 */
void Chip_Clock_SetMainClockSource(CHIP_SYSCTL_MAINCLKSRC_T src);

/**
 * @brief	Get main system clock source
 * @return	Clock source for main system
 * @note
 */
CHIP_SYSCTL_MAINCLKSRC_T Chip_Clock_GetMainClockSource( void );

/**
 * @brief	Set AsyncSyscon clock source
 * @param	src	: Clock source for AsyncSyscon system
 * @return	Nothing
 * @note	This function will also toggle the clock source update register
 * to update the clock source
 */
void Chip_Clock_SetAsyncSysconClockSource(CHIP_SYSCTL_ASYNCSYSCONCLKSRC_T src);

/**
 * @brief	Set CLKOUT clock source and divider
 * @param	src	: Clock source for CLKOUT
 * @param	div	: divider for CLKOUT clock
 * @return	Nothing
 * @note	Use 0 to disable, or a divider value of 1 to 255. The CLKOUT clock
 * rate is the clock source divided by the divider. This function will
 * also toggle the clock source update register to update the clock
 * source.
 */
void Chip_Clock_SetCLKOUTSource(CHIP_SYSCTL_CLKOUTSRC_T src, uint32_t div);

/**
 * @brief	Enable a system or peripheral clock
 * @param	clk	: Clock to enable
 * @return	Nothing
 */
void Chip_Clock_EnablePeriphClock(CHIP_SYSCTL_CLOCK_T clk);

/**
 * @brief	Disable a system or peripheral clock
 * @param	clk	: Clock to disable
 * @return	Nothing
 */
void Chip_Clock_DisablePeriphClock(CHIP_SYSCTL_CLOCK_T clk);

/**
 * @brief	Enable async peripheral clock
 * @param	clk	: Clock to enable
 * @return	Nothing
 */
void Chip_Clock_EnableAsyncPeriphClock(CHIP_ASYNC_SYSCTL_CLOCK_T clk);

/**
 * @brief	Disable async peripheral clock
 * @param	clk	: Clock to disable
 * @return	Nothing
 */
void Chip_Clock_DisableAsyncPeriphClock(CHIP_ASYNC_SYSCTL_CLOCK_T clk);

/**
 * @brief	Return System PLL input clock rate
 * @return	System PLL input clock rate
 */
uint32_t Chip_Clock_GetSystemPLLInClockRate(void);

/**
 * @brief	Return System PLL output clock rate
 * @return	System PLL output clock rate
 */
uint32_t Chip_Clock_GetSystemPLLOutClockRate(void);

/**
 * @brief	Return main clock rate
 * @return	main clock rate
 */
uint32_t Chip_Clock_GetMainClockRate(void);

/**
 * @brief	Return system clock rate
 * @return	system clock rate
 */
uint32_t Chip_Clock_GetSystemClockRate(void);

/**
 * @brief	Return Async Syscon clock rate
 * @return	Async syscon clock rate
 */
uint32_t Chip_Clock_GetAsyncSysconClockRate(void);

/**
 * @brief	Returns the RTC clock rate
 * @return	RTC oscillator clock rate in Hz
 */
STATIC INLINE uint32_t Chip_Clock_GetRTCOscRate(void)
{
	return SYSCTL_RTC_FREQ;
}

/**
 * @brief	Return estimated watchdog oscillator rate
 * @return	Estimated watchdog oscillator rate
 * @note	This rate is accurate to plus or minus 40%.
 */
STATIC INLINE uint32_t Chip_Clock_GetWDTOSCRate(void)
{
	return SYSCTL_WDTOSC_FREQ;
}

/**
 * @brief	Set PLL output based on the multiplier and input frequency
 * @param	multiply_by	: multiplier
 * @param	input_freq	: Clock input frequency of the PLL
 * @return	Nothing
 * @note	Note the input clock must be greater than 2MHz.
 */
void Chip_Clock_SetupSystemPLL(uint32_t multiply_by, uint32_t input_freq);

/**
 * @brief	Check if PLL is locked or not
 * @param	None
 * @return	true or false
 */
bool Chip_Clock_IsSystemPLLLocked(void);

/**
 * @}
 */

#ifdef __cplusplus
}
#endif

#endif /* __CLOCK_540XX_H_ */


text:
There are several design patterns that are repeated throughout
the repository.  This guide is meant to supplement the
[TypeScript Style Guide](https://github.com/jupyterlab/jupyterlab/wiki/TypeScript-Style-Guide).

## TypeScript

TypeScript is used in all of the source code.  TypeScript is used because
it provides features from the most recent EMCAScript 6 standards, while
providing type safety.  The TypeScript compiler eliminates an entire class
of bugs, while making it much easier to refactor code.

## Initialization Options

Objects will typically have an `IOptions` interface for
initializing the widget.  The use of this interface allows options
to be later added while preserving backward compatibility.

## ContentFactory Option

A common option for a widget is a `IContentFactory`, which is used to
customize the child content in the widget.
If not given, a `defaultRenderer` instance is used if no arguments are
required.  In this way, widgets can be customized
without subclassing them, and widgets can support customization
of their nested content.

## Static Namespace

An object class will typically have an exported static namespace
sharing the same name as the object.  The namespace is used
to declutter the class definition.

## Private Module Namespace

The "Private" module namespace is used to group variables and
functions that are not intended to be exported and may have
otherwise existed as module-level variables and functions.
The use of the namespace also makes it clear when a variable access
is to an imported name or from the module itself.  Finally,
the namespace allows the entire section to be collapsed in
an editor if desired.

## Disposables

JavaScript does not support "destructors", so the `IDisposable`
pattern is used to ensure resources are freed and can be claimed by the
Garbage Collector when no longer needed.  It should always be safe to
`dispose()` of an object more than once.  Typically the object that
creates another object is responsible for calling the dispose method
of that object unless explicitly stated otherwise.
To mirror the pattern  of construction, `super.dispose()` should be called
last in the `dispose()` method if there is a parent class.
Make sure any signal connections are cleared in either the local or parent
`dispose()` method.  Use a sentinel value to guard against reentry, typically
by checking if an internal value is null, and then immediately setting the
value to null.  A subclass should never override the `isDisposed` getter,
because it short-circuits the parent class getter.  The object should not
be considered disposed until the base class `dispose()` method is called.

## Messages

Messages are intended for many-to-one communication where outside objects
influence another object.  Messages can be conflated and processed
as a single message.  They can be posted and handled on the next animation
frame.

## Signals

Signals are intended for one-to-many communication where outside objects
react to changes on another object.  Signals are always emitted with
the sender as the first argument, and contain a single second argument
with the payload.  Signals should generally not be used to trigger the
"default" behavior for an action, but to allow others to trigger additional
behavior.  If a "default" behavior is intended to be provided by another
object, then a callback should be provided by that object.  Wherever possible
as signal connection should be made with the pattern
`.connect(this._onFoo, this)`.  Providing the `this` context allows the
connection to be properly cleared by `clearSignalData(this)`.  Using a
private method avoids allocating a closure for each connection.

## Models

Some of the more advanced widgets have a model associated with them.
The common pattern used is that the model is settable and must be set
outside of the constructor.  This means that any consumer of the widget
must account for a model that may be `null`, and may change at any time.
The widget should emit a `modelChanged` signal to allow consumers to
handle a change in model.  The reason to allow a model to swap is that
the same widget could be used to display different model content
while preserving the widget's location in the application.  The reason
the model cannot be provided in the constructor is the initialization
required for a model may have to call methods that are subclassed.
The subclassed methods would be called before the subclass constructor has
finished evaluating, resulting in undefined state.

## Getters vs. Methods

Prefer a method when the return value must be computed each time.
Prefer a getter for simple attribute lookup.
A getter should yield the same value every time.

## Data Structures

For public API, we have three options: JavaScript `Array`,
`IIterator`, and `ReadonlyArray` (an interface defined by TypeScript).

Prefer an `Array` for:
- A value that is meant to be mutable.

Prefer a `ReadonlyArray`
- A return value is the result of a newly allocated array, to avoid the
extra allocation of an iterator.
- A signal payload - since it will be consumed by multiple listeners.
- The values may need to be accessed randomly.
- A public attribute that is inherently static.

Prefer an `IIterator` for:
- A return value where the value is based on an internal data structure but
the value should not need to be accessed randomly.
- A set of return values that can be computed lazily.

## DOM Events

If an object instance should respond to DOM events, create a `handleEvent`
method for the class and register the object instance as the event handler. The
`handleEvent` method should switch on the event type and could call private
methods to carry out the actions. Often a widget class will add itself as an
event listener to its own node in the `onAfterAttach` method with something like
`this.node.addEventListener('mousedown', this)` and unregister itself in the
`onBeforeDetach` method with `this.node.removeEventListener('mousedown', this)`
Dispatching events from the `handleEvent` method makes it easier to trace, log,
and debug event handling. For more information about the `handleEvent` method,
see the [EventListener](https://developer.mozilla.org/en-US/docs/Web/API/EventListener)
API.

## Promises
We use Promises for asynchronous function calls, and a shim
for browsers that do not support them.  When handling a resolved or
rejected Promise, make sure to check for the current state (typically
by checking an `.isDisposed` property) before proceeding.

redpajama_set_name: RedPajamaGithub


text:
Nim ECDSA
======

This is intended to be an easy-to-use implementation of ECDSA cryptography
implemented only in Nim and released under the MIT license.

License
-------

Nim ECDSA is made available under the terms of the MIT License. Please see the
LICENSE file for more details.

Installation
------------

    $ nimble install ecdsa


text:
import { StackScreenProps } from "@react-navigation/stack"
import { ArtworkFilterNavigationStack } from "app/Components/ArtworkFilter"
import { ArtworksFiltersStore } from "app/Components/ArtworkFilter/ArtworkFilterStore"
import { ArtistIDsArtworksOptionsScreen } from "./ArtistIDsArtworksOptions"
import { ArtistIDsSaleArtworksOptionsScreen } from "./ArtistIDsSaleArtworksOptionsScreen"

export const ArtistIDsOptionsScreen = (
  props: StackScreenProps<ArtworkFilterNavigationStack, "ArtistIDsOptionsScreen">
) => {
  const filterType = ArtworksFiltersStore.useStoreState((state) => state.filterType)

  // TODO: Replace newSaleArtwork when AREnableArtworksConnectionForAuction is released
  if (filterType === "saleArtwork" || filterType === "newSaleArtwork") {
    return <ArtistIDsSaleArtworksOptionsScreen {...props} />
  }
  return <ArtistIDsArtworksOptionsScreen {...props} />
}


text:
<?php

/*
 * This file is part of Apostrophe
 * (c) 2009 P'unk Avenue LLC, www.punkave.com
 */

/**
 * @package    apostropheBlogPlugin
 * @subpackage Tasks
 * @author     Tom Boutell <tom@punkave.com>
 */

class aBlogGenerateTestPostsTask extends sfBaseTask
{
  protected function configure()
  {
    $this->addOptions(array(
      new sfCommandOption('application', null, sfCommandOption::PARAMETER_REQUIRED, 'The application name', 'frontend'),
      new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environment', 'dev'),
      new sfCommandOption('dictionary', null, sfCommandOption::PARAMETER_REQUIRED, 'The dictionary file', '/usr/share/dict/words'),
      new sfCommandOption('connection', null, sfCommandOption::PARAMETER_REQUIRED, 'The database connection', 'doctrine'),
      new sfCommandOption('amount', null, sfCommandOption::PARAMETER_REQUIRED, 'The number of events to be generated', '50'),
    ));

    $this->namespace        = 'apostrophe';
    $this->name             = 'generate-test-posts';
    $this->briefDescription = 'Adds 50 random test posts to the blog';
    $this->detailedDescription = <<<EOF
This task adds 50 test posts with more or less random content to the blog for test purposes.
Words for those posts come from /usr/share/dict/words. If you don't have that file this task
won't work for you. (It's mainly a testing tool for us, but I'd accept a patch to take the
dictionary name from a file.)
EOF;
  }

  protected function execute($args = array(), $options = array())
  {
    // initialize the database connection
    $databaseManager = new sfDatabaseManager($this->configuration);
    $connection = $databaseManager->getDatabase($options['connection'] ? $options['connection'] : null)->getConnection();
    // So we can play with app.yml settings from the application
    $context = sfContext::createInstance($this->configuration);

    $admin = Doctrine::getTable('sfGuardUser')->findOneByUsername('admin');

    for ($i = 0; ($i < $options['amount']); $i++)
    {
      echo("Creating post " . ($i + 1) . " of ".$options['amount']."...\n");
      $post = new aBlogPost();

      $post->author_id = $admin->id;
      $post->status = 'published';
      $post->published_at = aDate::mysql(strtotime('-' . ($i + 1) . ' days'));
      $title = implode(' ', $this->getWords(mt_rand(5, 10), $options));
      $body = implode(' ', $this->getWords(mt_rand(20, 100), $options));
      $post->setTitle($title);
      $post->save();
      $slot = $post->Page->createSlot('aRichText');
      $slot->value = $body;
      $slot->save();
      $post->Page->newAreaVersion('blog-body', 'update',
        array(
          'permid' => 1,
          'slot' => $slot));
    }
  }

  protected $words = null;
  protected function getWords($count, $options)
  {
    if (is_null($this->words))
    {
      $this->words = file($options['dictionary'], FILE_IGNORE_NEW_LINES);
    }
    $result = array();
    for ($i = 0; ($i < $count); $i++)
    {
      $result[] = $this->words[mt_rand(0, count($this->words) - 1)];
    }
    return $result;
  }
}


text:
describe("geo.map", function() {

  describe('cdb.geo.MapLayer', function() {
    var layer;

    beforeEach(function() {
      layer  = new cdb.geo.MapLayer();
      layer.url = function() {return true};
      layer.sync = function() {return true};
    });
  });

  describe('GMapsBaseLayer', function() {
    it("should be type GMapsBase", function() {
      var layer = new cdb.geo.GMapsBaseLayer();
      expect(layer.get('type')).toEqual("GMapsBase");
    });
  });

  describe('TileLayer', function() {
    it("should be type tiled", function() {
      var layer = new cdb.geo.TileLayer();
      expect(layer.get('type')).toEqual("Tiled");
    });
  });

  describe('CartoDBLayer', function() {
    it("should be type CartoDB", function() {
      var layer = new cdb.geo.CartoDBLayer();
      expect(layer.get('type')).toEqual("CartoDB");
    });
  });

  describe('CartoDBGroupLayer', function() {
    it("should be type layergroup", function() {
      var layer = new cdb.geo.CartoDBGroupLayer();
      expect(layer.get('type')).toEqual("layergroup");
    });
  });

  describe("Layers", function() {
    var layers;

    beforeEach(function() {
      layers = new cdb.geo.Layers();
    });

    it("should compare equal layers correctly", function() {
      var layer1 = new cdb.geo.PlainLayer({ name: 'Positron' });
      var layer2 = new cdb.geo.PlainLayer({});
      var layer3 = new cdb.geo.PlainLayer({});
      var layer4 = new cdb.geo.PlainLayer({});

      expect(layer3.isEqual(layer4)).toBeTruthy();
      expect(layer1.isEqual(layer2)).not.toBeTruthy();

      layers.add(layer4);
      layers.add(layer3);

      expect(layer3.isEqual(layer4)).toBeTruthy();
    })

    it("should compare TileLayers", function() {
      var layer1 = new cdb.geo.TileLayer({ urlTemplate: 'urlTemplate', name: 'layer1', other: 'something' });
      var layer2 = new cdb.geo.TileLayer({ urlTemplate: 'urlTemplate', name: 'layer2', other: 'else' });

      expect(layer1.isEqual(layer2)).toBeFalsy();

      layer2.set({ name: 'layer1' }, { silent: true});

      expect(layer1.isEqual(layer2)).toBeTruthy();
    })

    it("should re-assign order when new layers are added to the collection", function() {
      var baseLayer = new cdb.geo.TileLayer();
      var layer1 = new cdb.geo.CartoDBLayer();
      var layer2 = new cdb.geo.CartoDBLayer();
      var layer3 = new cdb.geo.CartoDBLayer();

      // Sets the order to 0
      layers.add(baseLayer);

      expect(baseLayer.get('order')).toEqual(0);

      // Sets the order to 1
      layers.add(layer1);
      layers.add(layer2);

      expect(baseLayer.get('order')).toEqual(0);
      expect(layer1.get('order')).toEqual(1);
      expect(layer2.get('order')).toEqual(2);

      // Sets the order to 1 and re-orders the rest of the layers
      layers.add(layer3, { at: 1});

      expect(baseLayer.get('order')).toEqual(0);
      expect(layer1.get('order')).toEqual(2);
      expect(layer2.get('order')).toEqual(3);
      expect(layer3.get('order')).toEqual(1);

      var torqueLayer = new cdb.geo.TorqueLayer({});

      // Torque layer should be at the top
      layers.add(torqueLayer);

      expect(baseLayer.get('order')).toEqual(0);
      expect(layer1.get('order')).toEqual(2);
      expect(layer2.get('order')).toEqual(3);
      expect(layer3.get('order')).toEqual(1);
      expect(torqueLayer.get('order')).toEqual(4);

      var tiledLayer = new cdb.geo.TileLayer({});

      // Tiled layer should be at the top
      layers.add(tiledLayer);

      expect(baseLayer.get('order')).toEqual(0);
      expect(layer1.get('order')).toEqual(2);
      expect(layer2.get('order')).toEqual(3);
      expect(layer3.get('order')).toEqual(1);
      expect(torqueLayer.get('order')).toEqual(4);
      expect(tiledLayer.get('order')).toEqual(5);

      var layer4 = new cdb.geo.CartoDBLayer({});
      layers.add(layer4);

      expect(baseLayer.get('order')).toEqual(0);
      expect(layer1.get('order')).toEqual(2);
      expect(layer2.get('order')).toEqual(3);
      expect(layer3.get('order')).toEqual(1);
      expect(layer4.get('order')).toEqual(4);
      expect(torqueLayer.get('order')).toEqual(5);
      expect(tiledLayer.get('order')).toEqual(6);
    });

    it("should re-assign order when new layers are removed from the collection", function() {
      var baseLayer = new cdb.geo.TileLayer();
      var layer1 = new cdb.geo.CartoDBLayer();
      var layer2 = new cdb.geo.CartoDBLayer();
      var torqueLayer = new cdb.geo.TorqueLayer({});
      var labelsLayer = new cdb.geo.TileLayer();

      // Sets the order to 0
      layers.add(baseLayer);
      layers.add(layer1);
      layers.add(layer2);
      layers.add(torqueLayer);
      layers.add(labelsLayer);

      expect(baseLayer.get('order')).toEqual(0);
      expect(layer1.get('order')).toEqual(1);
      expect(layer2.get('order')).toEqual(2);
      expect(torqueLayer.get('order')).toEqual(3);
      expect(labelsLayer.get('order')).toEqual(4);

      layers.remove(layer1);

      expect(baseLayer.get('order')).toEqual(0);
      expect(layer2.get('order')).toEqual(1);
      expect(torqueLayer.get('order')).toEqual(2);
      expect(labelsLayer.get('order')).toEqual(3);

      layers.remove(torqueLayer);

      expect(baseLayer.get('order')).toEqual(0);
      expect(layer2.get('order')).toEqual(1);
      expect(labelsLayer.get('order')).toEqual(2);

      layers.remove(labelsLayer);

      expect(baseLayer.get('order')).toEqual(0);
      expect(layer2.get('order')).toEqual(1);
    });
  });

  describe("Map", function() {
    var map;

    beforeEach(function() {
      map = new cdb.geo.Map();
    });

    it("should raise only one change event on setBounds", function() {
      var c = 0;
      map.bind('change:view_bounds_ne', function() {
        c++;
      });
      map.setBounds([[1,2],[1,2]]);
      expect(c).toEqual(1);
    });

    it("should not change center or zoom when the bounds are not ok", function() {
      var c = 0;
      map.bind('change:center', function() {
        c++;
      });
      map.setBounds([[1,2],[1,2]]);
      expect(c).toEqual(0);
    });

    it("should not change bounds when map size is 0", function() {
      map.set('zoom', 10);
      var bounds = [[43.100982876188546, 35.419921875], [60.23981116999893, 69.345703125]]
      map.fitBounds(bounds, {x: 0, y: 0});
      expect(map.get('zoom')).toEqual(10);
    });

    it("should adjust zoom to layer", function() {
      expect(map.get('maxZoom')).toEqual(40);
      expect(map.get('minZoom')).toEqual(0);

      var layer = new cdb.geo.PlainLayer({ minZoom: 5, maxZoom: 20 });
      map.layers.reset(layer);
      expect(map.get('maxZoom')).toEqual(20);
      expect(map.get('minZoom')).toEqual(5);

      var layer = new cdb.geo.PlainLayer({ minZoom: "7", maxZoom: "31" });
      map.layers.reset(layer);
      expect(map.get('maxZoom')).toEqual(31);
      expect(map.get('minZoom')).toEqual(7);
    });

    it("shouldn't set a NaN zoom", function() {
      var layer = new cdb.geo.PlainLayer({ minZoom: NaN, maxZoom: NaN });
      map.layers.reset(layer);
      expect(map.get('maxZoom')).toEqual(40);
      expect(map.get('minZoom')).toEqual(0);
    });

    it('should update the attributions of the map when layers are reset/added/removed', function() {

      map = new cdb.geo.Map();

      // Map has the default CartoDB attribution
      expect(map.get('attribution')).toEqual([
        "CartoDB attribution"
      ]);

      var layer1 = new cdb.geo.CartoDBLayer({ attribution: 'attribution1' });
      var layer2 = new cdb.geo.CartoDBLayer({ attribution: 'attribution1' });
      var layer3 = new cdb.geo.CartoDBLayer({ attribution: 'wadus' });
      var layer4 = new cdb.geo.CartoDBLayer({ attribution: '' });

      map.layers.reset([ layer1, layer2, layer3, layer4 ]);

      // Attributions have been updated removing duplicated and empty attributions
      expect(map.get('attribution')).toEqual([
        "attribution1",
        "wadus",
        "CartoDB attribution",
      ]);

      var layer = new cdb.geo.CartoDBLayer({ attribution: 'attribution2' });

      map.layers.add(layer);

      // The attribution of the new layer has been appended before the default CartoDB attribution
      expect(map.get('attribution')).toEqual([
        "attribution1",
        "wadus",
        "attribution2",
        "CartoDB attribution",
      ]);

      layer.set('attribution', 'new attribution');

      // The attribution of the layer has been updated in the map
      expect(map.get('attribution')).toEqual([
        "attribution1",
        "wadus",
        "new attribution",
        "CartoDB attribution",
      ]);

      map.layers.remove(layer);

      expect(map.get('attribution')).toEqual([
        "attribution1",
        "wadus",
        "CartoDB attribution",
      ]);

      // Addind a layer with the default attribution
      var layer = new cdb.geo.CartoDBLayer();

      map.layers.add(layer, { at: 0 });

      // Default CartoDB only appears once and it's the last one
      expect(map.get('attribution')).toEqual([
        "attribution1",
        "wadus",
        "CartoDB attribution",
      ]);
    })
  });

  describe('MapView', function() {

    beforeEach(function() {
      this.container = $('
').css('height', '200px');

      this.map = new cdb.geo.Map();
      this.mapView = new cdb.geo.MapView({
        el: this.container,
        map: this.map
      });
    });

    it('should be able to add a infowindow', function() {
      var infow = new cdb.geo.ui.Infowindow({mapView: this.mapView, model: new Backbone.Model()});
      this.mapView.addInfowindow(infow);

      expect(this.mapView._subviews[infow.cid]).toBeTruthy()
      expect(this.mapView._subviews[infow.cid] instanceof cdb.geo.ui.Infowindow).toBeTruthy()
    });

    it('should be able to retrieve the infowindows', function() {
      var infow = new cdb.geo.ui.Infowindow({mapView: this.mapView, model: new Backbone.Model()});
      this.mapView._subviews['irrelevant'] = new Backbone.View();
      this.mapView.addInfowindow(infow);

      var infowindows = this.mapView.getInfoWindows()

      expect(infowindows.length).toEqual(1);
      expect(infowindows[0]).toEqual(infow);
    });
  });
});


text:
<?xml version='1.0' encoding='UTF-8'?>
<Document>
  <Header>
    <SchemaName>Location</SchemaName>
    <Identifier>location_geonames_2745154</Identifier>
    <DocumentState>public</DocumentState>
    <TimeStamp>1390753461934</TimeStamp>
    <SummaryFields>
      <Title>NL > North Brabant > Vught</Title>
    </SummaryFields>
  </Header>
  <Body>
    <Location>
      <GeopoliticalHierarchy>NL,North Brabant,Vught</GeopoliticalHierarchy>
      <LocationName>
        <Appelation>Vught</Appelation>
        <LocationNameType>populated place</LocationNameType>
        <Comments>Fughte</Comments>
      </LocationName>
      <Coordinates>
        <Longitude>5.2875</Longitude>
        <Latitude>51.65333</Latitude>
      </Coordinates>
      <GeonamesURI>http://www.geonames.org/2745154</GeonamesURI>
      <WikipediaLink/>
      <DbpediaLink/>
    </Location>
  </Body>
</Document>


text:
package com.parallelsymmetry.cirrus.painter;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Shape;

import javax.swing.JComponent;
import javax.swing.JSpinner;
import javax.swing.JSpinner.DefaultEditor;

import com.parallelsymmetry.cirrus.painter.CirrusShapeGenerator.CornerSize;
import com.parallelsymmetry.cirrus.painter.CirrusShapeGenerator.CornerStyle;
import com.parallelsymmetry.cirrus.painter.PaintContext.CacheMode;

/**
 * SpinnerNextButtonPainter implementation.
 */
public final class SpinnerNextButtonPainter extends AbstractCommonColorsPainter {

	public static final int BACKGROUND_DISABLED = 0;

	public static final int BACKGROUND_ENABLED = 1;

	public static final int BACKGROUND_FOCUSED = 2;

	public static final int BACKGROUND_MOUSEOVER = 3;

	public static final int BACKGROUND_MOUSEOVER_FOCUSED = 4;

	public static final int BACKGROUND_PRESSED = 5;

	public static final int BACKGROUND_PRESSED_FOCUSED = 6;

	public static final int FOREGROUND_DISABLED = 10;

	public static final int FOREGROUND_ENABLED = 11;

	public static final int FOREGROUND_FOCUSED = 12;

	public static final int FOREGROUND_MOUSEOVER = 13;

	public static final int FOREGROUND_MOUSEOVER_FOCUSED = 14;

	public static final int FOREGROUND_PRESSED = 15;

	public static final int FOREGROUND_PRESSED_FOCUSED = 16;

	private Color spinnerNextBorderBottomEnabled = decodeColor( "spinnerNextBorderBottomEnabled" );

	private Color spinnerNextBorderBottomPressed = decodeColor( "spinnerNextBorderBottomPressed" );

	private Color spinnerNextInteriorBottomEnabled = decodeColor( "spinnerNextInteriorBottomEnabled" );

	private Color spinnerNextInteriorBottomMouseover = decodeColor( "spinnerNextInteriorBottomMouseover" );

	private Color spinnerNextInteriorBottomPressed = decodeColor( "spinnerNextInteriorBottomPressed" );

	private TwoColors pressedButtonBorder = getCommonBorderColors( CommonControlState.PRESSED );

	private TwoColors spinnerNextBorderEnabled = new TwoColors( pressedButtonBorder.top, spinnerNextBorderBottomEnabled );

	private TwoColors spinnerNextBorderPressed = new TwoColors( pressedButtonBorder.top, spinnerNextBorderBottomPressed );

	private TwoColors spinnerNextBorderDisabled = disable( spinnerNextBorderEnabled );

	private FourColors mouseoverButtonInterior = getCommonInteriorColors( CommonControlState.MOUSEOVER );

	private FourColors pressedButtonInterior = getCommonInteriorColors( CommonControlState.PRESSED );

	private FourColors selectedButtonInterior = getCommonInteriorColors( CommonControlState.SELECTED );

	private TwoColors spinnerNextInteriorEnabled = new TwoColors( selectedButtonInterior.top, spinnerNextInteriorBottomEnabled );

	private TwoColors spinnerNextInteriorMouseover = new TwoColors( mouseoverButtonInterior.top, spinnerNextInteriorBottomMouseover );

	private TwoColors spinnerNextInteriorPressed = new TwoColors( pressedButtonInterior.top, spinnerNextInteriorBottomPressed );

	private TwoColors spinnerNextInteriorDisabled = desaturate( desaturate( spinnerNextInteriorEnabled ) );

	private PaintContext ctx;

	private CommonControlState state;

	private boolean focused;

	private boolean isForeground;

	public SpinnerNextButtonPainter( int type ) {
		this.ctx = new PaintContext( CacheMode.NO_CACHING );

		state = getButtonState( type );

		switch( type ) {
			case BACKGROUND_FOCUSED:
			case BACKGROUND_MOUSEOVER_FOCUSED:
			case BACKGROUND_PRESSED_FOCUSED:
			case FOREGROUND_FOCUSED:
			case FOREGROUND_MOUSEOVER_FOCUSED:
			case FOREGROUND_PRESSED_FOCUSED:
				focused = true;
			default:
				focused = false;
		}

		isForeground = isForeground( type );
	}

	@Override
	protected void doPaint( Graphics2D g, JComponent c, int width, int height, Object[] extendedCacheKeys ) {
		if( isForeground ) {
			paintArrow( g, width, height );
		} else {
			paintButton( g, c, width, height );
		}
	}

	@Override
	protected PaintContext getPaintContext() {
		return ctx;
	}

	private CommonControlState getButtonState( int type ) {
		switch( type ) {
			case BACKGROUND_DISABLED:
			case FOREGROUND_DISABLED:
				return CommonControlState.DISABLED;
			case BACKGROUND_ENABLED:
			case BACKGROUND_FOCUSED:
			case FOREGROUND_ENABLED:
			case FOREGROUND_FOCUSED:
				return CommonControlState.ENABLED;
			case BACKGROUND_MOUSEOVER:
			case BACKGROUND_MOUSEOVER_FOCUSED:
			case FOREGROUND_MOUSEOVER:
			case FOREGROUND_MOUSEOVER_FOCUSED:
				return CommonControlState.MOUSEOVER;
			case BACKGROUND_PRESSED_FOCUSED:
			case BACKGROUND_PRESSED:
			case FOREGROUND_PRESSED_FOCUSED:
			case FOREGROUND_PRESSED:
				return CommonControlState.PRESSED;
			default:
				return null;
		}
	}

	private boolean isForeground( int type ) {
		switch( type ) {
			case FOREGROUND_DISABLED:
			case FOREGROUND_ENABLED:
			case FOREGROUND_FOCUSED:
			case FOREGROUND_MOUSEOVER:
			case FOREGROUND_MOUSEOVER_FOCUSED:
			case FOREGROUND_PRESSED:
			case FOREGROUND_PRESSED_FOCUSED:
				return true;
			default:
				return false;
		}
	}

	private void paintButton( Graphics2D g, JComponent c, int width, int height ) {
		boolean useToolBarColors = isInToolBar( c );
		Shape s;

		JSpinner spinner = (JSpinner)c.getParent();
		boolean editorFocused = false;
		JComponent editor = spinner.getEditor();
		if( editor instanceof DefaultEditor ) {
			editorFocused = ( (DefaultEditor)editor ).getTextField().isFocusOwner();
		}
		if( focused || editorFocused ) {
			s = createButtonShape( 0, 0, width, height, CornerSize.OUTER_FOCUS );
			g.setPaint( getFocusPaint( s, FocusType.OUTER_FOCUS, useToolBarColors ) );
			g.fill( s );

			s = createButtonShape( 0, 1, width - 1, height - 1, CornerSize.INNER_FOCUS );
			g.setPaint( getFocusPaint( s, FocusType.INNER_FOCUS, useToolBarColors ) );
			g.fill( s );
		}

		s = createButtonShape( 0, 2, width - 2, height - 2, CornerSize.BORDER );
		g.setPaint( getSpinnerNextBorderPaint( s, state ) );
		g.fill( s );

		s = createButtonShape( 1, 3, width - 4, height - 4, CornerSize.INTERIOR );
		g.setPaint( getSpinnerNextInteriorPaint( s, state ) );
		g.fill( s );
	}

	private void paintArrow( Graphics2D g, int width, int height ) {
		Shape s = createArrowShape( width, height );
		g.setPaint( getCommonArrowPaint( s, state ) );
		g.fill( s );
	}

	private Shape createButtonShape( int x, int y, int width, int height, CornerSize size ) {
		return shapeGenerator.createRoundRectangle( x, y, width, height, size, CornerStyle.SQUARE, CornerStyle.SQUARE, CornerStyle.SQUARE, CornerStyle.ROUNDED );
	}

	private Shape createArrowShape( int left, int height ) {
		int centerX = left / 2 - 3;
		int centerY = height / 2 - 1;
		return shapeGenerator.createArrowUp( centerX, centerY, 5, 4 );
	}

	public Paint getSpinnerNextBorderPaint( Shape s, CommonControlState type ) {
		TwoColors colors = getSpinnerNextBorderColors( type );
		return createVerticalGradient( s, colors );
	}

	public Paint getSpinnerNextInteriorPaint( Shape s, CommonControlState type ) {
		TwoColors colors = getSpinnerNextInteriorColors( type );
		return createVerticalGradient( s, colors );
	}

	private TwoColors getSpinnerNextBorderColors( CommonControlState type ) {
		switch( type ) {
			case DISABLED:
				return spinnerNextBorderDisabled;
			case ENABLED:
			case MOUSEOVER:
				return spinnerNextBorderEnabled;
			case PRESSED:
				return spinnerNextBorderPressed;
			default:
				return null;
		}
	}

	private TwoColors getSpinnerNextInteriorColors( CommonControlState type ) {
		switch( type ) {
			case DISABLED:
				return spinnerNextInteriorDisabled;
			case ENABLED:
				return spinnerNextInteriorEnabled;
			case MOUSEOVER:
				return spinnerNextInteriorMouseover;
			case PRESSED:
				return spinnerNextInteriorPressed;
			default:
				return null;
		}
	}
}


text:
<!doctype html>

    <title>Blacklist</title>

    <link rel=stylesheet href="bootstrap/css/bootstrap.min.css" type="text/css" >

      Cancel Unlisting


text:
import React, { PureComponent } from 'react';
import Radium from 'radium';

import { styles } from './styles';
import { theme } from '../../theme';
import { strings } from '../../res/strings';

import brick from '../../res/media/brick.png';
import mandelbrot from '../../res/media/mandelbrot.png';
import course from '../../res/media/wwu.png';

class Projects extends PureComponent {
  render() {
    document.title = `Projects - ${strings.title}`;

    return (

{strings.projectsTitle}

{strings.projectOneTitle}

{strings.projectOneDescription}

{strings.projectTwoTitle}

{strings.projectTwoDescription}

{strings.projectThreeTitle}

{strings.projectThreeDescription}

{strings.projectsMore}

    );
  }
}

Projects = Radium(Projects);
export { Projects };


text:
namespace SSLLabsApiWrapper.Models.Response.BaseSubModels
{
	public class Wrapper
	{
		public int ApiPassCount { get; set; }
		public string ApiCommandUrl { get; set; }
		public string ApiRawResponse { get; set; }
	}
}


text:
using System;
using System.Diagnostics.CodeAnalysis;

namespace Octokit.Reactive
{
    public interface IObservableOrganizationsClient
    {
        /// <summary>
        /// Returns a client to manage members of an organization.
        /// </summary>
        IObservableOrganizationMembersClient Member { get; }

        /// <summary>
        /// Returns the specified organization.
        /// </summary>
        /// <param name="org">The login of the specified organization,</param>
        /// <returns></returns>
        [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Get"
            , Justification = "It's fine. Trust us.")]
        IObservable<Organization> Get(string org);

        /// <summary>
        /// Returns all the organizations for the current user.
        /// </summary>
        /// <returns></returns>
        [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate",
            Justification = "Method makes a network request")]
        IObservable<Organization> GetAllForCurrent();

        /// <summary>
        /// Returns all the organizations for the specified user
        /// </summary>
        /// <param name="user">The login for the user</param>
        /// <returns></returns>
        IObservable<Organization> GetAll(string user);
    }
}


text:
namespace chainbase {
class database;
}

namespace b1::chain_kv {
   struct database;
   class undo_stack;
}

namespace eosio { namespace chain {

   class apply_context;

   inline constexpr name kvram_id  = "eosio.kvram"_n;

   enum class kv_it_stat {
      iterator_ok     = 0,  // Iterator is positioned at a key-value pair
      iterator_erased = -1, // The key-value pair that the iterator used to be positioned at was erased
      iterator_end    = -2, // Iterator is out-of-bounds
   };

   struct kv_iterator {
      virtual ~kv_iterator() {}

      virtual bool       is_kv_chainbase_context_iterator() const                                       = 0;
      virtual bool       is_kv_rocksdb_context_iterator() const                                       = 0;
      virtual kv_it_stat kv_it_status()                                                                 = 0;
      virtual int32_t    kv_it_compare(const kv_iterator& rhs)                                          = 0;
      virtual int32_t    kv_it_key_compare(const char* key, uint32_t size)                              = 0;
      virtual kv_it_stat kv_it_move_to_end()                                                            = 0;
      virtual kv_it_stat kv_it_next(uint32_t* found_key_size, uint32_t* found_value_size)               = 0;
      virtual kv_it_stat kv_it_prev(uint32_t* found_key_size, uint32_t* found_value_size)               = 0;
      virtual kv_it_stat kv_it_lower_bound(const char* key, uint32_t size,
                                          uint32_t* found_key_size, uint32_t* found_value_size)         = 0;
      virtual kv_it_stat kv_it_key(uint32_t offset, char* dest, uint32_t size, uint32_t& actual_size)   = 0;
      virtual kv_it_stat kv_it_value(uint32_t offset, char* dest, uint32_t size, uint32_t& actual_size) = 0;
      virtual std::optional<name> kv_it_payer()                                                         = 0;
   };

   struct kv_resource_trace {
      enum class operation {
         create  = 0, // The operation represents the creation of a key-value pair
         update  = 1, // The operation represents the update of a key-value pair
         erase   = 2, // The operation represents the deletion of a key-value pair
      };

      kv_resource_trace(const char* key, uint32_t key_size, operation op): key(key, key_size), op(op) {}

      std::string_view key;
      operation op;

      const char* op_to_string() const {
         if (op == operation::create) return "create";
         if (op == operation::update) return "update";
         if (op == operation::erase) return "erase";

         return "unknown";
      }
   };

   struct kv_resource_manager {
      void     update_table_usage(account_name payer, int64_t delta, const kv_resource_trace& trace) { return _update_table_usage(*_context, delta, trace, payer); }
      apply_context* _context;
      uint64_t       billable_size;
      void (*_update_table_usage)(apply_context&, int64_t delta, const kv_resource_trace& trace, account_name payer);
   };

   kv_resource_manager create_kv_resource_manager(apply_context& context);

   struct kv_context {
      virtual ~kv_context() {}

      virtual int64_t  kv_erase(uint64_t contract, const char* key, uint32_t key_size)                     = 0;
      virtual int64_t  kv_set(uint64_t contract, const char* key, uint32_t key_size, const char* value,
                              uint32_t value_size, account_name payer)                                     = 0;
      virtual bool     kv_get(uint64_t contract, const char* key, uint32_t key_size, uint32_t& value_size) = 0;
      virtual uint32_t kv_get_data(uint32_t offset, char* data, uint32_t data_size)                        = 0;

      virtual std::unique_ptr<kv_iterator> kv_it_create(uint64_t contract, const char* prefix, uint32_t size) = 0;

     protected:
      // Updates resource usage for payer and returns resource delta
      template<typename Resource_manager>
      int64_t create_table_usage(Resource_manager& resource_manager, const account_name& payer, const char* key, const uint32_t key_size, const uint32_t value_size) {
         const int64_t resource_delta = (static_cast<int64_t>(resource_manager.billable_size) + key_size + value_size);
         resource_manager.update_table_usage(payer, resource_delta, kv_resource_trace(key, key_size, kv_resource_trace::operation::create));
         return resource_delta;
      }

      template<typename Resource_manager>
      int64_t erase_table_usage(Resource_manager& resource_manager, const account_name& payer, const char* key, const uint32_t key_size, const uint32_t value_size) {
         const int64_t resource_delta = -(static_cast<int64_t>(resource_manager.billable_size) + key_size + value_size);
         resource_manager.update_table_usage(payer, resource_delta, kv_resource_trace(key, key_size, kv_resource_trace::operation::erase));
         return resource_delta;
      }

      template<typename Resource_manager>
      int64_t update_table_usage(Resource_manager& resource_manager, const account_name& old_payer, const account_name& new_payer, const char* key, const uint32_t key_size, const uint32_t old_value_size, const uint32_t new_value_size) {
         // 64-bit arithmetic cannot overflow, because both the key and value are limited to 32-bits
         const int64_t old_size = key_size + old_value_size;
         const int64_t new_size = key_size + new_value_size;
         const int64_t resource_delta = new_size - old_size;

         if (old_payer != new_payer) {
            // refund the existing payer
            resource_manager.update_table_usage(old_payer, -(old_size + resource_manager.billable_size), kv_resource_trace(key, key_size, kv_resource_trace::operation::update));
            // charge the new payer for full amount
            resource_manager.update_table_usage(new_payer, new_size + resource_manager.billable_size, kv_resource_trace(key, key_size, kv_resource_trace::operation::update));
         } else if (old_size != new_size) {
            // adjust delta for the existing payer
            resource_manager.update_table_usage(new_payer, resource_delta, kv_resource_trace(key, key_size, kv_resource_trace::operation::update));
         } // No need for a final "else" as usage does not change

         return resource_delta;
      }
   };

   std::unique_ptr<kv_context> create_kv_chainbase_context(chainbase::database& db, name receiver,
                                                           kv_resource_manager resource_manager, const kv_database_config& limits);

}} // namespace eosio::chain


text:
namespace act
{
	class	Blob;
	class	ITokenConfig;

	typedef ITokenConfig*(*CreateTokenConfigPtr)(const char*, const Blob&);
	typedef FactoryRegistry<ITokenConfig, CreateTokenConfigPtr>	TokenConfigReg;

} // namespace act

#endif // ACT_TokenConfigReg_h


text:
3.0 Medium Voltage Devices (5V)
===============================

 .. csv-table::
    :file: tables_clear/3_Medium_Voltage_Devices5v.csv


text:
require 'git_change'
class GitPatch
  def initialize(commit_id, repository, truncation_threshold = nil)
    @commit_id = commit_id
    @repository = repository
    @changes = []
    @current_change_lines = []
    @truncation_threshold = truncation_threshold
  end

  def changes
    @changes
  end

  def done_adding_lines
    add_current_change
  end

  def add_line(line)
    if (line =~ /^diff --git/ && @current_change_lines.size > 0)
      add_current_change
    end

    if @truncation_threshold && @current_change_lines.size == @truncation_threshold
      @current_change_truncated = true
    end

    if @truncation_threshold.nil? || @current_change_lines.size < @truncation_threshold
      @current_change_lines << line
    end
  end

  def add_current_change
    if @current_change_lines.size > 1
      @changes << GitGitChange::Factory.construct(
              @commit_id,
              @current_change_lines,
              @repository,
              @current_change_truncated
      )
    end
    @current_change_truncated = false
    @current_change_lines = []
  end
end


text:
def default_layout
  {layout: :layout}
end

def to_card(path, opts = {})
  erb(path, opts.merge(layout: :"layout/card"))
end

def to_page(path, opts = {})
  page = erb(path, opts.merge(layout: :"layout/page"))
  erb(page, opts.merge(default_layout))
end

def full_page_card(path, opts = {})
  card = to_card(path, opts)
  erb(card, opts.merge(default_layout))
end

def escape_html(html, opts = {})
  Rack::Utils.escape_html(html.to_s)
end

def html_title
  $app_name.capitalize
end


text:
/******************************************************************************************
*******************************************************************************************

                        collision worker - collision_worker.js

******************************************************************************************
******************************************************************************************
    This class can be used only to define database schema , upgrade  and init database
*******************************************************************************************
******************************************************************************************/

this.first_check=false;
//object array with updated position of all objects on scene
this.object_ids=[];

//only agent array to speed_up agent relative position calculation
this.agent_objs=[];

//array with relative position of near agents for each agent
this.agent_relativ_pos={};

//TO-DO: this parameters must be set dinamically from a specific message by the user
var collision_distance=10;
//TO-DO:WIFI Distance must be customized for each agents/object trough a parameter in the dedicated array
var wifi_distance=4000;
var laserFinder_distance=300;
//TO-DO for this parameters additional control on the minimum value must be introduced
var loop_collision_time=4000;
var object_limit=100;

var stub_obj_pos=[{
        x:0,
        y:0,
        z:0,
        type:"N/A",
        object_id:0
}];

this.checkForCollision = function(){

    var collision_message=collision_detection(this.object_ids)

    if(collision_message!=null &&collision_message.detected){
        console.log("COLLISION DETECTED object 1 ID:"+collision_message.object_id[0]);
        console.log("COLLISION DETECTED object 2 ID:"+collision_message.object_id[1]);
        if(collision_message.type[0]=='agent'){
            setDisabledInList(collision_message.object_id[0]);
        }
        if(collision_message.type[1]=='agent'){
            setDisabledInList(collision_message.object_id[1]);
        }

        self.postMessage(collision_message);
    }

    //check if must be moved to a dedicated cycle with a different delay
    agent_relative_pos_eval(this.object_ids);

    setTimeout(function(){checkForCollision()},loop_collision_time);
    //console.log(this.object_ids);

}

function init_obj_array(){

    for(var i=0; i<object_limit; i++){

            this.object_ids.push(stub_obj_pos);
    }

}

self.addEventListener('message', function(e) {
     move_par=e.data;
     var agent_id=move_par[0].agent_id;
     var x=move_par[0].x;
     var y=move_par[0].y;
     var z=move_par[0].z;
     var type=move_par[0].type;

     if(!this.first_check){
         //init_obj_array();
     }

     addRefrObj_pos(agent_id,type,x,y,z);

    if(!this.first_check){
        this.first_check=true;
        checkForCollision(this.object_ids);

        //console.log(this.object_ids);

     }

}, false);

function collision_detection(object_ids){

    for (var i = object_ids.length - 1; i >= 0; i--) {

        //first version disabled agents are not evaluated
        //if(object_ids[i].type=='agent'&&!object_ids[i].disabled){
        //check the collisions/distance only for objects of agent type
        if(object_ids[i].type=='agent'){
            for (var k = object_ids.length - 1; k >= 0; k--) {
                if(object_ids[i].object_id!=object_ids[k].object_id){

                    var distance=evalDistance(object_ids[i].x,object_ids[i].y,object_ids[i].z,object_ids[k].x,object_ids[k].y,object_ids[k].z);
                    if(distance<collision_distance){
                            var collision_message = {
                            detected: true,
                            object_id:[object_ids[i].object_id,object_ids[k].object_id],
                            type:[object_ids[i].type,object_ids[k].type]
                        };
                        console.log("Objects distance: "+ distance);
                        return collision_message
                    }
                }
            }
        }
    }
}

this.setDisabledInList = function (object_id){
    for (var i = this.object_ids.length - 1; i >= 0; i--) {
            if(object_ids[i].object_id==object_id){
                object_ids[i].disabled=true;
                console.log("agent:"+object_id+" DISABLED");
            }
        }
}

this.addRefrObj_pos = function (object_id,type,x,y,z) {
    var found=false;
    var disabled=false;

        // refresh object position (only moving obiject will need throw a msg with a new position)
        //ciclo for al contrario = BESTIA DI SATANA
        for (var i = this.object_ids.length - 1; i >= 0; i--) {
            if(object_ids[i].object_id==object_id){
                found=true;
                disabled=object_ids[i].disabled;
                object_ids[i].x=x;
                object_ids[i].y=y;
                object_ids[i].z=z;
            }
        }

        //add object to array
        if(!found&&!disabled){
            var object = {
                x: x,
                y: y,
                z: z,
                object_id:object_id,
                type:type,
                disabled:false
            };
            this.object_ids.push(object);
            console.log("add object:"+object + "to collision worker buffer");

            //add object to agent array
            if(object.type=="agent"){
                this.agent_objs.push(object);
            }
        }

};

function agent_relative_pos_eval(agent_objs){

    /**************************************************************************************
    For each agent all the position of the others agents it's computed and stored in a array.
    The positions array is then sent to the each agent, this capability can be used to
    simulate a laser-finder sensor or an overlay network through a filter on distance among
    the agents.
    **************************************************************************************/

    for (var i = object_ids.length - 1; i >= 0; i--) {
        //reset detected object array
        this.agent_relativ_pos=[];

        //check if the agent is active
        if(!object_ids[i].disabled){
            for (var k = object_ids.length - 1; i >= 0; i--) {
                //check only other agents
                if(object_ids[i].object_id!=object_ids[k].object_id){

                    var distance= evalDistance(object_ids[i].x,object_ids[i].y,object_ids[i].z,object_ids[k].x,object_ids[k].y,object_ids[k].z);

                    //check for wi-fi distance (default simulation of a wi-fi network comm. channel)
                    if(distance<this.wifi_distance){
                        this.agent_relativ_pos.push(object_ids[k]);
                    }
                }
            }
        }

        //check if agent_relativ_pos is not empty
        if(agent_relativ_pos.length>0){

            var detection_message = {
                detected: true,
                //agent_id:object_ids[i].object_id,
                agents_relativ_pos:this.agent_relativ_pos
            };

            //return relative position to the agent
            self.postMessage(detection_message);
            //console.log(detection_message);

        }

    }
}

function evalDistance(x1,y1,z1,x2,y2,z2){

         var distance= Math.sqrt( Math.pow((x1 - x2),2) +   Math.pow((y1 - y2),2)  +  Math.pow((z1 - z2),2));

         return distance;
}


text:
"""Dataset Classes.

Dataset abstraction/factory to allow us to easily use tensorflow datasets (TFDS)
with JAX/FLAX, by defining a bunch of wrappers, including preprocessing.
"""

import abc
from typing import MutableMapping, Optional

import tensorflow.compat.v2 as tf
import tensorflow_datasets as tfds

class Dataset(metaclass=abc.ABCMeta):
  """Base class for datasets.

  Attributes:
      DATAKEY: The key used for the data component of a Tensorflow Dataset
        (TFDS) sample, e.g. 'image' for image datasets.
      LABELKEY: The key used fot the label component of a Tensorflow Dataset
        sample, i.e. 'label'.
      name: The TFDS name of the dataset.
      batch_size: The batch size to use for the training dataset.
      batch_size_test: The batch size to use for the test dataset.
      num_classes: the number of supervised classes in the dataset.
      shape: the shape of an input data array.
  """

  DATAKEY: Optional[str] = None
  LABELKEY: str = 'label'

  def __init__(self,
               name,
               batch_size,
               batch_size_test,
               shuffle_buffer_size,
               prefetch_size = 1,
               seed = None):  # pytype: disable=annotation-type-mismatch
    """Base class for datasets.

    Args:
        name: The TFDS name of the dataset.
        batch_size: The batch size to use for the training dataset.
        batch_size_test: The batch size to use for the test dataset.
        shuffle_buffer_size: The buffer size to use for dataset shuffling.
        prefetch_size: The number of mini-batches to prefetch.
        seed: The random seed used to shuffle.

    Returns:
        A Dataset object.
    """
    super().__init__()
    self.name = name
    self.batch_size = batch_size
    self.batch_size_test = batch_size_test
    self._shuffle_buffer_size = shuffle_buffer_size
    self._prefetch_size = prefetch_size

    self._train_ds, self._train_info = tfds.load(
        self.name,
        split=tfds.Split.TRAIN,
        data_dir=self._dataset_dir(),
        with_info=True)
    self._train_ds = self._train_ds.shuffle(
        self._shuffle_buffer_size,
        seed).map(self.preprocess).cache().map(self.augment).batch(
            self.batch_size, drop_remainder=True).prefetch(self._prefetch_size)

    self._test_ds, self._test_info = tfds.load(
        self.name,
        split=tfds.Split.TEST,
        data_dir=self._dataset_dir(),
        with_info=True)
    self._test_ds = self._test_ds.map(self.preprocess).cache().batch(
        self.batch_size_test).prefetch(self._prefetch_size)

    self.num_classes = self._train_info.features['label'].num_classes
    self.shape = self._train_info.features['image'].shape

  def _dataset_dir(self):
    """Returns the dataset path for the TFDS data."""
    return None

  def get_train(self):
    """Returns the training dataset."""
    return iter(tfds.as_numpy(self._train_ds))

  def get_train_len(self):
    """Returns the length of the training dataset."""
    return self._train_info.splits['train'].num_examples

  def get_test(self):
    """Returns the test dataset."""
    return iter(tfds.as_numpy(self._test_ds))

  def get_test_len(self):
    """Returns the length of the test dataset."""
    return self._test_info.splits['test'].num_examples

  def preprocess(
      self, data):
    """Preprocessing fn used by TFDS map for normalization.

    This function is for transformations that can be cached, e.g.
    normalization/whitening.

    Args:
      data: Data sample.

    Returns:
    Data after being normalized/transformed.
    """
    return data

  def augment(
      self, data):
    """Preprocessing fn used by TFDS map for augmentation at training time.

    This function is for transformations that should not be cached, e.g. random
    augmentation that should change for every sample, and are only applied at
    training time.

    Args:
      data: Data sample.

    Returns:
    Data after being augmented/transformed.
    """
    return data

class ImageDataset(Dataset):
  """Base class for image datasets."""

  DATAKEY = 'image'

  def preprocess(
      self, data):
    """Preprocessing function used by TFDS map for normalization.

    This function is for transformations that can be cached, e.g.
    normalization/whitening.

    Args:
      data: Data sample.

    Returns:
      Data after being normalized/transformed.
    """
    data = super().preprocess(data)
    # Ensure we only provide the image and label, stripping out other keys.
    return dict((key, val)
                for key, val in data.items()
                if key in [self.LABELKEY, self.DATAKEY])


text:
<!DOCTYPE html PUBLIC  "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<title>Организационные расходы</title>
<?php include_once('html/tiles/head-basic.html'); ?>

<?php include_once('html/tiles/header.html'); ?>

<?php include_once('html/tiles/sideblock.html'); ?>

    Организационные расходы

<form action="/projects/costs/save" method="post" class="formdatagrid">

<?php echo <<<EOD

<input type="input" value="Период" class="period tophead" readonly="true"/>
<input type="input" value="Сумма расходов" class="tophead" readonly="true"/>

EOD;
for($i=1; $i<=$n; $i++){
echo <<<EOD

<input type="input" class="period" value="$i" readonly="true"/>
<input type="input" name="costs.organizational.$i" value="{$data[$i]}" class="cell"/>

EOD;
} ?>

</form>

<?php include_once('html/tiles/footer.html'); ?>


text:
package com.video.synopsis.process;

import com.video.synopsis.utils.PropUtils;
import org.bytedeco.javacpp.opencv_core;
import org.bytedeco.javacpp.opencv_core.IplImage;
import org.bytedeco.javacpp.opencv_highgui;
import org.bytedeco.javacpp.opencv_highgui.CvVideoWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class ImageToVideo {

    private static final Logger _log = LoggerFactory.getLogger(ImageToVideo.class);

    private static Map<String, File> imageMap = new HashMap<>();
    private static Double fps = 120.0;

    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd_hh_mm_ss_SSS");

    @Autowired
    private PropUtils propUtils;

    public String generatedAimVideo(String imagePath, String backgroundPath, String videoPath) {
        BufferedImage bufferedImage;
        try {
            _log.info("Start read background jpg...");
            bufferedImage = ImageIO.read(new File(backgroundPath + "background.jpg"));
            _log.info("End read background jpg...");
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        int width = bufferedImage.getWidth();
        int height = bufferedImage.getHeight();

        //新建CvVideoWriter 变量vw用于保存合成视频,并且保存到对应路径
        BackgroundSubtraction.mkDir(new File(videoPath));
        String resultPath = videoPath.concat("/").
                concat(String.format(/*propUtils.getProperty("store.file.path")*/"VideoSynopsis%s.avi",
                        sdf.format(new Date())));
        CvVideoWriter vw = opencv_highgui.cvCreateVideoWriter(resultPath,
                opencv_highgui.CV_FOURCC((byte) 'D', (byte) 'I', (byte) 'V', (byte) 'X'), fps, opencv_core.cvSize(width, height));
        File folder = new File(imagePath);
        File[] listOfFiles = folder.listFiles();
        for (File file : listOfFiles) {
            if (file.isFile()) {
                _log.info("file.getName() :" + file.getName());
                imageMap.put(file.getName(), file);
            }
        }

        IplImage img;
        for (int index = 1; index < listOfFiles.length; index++) {
            BufferedImage screen = getImage(index);
            BufferedImage bgrScreen = convertToType(screen, BufferedImage.TYPE_3BYTE_BGR);

            img = IplImage.createFrom(bgrScreen);
            opencv_highgui.cvWriteFrame(vw, img);//合成视频文件
        }
        opencv_highgui.cvReleaseVideoWriter(vw);
        _log.info("Done");
        return resultPath;
    }

    public static BufferedImage convertToType(BufferedImage sourceImage, int targetType) {
        BufferedImage image;
        if (sourceImage.getType() == targetType) {
            image = sourceImage;
        } else {
            image = new BufferedImage(sourceImage.getWidth(),
                    sourceImage.getHeight(), targetType);
            image.getGraphics().drawImage(sourceImage, 0, 0, null);
        }
        return image;
    }

    private static BufferedImage getImage(int index) {

        try {
            String fileName = index + ".jpg";
            _log.info("fileName :" + fileName);
            File img = imageMap.get(fileName);
            BufferedImage in;
            if (img != null) {
                _log.info("img :" + img.getName());
                in = ImageIO.read(img);
            } else {
                _log.info("index :" + index);
                img = imageMap.get(1);
                in = ImageIO.read(img);
            }
            return in;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}


text:
//-----------------------------------------------------------------------
// <copyright file="MixinIsTargetsNestedClassSpec.cs" company="Copacetic Software">
// Copyright (c) Copacetic Software.
// <author>Philip Pittle</author>
// <date>Thursday, February 20, 2014 8:58:00 PM</date>
// Licensed under the Apache License, Version 2.0,
// you may not use this file except in compliance with this License.
//
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an 'AS IS' BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//-----------------------------------------------------------------------

using CopaceticSoftware.pMixins.CodeGenerator.Tests.IntegrationTests.CompileTests.AdvancedMixinTypes;
using CopaceticSoftware.pMixins.TheorySandbox.COVERED.AsIsWrapper;

namespace CopaceticSoftware.pMixins.TheorySandbox.COVERED.MixinIsTargetsNestedClass
{ //TODO:  Because Mixin is nested and listed as private, we can't create
//wrapper classes in a separate namespace.  Investigate if it's ok
//to create them in a nested class.

    /// <summary>
    /// Covered by:
    ///     <see cref="MixinIsPrivateNestedTypeInTarget"/>
    /// </summary>
    public class BaseClass
    {
        public string BaseMethod()
        {
            return "Base Method";
        }
    }

    public interface IInterface
    {
        string IInterfaceMethod();
    }

    /// <summary>
    /// Covered by:
    ///     <see cref="MixinIsPrivateNestedTypeInTarget"/>
    /// </summary>
    [BasicMixin(Target = typeof(MixinIsTargetsNestedClassSpec.PrivateMixin))]
    public partial class MixinIsTargetsNestedClassSpec
    {
        private class PrivateMixin : BaseClass, IInterface
        {
            public PrivateMixin(string name)
            {
            }

            public string MixinMethod()
            {
                return "Nested Private Mixin";
            }

            public string IInterfaceMethod()
            {
                return "IInterfaceMethod";
            }
        }

        PrivateMixin IMixinConstructorRequirement<MixinIsTargetsNestedClassSpec.PrivateMixin>.InitializeMixin()
        {
            return new PrivateMixin("");
        }

    }

    interface IMixinConstructorRequirement<out TMixin>
    {
        TMixin InitializeMixin();
    }

/*/////////////////////////////////////////
/// Generated Code
/////////////////////////////////////////*/

    public partial class MixinIsTargetsNestedClassSpec :
        IMixinConstructorRequirement<MixinIsTargetsNestedClassSpec.PrivateMixin>,
        IWrap<MixinIsTargetsNestedClassSpec.PrivateMixin>,
        IInterface // inherit from mixin's interfaces
    {
        private class __pMixinAutoGenerated
        {
            public class CopaceticSoftware_pMixin_TheorySandbox_MixinIsTargetsNestedClass_PrivateMixin
            {
                //don't need protected wrapper

                //don't need abstract wrapper

                public sealed class MasterWrapper
                {
                    public readonly PrivateMixin PrivateMixin;

                    public MasterWrapper(MixinIsTargetsNestedClassSpec target)
                    {
                        this.PrivateMixin =
                            ((IMixinConstructorRequirement<MixinIsTargetsNestedClassSpec.PrivateMixin>)target)
                                .InitializeMixin();
                    }

                    public string BaseMethod()
                    {
                        return PrivateMixin.BaseMethod();
                    }

                    public string MixinMethod()
                    {
                        return PrivateMixin.MixinMethod();
                    }

                    public string IInterfaceMethod()
                    {
                        return PrivateMixin.IInterfaceMethod();
                    }
                }
            }
        }

        private sealed partial class __Mixins
        {
            public static readonly global::System.Object ____Lock = new global::System.Object();

            public readonly __pMixinAutoGenerated.CopaceticSoftware_pMixin_TheorySandbox_MixinIsTargetsNestedClass_PrivateMixin.MasterWrapper PrivateMixinMasterWrapper;

            public __Mixins(MixinIsTargetsNestedClassSpec target)
            {
                this.PrivateMixinMasterWrapper =
                    new DefaultMixinActivator()
                        .CreateInstance<__pMixinAutoGenerated.CopaceticSoftware_pMixin_TheorySandbox_MixinIsTargetsNestedClass_PrivateMixin.MasterWrapper>(
                            target);
            }
        }

        private __Mixins _____mixins;
        private __Mixins ___mixins
        {
            get
            {
                if (null == _____mixins)
                {
                    lock (__Mixins.____Lock)
                    {
                        if (null == _____mixins)
                        {
                            _____mixins = new __Mixins(this);
                        }
                    }
                }
                return _____mixins;
            }
        }

        public string BaseMethod()
        {
            return ___mixins.PrivateMixinMasterWrapper.BaseMethod();
        }
        public string MixinMethod()
        {
            return ___mixins.PrivateMixinMasterWrapper.MixinMethod();
        }

        public string IInterfaceMethod()
        {
            return ___mixins.PrivateMixinMasterWrapper.IInterfaceMethod();
        }

        /// <summary>
        /// Static implicit operator to Mixin's public base class
        /// </summary>
        public static implicit operator BaseClass(MixinIsTargetsNestedClassSpec target)
        {
            return target.___mixins.PrivateMixinMasterWrapper.PrivateMixin;
        }

        PrivateMixin IWrap<MixinIsTargetsNestedClassSpec.PrivateMixin>.GetWrappedItem()
        {
            return ___mixins.PrivateMixinMasterWrapper.PrivateMixin;
        }
    }
}


text:
A golang implementation of the BIP0039 spec for mnemonic seeds

## Credits

English wordlist and test vectors are from the standard Python BIP0039 implementation
from the Trezor guys: [https://github.com/trezor/python-mnemonic](https://github.com/trezor/python-mnemonic)

## Example

```go
package main

import (
  "github.com/tyler-smith/go-bip39"
  "github.com/tyler-smith/go-bip32"
  "fmt"
)

func main(){
  // Generate a mnemonic for memorization or user-friendly seeds
  entropy, _ := bip39.NewEntropy(256)
  mnemonic, _ := bip39.NewMnemonic(entropy)

  // Generate a Bip32 HD wallet for the mnemonic and a user supplied password
  seed := bip39.NewSeed(mnemonic, "Secret Passphrase")

  masterKey, _ := bip32.NewMasterKey(seed)
  publicKey := masterKey.PublicKey()

  // Display mnemonic and keys
  fmt.Println("Mnemonic: ", mnemonic)
  fmt.Println("Master private key: ", masterKey)
  fmt.Println("Master public key: ", publicKey)
}
```


text:
"use strict";
var R = require('ramda');

function isFeatureEnabledInSettings(feature, settingsField) {
  if (R.isNil(settingsField)) {
    return false;
  }
  if (settingsField.hasOwnProperty("value")
    && R.is(Object, settingsField.value)
    && settingsField.value.hasOwnProperty("features")
    && settingsField.value.features.hasOwnProperty("value")
    && R.is(Array, settingsField.value.features.value)) {
    return !!R.find(function (f) {
      return f.id.value === feature;
    }, settingsField.value.features.value);
  } else if (settingsField.hasOwnProperty("features")
    && R.is(Array, settingsField.features)) {
    return !!R.find(function (f) {
      return f.id === feature;
    }, settingsField.features);
  }
  return false;
}

function isFeatureEnabledForAnyAccount(feature, authenticationUIProps) {
  var accountTypes = [
    'contractorAccounts',
    'customerAccounts',
    'operationsAccounts',
    'partnerAccounts'
  ];
  var features = R.flatten(
    R.map(function(type) {
      var relationName = type.slice(0, -1);
      return R.pipe(
        R.filter(function (mapping) {
          return mapping[relationName].settings && mapping[relationName].settings.features;
        }),
        R.map(function (mapping) {
          return mapping[relationName].settings.features;
        })
      )(authenticationUIProps[type]);
    }, accountTypes)
  );
  return !!R.find(function (f) {
    return f.id === feature;
  }, features);
}

module.exports = {
  "isFeatureEnabledInSettings": isFeatureEnabledInSettings,
  "isFeatureEnabledForAnyAccount": isFeatureEnabledForAnyAccount
};


text:
/*
 * Uglify Configuration
 *
 * See all options: https://github.com/gruntjs/grunt-contrib-uglify
 */
module.exports = function( grunt ) {

    grunt.config( 'uglify', {

        dist: {

            files: {
            	'js/app/popup-min.js': ['js/app/popup.js'],
            	'js/plugin/bootstrap-min.js': ['js/plugin/bootstrap.js'],
            	'js/plugin/content-scripts-min.js': ['js/plugin/content-scripts.js'],
        			}

        }
    });

    grunt.loadNpmTasks('grunt-contrib-uglify');
};


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Tax',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('rate', models.FloatField(default=0, verbose_name='Rate')),
                ('description', models.TextField(verbose_name='Description', blank=True)),
            ],
        ),
    ]


text:
using System;
using System.Buffers;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace StackExchange.Metrics.Infrastructure
{

    /// <summary>
    /// Abstract implementation of <see cref="BufferedMetricHandler" /> that posts content to an HTTP endpoint.
    /// </summary>
    public abstract class BufferedHttpMetricHandler : BufferedMetricHandler
    {
        private readonly Lazy<HttpClient> _httpClientFactory;

        /// <summary>
        /// Constructs an instance of <see cref="BufferedHttpMetricHandler" /> that sends metric data using an <see cref="HttpClient" />.
        /// </summary>
        protected BufferedHttpMetricHandler()
        {
            _httpClientFactory = new Lazy<HttpClient>(CreateHttpClient);
        }

        /// <inheritdoc />
        public override void Dispose()
        {
            if (_httpClientFactory.IsValueCreated)
            {
                _httpClientFactory.Value.Dispose();
            }
        }

        /// <inheritdoc />
        protected override ValueTask SendAsync(PayloadType payloadType, ReadOnlySequence<byte> sequence)
        {
            switch (payloadType)
            {
                case PayloadType.Metadata:
                    return SendMetadataAsync(sequence);
                case PayloadType.Counter:
                    return SendCounterAsync(sequence);
                case PayloadType.CumulativeCounter:
                    return SendCumulativeCounterAsync(sequence);
                case PayloadType.Gauge:
                    return SendGaugeAsync(sequence);
                default:
                    throw new ArgumentOutOfRangeException(nameof(payloadType));
            }
        }

        /// <summary>
        /// Sends a buffer containing counters to an HTTP endpoint.
        /// </summary>
        /// <param name="sequence">
        /// <see cref="ReadOnlySequence{T}" /> containing the data to send.
        /// </param>
        protected abstract ValueTask SendCounterAsync(ReadOnlySequence<byte> sequence);

        /// <summary>
        /// Sends a buffer containing cumulative counter metrics to an HTTP endpoint.
        /// </summary>
        /// <param name="sequence">
        /// <see cref="ReadOnlySequence{T}" /> containing the data to send.
        /// </param>
        protected abstract ValueTask SendCumulativeCounterAsync(ReadOnlySequence<byte> sequence);

        /// <summary>
        /// Sends a buffer containing gauge metrics to an HTTP endpoint.
        /// </summary>
        /// <param name="sequence">
        /// <see cref="ReadOnlySequence{T}" /> containing the data to send.
        /// </param>
        protected abstract ValueTask SendGaugeAsync(ReadOnlySequence<byte> sequence);

        /// <summary>
        /// Sends a buffer containing metadata to an HTTP endpoint.
        /// </summary>
        /// <param name="sequence">
        /// <see cref="ReadOnlySequence{T}" /> containing the data to send.
        /// </param>
        protected abstract ValueTask SendMetadataAsync(ReadOnlySequence<byte> sequence);

        /// <summary>
        /// Gets the length of the preamble for a given type of payload.
        /// </summary>
        /// <param name="payloadType">
        /// A <see cref="PayloadType" /> value.
        /// </param>
        protected abstract int GetPreambleLength(PayloadType payloadType);

        /// <summary>
        /// Writes a preamble to the underlying HTTP stream.
        /// </summary>
        /// <param name="stream">Stream to write to.</param>
        /// <param name="payloadType">
        /// A <see cref="PayloadType" /> value.
        /// </param>
        protected abstract Task WritePreambleAsync(Stream stream, PayloadType payloadType);

        /// <summary>
        /// Gets the length of the postamble for a given type of payload
        /// </summary>
        /// <param name="payloadType">
        /// A <see cref="PayloadType" /> value.
        /// </param>
        protected abstract int GetPostambleLength(PayloadType payloadType);

        /// <summary>
        /// Writes a postamble to the underlying HTTP stream.
        /// </summary>
        /// <param name="stream">Stream to write to.</param>
        /// <param name="payloadType">
        /// A <see cref="PayloadType" /> value.
        /// </param>
        protected abstract Task WritePostambleAsync(Stream stream, PayloadType payloadType);

        /// <summary>
        /// Creates an <see cref="HttpClient" /> used for sending data to the endpoint.
        /// </summary>
        protected virtual HttpClient CreateHttpClient() => new HttpClient();

        /// <inheritdoc />
        protected async ValueTask SendAsync(Uri uri, HttpMethod method, PayloadType payloadType, MediaTypeHeaderValue mediaType, ReadOnlySequence<byte> sequence, bool gzip = true)
        {
            if (uri == null)
            {
                return;
            }

            var preambleLength = GetPreambleLength(payloadType);
            var postambleLength = GetPostambleLength(payloadType);
            var request = new HttpRequestMessage(method, uri)
            {
                Content = new ReadOnlySequenceContent(gzip, payloadType, mediaType, sequence, preambleLength, WritePreambleAsync, postambleLength, WritePostambleAsync)
            };

            var response = await _httpClientFactory.Value.SendAsync(request);
            if (!response.IsSuccessStatusCode)
            {
                var requestText = string.Empty;
                var responseText = string.Empty;
                try
                {
                    requestText = await request.Content.ReadAsStringAsync();
                    responseText = await response.Content.ReadAsStringAsync();
                }
                catch
                {
                    // nothing we can do here
                }

                throw new HttpRequestException($"Response status code does not indicate success: {response.StatusCode}.")
                {
                    Data =
                    {
                        ["Request"] = requestText,
                        ["Response"] = responseText
                    }
                };
            }
        }

        private class ReadOnlySequenceContent : HttpContent
        {
            readonly bool _gzip;
            readonly PayloadType _type;
            readonly ReadOnlySequence<byte> _sequence;
            readonly Func<Stream, PayloadType, Task> _writePreamble;
            readonly Func<Stream, PayloadType, Task> _writePostamble;
            readonly long _length;

            public ReadOnlySequenceContent(
                bool gzip,
                PayloadType type,
                MediaTypeHeaderValue mediaType,
                in ReadOnlySequence<byte> sequence,
                int preambleLength,
                Func<Stream, PayloadType, Task> writePreamble,
                int postambleLength,
                Func<Stream, PayloadType, Task> writePostamble
            )
            {
                _gzip = gzip;
                _type = type;
                _sequence = sequence;
                _length = sequence.Length + preambleLength + postambleLength;
                _writePreamble = writePreamble;
                _writePostamble = writePostamble;

                Headers.ContentType = mediaType;
                if (gzip)
                {
                    Headers.ContentEncoding.Add("gzip");
                }
            }

            protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context)
            {
                IDisposable toDispose = null;
                if (_gzip)
                {
                    toDispose = stream = new GZipStream(stream, CompressionMode.Compress, leaveOpen: true);
                }

                using (toDispose)
                {
                    await _writePreamble(stream, _type);
                    await stream.WriteAsync(_sequence);
                    await _writePostamble(stream, _type);
                }
            }

            protected override bool TryComputeLength(out long length)
            {
                length = _length;
                return false;
            }
        }
    }
}


text:
from typing import List, Optional

from ...requests import Request
from ...responses import StreamResponse
from ._history_item import HistoryItem
from ._history_request import HistoryRequest
from ._history_response import HistoryResponse

__all__ = ("HistoryRepository",)

class HistoryRepository:
    def __init__(self) -> None:
        self._storage: List[HistoryItem] = []

    async def add(self,
                  request: Request,
                  response: StreamResponse,
                  tags: Optional[List[str]] = None) -> None:
        req = await HistoryRequest.from_request(request)
        res = await HistoryResponse.from_response(response)
        self._storage.insert(0, {
            "request": req,
            "response": res,
            "tags": tags or [],
        })

    async def delete_by_tag(self, tag: str) -> None:
        self._storage = [x for x in self._storage if tag not in x["tags"]]

    async def get_by_tag(self, tag: str) -> List[HistoryItem]:
        return [x for x in self._storage if tag in x["tags"]]


text:
import java.awt.Graphics;
import java.awt.Image;

public class Sprite {
    private Image image; //изображение

    public Sprite(Image image) {
        this.image = image;
    }

    public int getWidth() { //получаем ширину картинки
        return image.getWidth(null);
    }

    public int getHeight() { //получаем высоту картинки
        return image.getHeight(null);
    }

    public void draw(Graphics g,int x,int y, int scale) { //рисуем картинку
        g.drawImage(image, x, y, scale, scale, null);
    }
}


text:
function R = resistance(g)
% R = resistance(g) --- calculate resistances between vertices
% g is a connected, undirected weighted graph. Returns a matrix R whose
% (i,j)-entry is the effective resistance between vertices i and j
% where we assume each edge represents a resistance equal to the weight
% of the edge.
%
% Author: Somit Gupta

if(isconnected(g)) %to test for connected graphs as the formulae works only for connected graphs
	l= laplacian(g); % gets the laplacian of the graph
	m=nv(g); %no of vertices
	% R=[0];
	lp=pinv(l);

	d=diag(lp);
	rowMatrix=d*ones(1,m);
	R = rowMatrix+rowMatrix'-2*lp;
else
    error('The graph is not connected')
end


text:
/* @flow */

import DataType from '../data-types';
import FieldType from '../field-type';

export default class NumberSchema {
  name: string;
  fieldType: DataType;
  type: FieldType;
  isRequired: boolean;
  decimalPlaces: number;
  defaultValue: number;
  minValue: number;
  maxValue: number;
  labelText: string;
  disabled: boolean;

  constructor(name: string) {
    this.name = name;
    this.fieldType = DataType.Number;
    this.type = FieldType.Number;
    this.isRequired = false;
    this.decimalPlaces = 0;
    this.disabled = false;
    this.defaultValue = '';
  }

  readOnly() : NumberSchema {
    this.disabled = true;
    return this;
  }

  default(defaultValue: number): NumberSchema {
    this.defaultValue = defaultValue;
    return this;
  }

  decimal(decimalPlaces: number) : NumberSchema {
    this.decimalPlaces = decimalPlaces;
    return this;
  }

  min(minValue: number) : NumberSchema {
    this.minValue = minValue;
    return this;
  }

  max(maxValue: number) : NumberSchema {
    this.maxValue = maxValue;
    return this;
  }

  mandatory() : NumberSchema {
    this.isRequired = true;
    return this;
  }

  label(labelText: string) : NumberSchema {
    this.labelText = labelText;
    return this;
  }
}