text:
/**************************************************************************//**
 * @file     timer_reg.h
 * @version  V1.00
 * @brief    TIMER register definition header file
 *
 * SPDX-License-Identifier: Apache-2.0
 * @copyright (C) 2018 Nuvoton Technology Corp. All rights reserved.
 *****************************************************************************/
#ifndef __TIMER_REG_H__
#define __TIMER_REG_H__

#if defined ( __CC_ARM   )
#pragma anon_unions
#endif

/**
   @addtogroup REGISTER Control Register
   @{
*/

/**
    @addtogroup TIMER Timer Controller (TIMER)
    Memory Mapped Structure for TIMER Controller
@{ */

typedef struct
{

    /**
     * @var TIMER_T::CTL
     * Offset: 0x00/0x20  Timer0~3 Control Register
     * ---------------------------------------------------------------------------------------------------
     * |Bits    |Field     |Descriptions
     * | :----: | :----:   | :---- |
     * |[7:0]   |PSC       |Prescale Counter
     * |        |          |Timer input clock or event source is divided by (PSC+1) before it is fed to the timer up counter. If this field is 0 (PSC = 0), then there is no scaling.
     * |        |          |Note: Update prescale counter value will reset internal 8-bit prescale counter and 24-bit up counter value.
     * |[8]     |TRGPDMA   |Trigger PDMA Enable Bit
     * |        |          |If this bit is set to 1, timer time-out interrupt or capture interrupt can trigger PDMA.
     * |        |          |0 = Timer interrupt trigger PDMA Disabled.
     * |        |          |1 = Timer interrupt trigger PDMA Enabled.
     * |        |          |Note: If TRGSSEL (TIMERx_CTL[18]) = 0, time-out interrupt signal will trigger PDMA. If TRGSSEL (TIMERx_CTL[18]) = 1, capture interrupt signal will trigger PDMA.
     * |[9]     |TRGBPWM   |Trigger BPWM Enable Bit
     * |        |          |If this bit is set to 1, timer time-out interrupt or capture interrupt can trigger BPWM.
     * |        |          |0 = Timer interrupt trigger BPWM Disabled.
     * |        |          |1 = Timer interrupt trigger BPWM Enabled.
     * |        |          |Note: If TRGSSEL (TIMERx_CTL[18]) = 0, time-out interrupt signal will trigger BPWM. If TRGSSEL (TIMERx_CTL[18]) = 1, capture interrupt signal will trigger BPWM.
     * |[10]    |INTRGEN   |Inter-timer Trigger Mode Enable Bit
     * |        |          |Setting this bit will enable the inter-timer trigger capture function.
     * |        |          |The Timer0/2 will be in event counter mode and counting with external clock source or event. Also, Timer1/3 will be in trigger-counting mode of capture function.
     * |        |          |0 = Inter-Timer Trigger mode Disabled.
     * |        |          |1 = Inter-Timer Trigger mode Enabled.
     * |        |          |Note: For Timer1/3, this bit is ignored and the read back value is always 0.
     * |[16]    |CAPSRC    |Capture Pin Source Selection
     * |        |          |0 = Capture Function source is from TMx_EXT (x= 0~3) pin.
     * |        |          |1 = Capture Function source is from internal ACMP output signal or LIRC. User can set INTERCAPSEL (TIMERx_EXTCTL[10:8]) to decide which internal ACMP output signal or LIRC as timer capture source.
     * |[18]    |TRGSSEL   |Trigger Source Select Bit
     * |        |          |This bit is used to select trigger source is from Timer time-out interrupt signal or capture interrupt signal.
     * |        |          |0 = Timer time-out interrupt signal is used to trigger PWM, ADC and PDMA.
     * |        |          |1 = Capture interrupt signal is used to trigger PWM, ADC and PDMA.
     * |[19]    |TRGPWM    |Trigger PWM Enable Bit
     * |        |          |If this bit is set to 1, timer time-out interrupt or capture interrupt can trigger PWM.
     * |        |          |0 = Timer interrupt trigger PWM Disabled.
     * |        |          |1 = Timer interrupt trigger PWM Enabled.
     * |        |          |Note: If TRGSSEL (TIMERx_CTL[18]) = 0, time-out interrupt signal will trigger PWM. If TRGSSEL (TIMERx_CTL[18]) = 1, capture interrupt signal will trigger PWM.
     * |[21]    |TRGADC    |Trigger ADC Enable Bit
     * |        |          |If this bit is set to 1, timer time-out interrupt or capture interrupt can trigger ADC.
     * |        |          |0 = Timer interrupt trigger ADC Disabled.
     * |        |          |1 = Timer interrupt trigger ADC Enabled.
     * |        |          |Note: If TRGSSEL (TIMERx_CTL[18]) = 0, time-out interrupt signal will trigger ADC. If TRGSSEL (TIMERx_CTL[18]) = 1, capture interrupt signal will trigger ADC.
     * |[22]    |TGLPINSEL |Toggle-output Pin Select
     * |        |          |0 = Toggle mode output to Tx (Timer Event Counter Pin).
     * |        |          |1 = Toggle mode output to Tx_EXT (Timer External Capture Pin).
     * |[23]    |WKEN      |Wake-up Function Enable Bit
     * |        |          |If this bit is set to 1, while timer interrupt flag TIF (TIMERx_INTSTS[0]) is 1 and INTEN (TIMERx_CTL[29]) is enabled, the timer interrupt signal will generate a wake-up trigger event to CPU.
     * |        |          |0 = Wake-up function Disabled if timer interrupt signal generated.
     * |        |          |1 = Wake-up function Enabled if timer interrupt signal generated.
     * |[24]    |EXTCNTEN  |Event Counter Mode Enable Bit
     * |        |          |This bit is for external counting pin function enabled.
     * |        |          |0 = Event counter mode Disabled.
     * |        |          |1 = Event counter mode Enabled.
     * |        |          |Note1: When timer is used as an event counter, this bit should be set to 1 and select PCLKx (x=0~1) as timer clock source.
     * |        |          |Note2: When TMR0/TMR2 INTRGEN is set to 1, this bit is forced to 1. When INTRGEN is 1 and TMR1/TMR3 CAPIF (TIMERx_EINTSTS[0]) is 1, this bit is forced to 0.
     * |[25]    |ACTSTS    |Timer Active Status Bit (Read Only)
     * |        |          |This bit indicates the 24-bit up counter status.
     * |        |          |0 = 24-bit up counter is not active.
     * |        |          |1 = 24-bit up counter is active.
     * |        |          |Note: This bit may active when CNT 0 transition to CNT 1.
     * |[26]    |RSTCNT    |Timer Counter Reset Bit
     * |        |          |Setting this bit will reset the 24-bit up counter value CNT (TIMERx_CNT[23:0]) and also force CNTEN (TIMERx_CTL[30]) to 0 if ACTSTS (TIMERx_CTL[25]) is 1.
     * |        |          |0 = No effect.
     * |        |          |1 = Reset internal 8-bit prescale counter, 24-bit up counter value and CNTEN bit.
     * |        |          |Note: This bit will be auto cleared.
     * |[28:27] |OPMODE    |Timer Counting Mode Select
     * |        |          |00 = The timer controller is operated in One-shot mode.
     * |        |          |01 = The timer controller is operated in Periodic mode.
     * |        |          |10 = The timer controller is operated in Toggle-output mode.
     * |        |          |11 = The timer controller is operated in Continuous Counting mode.
     * |[29]    |INTEN     |Timer Interrupt Enable Bit
     * |        |          |0 = Timer time-out interrupt Disabled.
     * |        |          |1 = Timer time-out interrupt Enabled.
     * |        |          |Note: If this bit is enabled, when the timer time-out interrupt flag TIF is set to 1, the timer interrupt signal is generated and inform to CPU.
     * |[30]    |CNTEN     |Timer Counting Enable Bit
     * |        |          |0 = Stops/Suspends counting.
     * |        |          |1 = Starts counting.
     * |        |          |Note1: In stop status, and then set CNTEN to 1 will enable the 24-bit up counter to keep counting from the last stop counting value.
     * |        |          |Note2: This bit is auto-cleared by hardware in one-shot mode (TIMER_CTL[28:27] = 00) when the timer time-out interrupt flag TIF (TIMERx_INTSTS[0]) is generated.
     * |        |          |Note3: Set enable/disable this bit needs 2 * TMR_CLK period to become active, user can read ACTSTS (TIMERx_CTL[25]) to check enable/disable command is completed or not.
     * |[31]    |ICEDEBUG  |ICE Debug Mode Acknowledge Disable Bit (Write Protect)
     * |        |          |0 = ICE debug mode acknowledgement effects TIMER counting.
     * |        |          |TIMER counter will be held while CPU is held by ICE.
     * |        |          |1 = ICE debug mode acknowledgement Disabled.
     * |        |          |TIMER counter will keep going no matter CPU is held by ICE or not.
     * |        |          |Note: This bit is write protected. Refer to the SYS_REGLCTL register.
     * @var TIMER_T::CMP
     * Offset: 0x04/0x24  Timer0~3 Comparator Register
     * ---------------------------------------------------------------------------------------------------
     * |Bits    |Field     |Descriptions
     * | :----: | :----:   | :---- |
     * |[23:0]  |CMPDAT    |Timer Comparator Value
     * |        |          |CMPDAT is a 24-bit compared value register
     * |        |          |When the internal 24-bit up counter value is equal to CMPDAT value, the TIF (TIMERx_INTSTS[0] Timer Interrupt Flag) will set to 1.
     * |        |          |Time-out period = (Period of timer clock input) * (8-bit PSC + 1) * (24-bit CMPDAT).
     * |        |          |Note1: Never write 0x0 or 0x1 in CMPDAT field, or the core will run into unknown state.
     * |        |          |Note2: When timer is operating at continuous counting mode, the 24-bit up counter will keep counting continuously even if user writes a new value into CMPDAT field. But if timer is operating at other modes, the 24-bit up counter will restart counting from 0 and using newest CMPDAT value to be the timer compared value while user writes a new value into CMPDAT field.
     * @var TIMER_T::INTSTS
     * Offset: 0x08/0x28  Timer0~3 Interrupt Status Register
     * ---------------------------------------------------------------------------------------------------
     * |Bits    |Field     |Descriptions
     * | :----: | :----:   | :---- |
     * |[0]     |TIF       |Timer Interrupt Flag
     * |        |          |This bit indicates the interrupt flag status of Timer while 24-bit timer up counter CNT (TIMERx_CNT[23:0]) value reaches to CMPDAT (TIMERx_CMP[23:0]) value.
     * |        |          |0 = No effect.
     * |        |          |1 = CNT value matches the CMPDAT value.
     * |        |          |Note: This bit is cleared by writing 1 to it.
     * |[1]     |TWKF      |Timer Wake-up Flag
     * |        |          |This bit indicates the interrupt wake-up flag status of timer.
     * |        |          |0 = Timer does not cause CPU wake-up.
     * |        |          |1 = CPU wake-up from Idle or Power-down mode if timer time-out interrupt signal generated.
     * |        |          |Note: This bit is cleared by writing 1 to it.
     * @var TIMER_T::CNT
     * Offset: 0x0C/0x2C  Timer0~3 Data Register
     * ---------------------------------------------------------------------------------------------------
     * |Bits    |Field     |Descriptions
     * | :----: | :----:   | :---- |
     * |[23:0]  |CNT       |Timer Data Register
     * |        |          |Read this register to get CNT value. For example:
     * |        |          |If EXTCNTEN (TIMERx_CTL[24]) is 0, user can read CNT value for getting current 24-bit counter value.
     * |        |          |If EXTCNTEN (TIMERx_CTL[24]) is 1, user can read CNT value for getting current 24-bit event input counter value.
     * @var TIMER_T::CAP
     * Offset: 0x10/0x30  Timer0~3 Capture Data Register
     * ---------------------------------------------------------------------------------------------------
     * |Bits    |Field     |Descriptions
     * | :----: | :----:   | :---- |
     * |[23:0]  |CAPDAT    |Timer Capture Data Register
     * |        |          |When CAPEN (TIMERx_EXTCTL[3]) bit is set, CAPFUNCS (TIMERx_EXTCTL[4]) bit is 0, and a transition on TMx_EXT pin matched the CAPEDGE (TIMERx_EXTCTL[2:1]) setting, CAPIF (TIMERx_EINTSTS[0]) will set to 1 and the current timer counter value CNT (TIMERx_CNT[23:0]) will be auto-loaded into this CAPDAT field.
     * @var TIMER_T::EXTCTL
     * Offset: 0x14/0x34  Timer0~3 External Control Register
     * ---------------------------------------------------------------------------------------------------
     * |Bits    |Field     |Descriptions
     * | :----: | :----:   | :---- |
     * |[0]     |CNTPHASE  |Timer External Count Phase
     * |        |          |This bit indicates the detection phase of external counting pin TMx (x= 0~3).
     * |        |          |0 = A falling edge of external counting pin will be counted.
     * |        |          |1 = A rising edge of external counting pin will be counted.
     * |[2:1]   |CAPEDGE   |Timer External Capture Pin Edge Detect
     * |        |          |00 = A Falling edge on Tx_EXT (x= 0~3) pin, LIRC or ACMPx (x=0~1) will be detected.
     * |        |          |01 = A Rising edge on Tx_EXT (x= 0~3) pin, LIRC or ACMPx (x=0~1) will be detected.
     * |        |          |10 = Either Rising or Falling edge on Tx_EXT (x= 0~3) pin, LIRC or ACMPx (x=0~1) will be detected.
     * |        |          |11 = Reserved.
     * |[3]     |CAPEN     |Timer Capture Enable Bit
     * |        |          |This bit enables the capture input function.
     * |        |          |0 =Capture source Disabled.
     * |        |          |1 =Capture source Enabled.
     * |        |          |Note: TMR1/TMR3 CAPEN will be forced to 1 when TMR0/TMR2 INTRGEN is enabled.
     * |[4]     |CAPFUNCS  |Capture Function Selection
     * |        |          |0 = External Capture Mode Enabled.
     * |        |          |1 = External Reset Mode Enabled.
     * |        |          |Note1: When CAPFUNCS is 0, transition on TMx_EXT (x= 0~3) pin is using to save current 24-bit timer counter value (CNT value) to CAPDAT field.
     * |        |          |Note2: When CAPFUNCS is 1, transition on TMx_EXT (x= 0~3) pin is using to save current 24-bit timer counter value (CNT value) to CAPDAT field then CNT value will be reset immediately.
     * |[5]     |CAPIEN    |Timer External Capture Interrupt Enable Bit
     * |        |          |0 = TMx_EXT (x= 0~3) pin, LIRC, or ACMP detection Interrupt Disabled.
     * |        |          |1 = TMx_EXT (x= 0~3) pin, LIRC, or ACMP detection Interrupt Enabled.
     * |        |          |Note: CAPIEN is used to enable timer external interrupt
     * |        |          |If CAPIEN enabled, timer will rise an interrupt when CAPIF (TIMERx_EINTSTS[0]) is 1.
     * |        |          |For example, while CAPIEN = 1, CAPEN = 1, and CAPEDGE = 00, a 1 to 0 transition on the Tx_EXT (x= 0~3) pin, or ACMP will cause the CAPIF to be set then the interrupt signal is generated and sent to NVIC to inform CPU.
     * |[6]     |CAPDBEN   |Timer External Capture Pin De-bounce Enable Bit
     * |        |          |0 = TMx_EXT (x= 0~3) pin de-bounce or ACMP output de-bounce Disabled.
     * |        |          |1 = TMx_EXT (x= 0~3) pin de-bounce or ACMP output de-bounce Enabled.
     * |        |          |Note: If this bit is enabled, the edge detection of TMx_EXT pin or ACMP output is detected with de-bounce circuit.
     * |[7]     |CNTDBEN   |Timer Counter Pin De-bounce Enable Bit
     * |        |          |0 = TMx (x= 0~3) pin de-bounce Disabled.
     * |        |          |1 = TMx (x= 0~3) pin de-bounce Enabled.
     * |        |          |Note: If this bit is enabled, the edge detection of TMx pin is detected with de-bounce circuit.
     * |[10:8]  |INTERCAPSEL|Internal Capture Source Selection to Trigger Capture Function
     * |        |          |000 = Capture Function source is from internal ACMP0 output signal.
     * |        |          |001 = Capture Function source is from internal ACMP1 output signal.
     * |        |          |101 = Capture Function source is from LIRC.
     * |        |          |Others = Reserved.
     * |        |          |Note: these bits only available when CAPSRC (TIMERx_CTL[16]) is 1.
     * |[16]    |ECNTSSEL  |Event Counter Source Selection to Trigger Event Counter Function
     * |        |          |0 = Event Counter input source is from TMx (x= 0~3) pin.
     * |        |          |1 = Event Counter input source is from USB internal SOF output signal.
     * @var TIMER_T::EINTSTS
     * Offset: 0x18/0x38  Timer0~3 External Interrupt Status Register
     * ---------------------------------------------------------------------------------------------------
     * |Bits    |Field     |Descriptions
     * | :----: | :----:   | :---- |
     * |[0]     |CAPIF     |Timer External Capture Interrupt Flag
     * |        |          |This bit indicates the timer external capture interrupt flag status.
     * |        |          |0 = TMx_EXT (x= 0~3) pin interrupt did not occur.
     * |        |          |1 = TMx_EXT (x= 0~3) pin interrupt occurred.
     * |        |          |Note1: This bit is cleared by writing 1 to it.
     * |        |          |Note2: When CAPEN (TIMERx_EXTCTL[3]) bit is set, CAPFUNCS (TIMERx_EXTCTL[4]) bit is 0, and a transition on Tx_EXT (x= 0~3) pin matched the CAPEDGE (TIMERx_EXTCTL[2:1]) setting, this bit will set to 1 by hardware.
     * |        |          |Note3: There is a new incoming capture event detected before CPU clearing the CAPIF status. If the above condition occurred, the Timer will keep register TIMERx_CAP unchanged and drop the new capture value.
     */
    __IO uint32_t CTL;                   /*!< [0x0000] Timer0 Control Register                                          */
    __IO uint32_t CMP;                   /*!< [0x0004] Timer0 Comparator Register                                       */
    __IO uint32_t INTSTS;                /*!< [0x0008] Timer0 Interrupt Status Register                                 */
    __I  uint32_t CNT;                   /*!< [0x000c] Timer0 Data Register                                             */
    __I  uint32_t CAP;                   /*!< [0x0010] Timer0 Capture Data Register                                     */
    __IO uint32_t EXTCTL;                /*!< [0x0014] Timer0 External Control Register                                 */
    __IO uint32_t EINTSTS;               /*!< [0x0018] Timer0 External Interrupt Status Register                        */
} TIMER_T;

/**
    @addtogroup TIMER_CONST TIMER Bit Field Definition
    Constant Definitions for TIMER Controller
@{ */

#define TIMER_CTL_PSC_Pos                (0)                                               /*!< TIMER_T::CTL: PSC Position             */
#define TIMER_CTL_PSC_Msk                (0xfful << TIMER_CTL_PSC_Pos)                     /*!< TIMER_T::CTL: PSC Mask                 */

#define TIMER_CTL_TRGPDMA_Pos            (8)                                               /*!< TIMER_T::CTL: TRGPDMA Position         */
#define TIMER_CTL_TRGPDMA_Msk            (0x1ul << TIMER_CTL_TRGPDMA_Pos)                  /*!< TIMER_T::CTL: TRGPDMA Mask             */

#define TIMER_CTL_TRGBPWM_Pos            (9)                                               /*!< TIMER_T::CTL: TRGBPWM Position         */
#define TIMER_CTL_TRGBPWM_Msk            (0x1ul << TIMER_CTL_TRGBPWM_Pos)                  /*!< TIMER_T::CTL: TRGBPWM Mask             */

#define TIMER_CTL_INTRGEN_Pos            (10)                                              /*!< TIMER_T::CTL: INTRGEN Position         */
#define TIMER_CTL_INTRGEN_Msk            (0x1ul << TIMER_CTL_INTRGEN_Pos)                  /*!< TIMER_T::CTL: INTRGEN Mask             */

#define TIMER_CTL_CAPSRC_Pos             (16)                                              /*!< TIMER_T::CTL: CAPSRC Position          */
#define TIMER_CTL_CAPSRC_Msk             (0x1ul << TIMER_CTL_CAPSRC_Pos)                   /*!< TIMER_T::CTL: CAPSRC Mask              */

#define TIMER_CTL_TRGSSEL_Pos            (18)                                              /*!< TIMER_T::CTL: TRGSSEL Position         */
#define TIMER_CTL_TRGSSEL_Msk            (0x1ul << TIMER_CTL_TRGSSEL_Pos)                  /*!< TIMER_T::CTL: TRGSSEL Mask             */

#define TIMER_CTL_TRGPWM_Pos             (19)                                              /*!< TIMER_T::CTL: TRGPWM Position          */
#define TIMER_CTL_TRGPWM_Msk             (0x1ul << TIMER_CTL_TRGPWM_Pos)                   /*!< TIMER_T::CTL: TRGPWM Mask              */

#define TIMER_CTL_TRGADC_Pos             (21)                                              /*!< TIMER_T::CTL: TRGADC Position          */
#define TIMER_CTL_TRGADC_Msk             (0x1ul << TIMER_CTL_TRGADC_Pos)                   /*!< TIMER_T::CTL: TRGADC Mask              */

#define TIMER_CTL_TGLPINSEL_Pos          (22)                                              /*!< TIMER_T::CTL: TGLPINSEL Position       */
#define TIMER_CTL_TGLPINSEL_Msk          (0x1ul << TIMER_CTL_TGLPINSEL_Pos)                /*!< TIMER_T::CTL: TGLPINSEL Mask           */

#define TIMER_CTL_WKEN_Pos               (23)                                              /*!< TIMER_T::CTL: WKEN Position            */
#define TIMER_CTL_WKEN_Msk               (0x1ul << TIMER_CTL_WKEN_Pos)                     /*!< TIMER_T::CTL: WKEN Mask                */

#define TIMER_CTL_EXTCNTEN_Pos           (24)                                              /*!< TIMER_T::CTL: EXTCNTEN Position        */
#define TIMER_CTL_EXTCNTEN_Msk           (0x1ul << TIMER_CTL_EXTCNTEN_Pos)                 /*!< TIMER_T::CTL: EXTCNTEN Mask            */

#define TIMER_CTL_ACTSTS_Pos             (25)                                              /*!< TIMER_T::CTL: ACTSTS Position          */
#define TIMER_CTL_ACTSTS_Msk             (0x1ul << TIMER_CTL_ACTSTS_Pos)                   /*!< TIMER_T::CTL: ACTSTS Mask              */

#define TIMER_CTL_RSTCNT_Pos             (26)                                              /*!< TIMER_T::CTL: RSTCNT Position          */
#define TIMER_CTL_RSTCNT_Msk             (0x1ul << TIMER_CTL_RSTCNT_Pos)                   /*!< TIMER_T::CTL: RSTCNT Mask              */

#define TIMER_CTL_OPMODE_Pos             (27)                                              /*!< TIMER_T::CTL: OPMODE Position          */
#define TIMER_CTL_OPMODE_Msk             (0x3ul << TIMER_CTL_OPMODE_Pos)                   /*!< TIMER_T::CTL: OPMODE Mask              */

#define TIMER_CTL_INTEN_Pos              (29)                                              /*!< TIMER_T::CTL: INTEN Position           */
#define TIMER_CTL_INTEN_Msk              (0x1ul << TIMER_CTL_INTEN_Pos)                    /*!< TIMER_T::CTL: INTEN Mask               */

#define TIMER_CTL_CNTEN_Pos              (30)                                              /*!< TIMER_T::CTL: CNTEN Position           */
#define TIMER_CTL_CNTEN_Msk              (0x1ul << TIMER_CTL_CNTEN_Pos)                    /*!< TIMER_T::CTL: CNTEN Mask               */

#define TIMER_CTL_ICEDEBUG_Pos           (31)                                              /*!< TIMER_T::CTL: ICEDEBUG Position        */
#define TIMER_CTL_ICEDEBUG_Msk           (0x1ul << TIMER_CTL_ICEDEBUG_Pos)                 /*!< TIMER_T::CTL: ICEDEBUG Mask            */

#define TIMER_CMP_CMPDAT_Pos             (0)                                               /*!< TIMER_T::CMP: CMPDAT Position          */
#define TIMER_CMP_CMPDAT_Msk             (0xfffffful << TIMER_CMP_CMPDAT_Pos)              /*!< TIMER_T::CMP: CMPDAT Mask              */

#define TIMER_INTSTS_TIF_Pos             (0)                                               /*!< TIMER_T::INTSTS: TIF Position          */
#define TIMER_INTSTS_TIF_Msk             (0x1ul << TIMER_INTSTS_TIF_Pos)                   /*!< TIMER_T::INTSTS: TIF Mask              */

#define TIMER_INTSTS_TWKF_Pos            (1)                                               /*!< TIMER_T::INTSTS: TWKF Position         */
#define TIMER_INTSTS_TWKF_Msk            (0x1ul << TIMER_INTSTS_TWKF_Pos)                  /*!< TIMER_T::INTSTS: TWKF Mask             */

#define TIMER_CNT_CNT_Pos                (0)                                               /*!< TIMER_T::CNT: CNT Position             */
#define TIMER_CNT_CNT_Msk                (0xfffffful << TIMER_CNT_CNT_Pos)                 /*!< TIMER_T::CNT: CNT Mask                 */

#define TIMER_CAP_CAPDAT_Pos             (0)                                               /*!< TIMER_T::CAP: CAPDAT Position          */
#define TIMER_CAP_CAPDAT_Msk             (0xfffffful << TIMER_CAP_CAPDAT_Pos)              /*!< TIMER_T::CAP: CAPDAT Mask              */

#define TIMER_EXTCTL_CNTPHASE_Pos        (0)                                               /*!< TIMER_T::EXTCTL: CNTPHASE Position     */
#define TIMER_EXTCTL_CNTPHASE_Msk        (0x1ul << TIMER_EXTCTL_CNTPHASE_Pos)              /*!< TIMER_T::EXTCTL: CNTPHASE Mask         */

#define TIMER_EXTCTL_CAPEDGE_Pos         (1)                                               /*!< TIMER_T::EXTCTL: CAPEDGE Position      */
#define TIMER_EXTCTL_CAPEDGE_Msk         (0x3ul << TIMER_EXTCTL_CAPEDGE_Pos)               /*!< TIMER_T::EXTCTL: CAPEDGE Mask          */

#define TIMER_EXTCTL_CAPEN_Pos           (3)                                               /*!< TIMER_T::EXTCTL: CAPEN Position        */
#define TIMER_EXTCTL_CAPEN_Msk           (0x1ul << TIMER_EXTCTL_CAPEN_Pos)                 /*!< TIMER_T::EXTCTL: CAPEN Mask            */

#define TIMER_EXTCTL_CAPFUNCS_Pos        (4)                                               /*!< TIMER_T::EXTCTL: CAPFUNCS Position     */
#define TIMER_EXTCTL_CAPFUNCS_Msk        (0x1ul << TIMER_EXTCTL_CAPFUNCS_Pos)              /*!< TIMER_T::EXTCTL: CAPFUNCS Mask         */

#define TIMER_EXTCTL_CAPIEN_Pos          (5)                                               /*!< TIMER_T::EXTCTL: CAPIEN Position       */
#define TIMER_EXTCTL_CAPIEN_Msk          (0x1ul << TIMER_EXTCTL_CAPIEN_Pos)                /*!< TIMER_T::EXTCTL: CAPIEN Mask           */

#define TIMER_EXTCTL_CAPDBEN_Pos         (6)                                               /*!< TIMER_T::EXTCTL: CAPDBEN Position      */
#define TIMER_EXTCTL_CAPDBEN_Msk         (0x1ul << TIMER_EXTCTL_CAPDBEN_Pos)               /*!< TIMER_T::EXTCTL: CAPDBEN Mask          */

#define TIMER_EXTCTL_CNTDBEN_Pos         (7)                                               /*!< TIMER_T::EXTCTL: CNTDBEN Position      */
#define TIMER_EXTCTL_CNTDBEN_Msk         (0x1ul << TIMER_EXTCTL_CNTDBEN_Pos)               /*!< TIMER_T::EXTCTL: CNTDBEN Mask          */

#define TIMER_EXTCTL_INTERCAPSEL_Pos     (8)                                               /*!< TIMER_T::EXTCTL: INTERCAPSEL Position  */
#define TIMER_EXTCTL_INTERCAPSEL_Msk     (0x7ul << TIMER_EXTCTL_INTERCAPSEL_Pos)           /*!< TIMER_T::EXTCTL: INTERCAPSEL Mask      */

#define TIMER_EXTCTL_ECNTSSEL_Pos        (16)                                              /*!< TIMER_T::EXTCTL: ECNTSSEL Position     */
#define TIMER_EXTCTL_ECNTSSEL_Msk        (0x1ul << TIMER_EXTCTL_ECNTSSEL_Pos)              /*!< TIMER_T::EXTCTL: ECNTSSEL Mask         */

#define TIMER_EINTSTS_CAPIF_Pos          (0)                                               /*!< TIMER_T::EINTSTS: CAPIF Position       */
#define TIMER_EINTSTS_CAPIF_Msk          (0x1ul << TIMER_EINTSTS_CAPIF_Pos)                /*!< TIMER_T::EINTSTS: CAPIF Mask           */

/**@}*/ /* TIMER_CONST */
/**@}*/ /* end of TIMER register group */
/**@}*/ /* end of REGISTER group */

#if defined ( __CC_ARM   )
#pragma no_anon_unions
#endif

#endif /* __TIMER_REG_H__ */


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

    <meta http-equiv="Content-Language" content="en-ca" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link rel="stylesheet" type="text/css" href="../style.css" />
    <title><available> Task</title>

            NAnt

          Help

          Task Reference
           <available>

                        v0.86-beta1

<available>

[This is preliminary documentation and subject to change.]

      (Deprecated)

 Checks if a resource is available at runtime.

 The specified property is set to true if the requested resource is available at runtime, and false if the resource is not available.

      Note:  we advise you to use the following functions instead:

          Function
          Description

            file::exists()

          Determines whether the specified file exists.

            directory::exists()

          Determines whether the given path refers to an existing directory on disk.

            framework::exists()

          Checks whether the specified framework exists..

            framework::sdk-exists()

          Checks whether the SDK for the specified framework is installed.

Parameters

          Attribute
          Type
          Description
          Required

          property
          string
           The property that must be set if the resource is available.
          True

          resource
          string
           The resource which must be available.
          True

          type

            ResourceType

           The type of resource which must be present.
          True

          failonerror
          bool
           Determines if task failure stops the build, or is just reported. The default is true.
          False

          if
          bool
           If true then the task will be executed; otherwise, skipped. The default is true.
          False

          unless
          bool
           Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false.
          False

          verbose
          bool
           Determines whether the task should report detailed build log messages. The default is false.
          False

Examples

 Sets the myfile.present property to true if the file is available on the filesystem and false if the file is not available.

<available type="File" resource="myfile.txt" property="myfile.present" />

 Sets the build.dir.present property to true if the directory is available on the filesystem and false if the directory is not available.

<available type="Directory" resource="build" property="build.dir.present" />

 Sets the mono-0.21.framework.present property to true if the Mono 0.21 framework is available on the current system and false if the framework is not available.

<available type="Framework" resource="mono-0.21" property="mono-0.21.framework.present" />

 Sets the net-1.1.frameworksdk.present property to true if the .NET 1.1 Framework SDK is available on the current system and false if the SDK is not available.

<available type="FrameworkSDK" resource="net-1.1" property="net-1.1.frameworksdk.present" />

Requirements

      Assembly: NAnt.Core (0.86.2898.0)

redpajama_set_name: RedPajamaGithub


text:
class TransferMailer < ApplicationMailer
  def created_transfer(transfer)
    @transfer = transfer
    mail(to: @transfer.to.email,
         subject: "#{@transfer.from} has
                   send you a transfer of #{@transfer.amount} PLN")
  end

  def pending_transfers(transfers, user)
    @transfers = transfers
    @user = user
    mail(to: @user.email, subject: 'You have pending transfers!')
  end

  def accepted_transfer(transfer)
    status_email(transfer, 'accepted')
  end

  def rejected_transfer(transfer)
    status_email(transfer, 'rejected')
  end

  private

  def status_email(transfer, direction)
    @transfer = transfer
    mail(to: @transfer.from.email,
         subject: "#{@transfer.to} has #{direction} your transfer of
                   #{@transfer.amount} PLN")
  end
end


text:
namespace {

base::android::RegistrationMethod kMojoRegisteredMethods[] = {
  { "CoreImpl", mojo::android::RegisterCoreImpl },
  { "MojoTestCase", mojo::android::RegisterMojoTestCase },
  { "ValidationTestUtil", mojo::android::RegisterValidationTestUtil },
};

bool RegisterJNI(JNIEnv* env) {
  return base::android::RegisterJni(env) &&
      RegisterNativeMethods(env, kMojoRegisteredMethods,
                            arraysize(kMojoRegisteredMethods));
}

bool Init() {
  mojo::embedder::Init(mojo::embedder::CreateSimplePlatformSupport());
  return true;
}

}  // namespace

JNI_EXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved) {
  std::vector<base::android::RegisterCallback> register_callbacks;
  register_callbacks.push_back(base::Bind(&RegisterJNI));
  std::vector<base::android::InitCallback> init_callbacks;
  init_callbacks.push_back(base::Bind(&Init));
  if (!base::android::OnJNIOnLoadRegisterJNI(vm, register_callbacks) ||
      !base::android::OnJNIOnLoadInit(init_callbacks))
    return -1;

  return JNI_VERSION_1_4;
}


text:
<?php

namespace Acme;

require_once __DIR__ . '/../bootstrap.php';

class Thumbnail
{
    /** @var \Volcanus\Thumbnail\Image */
    public $image;

    /** @var string */
    public $title;

    /** @var bool */
    public $callScript = false;

    /**
     * Thumbnail constructor.
     *
     * @param array $props
     */
    public function __construct($props)
    {
        if (isset($props['image'])) {
            $this->image = $props['image'];
        }
        if (isset($props['title'])) {
            $this->title = $props['title'];
        }
        if (isset($props['callScript'])) {
            $this->callScript = $props['callScript'];
        }
    }
}

/**
 * @param string $var
 * @return string
 */
function h($var)
{
    return htmlspecialchars($var, ENT_QUOTES, 'UTF-8');
}

/**
 * @param string $path
 * @return mixed
 */
function getOrientationFrom($path)
{
    $errorLevel = error_reporting();
    $errorLevelChanged = ($errorLevel & E_WARNING);
    if ($errorLevelChanged) {
        error_reporting($errorLevel ^ E_WARNING);
    }
    $exif = exif_read_data($path);
    if ($errorLevelChanged) {
        error_reporting($errorLevel);
    }
    if (isset($exif['Orientation'])) {
        return $exif['Orientation'];
    }
    return null;
}

$images_dir = __DIR__ . DIRECTORY_SEPARATOR . '/images';

$original = new \Volcanus\Thumbnail\Image([
    'path' => $images_dir . DIRECTORY_SEPARATOR . '800-600.png',
]);

if (isset($_GET['thumbnail'])) {
    $extension = pathinfo($_GET['thumbnail'], PATHINFO_EXTENSION);
    $conditions = explode('x', pathinfo($_GET['thumbnail'], PATHINFO_FILENAME));
    $image = clone $original;
    $thumbnail = $image->resize(
        (isset($conditions[0])) ? intval($conditions[0]) : null,
        (isset($conditions[1])) ? intval($conditions[1]) : null
    );
    /** @noinspection PhpUnusedLocalVariableInspection */
    $imageType = IMAGETYPE_PNG;
    switch (strtolower($extension)) {
        case 'gif':
            $imageType = IMAGETYPE_GIF;
            break;
        case 'jpg':
        case 'jpeg':
            $imageType = IMAGETYPE_JPEG;
            break;
        case 'png':
        default:
            $imageType = IMAGETYPE_PNG;
            break;
    }
    header('Content-Type', image_type_to_mime_type($imageType));
    $thumbnail->output(null, $imageType, 100);
    exit;
}

$thumbnails = [];

$thumbnails[] = new Thumbnail([
    'image' => $original,
    'title' => 'オリジナル',
]);

// resize to 400x300
$image = clone $original;
$thumbnails[] = new Thumbnail([
    'image' => $image->resize(400, 300),
    'title' => 'resize(400, 300)',
    'callScript' => true,
]);

// resize to 600
$image = clone $original;
$thumbnails[] = new Thumbnail([
    'image' => $image->resize(600),
    'title' => 'resize(600)',
    'callScript' => true,
]);

// resize to 30%
$image = clone $original;
$thumbnails[] = new Thumbnail([
    'image' => $image->resizeByPercent(30),
    'title' => 'resizeByPercent(30)',
]);

$image = clone $original;
$thumbnails[] = new Thumbnail([
    'image' => $image->resizeFromCenter(200),
    'title' => 'resizeFromCenter(200)',
]);

// clip from (0,0) to 300x200
$image = clone $original;
$thumbnails[] = new Thumbnail([
    'image' => $image->clip(0, 0, 300, 200),
    'title' => 'clip(0, 0, 300, 200)',
]);

// resize to 400x300 then clip from (0,0) to 300x200
$image = clone $original;
$thumbnails[] = new Thumbnail([
    'image' => $image->resize(400, 300)->clip(0, 0, 300, 200),
    'title' => 'resize(400, 300)->clip(0, 0, 300, 200)',
]);

// resize 10% then rotate orientation(1)
$path = $images_dir . DIRECTORY_SEPARATOR . 'orientation(1).jpg';
$orientation = getOrientationFrom($path);
$original = new \Volcanus\Thumbnail\Image([
    'path' => $path,
]);
$image = clone $original;
$thumbnails[] = new Thumbnail([
    'image' => $image->resizeByPercent(10)->rotateByOrientation($orientation),
    'title' => sprintf('resizeByPercent(10)->rotateByOrientation(%d)', $orientation),
]);

// resize 10% then rotate orientation(3)
$path = $images_dir . DIRECTORY_SEPARATOR . 'orientation(3).jpg';
$orientation = getOrientationFrom($path);
$original = new \Volcanus\Thumbnail\Image([
    'path' => $path,
]);
$image = clone $original;
$thumbnails[] = new Thumbnail([
    'image' => $image->resizeByPercent(10)->rotateByOrientation($orientation),
    'title' => sprintf('resizeByPercent(10)->rotateByOrientation(%d)', $orientation),
]);

// resize 10% then rotate orientation(6)
$path = $images_dir . DIRECTORY_SEPARATOR . 'orientation(6).jpg';
$orientation = getOrientationFrom($path);
$original = new \Volcanus\Thumbnail\Image([
    'path' => $path,
]);
$image = clone $original;
$thumbnails[] = new Thumbnail([
    'image' => $image->resizeByPercent(10)->rotateByOrientation($orientation),
    'title' => sprintf('resizeByPercent(10)->rotateByOrientation(%d)', $orientation),
]);

// resize 10% then rotate orientation(8)
$path = $images_dir . DIRECTORY_SEPARATOR . 'orientation(8).jpg';
$orientation = getOrientationFrom($path);
$original = new \Volcanus\Thumbnail\Image([
    'path' => $path,
]);
$image = clone $original;
$thumbnails[] = new Thumbnail([
    'image' => $image->resizeByPercent(10)->rotateByOrientation($orientation),
    'title' => sprintf('resizeByPercent(10)->rotateByOrientation(%d)', $orientation),
]);

?>
<!DOCTYPE html>

    <meta charset="utf-8"/>
    <title>Thumbnailテスト</title>

Thumbnailテスト

    <?php foreach ($thumbnails as $thumbnail) : ?>

                <img src="<?= h($thumbnail->image->dataUri()) ?>"/>

PNG (DataURI) <?= h($thumbnail->image->getWidth()) ?>
                    x <?= h($thumbnail->image->getHeight()) ?>

<?= h($thumbnail->title) ?>

        <?php if ($thumbnail->callScript) : ?>

                    <img src="?thumbnail=<?= rawurlencode($thumbnail->image->getWidth()) ?>x<?= rawurlencode($thumbnail->image->getHeight()) ?>.jpg"/>

JPEG (スクリプトコール) <?= h($thumbnail->image->getWidth()) ?>
                        x <?= h($thumbnail->image->getHeight()) ?>

<?= h($thumbnail->title) ?>

        <?php endif ?>
    <?php endforeach ?>


text:
int main() {
  fprintf(stderr, "Please install gflags to run this test... Skipping...\n");
  return 0;
}
#else

#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif

#include <gflags/gflags.h>
#include <inttypes.h>
#include <algorithm>
#include <atomic>
#include <functional>
#include <memory>
#include <thread>
#include <vector>

#include "dynamic_bloom.h"
#include "port/port.h"
#include "util/arena.h"
#include "util/logging.h"
#include "util/testharness.h"
#include "util/testutil.h"
#include "util/stop_watch.h"

using GFLAGS::ParseCommandLineFlags;

DEFINE_int32(bits_per_key, 10, "");
DEFINE_int32(num_probes, 6, "");
DEFINE_bool(enable_perf, false, "");

namespace rocksdb {

static Slice Key(uint64_t i, char* buffer) {
  memcpy(buffer, &i, sizeof(i));
  return Slice(buffer, sizeof(i));
}

class DynamicBloomTest : public testing::Test {};

TEST_F(DynamicBloomTest, EmptyFilter) {
  Arena arena;
  DynamicBloom bloom1(&arena, 100, 0, 2);
  ASSERT_TRUE(!bloom1.MayContain("hello"));
  ASSERT_TRUE(!bloom1.MayContain("world"));

  DynamicBloom bloom2(&arena, CACHE_LINE_SIZE * 8 * 2 - 1, 1, 2);
  ASSERT_TRUE(!bloom2.MayContain("hello"));
  ASSERT_TRUE(!bloom2.MayContain("world"));
}

TEST_F(DynamicBloomTest, Small) {
  Arena arena;
  DynamicBloom bloom1(&arena, 100, 0, 2);
  bloom1.Add("hello");
  bloom1.Add("world");
  ASSERT_TRUE(bloom1.MayContain("hello"));
  ASSERT_TRUE(bloom1.MayContain("world"));
  ASSERT_TRUE(!bloom1.MayContain("x"));
  ASSERT_TRUE(!bloom1.MayContain("foo"));

  DynamicBloom bloom2(&arena, CACHE_LINE_SIZE * 8 * 2 - 1, 1, 2);
  bloom2.Add("hello");
  bloom2.Add("world");
  ASSERT_TRUE(bloom2.MayContain("hello"));
  ASSERT_TRUE(bloom2.MayContain("world"));
  ASSERT_TRUE(!bloom2.MayContain("x"));
  ASSERT_TRUE(!bloom2.MayContain("foo"));
}

TEST_F(DynamicBloomTest, SmallConcurrentAdd) {
  Arena arena;
  DynamicBloom bloom1(&arena, 100, 0, 2);
  bloom1.AddConcurrently("hello");
  bloom1.AddConcurrently("world");
  ASSERT_TRUE(bloom1.MayContain("hello"));
  ASSERT_TRUE(bloom1.MayContain("world"));
  ASSERT_TRUE(!bloom1.MayContain("x"));
  ASSERT_TRUE(!bloom1.MayContain("foo"));

  DynamicBloom bloom2(&arena, CACHE_LINE_SIZE * 8 * 2 - 1, 1, 2);
  bloom2.AddConcurrently("hello");
  bloom2.AddConcurrently("world");
  ASSERT_TRUE(bloom2.MayContain("hello"));
  ASSERT_TRUE(bloom2.MayContain("world"));
  ASSERT_TRUE(!bloom2.MayContain("x"));
  ASSERT_TRUE(!bloom2.MayContain("foo"));
}

static uint32_t NextNum(uint32_t num) {
  if (num < 10) {
    num += 1;
  } else if (num < 100) {
    num += 10;
  } else if (num < 1000) {
    num += 100;
  } else {
    num += 1000;
  }
  return num;
}

TEST_F(DynamicBloomTest, VaryingLengths) {
  char buffer[sizeof(uint64_t)];

  // Count number of filters that significantly exceed the false positive rate
  int mediocre_filters = 0;
  int good_filters = 0;
  uint32_t num_probes = static_cast<uint32_t>(FLAGS_num_probes);

  fprintf(stderr, "bits_per_key: %d  num_probes: %d\n", FLAGS_bits_per_key,
          num_probes);

  for (uint32_t enable_locality = 0; enable_locality < 2; ++enable_locality) {
    for (uint32_t num = 1; num <= 10000; num = NextNum(num)) {
      uint32_t bloom_bits = 0;
      Arena arena;
      if (enable_locality == 0) {
        bloom_bits = std::max(num * FLAGS_bits_per_key, 64U);
      } else {
        bloom_bits = std::max(num * FLAGS_bits_per_key,
                              enable_locality * CACHE_LINE_SIZE * 8);
      }
      DynamicBloom bloom(&arena, bloom_bits, enable_locality, num_probes);
      for (uint64_t i = 0; i < num; i++) {
        bloom.Add(Key(i, buffer));
        ASSERT_TRUE(bloom.MayContain(Key(i, buffer)));
      }

      // All added keys must match
      for (uint64_t i = 0; i < num; i++) {
        ASSERT_TRUE(bloom.MayContain(Key(i, buffer))) << "Num " << num
                                                      << "; key " << i;
      }

      // Check false positive rate

      int result = 0;
      for (uint64_t i = 0; i < 10000; i++) {
        if (bloom.MayContain(Key(i + 1000000000, buffer))) {
          result++;
        }
      }
      double rate = result / 10000.0;

      fprintf(stderr,
              "False positives: %5.2f%% @ num = %6u, bloom_bits = %6u, "
              "enable locality?%u\n",
              rate * 100.0, num, bloom_bits, enable_locality);

      if (rate > 0.0125)
        mediocre_filters++;  // Allowed, but not too often
      else
        good_filters++;
    }

    fprintf(stderr, "Filters: %d good, %d mediocre\n", good_filters,
            mediocre_filters);
    ASSERT_LE(mediocre_filters, good_filters / 5);
  }
}

TEST_F(DynamicBloomTest, perf) {
  StopWatchNano timer(Env::Default());
  uint32_t num_probes = static_cast<uint32_t>(FLAGS_num_probes);

  if (!FLAGS_enable_perf) {
    return;
  }

  for (uint32_t m = 1; m <= 8; ++m) {
    Arena arena;
    const uint32_t num_keys = m * 8 * 1024 * 1024;
    fprintf(stderr, "testing %" PRIu32 "M keys\n", m * 8);

    DynamicBloom std_bloom(&arena, num_keys * 10, 0, num_probes);

    timer.Start();
    for (uint64_t i = 1; i <= num_keys; ++i) {
      std_bloom.Add(Slice(reinterpret_cast<const char*>(&i), 8));
    }

    uint64_t elapsed = timer.ElapsedNanos();
    fprintf(stderr, "standard bloom, avg add latency %" PRIu64 "\n",
            elapsed / num_keys);

    uint32_t count = 0;
    timer.Start();
    for (uint64_t i = 1; i <= num_keys; ++i) {
      if (std_bloom.MayContain(Slice(reinterpret_cast<const char*>(&i), 8))) {
        ++count;
      }
    }
    ASSERT_EQ(count, num_keys);
    elapsed = timer.ElapsedNanos();
    assert(count > 0);
    fprintf(stderr, "standard bloom, avg query latency %" PRIu64 "\n",
            elapsed / count);

    // Locality enabled version
    DynamicBloom blocked_bloom(&arena, num_keys * 10, 1, num_probes);

    timer.Start();
    for (uint64_t i = 1; i <= num_keys; ++i) {
      blocked_bloom.Add(Slice(reinterpret_cast<const char*>(&i), 8));
    }

    elapsed = timer.ElapsedNanos();
    fprintf(stderr,
            "blocked bloom(enable locality), avg add latency %" PRIu64 "\n",
            elapsed / num_keys);

    count = 0;
    timer.Start();
    for (uint64_t i = 1; i <= num_keys; ++i) {
      if (blocked_bloom.MayContain(
              Slice(reinterpret_cast<const char*>(&i), 8))) {
        ++count;
      }
    }

    elapsed = timer.ElapsedNanos();
    assert(count > 0);
    fprintf(stderr,
            "blocked bloom(enable locality), avg query latency %" PRIu64 "\n",
            elapsed / count);
    ASSERT_TRUE(count == num_keys);
  }
}

TEST_F(DynamicBloomTest, concurrent_with_perf) {
  StopWatchNano timer(Env::Default());
  uint32_t num_probes = static_cast<uint32_t>(FLAGS_num_probes);

  uint32_t m_limit = FLAGS_enable_perf ? 8 : 1;
  uint32_t locality_limit = FLAGS_enable_perf ? 1 : 0;

  uint32_t num_threads = 4;
  std::vector<port::Thread> threads;

  for (uint32_t m = 1; m <= m_limit; ++m) {
    for (uint32_t locality = 0; locality <= locality_limit; ++locality) {
      Arena arena;
      const uint32_t num_keys = m * 8 * 1024 * 1024;
      fprintf(stderr, "testing %" PRIu32 "M keys with %" PRIu32 " locality\n",
              m * 8, locality);

      DynamicBloom std_bloom(&arena, num_keys * 10, locality, num_probes);

      timer.Start();

      std::function<void(size_t)> adder = [&](size_t t) {
        for (uint64_t i = 1 + t; i <= num_keys; i += num_threads) {
          std_bloom.AddConcurrently(
              Slice(reinterpret_cast<const char*>(&i), 8));
        }
      };
      for (size_t t = 0; t < num_threads; ++t) {
        threads.emplace_back(adder, t);
      }
      while (threads.size() > 0) {
        threads.back().join();
        threads.pop_back();
      }

      uint64_t elapsed = timer.ElapsedNanos();
      fprintf(stderr, "standard bloom, avg parallel add latency %" PRIu64
                      " nanos/key\n",
              elapsed / num_keys);

      timer.Start();

      std::function<void(size_t)> hitter = [&](size_t t) {
        for (uint64_t i = 1 + t; i <= num_keys; i += num_threads) {
          bool f =
              std_bloom.MayContain(Slice(reinterpret_cast<const char*>(&i), 8));
          ASSERT_TRUE(f);
        }
      };
      for (size_t t = 0; t < num_threads; ++t) {
        threads.emplace_back(hitter, t);
      }
      while (threads.size() > 0) {
        threads.back().join();
        threads.pop_back();
      }

      elapsed = timer.ElapsedNanos();
      fprintf(stderr, "standard bloom, avg parallel hit latency %" PRIu64
                      " nanos/key\n",
              elapsed / num_keys);

      timer.Start();

      std::atomic<uint32_t> false_positives(0);
      std::function<void(size_t)> misser = [&](size_t t) {
        for (uint64_t i = num_keys + 1 + t; i <= 2 * num_keys;
             i += num_threads) {
          bool f =
              std_bloom.MayContain(Slice(reinterpret_cast<const char*>(&i), 8));
          if (f) {
            ++false_positives;
          }
        }
      };
      for (size_t t = 0; t < num_threads; ++t) {
        threads.emplace_back(misser, t);
      }
      while (threads.size() > 0) {
        threads.back().join();
        threads.pop_back();
      }

      elapsed = timer.ElapsedNanos();
      fprintf(stderr, "standard bloom, avg parallel miss latency %" PRIu64
                      " nanos/key, %f%% false positive rate\n",
              elapsed / num_keys, false_positives.load() * 100.0 / num_keys);
    }
  }
}

}  // namespace rocksdb

int main(int argc, char** argv) {
  ::testing::InitGoogleTest(&argc, argv);
  ParseCommandLineFlags(&argc, &argv, true);

  return RUN_ALL_TESTS();
}

#endif  // GFLAGS


text:
namespace Sass {
  namespace Util {

    std::string normalize_underscores(const std::string& str);
    std::string normalize_decimals(const std::string& str);
    std::string normalize_sixtuplet(const std::string& col);

    bool containsAnyPrintableStatements(Block* b);

    bool isPrintable(Ruleset* r);
    bool isPrintable(Feature_Block* r);
    bool isPrintable(Media_Block* r);
    bool isPrintable(Block* b);
    bool isAscii(int ch);

  }
}
#endif


text:
struct collision_model {
    friend class collision_system;

    collision_model() {
        offset = 0;
        count = 0;
		max_radius;
    }

    bool operator<(const collision_model& other) {
        return offset < other.offset;
    }

	float max_radius;
protected:
    uint32_t offset;
    uint32_t count;
};

class collision_system : public sys<collision_model> {
public:
    using VertexIterator = std::vector<vec2>::iterator;
    using EntryIterator = std::vector<collision_model>::iterator;
    collision_system(game_world* world);
    virtual ~collision_system();
	void add_mesh(collision_model& entry, vec2 position);
	void add_mesh(collision_model& entry, VertexIterator begin, VertexIterator end);
	bool check(component_handle handle, vec2 position);
	bool check_bounds(component_handle handle, vec2 position);

private:
    std::vector<vec2> verticies;
public:
    virtual void on_removing(collision_model& entry) override;
};


text:
module Rouge
  module Lexers
    load_lexer 'c.rb'

    class HLSL < C
      title "HLSL"
      desc "HLSL, the High Level Shading Language for DirectX (docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl)"
      tag 'hlsl'
      filenames '*.hlsl', '*.hlsli'
      mimetypes 'text/x-hlsl'

      def self.keywords
        @keywords ||= Set.new %w(
          asm asm_fragment break case cbuffer centroid class column_major
          compile compile_fragment const continue default discard do else export
          extern for fxgroup globallycoherent groupshared if in inline inout
          interface line lineadj linear namespace nointerpolation noperspective
          NULL out packoffset pass pixelfragment point precise return register
          row_major sample sampler shared stateblock stateblock_state static
          struct switch tbuffer technique technique10 technique11 texture
          typedef triangle uniform vertexfragment volatile while
        )
      end

      def self.keywords_type
        @keywords_type ||= Set.new %w(
          dword matrix snorm string unorm unsigned void vector BlendState Buffer
          ByteAddressBuffer ComputeShader DepthStencilState DepthStencilView
          DomainShader GeometryShader HullShader InputPatch LineStream
          OutputPatch PixelShader PointStream RasterizerState RenderTargetView
          RasterizerOrderedBuffer RasterizerOrderedByteAddressBuffer
          RasterizerOrderedStructuredBuffer RasterizerOrderedTexture1D
          RasterizerOrderedTexture1DArray RasterizerOrderedTexture2D
          RasterizerOrderedTexture2DArray RasterizerOrderedTexture3D RWBuffer
          RWByteAddressBuffer RWStructuredBuffer RWTexture1D RWTexture1DArray
          RWTexture2D RWTexture2DArray RWTexture3D SamplerState
          SamplerComparisonState StructuredBuffer Texture1D Texture1DArray
          Texture2D Texture2DArray Texture2DMS Texture2DMSArray Texture3D
          TextureCube TextureCubeArray TriangleStream VertexShader

          bool1 bool2 bool3 bool4 BOOL1 BOOL2 BOOL3 BOOL4
          int1 int2 int3 int4
          half1 half2 half3 half4
          float1 float2 float3 float4
          double1 double2 double3 double4

          bool1x1 bool1x2 bool1x3 bool1x4 bool2x1 bool2x2 bool2x3 bool2x4
          bool3x1 bool3x2 bool3x3 bool3x4 bool4x1 bool4x2 bool4x3 bool4x4
          BOOL1x1 BOOL1x2 BOOL1x3 BOOL1x4 BOOL2x1 BOOL2x2 BOOL2x3 BOOL2x4
          BOOL3x1 BOOL3x2 BOOL3x3 BOOL3x4 BOOL4x1 BOOL4x2 BOOL4x3 BOOL4x4
          half1x1 half1x2 half1x3 half1x4 half2x1 half2x2 half2x3 half2x4
          half3x1 half3x2 half3x3 half3x4 half4x1 half4x2 half4x3 half4x4
          int1x1 int1x2 int1x3 int1x4 int2x1 int2x2 int2x3 int2x4
          int3x1 int3x2 int3x3 int3x4 int4x1 int4x2 int4x3 int4x4
          float1x1 float1x2 float1x3 float1x4 float2x1 float2x2 float2x3 float2x4
          float3x1 float3x2 float3x3 float3x4 float4x1 float4x2 float4x3 float4x4
          double1x1 double1x2 double1x3 double1x4 double2x1 double2x2 double2x3 double2x4
          double3x1 double3x2 double3x3 double3x4 double4x1 double4x2 double4x3 double4x4
        )
      end

      def self.reserved
        @reserved ||= Set.new %w(
          auto catch char const_cast delete dynamic_cast enum explicit friend
          goto long mutable new operator private protected public
          reinterpret_cast short signed sizeof static_cast template this throw
          try typename union unsigned using virtual
        )
      end

      def self.builtins
        @builtins ||= Set.new %w(
          abort abs acos all AllMemoryBarrier AllMemoryBarrierWithGroupSync any
          AppendStructuredBuffer asdouble asfloat asin asint asuint asuint atan
          atan2 ceil CheckAccessFullyMapped clamp clip CompileShader
          ConsumeStructuredBuffer cos cosh countbits cross D3DCOLORtoUBYTE4 ddx
          ddx_coarse ddx_fine ddy ddy_coarse ddy_fine degrees determinant
          DeviceMemoryBarrier DeviceMemoryBarrierWithGroupSync distance dot dst
          errorf EvaluateAttributeAtCentroid EvaluateAttributeAtSample
          EvaluateAttributeSnapped exp exp2 f16tof32 f32tof16 faceforward
          firstbithigh firstbitlow floor fma fmod frac frexp fwidth
          GetRenderTargetSampleCount GetRenderTargetSamplePosition
          GlobalOrderedCountIncrement GroupMemoryBarrier
          GroupMemoryBarrierWithGroupSync InterlockedAdd InterlockedAnd
          InterlockedCompareExchange InterlockedCompareStore InterlockedExchange
          InterlockedMax InterlockedMin InterlockedOr InterlockedXor isfinite
          isinf isnan ldexp length lerp lit log log10 log2 mad max min modf
          msad4 mul noise normalize pow printf Process2DQuadTessFactorsAvg
          Process2DQuadTessFactorsMax Process2DQuadTessFactorsMin
          ProcessIsolineTessFactors ProcessQuadTessFactorsAvg
          ProcessQuadTessFactorsMax ProcessQuadTessFactorsMin
          ProcessTriTessFactorsAvg ProcessTriTessFactorsMax
          ProcessTriTessFactorsMin QuadReadLaneAt QuadSwapX QuadSwapY radians
          rcp reflect refract reversebits round rsqrt saturate sign sin sincos
          sinh smoothstep sqrt step tan tanh tex1D tex1D tex1Dbias tex1Dgrad
          tex1Dlod tex1Dproj tex2D tex2D tex2Dbias tex2Dgrad tex2Dlod tex2Dproj
          tex3D tex3D tex3Dbias tex3Dgrad tex3Dlod tex3Dproj texCUBE texCUBE
          texCUBEbias texCUBEgrad texCUBElod texCUBEproj transpose trunc
          WaveAllBitAnd WaveAllMax WaveAllMin WaveAllBitOr WaveAllBitXor
          WaveAllEqual WaveAllProduct WaveAllSum WaveAllTrue WaveAnyTrue
          WaveBallot WaveGetLaneCount WaveGetLaneIndex WaveGetOrderedIndex
          WaveIsHelperLane WaveOnce WavePrefixProduct WavePrefixSum
          WaveReadFirstLane WaveReadLaneAt

          SV_CLIPDISTANCE SV_CLIPDISTANCE0 SV_CLIPDISTANCE1 SV_CULLDISTANCE
          SV_CULLDISTANCE0 SV_CULLDISTANCE1 SV_COVERAGE SV_DEPTH
          SV_DEPTHGREATEREQUAL SV_DEPTHLESSEQUAL SV_DISPATCHTHREADID
          SV_DOMAINLOCATION SV_GROUPID SV_GROUPINDEX SV_GROUPTHREADID
          SV_GSINSTANCEID SV_INNERCOVERAGE SV_INSIDETESSFACTOR SV_INSTANCEID
          SV_ISFRONTFACE SV_OUTPUTCONTROLPOINTID SV_POSITION SV_PRIMITIVEID
          SV_RENDERTARGETARRAYINDEX SV_SAMPLEINDEX SV_STENCILREF SV_TESSFACTOR
          SV_VERTEXID SV_VIEWPORTARRAYINDEX

          allow_uav_condition branch call domain earlydepthstencil fastopt
          flatten forcecase instance loop maxtessfactor numthreads
          outputcontrolpoints outputtopology partitioning patchconstantfunc
          unroll

          BINORMAL BINORMAL0 BINORMAL1 BINORMAL2 BINORMAL3 BINORMAL4
          BLENDINDICES0 BLENDINDICES1 BLENDINDICES2 BLENDINDICES3 BLENDINDICES4
          BLENDWEIGHT0 BLENDWEIGHT1 BLENDWEIGHT2 BLENDWEIGHT3 BLENDWEIGHT4 COLOR
          COLOR0 COLOR1 COLOR2 COLOR3 COLOR4 NORMAL NORMAL0 NORMAL1 NORMAL2
          NORMAL3 NORMAL4 POSITION POSITION0 POSITION1 POSITION2 POSITION3
          POSITION4 POSITIONT PSIZE0 PSIZE1 PSIZE2 PSIZE3 PSIZE4 TANGENT
          TANGENT0 TANGENT1 TANGENT2 TANGENT3 TANGENT4 TESSFACTOR0 TESSFACTOR1
          TESSFACTOR2 TESSFACTOR3 TESSFACTOR4 TEXCOORD0 TEXCOORD1 TEXCOORD2
          TEXCOORD3 TEXCOORD4

          FOG PSIZE

          VFACE VPOS

          DEPTH0 DEPTH1 DEPTH2 DEPTH3 DEPTH4
        )
      end

      ws = %r((?:\s|//.*?\n|/[*].*?[*]/)+)
      id = /[a-zA-Z_][a-zA-Z0-9_]*/

      state :root do
        mixin :expr_whitespace
        rule %r(
          ([\w*\s]+?[\s*])                  # return arguments
          (#{id})                           # function name
          (\s*\([^;]*?\)(?:\s*:\s+#{id})?)  # signature
          (#{ws}?)({|;)                     # open brace or semicolon
        )mx do |m|
          # This is copied from the C lexer
          recurse m[1]
          token Name::Function, m[2]
          recurse m[3]
          recurse m[4]
          token Punctuation, m[5]
          if m[5] == ?{
            push :function
          end
        end
        rule %r/\{/, Punctuation, :function
        mixin :statements
      end
    end
  end
end


text:
({
        newComponentInit:function(cmp, evt){
            //Will be used in JS test
            cmp._testNewCmpInitFlag = true;
            cmp._testNewCmpInitEvt = evt;
        }

})


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var BundleItem = /** @class */ (function () {
    function BundleItem(moduleName, filename, source, sourceMap, dependencies) {
        if (dependencies === void 0) { dependencies = []; }
        this.moduleName = moduleName;
        this.filename = filename;
        this.source = source;
        this.sourceMap = sourceMap;
        this.dependencies = dependencies;
        this.transformedScript = false;
    }
    BundleItem.prototype.isNpmModule = function () {
        return this.moduleName.charAt(0) !== "." && this.moduleName.charAt(0) !== "/";
    };
    BundleItem.prototype.isScript = function () {
        return (this.filename && /\.(js|jsx|ts|tsx)$/.test(this.filename))
            || this.transformedScript;
    };
    BundleItem.prototype.isTypingsFile = function () {
        return this.filename && /\.d\.ts$/.test(this.filename);
    };
    BundleItem.prototype.isTypescriptFile = function () {
        return this.filename && !this.isTypingsFile() && /\.(ts|tsx)$/.test(this.filename);
    };
    return BundleItem;
}());
exports.BundleItem = BundleItem;
//# sourceMappingURL=bundle-item.js.map


text:
namespace Azure.ResourceManager.RecoveryServicesSiteRecovery.Models
{
    /// <summary> Site details provided during the time of site creation. </summary>
    public partial class FabricCreateOrUpdateContent
    {
        /// <summary> Initializes a new instance of FabricCreateOrUpdateContent. </summary>
        public FabricCreateOrUpdateContent()
        {
        }

        /// <summary> Fabric creation input. </summary>
        internal FabricCreationInputProperties Properties { get; set; }
        /// <summary>
        /// Fabric provider specific creation input.
        /// Please note <see cref="FabricSpecificCreationInput"/> is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes.
        /// The available derived classes include <see cref="AzureFabricCreationInput"/>, <see cref="InMageRcmFabricCreationInput"/> and <see cref="VMwareV2FabricCreationInput"/>.
        /// </summary>
        public FabricSpecificCreationInput FabricCreationInputCustomDetails
        {
            get => Properties is null ? default : Properties.CustomDetails;
            set
            {
                if (Properties is null)
                    Properties = new FabricCreationInputProperties();
                Properties.CustomDetails = value;
            }
        }
    }
}


text:
namespace GSoft.Dynamite.Binding
{
    /// <summary>
    /// A conversion handler.
    /// </summary>
    public interface IConverter
    {
        #region Methods

        /// <summary>
        /// Converts the specified value.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <param name="arguments">The arguments.</param>
        /// <returns>
        /// The converted value.
        /// </returns>
        object Convert(object value, ConversionArguments arguments);

        /// <summary>
        /// Converts the specified value back.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <param name="arguments">The arguments.</param>
        /// <returns>
        /// The converted value.
        /// </returns>
        object ConvertBack(object value, ConversionArguments arguments);

        #endregion
    }
}


text:
class tst_EndsWith : public QObject
{
    Q_OBJECT

private slots:
    void testEndsWithString();
    void testEndsWithWString();
    void testEndsWithByteArray();
};

void tst_EndsWith::testEndsWithString()
{
    std::string in = "http://test.com/index.html";
    QVERIFY(Calibri::endsWith(in, std::string(".html")));

    in = std::string();
    QVERIFY(!Calibri::endsWith(in, std::string("test")));
}

void tst_EndsWith::testEndsWithWString()
{
    std::wstring in = L"http://test.com/index.html";
    QVERIFY(Calibri::endsWith(in, std::wstring(L".html")));

    in = std::wstring();
    QVERIFY(!Calibri::endsWith(in, std::wstring(L"test")));
}

void tst_EndsWith::testEndsWithByteArray()
{
    Calibri::ByteArray in = "http://test.com/index.html";
    QVERIFY(Calibri::endsWith(in, Calibri::ByteArray(".html")));

    in = Calibri::ByteArray();
    QVERIFY(!Calibri::endsWith(in, Calibri::ByteArray("test")));
}

QTEST_MAIN(tst_EndsWith)

#include "tst_endswith.moc"


text:
/**
 *
 */
package org.cagrid.installer.tasks;

import org.cagrid.installer.model.CaGridInstallerModel;

/**
 * @author Joshua Phillips
 *
 */
public abstract class BasicTask extends AbstractTask {

	/**
	 * @param name
	 * @param description
	 */
	public BasicTask(String name, String description) {
		super(name, description);
	}

	/* (non-Javadoc)
	 * @see org.cagrid.installer.tasks.Task#execute(java.util.Map)
	 */
	public Object execute(CaGridInstallerModel model) throws Exception {
		Object result = internalExecute(model);
		setLastStep(getStepCount());
		return result;
	}

	protected abstract Object internalExecute(CaGridInstallerModel model) throws Exception;
}


text:
module JmPlayer
  module Data
    module Mongoid
      module Player
        module Writer
          EVENTS={
            insert: {ok: :player_insert_ok, ko: :player_insert_ko }
          }

          def self.included(klass)
            klass.extend ClassMethods
            klass.send(:include, ::Wisper::Publisher)
            #guard: raise unless klass.new.respond_to? :update_attributes
          end

          def insert_foo
            if save
              publish(EVENTS[:insert][:ok], self)
            else
              publish(EVENTS[:insert][:ko], self)
            end
          end

          module ClassMethods
          end
        end
      end
    end
  end
end


text:
<?php

namespace QCloudSDK\Core;

use GuzzleHttp\Psr7\Response;
use Psr\Http\Message\ServerRequestInterface;
use QCloudSDK\Core\Exceptions\HttpException;

abstract class AbstractCallback
{
    const BAD_REQUEST = '400';
    const FORBIDDEN = '403';
    const NOT_FOUND = '404';

    protected $handlers = [];
    /**
     * @var ServerRequestInterface
     */
    protected $request;
    /**
     * @var int
     */
    protected $handledCounter = 0;

    public function __construct()
    {
        $this->fallback();
    }

    /**
     * Register fallback event handlers
     */
    protected function fallback()
    {
        $this->on(self::BAD_REQUEST, [$this, 'defaultBadRequest']);
        $this->on(self::FORBIDDEN, [$this, 'defaultForbidden']);
        $this->on(self::NOT_FOUND, [$this, 'defaultNotFound']);
    }

    public function on(string $event, callable $callback)
    {
        $this->handlers[$event] = $callback;
        return $this;
    }

    protected function trigger(string $event, ... $args)
    {
        $this->handledCounter++;
        return isset($this->handlers[$event]) ? call_user_func_array($this->handlers[$event], $args) : null;
    }

    protected function defaultBadRequest()
    {
        throw new HttpException('Request body is not valid', self::BAD_REQUEST);
    }

    protected function defaultForbidden()
    {
        throw new HttpException('Request is not authentic', self::FORBIDDEN);
    }

    protected function defaultNotFound()
    {
        throw new HttpException('No handler defined for such request', self::NOT_FOUND);
    }

    abstract protected function checkRequest();

    protected function checkAuthentic()
    {
        return true;
    }

    abstract protected function dispatch();

    protected function makeRespondJSON($result = 0, $errmsg = 'OK')
    {
        return json_encode(compact('result', 'errmsg'));
    }

    public function respond(ServerRequestInterface $serverRequest)
    {
        $this->request = $serverRequest;
        $this->handledCounter = 0;
        try{
            if(!$this->checkRequest()) $this->trigger(self::BAD_REQUEST);
            if(!$this->checkAuthentic()) $this->trigger(self::FORBIDDEN);
            $this->dispatch();
            if($this->handledCounter === 0) $this->trigger(self::NOT_FOUND);
            return new Response(200, [], $this->makeRespondJSON());
        }catch (HttpException $e){
            return new Response($e->getCode(), [], $this->makeRespondJSON($e->getCode(), $e->getMessage()));
        }catch (\Exception $e){
            return new Response(500, [], $this->makeRespondJSON($e->getCode(), $e->getMessage()));
        }
    }

}


text:
Main header

Sidebar

        <md-progress-circular md-mode="determinate" value="{{main.experienceTilNextLevel}}" md-diameter="50px"></md-progress-circular>
        <md-progress-linear md-mode="determinate" value="{{main.experienceTilNextLevel}}"></md-progress-linear>

        <md-content class="md-padding autocomplete" layout="column">
          <md-chip-template>
            <md-chip class="level-chip">{{main.currentLevel}}</md-chip>
          </md-chip-template>
        </md-content>
        <md-content class="md-padding">
          <form name="characterForm">

              <md-input-container flex>
                Player First Name
                <input ng-model="user.playerFirstName">
              </md-input-container>
              <md-input-container flex>
                Player Last Name
                <input ng-model="user.playerLastName">
              </md-input-container>

              <md-input-container flex>
                Character First Name
                <input ng-model="user.characterFirstName">
              </md-input-container>
              <md-input-container flex>
                Character Last Name
                <input ng-model="user.characterLastName">
              </md-input-container>

              <md-input-container flex>
                Race
                <input ng-model="user.race">
              </md-input-container>
              <md-input-container flex>
                Sub-Race
                <input ng-model="user.subRace">
              </md-input-container>
              <md-input-container flex>
                Race Ability
                <input ng-model="user.raceAbility">
              </md-input-container>

              <md-input-container flex>
                Background
                <input ng-model="user.background">
              </md-input-container>
              <md-input-container flex>
                Alignment
                <input ng-model="user.alignment">
              </md-input-container>

              <md-input-container flex>
                Biography
                <textarea ng-model="user.biography" columns="1" md-maxlength="500"></textarea>
              </md-input-container>

          </form>
        </md-content>


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.fangxuele.tool.push.dao.TPushHistoryMapper">
    <resultMap id="BaseResultMap" type="com.fangxuele.tool.push.domain.TPushHistory">
        <id column="id" jdbcType="INTEGER" property="id"/>
        <result column="msg_id" jdbcType="INTEGER" property="msgId"/>
        <result column="msg_type" jdbcType="INTEGER" property="msgType"/>
        <result column="msg_name" jdbcType="VARCHAR" property="msgName"/>
        <result column="result" jdbcType="VARCHAR" property="result"/>
        <result column="csv_file" jdbcType="VARCHAR" property="csvFile"/>
        <result column="create_time" jdbcType="VARCHAR" property="createTime"/>
        <result column="modified_time" jdbcType="VARCHAR" property="modifiedTime"/>
    </resultMap>
    <sql id="Base_Column_List">
        id, msg_id, msg_type, msg_name, result, csv_file, create_time, modified_time
    </sql>
    <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List"/>
        from t_push_history
        where id = #{id,jdbcType=INTEGER}
    </select>
    <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
        delete
        from t_push_history
        where id = #{id,jdbcType=INTEGER}
    </delete>
    <insert id="insert" parameterType="com.fangxuele.tool.push.domain.TPushHistory">
        insert into t_push_history (id, msg_id, msg_type,
                                    msg_name, result, csv_file,
                                    create_time, modified_time)
        values (#{id,jdbcType=INTEGER}, #{msgId,jdbcType=INTEGER}, #{msgType,jdbcType=INTEGER},
                #{msgName,jdbcType=VARCHAR}, #{result,jdbcType=VARCHAR}, #{csvFile,jdbcType=VARCHAR},
                #{createTime,jdbcType=VARCHAR}, #{modifiedTime,jdbcType=VARCHAR})
    </insert>
    <insert id="insertSelective" parameterType="com.fangxuele.tool.push.domain.TPushHistory">
        insert into t_push_history
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="id != null">
                id,
            </if>
            <if test="msgId != null">
                msg_id,
            </if>
            <if test="msgType != null">
                msg_type,
            </if>
            <if test="msgName != null">
                msg_name,
            </if>
            <if test="result != null">
                result,
            </if>
            <if test="csvFile != null">
                csv_file,
            </if>
            <if test="createTime != null">
                create_time,
            </if>
            <if test="modifiedTime != null">
                modified_time,
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="id != null">
                #{id,jdbcType=INTEGER},
            </if>
            <if test="msgId != null">
                #{msgId,jdbcType=INTEGER},
            </if>
            <if test="msgType != null">
                #{msgType,jdbcType=INTEGER},
            </if>
            <if test="msgName != null">
                #{msgName,jdbcType=VARCHAR},
            </if>
            <if test="result != null">
                #{result,jdbcType=VARCHAR},
            </if>
            <if test="csvFile != null">
                #{csvFile,jdbcType=VARCHAR},
            </if>
            <if test="createTime != null">
                #{createTime,jdbcType=VARCHAR},
            </if>
            <if test="modifiedTime != null">
                #{modifiedTime,jdbcType=VARCHAR},
            </if>
        </trim>
    </insert>
    <update id="updateByPrimaryKeySelective" parameterType="com.fangxuele.tool.push.domain.TPushHistory">
        update t_push_history
        <set>
            <if test="msgId != null">
                msg_id = #{msgId,jdbcType=INTEGER},
            </if>
            <if test="msgType != null">
                msg_type = #{msgType,jdbcType=INTEGER},
            </if>
            <if test="msgName != null">
                msg_name = #{msgName,jdbcType=VARCHAR},
            </if>
            <if test="result != null">
                result = #{result,jdbcType=VARCHAR},
            </if>
            <if test="csvFile != null">
                csv_file = #{csvFile,jdbcType=VARCHAR},
            </if>
            <if test="createTime != null">
                create_time = #{createTime,jdbcType=VARCHAR},
            </if>
            <if test="modifiedTime != null">
                modified_time = #{modifiedTime,jdbcType=VARCHAR},
            </if>
        </set>
        where id = #{id,jdbcType=INTEGER}
    </update>
    <update id="updateByPrimaryKey" parameterType="com.fangxuele.tool.push.domain.TPushHistory">
        update t_push_history
        set msg_id        = #{msgId,jdbcType=INTEGER},
            msg_type      = #{msgType,jdbcType=INTEGER},
            msg_name      = #{msgName,jdbcType=VARCHAR},
            result        = #{result,jdbcType=VARCHAR},
            csv_file      = #{csvFile,jdbcType=VARCHAR},
            modified_time = #{modifiedTime,jdbcType=VARCHAR}
        where id = #{id,jdbcType=INTEGER}
    </update>

    <select id="selectByMsgType" parameterType="java.lang.Integer" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List"/>
        from t_push_history
        where msg_type = #{msgType,jdbcType=INTEGER}
        order by create_time desc
    </select>
</mapper>


text:
package org.databene.commons.accessor;

import org.databene.commons.Accessor;

/**
 * Two step Accessor, that uses one Accessor to fetch an object and another one to read a value from it.
 * Created: 12.06.2007 18:43:28
 * @author Volker Bergmann
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public class FetchingAccessor implements Accessor {

    private Accessor provider;
    private Accessor accessor;

    public FetchingAccessor(Accessor provider, Accessor accessor) {
        this.provider = provider;
        this.accessor = accessor;
    }

    @Override
	public Object getValue(Object o) {
        return accessor.getValue(provider.getValue(o));
    }

    @Override
    public String toString() {
        return getClass().getSimpleName() + "[accessor=" + accessor + ", provider=" + provider + "]";
    }

}


text:
package vinyldns

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"

	awsauth "github.com/smartystreets/go-aws-auth"
)

func concat(arr []string) string {
	var buff bytes.Buffer

	for _, elem := range arr {
		buff.WriteString(elem)
	}

	return buff.String()
}

func concatStrs(delim string, str ...string) string {
	return strings.Join(str, delim)
}

func resourceRequest(c *Client, url, method string, body []byte, responseStruct interface{}) error {
	if logRequests() {
		fmt.Printf("Request url: \n\t%s\nrequest body: \n\t%s \n\n", url, string(body))
	}
	req, err := http.NewRequest(method, url, bytes.NewReader(body))
	if err != nil {
		return err
	}

	req.Header.Set("User-Agent", c.UserAgent)
	req.Header.Set("Content-Type", "application/json")

	awsauth.Sign4(req, awsauth.Credentials{
		AccessKeyID:     c.AccessKey,
		SecretAccessKey: c.SecretKey,
	})

	resp, err := c.HTTPClient.Do(req)
	if err != nil {
		return err
	}

	bodyContents, err := ioutil.ReadAll(resp.Body)
	if logRequests() {
		fmt.Printf("Response status: \n\t%d\nresponse body: \n\t%s \n\n", resp.StatusCode, bodyContents)
	}
	if err != nil {
		return err
	}
	if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated && resp.StatusCode != http.StatusAccepted {
		dError := &Error{}
		dError.RequestURL = url
		dError.RequestMethod = method
		dError.RequestBody = string(body)
		dError.ResponseCode = resp.StatusCode
		dError.ResponseBody = string(bodyContents)
		return dError
	}
	err = json.Unmarshal(bodyContents, responseStruct)
	if err != nil {
		return err
	}
	return nil
}


text:
"""
Demo microbes service and methods
"""
__author__ = 'Dan Gunter <dkgunter@lbl.gov>, Bill Riehl <wjriehl@lbl.gov>, Michael Sneddon <mwsneddon@lbl.gov>, Roman Sutormin <rsutormin@lbl.gov>'
__date__ = '11/15/13'

## Imports
# Stdlib
import json
import os
import random
import numbers
import uuid
import hashlib
import re
import sys
# Local
import biokbase.narrative.common.service as service
from biokbase.narrative.common.service import init_service, method, finalize_service
from biokbase.workspace.client import Workspace as workspaceService
from biokbase.InvocationService.Client import InvocationService
from biokbase.fbaModelServices.Client import fbaModelServices
from biokbase.GenomeComparison.Client import GenomeComparison
from biokbase.assembly.client import Client as ArastClient
from biokbase.KBaseTrees.Client import KBaseTrees

## Globals

VERSION = (0, 0, 1)
NAME = "Microbes Comparative Genomics"

# Initialize
init_service(name=NAME, desc="Demo workflow microbes service", version=VERSION)

@method(name="Compute Pangenome")
def _compute_pan_genome(meth, genome_set,pangenome_id):
    """ Rapidly compute gene families for a set of phylogenetically close genomes

    :param genome_set: a Genome Set to compute pangenome for
    :type genome_set: kbtypes.KBaseSearch.GenomeSet
    :ui_name genome_set: Genome Set ID

    :param pangenome_id: ID for output pangenome
    :type pangenome_id: kbtypes.KBaseGenomes.Pangenome
    :ui_name pangenome_id: Pangenome ID

    :return: Generated Pangenome Object
    :rtype: kbtypes.KBaseGenomes.Pangenome
    :output_widget: kbasePanGenome
    """
    meth.stages = 2
    meth.advance("Computing pangenome (20 sec per genome)...")
    usertoken, workspace_id = meth.token, meth.workspace_id

    ws = workspaceService(service.URLS.workspace, token=usertoken)
    data = ws.get_objects([{'ref': workspace_id+'/'+genome_set}])[0]
    genome_set_elements = data['data']['elements']
    genomes = []
    gwss = []
    for key in genome_set_elements:
        array = genome_set_elements[key]['ref'].split('/')
        gwss.append(array[0])
        genomes.append(array[1])

    pangenome_parameters = {
        'genomes':genomes,
        'genome_workspaces':gwss,
        'workspace':workspace_id,
        'auth':usertoken,
        'wsurl':service.URLS.workspace}

    if pangenome_id:
        pangenome_parameters['output_id']=pangenome_id

    fbaclient = fbaModelServices(url = service.URLS.fba, token=usertoken)
    meta = fbaclient.build_pangenome(pangenome_parameters)

    return json.dumps({'ws': workspace_id, 'name':meta[1]})

@method(name="View Pangenome")
def _view_pan_genome(meth, pan_genome_id):
    """Show Pangenome object. [29]

    :param pan_genome_id: ID of pangenome object [29.1]
    :type pan_genome_id: kbtypes.KBaseGenomes.Pangenome
    :ui_name pan_genome_id: Pangenome ID

    :return: Generated Compare Genome
    :rtype: kbtypes.KBaseGenomes.Pangenome
    :output_widget: kbasePanGenome
    """

    meth.stages = 1 # for reporting progress

    return json.dumps({'ws': meth.workspace_id, 'name': pan_genome_id})

@method(name="Export gene sets from Pangenome")
def _export_gene_set_pan_genome(meth, pan_genome_id):
    """Export gene sets from Pangenome as external FeatureSet objects. [26]

    :param pan_genome_id: ID of pangenome object [26.1]
    :type pan_genome_id: kbtypes.KBaseGenomes.Pangenome
    :ui_name pan_genome_id: Pangenome ID

    :return: Generated Compare Genome
    :rtype: kbtypes.KBaseGenomes.Pangenome
    :output_widget: kbasePanGenome
    """

    meth.stages = 1 # for reporting progress

    return json.dumps({'ws': meth.workspace_id, 'name': pan_genome_id, 'withExport': 'true'})

@method(name="Genome Comparison from Pangenome")
def _compare_genomes(meth, pangenome_id):
    """Genome Comparison analysis based on the PanGenome input.

    :param pangenome_id: Pangenome ID
    :type pangenome_id: kbtypes.KBaseGenomes.Pangenome
    :ui_name pangenome_id: Pangenome ID

    :return: Uploaded Genome Comparison Data
    :rtype: kbtypes.KBaseGenomes.GenomeComparison
    :output_widget: kbaseGenomeComparisonViewer
    """
    meth.stages = 2
    meth.advance("Comparing all genomes in pangenome (1-2 minutes)...")

    #grab token and workspace info, setup the client
    token, ws = meth.token, meth.workspace_id;
    wss =[]
    fba = fbaModelServices(url = service.URLS.fba, token = token)

    meta = fba.compare_genomes({'pangenome_id': pangenome_id,
                                'pangenome_ws': ws,
                                'workspace': ws })

    return json.dumps({'ws': meth.workspace_id, 'id':meta[1]})

@method(name="View Genome Comparison")
def _compare_genomes(meth, genomecomp_id):
    """View genome comparison results.

        :param genomecomp_id: Genome comparison ID
        :type genomecomp_id: kbtypes.KBaseGenomes.GenomeComparison
        :ui_name genomecomp_id: Genome comparison ID

        :return: Uploaded Genome Comparison Data
        :rtype: kbtypes.KBaseGenomes.GenomeComparison
        :output_widget: kbaseGenomeComparisonViewer
        """
    meth.stages = 2
    meth.advance("Opening genome comparison...")
    token, ws = meth.token, meth.workspace_id;

    return json.dumps({'ws': meth.workspace_id, 'id': genomecomp_id})

@method(name="Compare Two Proteomes")
def _compare_proteomes(meth, genome1, genome2, out_proteome_cmp):
    """Start a job to run Blast between the proteomes of two genomes.
    The comparison information includes best-bidirectional hits. [17]

    :param genome1: Source genome1 ID [17.1]
    :type genome1: kbtypes.KBaseGenomes.Genome
    :ui_name genome1: Genome1 ID
    :param genome2: Source genome2 ID [17.2]
    :type genome2: kbtypes.KBaseGenomes.Genome
    :ui_name genome2: Genome2 ID
    :param out_proteome_cmp: Output proteome comparison ID. If empty, an ID will be chosen randomly. [17.3]
    :type out_proteome_cmp: kbtypes.GenomeComparison.ProteomeComparison
    :ui_name out_proteome_cmp: Output Proteome Comparison ID
    :return: Output Proteome Comparison ID
    :rtype: kbtypes.ProteomeComparison
    :output_widget: GenomeComparisonWidget
    """
    meth.stages = 1  # for reporting progress
    token = os.environ['KB_AUTH_TOKEN']
    workspace = os.environ['KB_WORKSPACE_ID']
    if not out_proteome_cmp:
        out_proteome_cmp = "proteome_cmp_" + ''.join([chr(random.randrange(0, 26) + ord('A')) for _ in xrange(8)])
    cmpClient = GenomeComparison(url = service.URLS.genomeCmp, token = token)
    blast_proteomes_params = {
        'genome1ws': workspace,
        'genome1id': genome1,
        'genome2ws': workspace,
        'genome2id': genome2,
        'output_ws': workspace,
        'output_id': out_proteome_cmp,
    }
    job_id = cmpClient.blast_proteomes(blast_proteomes_params)
    return json.dumps({'ws_name': workspace, 'ws_id': out_proteome_cmp, 'job_id': job_id})

@method(name="View Proteome Comparison")
def _view_proteome_cmp(meth, proteome_cmp):
    """Show the hit map result of running a comparison between two proteomes,
    which includes information about best-bidirectional hits. [18]

    :param proteome_cmp: Proteome comparison ID [18.1]
    :type proteome_cmp: kbtypes.GenomeComparison.ProteomeComparison
    :ui_name proteome_cmp: Proteome Comparison ID
    :return: Output Proteome Comparison ID
    :rtype: kbtypes.ProteomeComparison
    :output_widget: GenomeComparisonWidget
    """
    meth.stages = 1  # for reporting progress
    token = os.environ['KB_AUTH_TOKEN']
    workspace = os.environ['KB_WORKSPACE_ID']
    return json.dumps({'ws_name': workspace, 'ws_id': proteome_cmp})

@method(name="Insert Genome into Species Tree")
def _insert_genome_into_species_tree(meth, genome, neighbor_count, out_tree):
    """ Insert a Genome into a global genome tree composed of 49 conserved COGs [20]

    :param genome: a Genome to insert into the tree [20.1]
    :type genome: kbtypes.KBaseGenomes.Genome
    :ui_name genome: Genome ID
    :param neighbor_count: number of closest public genomes the tree will contain. (optional, default value is 100) [20.2]
    :type neighbor_count: kbtypes.Unicode
    :ui_name neighbor_count: Neighbor public genome count
    :param out_tree: Output species tree ID. If empty, an ID will be chosen randomly. [20.3]
    :type out_tree: kbtypes.KBaseTrees.Tree
    :ui_name out_tree: Output species tree ID
    :return: Species Tree Result
    :rtype: kbtypes.Unicode
    :output_widget: kbaseTree
    """
    meth.stages = 2
    meth.advance("Instantiating tree construction job...")
    token, workspace = meth.token, meth.workspace_id
    if not out_tree:
        out_tree = "sptree_" + ''.join([chr(random.randrange(0, 26) + ord('A')) for _ in xrange(8)])
    treeClient = KBaseTrees(url = service.URLS.trees, token = token)
    construct_species_tree_params = {
        'new_genomes': [workspace + '/' + genome],
        'use_ribosomal_s9_only': 0,
        'out_workspace': workspace,
        'out_tree_id': out_tree,
    }
    if neighbor_count:
        construct_species_tree_params['nearest_genome_count'] = int(neighbor_count)
    job_id = treeClient.construct_species_tree(construct_species_tree_params)
    return json.dumps({'treeID': out_tree, 'workspaceID': workspace, 'height':'500px', 'jobID': job_id})

@method(name="View Tree")
def _view_tree(meth, tree_id):
    """ View a Tree from your workspace [21]

    :param tree_id: a Tree id [21.1]
    :type tree_id: kbtypes.KBaseTrees.Tree
    :ui_name tree_id: Tree ID
    :return: Species Tree Result
    :rtype: kbtypes.Unicode
    :output_widget: kbaseTree
    """
    meth.stages = 1
    workspace = meth.workspace_id
    return json.dumps({'treeID': tree_id, 'workspaceID': workspace, 'height':'500px'})

@method(name="Build Genome Set From Tree")
def _build_genome_set_from_tree(meth, tree_id,genome_set):
    """ Build a genome set from the contents of the species tree, copying any CDM genomes
    into local workspace.

    :param species_tree: a species tree with close genomes
    :type species_tree: kbtypes.KBaseTrees.Tree
    :ui_name species_tree: Species Tree

    :param genome_set: ID to use when saving genome set
    :type genome_set: kbtypes.KBaseSearch.GenomeSet
    :ui_name genome_set: Output Genome Set ID

    :return: Genome Set Result
    :rtype: kbtypes.Unicode
    :output_widget: kbaseGenomeSetBuilder
    """

    meth.stages = 2
    meth.advance("Building genome set from tree...")
    token, workspace = meth.token, meth.workspace_id
    ws = workspaceService(service.URLS.workspace, token=token)
    data = ws.get_objects([{'ref': workspace+'/'+tree_id}])[0]
    wsid = data['info'][6]
    refs = data['data']['ws_refs']
    elements = {}
    gcount = 0
    namehash = {}
    objectids = []
    for key in refs:
        if key[:5] != "kb|g.":
            param = 'param'+`gcount`
            gcount = gcount+1
            ref = refs[key]['g'][0]
            objectids.append({'ref':ref})
            elements[param] = {'ref': ref}

    infos = ws.get_object_info(objectids,0);
    for item in infos:
        namehash[item[1]] = 1

    for key in refs:
        if key[:5] == "kb|g.":
            ref = refs[key]['g'][0]
            newname = data['data']['default_node_labels'][key];
            newname = re.sub('[^a-zA-Z0-9_\.]', '_', newname)
            if newname in namehash:
                count = 0
                testname = newname+'_'+`count`
                while testname in namehash:
                    count = count + 1
                    testname = newname+'_'+`count`

                newname = testname

            namehash[newname] = 1
            wsinfo = ws.copy_object({
                'to':{'workspace':workspace,'name':newname},
                'from':{'objid':ref.split('/')[1],'wsid':ref.split('/')[0]}
            })
            wsid = wsinfo[6]
            name = wsinfo[0]
            version = wsinfo[4]
            ref = `wsid`+"/"+`name`+"/"+`version`
            param = 'param'+`gcount`
            gcount = gcount+1
            elements[param] = {'ref': ref}

    description = 'GenomeSet of genome included in species tree ' + workspace + '/' + tree_id
    ws.save_objects({
        'workspace': workspace,
        'objects': [{
                'type': 'KBaseSearch.GenomeSet',
                'data': {'description': description,'elements': elements},
                'name': genome_set
        }]
    })

    return json.dumps({'loadExisting': 1,'genomeSetName': genome_set, 'wsName': workspace})

@method(name="Build Genome Set Object")
def _build_genome_set(meth, out_genome_set):
    """ Construct a Genome Set object [22]

    :param out_genome_set: Output genome set ID. If empty, an ID will be chosen randomly. [22.1]
    :type out_genome_set: kbtypes.KBaseSearch.GenomeSet
    :ui_name out_genome_set: Output genome set ID
    :return: Genome set Result
    :rtype: kbtypes.Unicode
    :output_widget: kbaseGenomeSetBuilder
    """
    meth.stages = 1
    token, workspace = meth.token, meth.workspace_id
    if not out_genome_set:
        out_genome_set = "genome_set_" + ''.join([chr(random.randrange(0, 26) + ord('A')) for _ in xrange(8)])
    return json.dumps({'genomeSetName': out_genome_set, 'wsName': workspace})

@method(name="Insert Set of Genomes into Species Tree")
def _insert_genome_set_into_species_tree(meth, genome_set, neighbor_count, out_tree):
    """ Insert a Genome Set into a global genome tree composed of 50 conserved COGs [23]

    :param genome_set: a Genome Set to insert into the tree [23.1]
    :type genome_set: kbtypes.KBaseSearch.GenomeSet
    :ui_name genome_set: Genome Set ID
    :param neighbor_count: number of closest public genomes the tree will contain. (optional, default value is 100) [23.2]
    :type neighbor_count: kbtypes.Unicode
    :ui_name neighbor_count: Neighbor public genome count
    :param out_tree: Output species tree ID. If empty, an ID will be chosen randomly. [23.3]
    :type out_tree: kbtypes.KBaseTrees.Tree
    :ui_name out_tree: Output species tree ID
    :return: Species Tree Result
    :rtype: kbtypes.Unicode
    :output_widget: kbaseTree
    """
    meth.stages = 2
    meth.advance("Instantiating tree construction job...")
    token, workspace = meth.token, meth.workspace_id
    if not out_tree:
        out_tree = "sptree_" + ''.join([chr(random.randrange(0, 26) + ord('A')) for _ in xrange(8)])

    ws = workspaceService(service.URLS.workspace, token=token)
    data = ws.get_objects([{'ref': workspace+'/'+genome_set}])[0]
    genome_set_elements = data['data']['elements']
    genome_refs = []
    for key in genome_set_elements:
        genome_refs.append(genome_set_elements[key]['ref'])
    treeClient = KBaseTrees(url = service.URLS.trees, token = token)
    construct_species_tree_params = {
        'new_genomes': genome_refs,
        'use_ribosomal_s9_only': 0,
        'out_workspace': workspace,
        'out_tree_id': out_tree,
    }
    if neighbor_count:
        construct_species_tree_params['nearest_genome_count'] = int(neighbor_count)
    job_id = treeClient.construct_species_tree(construct_species_tree_params)
    return json.dumps({'treeID': out_tree, 'workspaceID': workspace, 'height':'500px', 'jobID': job_id})

@method(name="Align Protein Sequences")
def _align_protein_sequences(meth, feature_set, alignment_method, out_msa):
    """Construct multiple sequence alignment object based on set of proteins. [27]

    :param feature_set: An object with protein features [27.1]
    :type feature_set: kbtypes.KBaseSearch.FeatureSet
    :ui_name feature_set: Feture Set Object
    :param alignment_method: name of alignment method (one of Muscle, Clustal, ProbCons, T-Coffee, Mafft), leave it blank for default Clustal method [27.2]
    :type alignment_method: kbtypes.Unicode
    :ui_name alignment_method: Multiple Alignment Method
    :param out_msa: Multiple sequence alignment object ID. If empty, an ID will be chosen randomly. [27.3]
    :type out_msa: kbtypes.KBaseTrees.MSA
    :ui_name out_msa: Output MSA ID
    :return: Preparation message
    :rtype: kbtypes.Unicode
    :output_widget: kbaseMSA
    """
    if not alignment_method:
        alignment_method = 'Clustal'
    if not out_msa:
        out_msa = "msa_" + ''.join([chr(random.randrange(0, 26) + ord('A')) for _ in xrange(8)])
    meth.stages = 1
    token, workspace = meth.token, meth.workspace_id
    ws = workspaceService(service.URLS.workspace, token=token)
    elements = ws.get_objects([{'ref': workspace+'/'+feature_set}])[0]['data']['elements']
    gene_sequences = {}
    for key in elements:
        elem = elements[key]['data']
        id = elem['id']
        if 'genome_ref' in elem:
            genome_obj_name = ws.get_object_info([{'ref' : elem['genome_ref']}],0)[0][1]
            id = genome_obj_name + '/' + id
        seq = elements[key]['data']['protein_translation']
        gene_sequences[id] = seq
    treeClient = KBaseTrees(url = service.URLS.trees, token = token)
    construct_multiple_alignment_params = {
        'gene_sequences': gene_sequences,
        'alignment_method': alignment_method,
        'out_workspace': workspace,
        'out_msa_id': out_msa
    }
    job_id = treeClient.construct_multiple_alignment(construct_multiple_alignment_params)
    return json.dumps({'workspaceID': workspace, 'msaID': out_msa, 'jobID' : job_id})

@method(name="View Multiple Alignment")
def _view_alignment(meth, msa_id):
    """View multiple sequence alignment. [29]

    :param msa_id: Multiple sequence alignment object ID.[29.1]
    :type msa_id: kbtypes.KBaseTrees.MSA
    :ui_name msa_id: MSA ID
    :return: Preparation message
    :rtype: kbtypes.Unicode
    :output_widget: kbaseMSA
    """
    return json.dumps({'workspaceID': meth.workspace_id, 'msaID': msa_id})

@method(name="Build Gene Tree")
def _build_gene_tree(meth, msa, out_tree):
    """ Build phylogenetic tree for multiple alignmnet of protein sequences [28]

    :param msa: a Multiple sequence alignment [28.1]
    :type msa: kbtypes.KBaseTrees.MSA
    :ui_name msa: MSA ID
    :param out_tree: Output gene tree ID. If empty, an ID will be chosen randomly. [28.2]
    :type out_tree: kbtypes.KBaseTrees.Tree
    :ui_name out_tree: Output gene tree ID
    :return: Species Tree Result
    :rtype: kbtypes.Unicode
    :output_widget: kbaseTree
    """
    meth.stages = 1
    token, workspace = meth.token, meth.workspace_id
    if not out_tree:
        out_tree = "genetree_" + ''.join([chr(random.randrange(0, 26) + ord('A')) for _ in xrange(8)])
    treeClient = KBaseTrees(url = service.URLS.trees, token = token)
    construct_tree_for_alignment_params = {
        'msa_ref': workspace + '/' + msa,
        'tree_method': 'FastTree',
        'out_workspace': workspace,
        'out_tree_id': out_tree
    }
    job_id = treeClient.construct_tree_for_alignment(construct_tree_for_alignment_params)
    return json.dumps({'treeID': out_tree, 'workspaceID': workspace, 'height':'500px', 'jobID': job_id})

#
#@method(name="Edit Data")
#def _edit_data(meth, obj_name, type):
#    """Edit data in your workspace.
#    :param object_name: name of the data object
#    :type object_id: kbtypes.WorkspaceObjectId
#    :ui_name object_id: Data Name
#    :param type: type of the data object
#    :type type: kbtypes.Unicode
#    :ui_name type: Data Type
#    :return: something
#    :rtype: kbtypes.Unicode
#    """
#
#
#    """
#    :output_widget: kbaseFbaResultViewer
#    """
#
#    meth.stages = 3
#    meth.advance("Setting up FBA parameters")
#
#    #grab token and workspace info, setup the client
#    token, workspaceName = meth.token, meth.workspace_id;
#
#    wsClient = workspaceService(service.URLS.workspace)
#    get_obj_params = {
#        'auth' : token,
#        ''
#    }
#    objData = wsClient.get_object();
#
#    return json.dumps({ "obj":objData })
#
#

# Finalize (registers service)
finalize_service()