text:
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM32F4xx_HAL_RTC_EX_H
#define __STM32F4xx_HAL_RTC_EX_H

#ifdef __cplusplus
 extern "C" {
#endif

/* Includes ------------------------------------------------------------------*/
#include "stm32f4xx_hal_def.h"

/** @addtogroup STM32F4xx_HAL_Driver
  * @{
  */

/** @addtogroup RTCEx
  * @{
  */

/* Exported types ------------------------------------------------------------*/
/** @defgroup RTCEx_Exported_Types RTCEx Exported Types
  * @{
  */

/**
  * @brief  RTC Tamper structure definition
  */
typedef struct
{
  uint32_t Tamper;                      /*!< Specifies the Tamper Pin.
                                             This parameter can be a value of @ref  RTCEx_Tamper_Pins_Definitions */

  uint32_t PinSelection;                /*!< Specifies the Tamper Pin.
                                             This parameter can be a value of @ref  RTCEx_Tamper_Pins_Selection */

  uint32_t Trigger;                     /*!< Specifies the Tamper Trigger.
                                             This parameter can be a value of @ref  RTCEx_Tamper_Trigger_Definitions */

  uint32_t Filter;                      /*!< Specifies the RTC Filter Tamper.
                                             This parameter can be a value of @ref RTCEx_Tamper_Filter_Definitions */

  uint32_t SamplingFrequency;           /*!< Specifies the sampling frequency.
                                             This parameter can be a value of @ref RTCEx_Tamper_Sampling_Frequencies_Definitions */

  uint32_t PrechargeDuration;           /*!< Specifies the Precharge Duration .
                                             This parameter can be a value of @ref RTCEx_Tamper_Pin_Precharge_Duration_Definitions */

  uint32_t TamperPullUp;                /*!< Specifies the Tamper PullUp .
                                             This parameter can be a value of @ref RTCEx_Tamper_Pull_UP_Definitions */

  uint32_t TimeStampOnTamperDetection;  /*!< Specifies the TimeStampOnTamperDetection.
                                             This parameter can be a value of @ref RTCEx_Tamper_TimeStampOnTamperDetection_Definitions */
}RTC_TamperTypeDef;
/**
  * @}
  */

/* Exported constants --------------------------------------------------------*/
/** @defgroup RTCEx_Exported_Constants RTCEx Exported Constants
  * @{
  */

/** @defgroup RTCEx_Backup_Registers_Definitions RTC Backup Registers Definitions
  * @{
  */
#define RTC_BKP_DR0                       ((uint32_t)0x00000000)
#define RTC_BKP_DR1                       ((uint32_t)0x00000001)
#define RTC_BKP_DR2                       ((uint32_t)0x00000002)
#define RTC_BKP_DR3                       ((uint32_t)0x00000003)
#define RTC_BKP_DR4                       ((uint32_t)0x00000004)
#define RTC_BKP_DR5                       ((uint32_t)0x00000005)
#define RTC_BKP_DR6                       ((uint32_t)0x00000006)
#define RTC_BKP_DR7                       ((uint32_t)0x00000007)
#define RTC_BKP_DR8                       ((uint32_t)0x00000008)
#define RTC_BKP_DR9                       ((uint32_t)0x00000009)
#define RTC_BKP_DR10                      ((uint32_t)0x0000000A)
#define RTC_BKP_DR11                      ((uint32_t)0x0000000B)
#define RTC_BKP_DR12                      ((uint32_t)0x0000000C)
#define RTC_BKP_DR13                      ((uint32_t)0x0000000D)
#define RTC_BKP_DR14                      ((uint32_t)0x0000000E)
#define RTC_BKP_DR15                      ((uint32_t)0x0000000F)
#define RTC_BKP_DR16                      ((uint32_t)0x00000010)
#define RTC_BKP_DR17                      ((uint32_t)0x00000011)
#define RTC_BKP_DR18                      ((uint32_t)0x00000012)
#define RTC_BKP_DR19                      ((uint32_t)0x00000013)
/**
  * @}
  */

/** @defgroup RTCEx_Time_Stamp_Edges_definitions RTC TimeStamp Edges Definitions
  * @{
  */
#define RTC_TIMESTAMPEDGE_RISING          ((uint32_t)0x00000000)
#define RTC_TIMESTAMPEDGE_FALLING         ((uint32_t)0x00000008)
/**
  * @}
  */

/** @defgroup RTCEx_Tamper_Pins_Definitions RTC Tamper Pins Definitions
  * @{
  */
#define RTC_TAMPER_1                    RTC_TAFCR_TAMP1E
#define RTC_TAMPER_2                    RTC_TAFCR_TAMP2E
/**
  * @}
  */

/** @defgroup RTCEx_Tamper_Pins_Selection RTC tamper Pins Selection
  * @{
  */
#define RTC_TAMPERPIN_PC13                 ((uint32_t)0x00000000)
#if defined (STM32F446xx)
 #define RTC_TAMPERPIN_PA0                  ((uint32_t)0x00010000)
#else
 #define RTC_TAMPERPIN_PI8                  ((uint32_t)0x00010000)
#endif /* STM32F446xx */
/**
  * @}
  */

/** @defgroup RTCEx_TimeStamp_Pin_Selection RTC TimeStamp Pins Selection
  * @{
  */
#define RTC_TIMESTAMPPIN_PC13              ((uint32_t)0x00000000)
#if defined (STM32F446xx)
 #define RTC_TIMESTAMPPIN_PA0               ((uint32_t)0x00020000)
#else
 #define RTC_TIMESTAMPPIN_PI8               ((uint32_t)0x00020000)
#endif /* STM32F446xx */
/**
  * @}
  */

/** @defgroup RTCEx_Tamper_Trigger_Definitions RTC Tamper Triggers Definitions
  * @{
  */
#define RTC_TAMPERTRIGGER_RISINGEDGE       ((uint32_t)0x00000000)
#define RTC_TAMPERTRIGGER_FALLINGEDGE      ((uint32_t)0x00000002)
#define RTC_TAMPERTRIGGER_LOWLEVEL         RTC_TAMPERTRIGGER_RISINGEDGE
#define RTC_TAMPERTRIGGER_HIGHLEVEL        RTC_TAMPERTRIGGER_FALLINGEDGE
/**
  * @}
  */

/** @defgroup RTCEx_Tamper_Filter_Definitions RTC Tamper Filter Definitions
  * @{
  */
#define RTC_TAMPERFILTER_DISABLE   ((uint32_t)0x00000000)  /*!< Tamper filter is disabled */

#define RTC_TAMPERFILTER_2SAMPLE   ((uint32_t)0x00000800)  /*!< Tamper is activated after 2
                                                                consecutive samples at the active level */
#define RTC_TAMPERFILTER_4SAMPLE   ((uint32_t)0x00001000)  /*!< Tamper is activated after 4
                                                                consecutive samples at the active level */
#define RTC_TAMPERFILTER_8SAMPLE   ((uint32_t)0x00001800)  /*!< Tamper is activated after 8
                                                                consecutive samples at the active level. */
/**
  * @}
  */

/** @defgroup RTCEx_Tamper_Sampling_Frequencies_Definitions RTC Tamper Sampling Frequencies Definitions
  * @{
  */
#define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV32768  ((uint32_t)0x00000000)  /*!< Each of the tamper inputs are sampled
                                                                             with a frequency =  RTCCLK / 32768 */
#define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV16384  ((uint32_t)0x00000100)  /*!< Each of the tamper inputs are sampled
                                                                             with a frequency =  RTCCLK / 16384 */
#define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV8192   ((uint32_t)0x00000200)  /*!< Each of the tamper inputs are sampled
                                                                             with a frequency =  RTCCLK / 8192  */
#define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV4096   ((uint32_t)0x00000300)  /*!< Each of the tamper inputs are sampled
                                                                             with a frequency =  RTCCLK / 4096  */
#define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV2048   ((uint32_t)0x00000400)  /*!< Each of the tamper inputs are sampled
                                                                             with a frequency =  RTCCLK / 2048  */
#define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV1024   ((uint32_t)0x00000500)  /*!< Each of the tamper inputs are sampled
                                                                             with a frequency =  RTCCLK / 1024  */
#define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV512    ((uint32_t)0x00000600)  /*!< Each of the tamper inputs are sampled
                                                                             with a frequency =  RTCCLK / 512   */
#define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV256    ((uint32_t)0x00000700)  /*!< Each of the tamper inputs are sampled
                                                                             with a frequency =  RTCCLK / 256   */
/**
  * @}
  */

/** @defgroup RTCEx_Tamper_Pin_Precharge_Duration_Definitions RTC Tamper Pin Precharge Duration Definitions
  * @{
  */
#define RTC_TAMPERPRECHARGEDURATION_1RTCCLK ((uint32_t)0x00000000)  /*!< Tamper pins are pre-charged before
                                                                         sampling during 1 RTCCLK cycle */
#define RTC_TAMPERPRECHARGEDURATION_2RTCCLK ((uint32_t)0x00002000)  /*!< Tamper pins are pre-charged before
                                                                         sampling during 2 RTCCLK cycles */
#define RTC_TAMPERPRECHARGEDURATION_4RTCCLK ((uint32_t)0x00004000)  /*!< Tamper pins are pre-charged before
                                                                         sampling during 4 RTCCLK cycles */
#define RTC_TAMPERPRECHARGEDURATION_8RTCCLK ((uint32_t)0x00006000)  /*!< Tamper pins are pre-charged before
                                                                         sampling during 8 RTCCLK cycles */
/**
  * @}
  */

/** @defgroup RTCEx_Tamper_TimeStampOnTamperDetection_Definitions RTC Tamper TimeStamp On Tamper Detection Definitions
  * @{
  */
#define RTC_TIMESTAMPONTAMPERDETECTION_ENABLE  ((uint32_t)RTC_TAFCR_TAMPTS)  /*!< TimeStamp on Tamper Detection event saved        */
#define RTC_TIMESTAMPONTAMPERDETECTION_DISABLE ((uint32_t)0x00000000)        /*!< TimeStamp on Tamper Detection event is not saved */
/**
  * @}
  */

/** @defgroup  RTCEx_Tamper_Pull_UP_Definitions RTC Tamper Pull Up Definitions
  * @{
  */
#define RTC_TAMPER_PULLUP_ENABLE  ((uint32_t)0x00000000)            /*!< TimeStamp on Tamper Detection event saved        */
#define RTC_TAMPER_PULLUP_DISABLE ((uint32_t)RTC_TAFCR_TAMPPUDIS)   /*!< TimeStamp on Tamper Detection event is not saved */
/**
  * @}
  */

/** @defgroup RTCEx_Wakeup_Timer_Definitions RTC Wake-up Timer Definitions
  * @{
  */
#define RTC_WAKEUPCLOCK_RTCCLK_DIV16        ((uint32_t)0x00000000)
#define RTC_WAKEUPCLOCK_RTCCLK_DIV8         ((uint32_t)0x00000001)
#define RTC_WAKEUPCLOCK_RTCCLK_DIV4         ((uint32_t)0x00000002)
#define RTC_WAKEUPCLOCK_RTCCLK_DIV2         ((uint32_t)0x00000003)
#define RTC_WAKEUPCLOCK_CK_SPRE_16BITS      ((uint32_t)0x00000004)
#define RTC_WAKEUPCLOCK_CK_SPRE_17BITS      ((uint32_t)0x00000006)
/**
  * @}
  */

/** @defgroup RTCEx_Digital_Calibration_Definitions RTC Digital Calib Definitions
  * @{
  */
#define RTC_CALIBSIGN_POSITIVE            ((uint32_t)0x00000000)
#define RTC_CALIBSIGN_NEGATIVE            ((uint32_t)0x00000080)
/**
  * @}
  */

/** @defgroup RTCEx_Smooth_calib_period_Definitions RTC Smooth Calib Period Definitions
  * @{
  */
#define RTC_SMOOTHCALIB_PERIOD_32SEC   ((uint32_t)0x00000000)  /*!< If RTCCLK = 32768 Hz, Smooth calibration
                                                                    period is 32s,  else 2exp20 RTCCLK seconds */
#define RTC_SMOOTHCALIB_PERIOD_16SEC   ((uint32_t)0x00002000)  /*!< If RTCCLK = 32768 Hz, Smooth calibration
                                                                    period is 16s, else 2exp19 RTCCLK seconds */
#define RTC_SMOOTHCALIB_PERIOD_8SEC    ((uint32_t)0x00004000)  /*!< If RTCCLK = 32768 Hz, Smooth calibration
                                                                    period is 8s, else 2exp18 RTCCLK seconds */
/**
  * @}
  */

/** @defgroup RTCEx_Smooth_calib_Plus_pulses_Definitions RTC Smooth Calib Plus Pulses Definitions
  * @{
  */
#define RTC_SMOOTHCALIB_PLUSPULSES_SET    ((uint32_t)0x00008000)  /*!< The number of RTCCLK pulses added
                                                                       during a X -second window = Y - CALM[8:0]
                                                                       with Y = 512, 256, 128 when X = 32, 16, 8 */
#define RTC_SMOOTHCALIB_PLUSPULSES_RESET  ((uint32_t)0x00000000)  /*!< The number of RTCCLK pulses subbstited
                                                                       during a 32-second window = CALM[8:0] */
/**
  * @}
  */

/** @defgroup RTCEx_Add_1_Second_Parameter_Definitions RTC Add 1 Second Parameter Definitions
  * @{
  */
#define RTC_SHIFTADD1S_RESET      ((uint32_t)0x00000000)
#define RTC_SHIFTADD1S_SET        ((uint32_t)0x80000000)
/**
  * @}
  */

 /** @defgroup RTCEx_Calib_Output_selection_Definitions RTC Calib Output Selection Definitions
  * @{
  */
#define RTC_CALIBOUTPUT_512HZ            ((uint32_t)0x00000000)
#define RTC_CALIBOUTPUT_1HZ              ((uint32_t)0x00080000)
/**
  * @}
  */

/**
  * @}
  */

/* Exported macro ------------------------------------------------------------*/
/** @defgroup RTCEx_Exported_Macros RTCEx Exported Macros
  * @{
  */

/* ---------------------------------WAKEUPTIMER---------------------------------*/
/** @defgroup RTCEx_WakeUp_Timer RTC WakeUp Timer
  * @{
  */

/**
  * @brief  Enable the RTC WakeUp Timer peripheral.
  * @param  __HANDLE__: specifies the RTC handle.
  * @retval None
  */
#define __HAL_RTC_WAKEUPTIMER_ENABLE(__HANDLE__)                      ((__HANDLE__)->Instance->CR |= (RTC_CR_WUTE))

/**
  * @brief  Disable the RTC Wake-up Timer peripheral.
  * @param  __HANDLE__: specifies the RTC handle.
  * @retval None
  */
#define __HAL_RTC_WAKEUPTIMER_DISABLE(__HANDLE__)                     ((__HANDLE__)->Instance->CR &= ~(RTC_CR_WUTE))

/**
  * @brief  Enable the RTC WakeUpTimer interrupt.
  * @param  __HANDLE__: specifies the RTC handle.
  * @param  __INTERRUPT__: specifies the RTC WakeUpTimer interrupt sources to be enabled or disabled.
  *         This parameter can be:
  *            @arg RTC_IT_WUT: WakeUpTimer A interrupt
  * @retval None
  */
#define __HAL_RTC_WAKEUPTIMER_ENABLE_IT(__HANDLE__, __INTERRUPT__)    ((__HANDLE__)->Instance->CR |= (__INTERRUPT__))

/**
  * @brief  Disable the RTC WakeUpTimer interrupt.
  * @param  __HANDLE__: specifies the RTC handle.
  * @param  __INTERRUPT__: specifies the RTC WakeUpTimer interrupt sources to be enabled or disabled.
  *         This parameter can be:
  *            @arg RTC_IT_WUT: WakeUpTimer A interrupt
  * @retval None
  */
#define __HAL_RTC_WAKEUPTIMER_DISABLE_IT(__HANDLE__, __INTERRUPT__)   ((__HANDLE__)->Instance->CR &= ~(__INTERRUPT__))

/**
  * @brief  Check whether the specified RTC WakeUpTimer interrupt has occurred or not.
  * @param  __HANDLE__: specifies the RTC handle.
  * @param  __INTERRUPT__: specifies the RTC WakeUpTimer interrupt to check.
  *         This parameter can be:
  *            @arg RTC_IT_WUT:  WakeUpTimer A interrupt
  * @retval None
  */
#define __HAL_RTC_WAKEUPTIMER_GET_IT(__HANDLE__, __INTERRUPT__)            (((((__HANDLE__)->Instance->ISR) & ((__INTERRUPT__)>> 4)) != RESET)? SET : RESET)

/**
  * @brief  Check whether the specified RTC Wake Up timer interrupt has been enabled or not.
  * @param  __HANDLE__: specifies the RTC handle.
  * @param  __INTERRUPT__: specifies the RTC Wake Up timer interrupt sources to check.
  *         This parameter can be:
  *            @arg RTC_IT_WUT:  WakeUpTimer interrupt
  * @retval None
  */
#define __HAL_RTC_WAKEUPTIMER_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__)   (((((__HANDLE__)->Instance->CR) & (__INTERRUPT__)) != RESET) ? SET : RESET)

/**
  * @brief  Get the selected RTC WakeUpTimer's flag status.
  * @param  __HANDLE__: specifies the RTC handle.
  * @param  __FLAG__: specifies the RTC WakeUpTimer Flag to check.
  *          This parameter can be:
  *             @arg RTC_FLAG_WUTF
  *             @arg RTC_FLAG_WUTWF
  * @retval None
  */
#define __HAL_RTC_WAKEUPTIMER_GET_FLAG(__HANDLE__, __FLAG__)          (((((__HANDLE__)->Instance->ISR) & (__FLAG__)) != RESET)? SET : RESET)

/**
  * @brief  Clear the RTC Wake Up timer's pending flags.
  * @param  __HANDLE__: specifies the RTC handle.
  * @param  __FLAG__: specifies the RTC Tamper Flag sources to be enabled or disabled.
  *         This parameter can be:
  *            @arg RTC_FLAG_WUTF
  * @retval None
  */
#define __HAL_RTC_WAKEUPTIMER_CLEAR_FLAG(__HANDLE__, __FLAG__)            ((__HANDLE__)->Instance->ISR) = (~(((__FLAG__) | RTC_ISR_INIT)& 0x0000FFFF)|((__HANDLE__)->Instance->ISR & RTC_ISR_INIT))

/**
  * @brief  Enable interrupt on the RTC Wake-up Timer associated Exti line.
  * @retval None
  */
#define __HAL_RTC_WAKEUPTIMER_EXTI_ENABLE_IT()       (EXTI->IMR |= RTC_EXTI_LINE_WAKEUPTIMER_EVENT)

/**
  * @brief  Disable interrupt on the RTC Wake-up Timer associated Exti line.
  * @retval None
  */
#define __HAL_RTC_WAKEUPTIMER_EXTI_DISABLE_IT()      (EXTI->IMR &= ~(RTC_EXTI_LINE_WAKEUPTIMER_EVENT))

/**
  * @brief  Enable event on the RTC Wake-up Timer associated Exti line.
  * @retval None.
  */
#define __HAL_RTC_WAKEUPTIMER_EXTI_ENABLE_EVENT()    (EXTI->EMR |= RTC_EXTI_LINE_WAKEUPTIMER_EVENT)

/**
  * @brief  Disable event on the RTC Wake-up Timer associated Exti line.
  * @retval None.
  */
#define __HAL_RTC_WAKEUPTIMER_EXTI_DISABLE_EVENT()   (EXTI->EMR &= ~(RTC_EXTI_LINE_WAKEUPTIMER_EVENT))

/**
  * @brief  Enable falling edge trigger on the RTC Wake-up Timer associated Exti line.
  * @retval None.
  */
#define __HAL_RTC_WAKEUPTIMER_EXTI_ENABLE_FALLING_EDGE()   (EXTI->FTSR |= RTC_EXTI_LINE_WAKEUPTIMER_EVENT)

/**
  * @brief  Disable falling edge trigger on the RTC Wake-up Timer associated Exti line.
  * @retval None.
  */
#define __HAL_RTC_WAKEUPTIMER_EXTI_DISABLE_FALLING_EDGE()  (EXTI->FTSR &= ~(RTC_EXTI_LINE_WAKEUPTIMER_EVENT))

/**
  * @brief  Enable rising edge trigger on the RTC Wake-up Timer associated Exti line.
  * @retval None.
  */
#define __HAL_RTC_WAKEUPTIMER_EXTI_ENABLE_RISING_EDGE()    (EXTI->RTSR |= RTC_EXTI_LINE_WAKEUPTIMER_EVENT)

/**
  * @brief  Disable rising edge trigger on the RTC Wake-up Timer associated Exti line.
  * @retval None.
  */
#define __HAL_RTC_WAKEUPTIMER_EXTI_DISABLE_RISING_EDGE()   (EXTI->RTSR &= ~(RTC_EXTI_LINE_WAKEUPTIMER_EVENT))

/**
  * @brief  Enable rising & falling edge trigger on the RTC Wake-up Timer associated Exti line.
  * @retval None.
  */
#define __HAL_RTC_WAKEUPTIMER_EXTI_ENABLE_RISING_FALLING_EDGE() __HAL_RTC_WAKEUPTIMER_EXTI_ENABLE_RISING_EDGE();__HAL_RTC_WAKEUPTIMER_EXTI_ENABLE_FALLING_EDGE();

/**
  * @brief  Disable rising & falling edge trigger on the RTC Wake-up Timer associated Exti line.
  * This parameter can be:
  * @retval None.
  */
#define __HAL_RTC_WAKEUPTIMER_EXTI_DISABLE_RISING_FALLING_EDGE() __HAL_RTC_WAKEUPTIMER_EXTI_DISABLE_RISING_EDGE();__HAL_RTC_WAKEUPTIMER_EXTI_DISABLE_FALLING_EDGE();

/**
  * @brief Check whether the RTC Wake-up Timer associated Exti line interrupt flag is set or not.
  * @retval Line Status.
  */
#define __HAL_RTC_WAKEUPTIMER_EXTI_GET_FLAG()              (EXTI->PR & RTC_EXTI_LINE_WAKEUPTIMER_EVENT)

/**
  * @brief Clear the RTC Wake-up Timer associated Exti line flag.
  * @retval None.
  */
#define __HAL_RTC_WAKEUPTIMER_EXTI_CLEAR_FLAG()            (EXTI->PR = RTC_EXTI_LINE_WAKEUPTIMER_EVENT)

/**
  * @brief Generate a Software interrupt on the RTC Wake-up Timer associated Exti line.
  * @retval None.
  */
#define __HAL_RTC_WAKEUPTIMER_EXTI_GENERATE_SWIT()         (EXTI->SWIER |= RTC_EXTI_LINE_WAKEUPTIMER_EVENT)

/**
  * @}
  */

/* ---------------------------------TIMESTAMP---------------------------------*/
/** @defgroup RTCEx_Timestamp RTC Timestamp
  * @{
  */

/**
  * @brief  Enable the RTC TimeStamp peripheral.
  * @param  __HANDLE__: specifies the RTC handle.
  * @retval None
  */
#define __HAL_RTC_TIMESTAMP_ENABLE(__HANDLE__)                        ((__HANDLE__)->Instance->CR |= (RTC_CR_TSE))

/**
  * @brief  Disable the RTC TimeStamp peripheral.
  * @param  __HANDLE__: specifies the RTC handle.
  * @retval None
  */
#define __HAL_RTC_TIMESTAMP_DISABLE(__HANDLE__)                       ((__HANDLE__)->Instance->CR &= ~(RTC_CR_TSE))

/**
  * @brief  Enable the RTC TimeStamp interrupt.
  * @param  __HANDLE__: specifies the RTC handle.
  * @param  __INTERRUPT__: specifies the RTC TimeStamp interrupt sources to be enabled or disabled.
  *         This parameter can be:
  *            @arg RTC_IT_TS: TimeStamp interrupt
  * @retval None
  */
#define __HAL_RTC_TIMESTAMP_ENABLE_IT(__HANDLE__, __INTERRUPT__)      ((__HANDLE__)->Instance->CR |= (__INTERRUPT__))

/**
  * @brief  Disable the RTC TimeStamp interrupt.
  * @param  __HANDLE__: specifies the RTC handle.
  * @param  __INTERRUPT__: specifies the RTC TimeStamp interrupt sources to be enabled or disabled.
  *         This parameter can be:
  *            @arg RTC_IT_TS: TimeStamp interrupt
  * @retval None
  */
#define __HAL_RTC_TIMESTAMP_DISABLE_IT(__HANDLE__, __INTERRUPT__)     ((__HANDLE__)->Instance->CR &= ~(__INTERRUPT__))

/**
  * @brief  Check whether the specified RTC TimeStamp interrupt has occurred or not.
  * @param  __HANDLE__: specifies the RTC handle.
  * @param  __INTERRUPT__: specifies the RTC TimeStamp interrupt to check.
  *         This parameter can be:
  *            @arg RTC_IT_TS: TimeStamp interrupt
  * @retval None
  */
#define __HAL_RTC_TIMESTAMP_GET_IT(__HANDLE__, __INTERRUPT__)         (((((__HANDLE__)->Instance->ISR) & ((__INTERRUPT__)>> 4)) != RESET)? SET : RESET)

/**
  * @brief  Check whether the specified RTC Time Stamp interrupt has been enabled or not.
  * @param  __HANDLE__: specifies the RTC handle.
  * @param  __INTERRUPT__: specifies the RTC Time Stamp interrupt source to check.
  *         This parameter can be:
  *            @arg RTC_IT_TS: TimeStamp interrupt
  * @retval None
  */
#define __HAL_RTC_TIMESTAMP_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__)     (((((__HANDLE__)->Instance->CR) & (__INTERRUPT__)) != RESET) ? SET : RESET)

/**
  * @brief  Get the selected RTC TimeStamp's flag status.
  * @param  __HANDLE__: specifies the RTC handle.
  * @param  __FLAG__: specifies the RTC TimeStamp flag to check.
  *         This parameter can be:
  *            @arg RTC_FLAG_TSF
  *            @arg RTC_FLAG_TSOVF
  * @retval None
  */
#define __HAL_RTC_TIMESTAMP_GET_FLAG(__HANDLE__, __FLAG__)            (((((__HANDLE__)->Instance->ISR) & (__FLAG__)) != RESET)? SET : RESET)

/**
  * @brief  Clear the RTC Time Stamp's pending flags.
  * @param  __HANDLE__: specifies the RTC handle.
  * @param  __FLAG__: specifies the RTC Alarm Flag sources to be enabled or disabled.
  *          This parameter can be:
  *             @arg RTC_FLAG_TSF
  * @retval None
  */
#define __HAL_RTC_TIMESTAMP_CLEAR_FLAG(__HANDLE__, __FLAG__)          ((__HANDLE__)->Instance->ISR) = (~(((__FLAG__) | RTC_ISR_INIT)& 0x0000FFFF)|((__HANDLE__)->Instance->ISR & RTC_ISR_INIT))

/**
  * @}
  */

/* ---------------------------------TAMPER------------------------------------*/
/** @defgroup RTCEx_Tamper RTC Tamper
  * @{
  */

/**
  * @brief  Enable the RTC Tamper1 input detection.
  * @param  __HANDLE__: specifies the RTC handle.
  * @retval None
  */
#define __HAL_RTC_TAMPER1_ENABLE(__HANDLE__)                         ((__HANDLE__)->Instance->TAFCR |= (RTC_TAFCR_TAMP1E))

/**
  * @brief  Disable the RTC Tamper1 input detection.
  * @param  __HANDLE__: specifies the RTC handle.
  * @retval None
  */
#define __HAL_RTC_TAMPER1_DISABLE(__HANDLE__)                        ((__HANDLE__)->Instance->TAFCR &= ~(RTC_TAFCR_TAMP1E))

/**
  * @brief  Enable the RTC Tamper2 input detection.
  * @param  __HANDLE__: specifies the RTC handle.
  * @retval None
  */
#define __HAL_RTC_TAMPER2_ENABLE(__HANDLE__)                         ((__HANDLE__)->Instance->TAFCR |= (RTC_TAFCR_TAMP2E))

/**
  * @brief  Disable the RTC Tamper2 input detection.
  * @param  __HANDLE__: specifies the RTC handle.
  * @retval None
  */
#define __HAL_RTC_TAMPER2_DISABLE(__HANDLE__)                        ((__HANDLE__)->Instance->TAFCR &= ~(RTC_TAFCR_TAMP2E))

/**
  * @brief  Check whether the specified RTC Tamper interrupt has occurred or not.
  * @param  __HANDLE__: specifies the RTC handle.
  * @param  __INTERRUPT__: specifies the RTC Tamper interrupt to check.
  *         This parameter can be:
  *            @arg  RTC_IT_TAMP1
  *            @arg  RTC_IT_TAMP2
  * @retval None
  */
#define __HAL_RTC_TAMPER_GET_IT(__HANDLE__, __INTERRUPT__)       (((((__HANDLE__)->Instance->ISR) & ((__INTERRUPT__)>> 4)) != RESET)? SET : RESET)

/**
  * @brief  Check whether the specified RTC Tamper interrupt has been enabled or not.
  * @param  __HANDLE__: specifies the RTC handle.
  * @param  __INTERRUPT__: specifies the RTC Tamper interrupt source to check.
  *         This parameter can be:
  *            @arg RTC_IT_TAMP: Tamper interrupt
  * @retval None
  */
#define __HAL_RTC_TAMPER_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__)     (((((__HANDLE__)->Instance->TAFCR) & (__INTERRUPT__)) != RESET) ? SET : RESET)

/**
  * @brief  Get the selected RTC Tamper's flag status.
  * @param  __HANDLE__: specifies the RTC handle.
  * @param  __FLAG__: specifies the RTC Tamper Flag sources to be enabled or disabled.
  *          This parameter can be:
  *             @arg RTC_FLAG_TAMP1F
  *             @arg RTC_FLAG_TAMP2F
  * @retval None
  */
#define __HAL_RTC_TAMPER_GET_FLAG(__HANDLE__, __FLAG__)               (((((__HANDLE__)->Instance->ISR) & (__FLAG__)) != RESET)? SET : RESET)

/**
  * @brief  Clear the RTC Tamper's pending flags.
  * @param  __HANDLE__: specifies the RTC handle.
  * @param  __FLAG__: specifies the RTC Tamper Flag to clear.
  *          This parameter can be:
  *             @arg RTC_FLAG_TAMP1F
  *             @arg RTC_FLAG_TAMP2F
  * @retval None
  */
#define __HAL_RTC_TAMPER_CLEAR_FLAG(__HANDLE__, __FLAG__)         ((__HANDLE__)->Instance->ISR) = (~(((__FLAG__) | RTC_ISR_INIT)& 0x0000FFFF)|((__HANDLE__)->Instance->ISR & RTC_ISR_INIT))
/**
  * @}
  */

/* --------------------------TAMPER/TIMESTAMP---------------------------------*/
/** @defgroup RTCEx_Tamper_Timestamp EXTI RTC Tamper Timestamp EXTI
  * @{
  */

/**
  * @brief  Enable interrupt on the RTC Tamper and Timestamp associated Exti line.
  * @retval None
  */
#define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_ENABLE_IT()        (EXTI->IMR |= RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT)

/**
  * @brief  Disable interrupt on the RTC Tamper and Timestamp associated Exti line.
  * @retval None
  */
#define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_DISABLE_IT()       (EXTI->IMR &= ~(RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT))

/**
  * @brief  Enable event on the RTC Tamper and Timestamp associated Exti line.
  * @retval None.
  */
#define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_ENABLE_EVENT()    (EXTI->EMR |= RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT)

/**
  * @brief  Disable event on the RTC Tamper and Timestamp associated Exti line.
  * @retval None.
  */
#define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_DISABLE_EVENT()   (EXTI->EMR &= ~(RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT))

/**
  * @brief  Enable falling edge trigger on the RTC Tamper and Timestamp associated Exti line.
  * @retval None.
  */
#define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_ENABLE_FALLING_EDGE()   (EXTI->FTSR |= RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT)

/**
  * @brief  Disable falling edge trigger on the RTC Tamper and Timestamp associated Exti line.
  * @retval None.
  */
#define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_DISABLE_FALLING_EDGE()  (EXTI->FTSR &= ~(RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT))

/**
  * @brief  Enable rising edge trigger on the RTC Tamper and Timestamp associated Exti line.
  * @retval None.
  */
#define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_ENABLE_RISING_EDGE()    (EXTI->RTSR |= RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT)

/**
  * @brief  Disable rising edge trigger on the RTC Tamper and Timestamp associated Exti line.
  * @retval None.
  */
#define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_DISABLE_RISING_EDGE()   (EXTI->RTSR &= ~(RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT))

/**
  * @brief  Enable rising & falling edge trigger on the RTC Tamper and Timestamp associated Exti line.
  * @retval None.
  */
#define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_ENABLE_RISING_FALLING_EDGE() __HAL_RTC_TAMPER_TIMESTAMP_EXTI_ENABLE_RISING_EDGE();__HAL_RTC_TAMPER_TIMESTAMP_EXTI_ENABLE_FALLING_EDGE();

/**
  * @brief  Disable rising & falling edge trigger on the RTC Tamper and Timestamp associated Exti line.
  * This parameter can be:
  * @retval None.
  */
#define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_DISABLE_RISING_FALLING_EDGE() __HAL_RTC_TAMPER_TIMESTAMP_EXTI_DISABLE_RISING_EDGE();__HAL_RTC_TAMPER_TIMESTAMP_EXTI_DISABLE_FALLING_EDGE();

/**
  * @brief Check whether the RTC Tamper and Timestamp associated Exti line interrupt flag is set or not.
  * @retval Line Status.
  */
#define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_GET_FLAG()         (EXTI->PR & RTC_EXTI_LINE_WAKEUPTIMER_EVENT)

/**
  * @brief Clear the RTC Tamper and Timestamp associated Exti line flag.
  * @retval None.
  */
#define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_CLEAR_FLAG()       (EXTI->PR = RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT)

/**
  * @brief Generate a Software interrupt on the RTC Tamper and Timestamp associated Exti line
  * @retval None.
  */
#define __HAL_RTC_TAMPER_TIMESTAMP_EXTI_GENERATE_SWIT()    (EXTI->SWIER |= RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT)
/**
  * @}
  */

/* ------------------------------Calibration----------------------------------*/
/** @defgroup RTCEx_Calibration RTC Calibration
  * @{
  */

/**
  * @brief  Enable the Coarse calibration process.
  * @param  __HANDLE__: specifies the RTC handle.
  * @retval None
  */
#define __HAL_RTC_COARSE_CALIB_ENABLE(__HANDLE__)                       ((__HANDLE__)->Instance->CR |= (RTC_CR_DCE))

/**
  * @brief  Disable the Coarse calibration process.
  * @param  __HANDLE__: specifies the RTC handle.
  * @retval None
  */
#define __HAL_RTC_COARSE_CALIB_DISABLE(__HANDLE__)                      ((__HANDLE__)->Instance->CR &= ~(RTC_CR_DCE))

/**
  * @brief  Enable the RTC calibration output.
  * @param  __HANDLE__: specifies the RTC handle.
  * @retval None
  */
#define __HAL_RTC_CALIBRATION_OUTPUT_ENABLE(__HANDLE__)                 ((__HANDLE__)->Instance->CR |= (RTC_CR_COE))

/**
  * @brief  Disable the calibration output.
  * @param  __HANDLE__: specifies the RTC handle.
  * @retval None
  */
#define __HAL_RTC_CALIBRATION_OUTPUT_DISABLE(__HANDLE__)                ((__HANDLE__)->Instance->CR &= ~(RTC_CR_COE))

/**
  * @brief  Enable the clock reference detection.
  * @param  __HANDLE__: specifies the RTC handle.
  * @retval None
  */
#define __HAL_RTC_CLOCKREF_DETECTION_ENABLE(__HANDLE__)                 ((__HANDLE__)->Instance->CR |= (RTC_CR_REFCKON))

/**
  * @brief  Disable the clock reference detection.
  * @param  __HANDLE__: specifies the RTC handle.
  * @retval None
  */
#define __HAL_RTC_CLOCKREF_DETECTION_DISABLE(__HANDLE__)                ((__HANDLE__)->Instance->CR &= ~(RTC_CR_REFCKON))

/**
  * @brief  Get the selected RTC shift operation's flag status.
  * @param  __HANDLE__: specifies the RTC handle.
  * @param  __FLAG__: specifies the RTC shift operation Flag is pending or not.
  *          This parameter can be:
  *             @arg RTC_FLAG_SHPF
  * @retval None
  */
#define __HAL_RTC_SHIFT_GET_FLAG(__HANDLE__, __FLAG__)                (((((__HANDLE__)->Instance->ISR) & (__FLAG__)) != RESET)? SET : RESET)
/**
  * @}
  */

/**
  * @}
  */

/* Exported functions --------------------------------------------------------*/
/** @defgroup RTCEx_Exported_Functions RTCEx Exported Functions
  * @{
  */

/** @addtogroup RTCEx_Exported_Functions_Group1
  * @{
  */
/* RTC TimeStamp and Tamper functions *****************************************/
HAL_StatusTypeDef HAL_RTCEx_SetTimeStamp(RTC_HandleTypeDef *hrtc, uint32_t TimeStampEdge, uint32_t RTC_TimeStampPin);
HAL_StatusTypeDef HAL_RTCEx_SetTimeStamp_IT(RTC_HandleTypeDef *hrtc, uint32_t TimeStampEdge, uint32_t RTC_TimeStampPin);
HAL_StatusTypeDef HAL_RTCEx_DeactivateTimeStamp(RTC_HandleTypeDef *hrtc);
HAL_StatusTypeDef HAL_RTCEx_GetTimeStamp(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTimeStamp, RTC_DateTypeDef *sTimeStampDate, uint32_t Format);

HAL_StatusTypeDef HAL_RTCEx_SetTamper(RTC_HandleTypeDef *hrtc, RTC_TamperTypeDef* sTamper);
HAL_StatusTypeDef HAL_RTCEx_SetTamper_IT(RTC_HandleTypeDef *hrtc, RTC_TamperTypeDef* sTamper);
HAL_StatusTypeDef HAL_RTCEx_DeactivateTamper(RTC_HandleTypeDef *hrtc, uint32_t Tamper);
void HAL_RTCEx_TamperTimeStampIRQHandler(RTC_HandleTypeDef *hrtc);

void HAL_RTCEx_Tamper1EventCallback(RTC_HandleTypeDef *hrtc);
void HAL_RTCEx_Tamper2EventCallback(RTC_HandleTypeDef *hrtc);
void HAL_RTCEx_TimeStampEventCallback(RTC_HandleTypeDef *hrtc);
HAL_StatusTypeDef HAL_RTCEx_PollForTimeStampEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout);
HAL_StatusTypeDef HAL_RTCEx_PollForTamper1Event(RTC_HandleTypeDef *hrtc, uint32_t Timeout);
HAL_StatusTypeDef HAL_RTCEx_PollForTamper2Event(RTC_HandleTypeDef *hrtc, uint32_t Timeout);
/**
  * @}
  */

/** @addtogroup RTCEx_Exported_Functions_Group2
  * @{
  */
/* RTC Wake-up functions ******************************************************/
HAL_StatusTypeDef HAL_RTCEx_SetWakeUpTimer(RTC_HandleTypeDef *hrtc, uint32_t WakeUpCounter, uint32_t WakeUpClock);
HAL_StatusTypeDef HAL_RTCEx_SetWakeUpTimer_IT(RTC_HandleTypeDef *hrtc, uint32_t WakeUpCounter, uint32_t WakeUpClock);
uint32_t HAL_RTCEx_DeactivateWakeUpTimer(RTC_HandleTypeDef *hrtc);
uint32_t HAL_RTCEx_GetWakeUpTimer(RTC_HandleTypeDef *hrtc);
void HAL_RTCEx_WakeUpTimerIRQHandler(RTC_HandleTypeDef *hrtc);
void HAL_RTCEx_WakeUpTimerEventCallback(RTC_HandleTypeDef *hrtc);
HAL_StatusTypeDef HAL_RTCEx_PollForWakeUpTimerEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout);
/**
  * @}
  */

/** @addtogroup RTCEx_Exported_Functions_Group3
  * @{
  */
/* Extension Control functions ************************************************/
void HAL_RTCEx_BKUPWrite(RTC_HandleTypeDef *hrtc, uint32_t BackupRegister, uint32_t Data);
uint32_t HAL_RTCEx_BKUPRead(RTC_HandleTypeDef *hrtc, uint32_t BackupRegister);

HAL_StatusTypeDef HAL_RTCEx_SetCoarseCalib(RTC_HandleTypeDef *hrtc, uint32_t CalibSign, uint32_t Value);
HAL_StatusTypeDef HAL_RTCEx_DeactivateCoarseCalib(RTC_HandleTypeDef *hrtc);
HAL_StatusTypeDef HAL_RTCEx_SetSmoothCalib(RTC_HandleTypeDef *hrtc, uint32_t SmoothCalibPeriod, uint32_t SmoothCalibPlusPulses, uint32_t SmouthCalibMinusPulsesValue);
HAL_StatusTypeDef HAL_RTCEx_SetSynchroShift(RTC_HandleTypeDef *hrtc, uint32_t ShiftAdd1S, uint32_t ShiftSubFS);
HAL_StatusTypeDef HAL_RTCEx_SetCalibrationOutPut(RTC_HandleTypeDef *hrtc, uint32_t CalibOutput);
HAL_StatusTypeDef HAL_RTCEx_DeactivateCalibrationOutPut(RTC_HandleTypeDef *hrtc);
HAL_StatusTypeDef HAL_RTCEx_SetRefClock(RTC_HandleTypeDef *hrtc);
HAL_StatusTypeDef HAL_RTCEx_DeactivateRefClock(RTC_HandleTypeDef *hrtc);
HAL_StatusTypeDef HAL_RTCEx_EnableBypassShadow(RTC_HandleTypeDef *hrtc);
HAL_StatusTypeDef HAL_RTCEx_DisableBypassShadow(RTC_HandleTypeDef *hrtc);
/**
  * @}
  */

/** @addtogroup RTCEx_Exported_Functions_Group4
  * @{
  */
/* Extension RTC features functions *******************************************/
void HAL_RTCEx_AlarmBEventCallback(RTC_HandleTypeDef *hrtc);
HAL_StatusTypeDef HAL_RTCEx_PollForAlarmBEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout);
/**
  * @}
  */

/**
  * @}
  */

/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/** @defgroup RTCEx_Private_Constants RTCEx Private Constants
  * @{
  */
#define RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT  ((uint32_t)EXTI_IMR_MR21)  /*!< External interrupt line 21 Connected to the RTC Tamper and Time Stamp events */
#define RTC_EXTI_LINE_WAKEUPTIMER_EVENT       ((uint32_t)EXTI_IMR_MR22)  /*!< External interrupt line 22 Connected to the RTC Wake-up event */
/**
  * @}
  */

/* Private macros ------------------------------------------------------------*/
/** @defgroup RTCEx_Private_Macros RTCEx Private Macros
  * @{
  */

/** @defgroup RTCEx_IS_RTC_Definitions Private macros to check input parameters
  * @{
  */
#define IS_RTC_BKP(BKP)                   (((BKP) == RTC_BKP_DR0)  || \
                                           ((BKP) == RTC_BKP_DR1)  || \
                                           ((BKP) == RTC_BKP_DR2)  || \
                                           ((BKP) == RTC_BKP_DR3)  || \
                                           ((BKP) == RTC_BKP_DR4)  || \
                                           ((BKP) == RTC_BKP_DR5)  || \
                                           ((BKP) == RTC_BKP_DR6)  || \
                                           ((BKP) == RTC_BKP_DR7)  || \
                                           ((BKP) == RTC_BKP_DR8)  || \
                                           ((BKP) == RTC_BKP_DR9)  || \
                                           ((BKP) == RTC_BKP_DR10) || \
                                           ((BKP) == RTC_BKP_DR11) || \
                                           ((BKP) == RTC_BKP_DR12) || \
                                           ((BKP) == RTC_BKP_DR13) || \
                                           ((BKP) == RTC_BKP_DR14) || \
                                           ((BKP) == RTC_BKP_DR15) || \
                                           ((BKP) == RTC_BKP_DR16) || \
                                           ((BKP) == RTC_BKP_DR17) || \
                                           ((BKP) == RTC_BKP_DR18) || \
                                           ((BKP) == RTC_BKP_DR19))
#define IS_TIMESTAMP_EDGE(EDGE) (((EDGE) == RTC_TIMESTAMPEDGE_RISING) || \
                                 ((EDGE) == RTC_TIMESTAMPEDGE_FALLING))
#define IS_RTC_TAMPER(TAMPER) ((((TAMPER) & (uint32_t)0xFFFFFFF6) == 0x00) && ((TAMPER) != (uint32_t)RESET))

#if defined (STM32F446xx)
#define IS_RTC_TAMPER_PIN(PIN) (((PIN) == RTC_TAMPERPIN_PC13) || \
                                ((PIN) == RTC_TAMPERPIN_PA0))
#else
#define IS_RTC_TAMPER_PIN(PIN) (((PIN) == RTC_TAMPERPIN_PC13) || \
                                ((PIN) == RTC_TAMPERPIN_PI8))
#endif /* STM32F446xx */

#if defined (STM32F446xx)
#define IS_RTC_TIMESTAMP_PIN(PIN) (((PIN) == RTC_TIMESTAMPPIN_PC13) || \
                                   ((PIN) == RTC_TIMESTAMPPIN_PA0))
#else
#define IS_RTC_TIMESTAMP_PIN(PIN) (((PIN) == RTC_TIMESTAMPPIN_PC13) || \
                                   ((PIN) == RTC_TIMESTAMPPIN_PI8))
#endif /* STM32F446xx */
#define IS_RTC_TAMPER_TRIGGER(TRIGGER) (((TRIGGER) == RTC_TAMPERTRIGGER_RISINGEDGE) || \
                                        ((TRIGGER) == RTC_TAMPERTRIGGER_FALLINGEDGE) || \
                                        ((TRIGGER) == RTC_TAMPERTRIGGER_LOWLEVEL) || \
                                        ((TRIGGER) == RTC_TAMPERTRIGGER_HIGHLEVEL))
#define IS_RTC_TAMPER_FILTER(FILTER)  (((FILTER) == RTC_TAMPERFILTER_DISABLE) || \
                                       ((FILTER) == RTC_TAMPERFILTER_2SAMPLE) || \
                                       ((FILTER) == RTC_TAMPERFILTER_4SAMPLE) || \
                                       ((FILTER) == RTC_TAMPERFILTER_8SAMPLE))
#define IS_RTC_TAMPER_SAMPLING_FREQ(FREQ) (((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV32768)|| \
                                           ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV16384)|| \
                                           ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV8192) || \
                                           ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV4096) || \
                                           ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV2048) || \
                                           ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV1024) || \
                                           ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV512)  || \
                                           ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV256))
#define IS_RTC_TAMPER_PRECHARGE_DURATION(DURATION) (((DURATION) == RTC_TAMPERPRECHARGEDURATION_1RTCCLK) || \
                                                    ((DURATION) == RTC_TAMPERPRECHARGEDURATION_2RTCCLK) || \
                                                    ((DURATION) == RTC_TAMPERPRECHARGEDURATION_4RTCCLK) || \
                                                    ((DURATION) == RTC_TAMPERPRECHARGEDURATION_8RTCCLK))
#define IS_RTC_TAMPER_TIMESTAMPONTAMPER_DETECTION(DETECTION) (((DETECTION) == RTC_TIMESTAMPONTAMPERDETECTION_ENABLE) || \
                                                              ((DETECTION) == RTC_TIMESTAMPONTAMPERDETECTION_DISABLE))
#define IS_RTC_TAMPER_PULLUP_STATE(STATE) (((STATE) == RTC_TAMPER_PULLUP_ENABLE) || \
                                           ((STATE) == RTC_TAMPER_PULLUP_DISABLE))
#define IS_RTC_WAKEUP_CLOCK(CLOCK) (((CLOCK) == RTC_WAKEUPCLOCK_RTCCLK_DIV16)   || \
                                    ((CLOCK) == RTC_WAKEUPCLOCK_RTCCLK_DIV8)    || \
                                    ((CLOCK) == RTC_WAKEUPCLOCK_RTCCLK_DIV4)    || \
                                    ((CLOCK) == RTC_WAKEUPCLOCK_RTCCLK_DIV2)    || \
                                    ((CLOCK) == RTC_WAKEUPCLOCK_CK_SPRE_16BITS) || \
                                    ((CLOCK) == RTC_WAKEUPCLOCK_CK_SPRE_17BITS))

#define IS_RTC_WAKEUP_COUNTER(COUNTER)  ((COUNTER) <= 0xFFFF)
#define IS_RTC_CALIB_SIGN(SIGN) (((SIGN) == RTC_CALIBSIGN_POSITIVE) || \
                                 ((SIGN) == RTC_CALIBSIGN_NEGATIVE))

#define IS_RTC_CALIB_VALUE(VALUE) ((VALUE) < 0x20)

#define IS_RTC_SMOOTH_CALIB_PERIOD(PERIOD) (((PERIOD) == RTC_SMOOTHCALIB_PERIOD_32SEC) || \
                                            ((PERIOD) == RTC_SMOOTHCALIB_PERIOD_16SEC) || \
                                            ((PERIOD) == RTC_SMOOTHCALIB_PERIOD_8SEC))
#define IS_RTC_SMOOTH_CALIB_PLUS(PLUS) (((PLUS) == RTC_SMOOTHCALIB_PLUSPULSES_SET) || \
                                        ((PLUS) == RTC_SMOOTHCALIB_PLUSPULSES_RESET))

#define  IS_RTC_SMOOTH_CALIB_MINUS(VALUE) ((VALUE) <= 0x000001FF)
#define IS_RTC_SHIFT_ADD1S(SEL) (((SEL) == RTC_SHIFTADD1S_RESET) || \
                                 ((SEL) == RTC_SHIFTADD1S_SET))
#define IS_RTC_SHIFT_SUBFS(FS) ((FS) <= 0x00007FFF)
#define IS_RTC_CALIB_OUTPUT(OUTPUT)  (((OUTPUT) == RTC_CALIBOUTPUT_512HZ) || \
                                      ((OUTPUT) == RTC_CALIBOUTPUT_1HZ))
/**
  * @}
  */

/**
  * @}
  */

/**
  * @}
  */

/**
  * @}
  */

#ifdef __cplusplus
}
#endif

#endif /* __STM32F4xx_HAL_RTC_EX_H */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/


text:
package com.koch.ambeth.security;

import java.lang.reflect.Method;

import com.koch.ambeth.ioc.DefaultExtendableContainer;
import com.koch.ambeth.ioc.annotation.Autowired;
import com.koch.ambeth.ioc.config.Property;
import com.koch.ambeth.ioc.threadlocal.Forkable;
import com.koch.ambeth.ioc.threadlocal.IForkProcessor;
import com.koch.ambeth.ioc.threadlocal.IThreadLocalCleanupBean;
import com.koch.ambeth.merge.config.MergeConfigurationConstants;
import com.koch.ambeth.merge.security.ILightweightSecurityContext;
import com.koch.ambeth.merge.security.ISecurityActivation;
import com.koch.ambeth.util.exception.RuntimeExceptionUtil;
import com.koch.ambeth.util.state.AbstractStateRollback;
import com.koch.ambeth.util.state.IStateRollback;
import com.koch.ambeth.util.threading.IBackgroundWorkerDelegate;
import com.koch.ambeth.util.threading.IResultingBackgroundWorkerDelegate;
import com.koch.ambeth.util.threading.SensitiveThreadLocal;

public class SecurityContextHolder implements IAuthorizationChangeListenerExtendable,
		ISecurityContextHolder, IThreadLocalCleanupBean, ILightweightSecurityContext,
		ISecurityContextFactory {
	public static class SecurityContextForkProcessor implements IForkProcessor {
		@Override
		public Object resolveOriginalValue(Object bean, String fieldName, ThreadLocal<?> fieldValueTL) {
			return fieldValueTL.get();
		}

		@Override
		public Object createForkedValue(Object value) {
			if (value == null) {
				return null;
			}
			SecurityContextImpl original = (SecurityContextImpl) value;
			SecurityContextImpl forkedValue = new SecurityContextImpl(original.securityContextHolder);
			forkedValue.setAuthentication(original.getAuthentication());
			forkedValue.setAuthorization(original.getAuthorization());
			return forkedValue;
		}

		@Override
		public void returnForkedValue(Object value, Object forkedValue) {
			// Intended blank
		}
	}

	@Autowired
	protected IAuthenticatedUserHolder authenticatedUserHolder;

	@Autowired(optional = true)
	protected IAuthorizationProcess authorizationProcess;

	@Autowired(optional = true)
	protected ISecurityContextProvider securityContextProvider;

	@Autowired
	protected ISecurityActivation securityActivation;

	@Autowired(optional = true)
	protected ISecurityManager securityManager;

	@Property(name = MergeConfigurationConstants.SecurityActive, defaultValue = "false")
	protected boolean securityActive;

	protected final DefaultExtendableContainer<IAuthorizationChangeListener> authorizationChangeListeners =
			new DefaultExtendableContainer<>(
					IAuthorizationChangeListener.class, "authorizationChangeListener");

	@Forkable(processor = SecurityContextForkProcessor.class)
	protected final ThreadLocal<ISecurityContext> contextTL = new SensitiveThreadLocal<>();

	protected void notifyAuthorizationChangeListeners(IAuthorization authorization) {
		authenticatedUserHolder
				.setAuthenticatedSID(authorization != null ? authorization.getSID() : null);
		for (IAuthorizationChangeListener authorizationChangeListener : authorizationChangeListeners
				.getExtensionsShared()) {
			authorizationChangeListener.authorizationChanged(authorization);
		}
	}

	@Override
	public void cleanupThreadLocal() {
		clearContext();
	}

	@Override
	public void registerAuthorizationChangeListener(
			IAuthorizationChangeListener authorizationChangeListener) {
		authorizationChangeListeners.register(authorizationChangeListener);
	}

	@Override
	public void unregisterAuthorizationChangeListener(
			IAuthorizationChangeListener authorizationChangeListener) {
		authorizationChangeListeners.unregister(authorizationChangeListener);
	}

	@Override
	public ISecurityContext getContext() {
		ISecurityContext context = getContextIntern();
		if (context == null && securityContextProvider != null) {
			context = securityContextProvider.getSecurityContext();
		}
		return context;
	}

	protected ISecurityContext getContextIntern() {
		return contextTL.get();
	}

	/*
	 * (non-Javadoc)
	 * @see com.koch.ambeth.security.ISecurityContextFactory#createSecurityContext()
	 */
	@Override
	public ISecurityContext createSecurityContext() {
		return new SecurityContextImpl(this);
	}

	@Override
	public ISecurityContext getCreateContext() {
		ISecurityContext securityContext = getContext();
		if (securityContext == null) {
			securityContext = createSecurityContext();
			contextTL.set(securityContext);
		}
		return securityContext;
	}

	protected ISecurityContext getCreateContextIntern() {
		ISecurityContext securityContext = getContextIntern();
		if (securityContext == null) {
			securityContext = new SecurityContextImpl(this);
			contextTL.set(securityContext);
		}
		return securityContext;
	}

	@Override
	public void clearContext() {
		ISecurityContext securityContext = contextTL.get();
		if (securityContext != null) {
			securityContext.setAuthentication(null);
			securityContext.setAuthorization(null);
			contextTL.remove();
		}
	}

	@Override
	public IStateRollback pushAuthentication(IAuthentication authentication,
			IStateRollback... rollbacks) {
		ISecurityContext securityContext = getContextIntern();
		boolean created = false;
		if (securityContext == null) {
			securityContext = getCreateContextIntern();
			created = true;
		}
		boolean success = false;
		final IAuthorization oldAuthorization = securityContext.getAuthorization();
		final IAuthentication oldAuthentication = securityContext.getAuthentication();
		try {
			final boolean fCreated = created;
			if (oldAuthentication == authentication) {
				IStateRollback rollback = new AbstractStateRollback(rollbacks) {
					@Override
					protected void rollbackIntern() throws Exception {
						if (fCreated) {
							clearContext();
						}
					}
				};
				success = true;
				return rollback;
			}
			try {
				securityContext.setAuthentication(authentication);
				securityContext.setAuthorization(null);
				final ISecurityContext fSecurityContext = securityContext;
				IStateRollback rollback = new AbstractStateRollback(rollbacks) {
					@Override
					protected void rollbackIntern() throws Exception {
						fSecurityContext.setAuthentication(oldAuthentication);
						fSecurityContext.setAuthorization(oldAuthorization);
						if (fCreated) {
							clearContext();
						}
					}
				};
				success = true;
				return rollback;
			}
			finally {
				if (!success) {
					securityContext.setAuthentication(oldAuthentication);
					securityContext.setAuthorization(oldAuthorization);
				}
			}
		}
		finally {
			if (!success && created) {
				clearContext();
			}
		}
	}

	@Override
	public boolean isAuthenticated() {
		ISecurityContext securityContext = getContext();
		if (securityContext == null) {
			return false;
		}
		return securityContext.getAuthorization() != null;
	}

	@Override
	public void withAuthenticated(IBackgroundWorkerDelegate delegate) {
		ensureAuthenticated();
		try {
			delegate.invoke();
		}
		catch (Exception e) {
			throw RuntimeExceptionUtil.mask(e);
		}
	}

	@Override
	public <R> R withAuthenticated(IResultingBackgroundWorkerDelegate<R> delegate) {
		ensureAuthenticated();
		try {
			return delegate.invoke();
		}
		catch (Exception e) {
			throw RuntimeExceptionUtil.mask(e);
		}
	}

	@Override
	public void withAuthorized(Method method, IBackgroundWorkerDelegate delegate) {
		IAuthorization authorization = ensureAuthenticated();
		if (securityManager != null) {
			securityManager.checkMethodAccess(method, new Object[0], SecurityContextType.AUTHORIZED,
					authorization);
		}
		try {
			delegate.invoke();
		}
		catch (Exception e) {
			throw RuntimeExceptionUtil.mask(e);
		}
	}

	@Override
	public <R> R withAuthorized(Method method, IResultingBackgroundWorkerDelegate<R> delegate) {
		IAuthorization authorization = ensureAuthenticated();
		if (securityManager != null) {
			securityManager.checkMethodAccess(method, new Object[0], SecurityContextType.AUTHORIZED,
					authorization);
		}
		try {
			R result = delegate.invoke();
			if (securityManager != null) {
				result = securityManager.filterValue(result);
			}
			return result;
		}
		catch (Exception e) {
			throw RuntimeExceptionUtil.mask(e);
		}
	}

	protected IAuthorization ensureAuthenticated() {
		if (!securityActive) {
			return null;
		}
		ISecurityContext securityContext = getContext();
		IAuthorization authorization = securityContext != null ? securityContext.getAuthorization()
				: null;
		if (authorization != null) {
			if (!authorization.isValid()) {
				throw new SecurityException("Authorization invalid");
			}
			return null;
		}
		if (authorizationProcess != null) {
			authorizationProcess.ensureAuthorization();
			securityContext = getContext();
			authorization = securityContext != null ? securityContext.getAuthorization() : null;
		}
		if (authorization == null || !authorization.isValid()) {
			throw new SecurityException("Authorization invalid");
		}
		return authorization;
	}
}

redpajama_set_name: RedPajamaGithub


text:
export const enum BarEnum {
    Bar = 2
};


text:
    One of the searches Hudson does on LDAP is to locate the user record given the user name.
    If you specify a relative DN (from the root DN) here, Hudson will further narrow down
    searches to the sub-tree.

    But in practice, LDAP servers maintain an extensive index over the data, so specifying
    this field is rarely necessary.

    If you do specify this value, the field normally looks something like <tt>"ou=people"</tt>


text:
echo ">> Convering Module Featured Graphic SVG to PNG '$@'...";

if [[ "$#" -lt 3 || "$#" -gt 4 ]]; then
    echo "> Wrong $# parameters '$@'!";
    echo "> Ex: 'app-android: ../commons-android/pub/module-featured-graphic.sh \"STM\" \"Montréal\" \"QC, Canada\";'";
    echo "> Ex: 'app-android: ../commons-android/pub/module-featured-graphic.sh \"Société de Transport\" \"de Montréal\" \"Montréal\" \"QC, Canada\";'";
    exit -1;
fi

AGENCY_NAME_1="";
AGENCY_NAME_2="";
CITY="";
STATE_COUNTRY="";
if [[ "$#" -eq 3 ]]; then
    AGENCY_NAME_1=$1;
    AGENCY_NAME_2="";
    CITY=$2;
    STATE_COUNTRY=$3;
else
    AGENCY_NAME_1=$1;
    AGENCY_NAME_2=$2;
    CITY=$3;
    STATE_COUNTRY=$4;
fi

MAX_AGENCY_LENGTH=17;

MAX_CITY_LENGTH=77;

if [[ -z "${AGENCY_NAME_1}" ]]; then
    echo "> No agency name provided '$AGENCY_NAME_1'!";
    exit 1;
elif [ "${#AGENCY_NAME_1}" -gt "$MAX_AGENCY_LENGTH" ]; then
    echo "> Provided agency name '$AGENCY_NAME_1'(${#AGENCY_NAME_1}) is too long (max:$MAX_AGENCY_LENGTH)!";
    exit 1;
fi
if [[ "$#" -eq 4 ]]; then
    if [[ -z "${AGENCY_NAME_2}" ]]; then
        echo "> No agency name provided '$AGENCY_NAME_2'!";
        exit 1;
    elif [ "${#AGENCY_NAME_2}" -gt "$MAX_AGENCY_LENGTH" ]; then
        echo "> Provided agency name '$AGENCY_NAME_2'(${#AGENCY_NAME_2}) is too long (max:$MAX_AGENCY_LENGTH)!";
        exit 1;
    fi
fi
if [[ -z "${CITY}" ]]; then
    echo "> No city provided '$CITY'!";
    exit 1;
elif [ "${#CITY}" -gt "$MAX_CITY_LENGTH" ]; then
    echo "> Provided city '$CITY'(${#CITY}) is too long (max:$MAX_CITY_LENGTH)!";
    exit 1;
fi
if [[ -z "${STATE_COUNTRY}" ]]; then
    echo "> No state, country provided '$STATE_COUNTRY'!";
    exit 1;
fi
echo " - agency name: '$AGENCY_NAME_1' '$AGENCY_NAME_2'";
echo " - city: '$CITY'";
echo " - state & country: '$STATE_COUNTRY'";

COLOR="";
RES_DIR=src/main/res;
AGENCY_RTS_FILE=$RES_DIR/values/gtfs_rts_values_gen.xml;
AGENCY_BIKE_FILE=$RES_DIR/values/bike_station_values.xml;
TYPE=-1;
if [ -f $AGENCY_RTS_FILE ]; then
    echo "> Agency file: '$AGENCY_RTS_FILE'.";
    COLOR=$(grep -E "<string name=\"gtfs_rts_color\">[0-9A-Z]+</string>$" $AGENCY_RTS_FILE | tr -dc '0-9A-Z');
    # https://github.com/mtransitapps/parser/blob/master/src/main/java/org/mtransit/parser/gtfs/data/GRouteType.kt
    TYPE=$(grep -E "<integer name=\"gtfs_rts_agency_type\">[0-9]+</integer>$" $AGENCY_RTS_FILE | tr -dc '0-9');
elif [ -f $AGENCY_BIKE_FILE ]; then
    echo "> Agency file: '$AGENCY_BIKE_FILE'.";
    COLOR=$(grep -E "<string name=\"bike_station_color\">[0-9A-Z]+</string>$" $AGENCY_BIKE_FILE | tr -dc '0-9A-Z');
    TYPE=$(grep -E "<integer name=\"bike_station_agency_type\">[0-9]+</integer>$" $AGENCY_BIKE_FILE | tr -dc '0-9');
else
    echo " > No agency file! (rts:$AGENCY_RTS_FILE|bike:$AGENCY_BIKE_FILE)";
    exit -1;
fi
if [ -z "$COLOR" ] ; then
    echo " > No color found for agency type!";
    exit -1;
fi
echo " - color: $COLOR";
echo " - type: $TYPE";

# https://github.com/mtransitapps/mtransit-for-android/blob/mmathieum/src/main/java/org/mtransit/android/data/DataSourceType.java

SOURCE_GIT_PATH="pub/module-featured-graphic*.svg";
SOURCE="../commons-android/pub/module-featured-graphic.svg"; # BASE (ALL TYPE LAYERS HIDEEN)
if [ $TYPE -eq 0 ]; then # LIGHT_RAIL
    SOURCE="../commons-android/pub/module-featured-graphic-light-rail.svg";
    if [[ "$#" -eq 4 ]]; then
        SOURCE="../commons-android/pub/module-featured-graphic-light-rail-2.svg";
    fi
elif [ $TYPE -eq 1 ]; then # SUBWAY
    SOURCE="../commons-android/pub/module-featured-graphic-subway.svg";
    if [[ "$#" -eq 4 ]]; then
        SOURCE="../commons-android/pub/module-featured-graphic-subway-2.svg";
    fi
elif [ $TYPE -eq 2 ]; then # TRAIN
    SOURCE="../commons-android/pub/module-featured-graphic-train.svg";
    if [[ "$#" -eq 4 ]]; then
        SOURCE="../commons-android/pub/module-featured-graphic-train-2.svg";
    fi
elif [ $TYPE -eq 3 ]; then # BUS
    SOURCE="../commons-android/pub/module-featured-graphic-bus.svg";
    if [[ "$#" -eq 4 ]]; then
        SOURCE="../commons-android/pub/module-featured-graphic-bus-2.svg";
    fi
elif [ $TYPE -eq 4 ]; then # FERRY
    SOURCE="../commons-android/pub/module-featured-graphic-ferry.svg";
    if [[ "$#" -eq 4 ]]; then
        SOURCE="../commons-android/pub/module-featured-graphic-ferry-2.svg";
    fi
elif [ $TYPE -eq 100 ]; then # BIKE
    SOURCE="../commons-android/pub/module-featured-graphic-bike.svg";
    if [[ "$#" -eq 4 ]]; then
        SOURCE="../commons-android/pub/module-featured-graphic-bike-2.svg";
    fi
else
    echo "Unexpected agency type '$TYPE'!";
    exit -1;
fi
echo " - svg: $SOURCE";
DEST="src/main/play/listings/en-US/graphics/feature-graphic/1.png";
echo " - png: $DEST";

WIDTH=1024;
echo " - width: $WIDTH";
HEIGHT=500;
echo " - height: $HEIGHT";

FONT_INSTALLED=$(fc-list | grep -i roboto | grep -i condensed); # Roboto Condensed
if [[ -z "${FONT_INSTALLED}" ]]; then
    echo "> Font not installed! ('$FONT_INSTALLED')";
    exit 1;
fi

if ! [ -x "$(command -v inkscape)" ]; then
    echo "> Inkscape not installed!";
    exit ${RESULT};
fi

INKSCAPE_VERSION=$(inkscape --version);
echo "> Inkscape version: $INKSCAPE_VERSION"; # requires v1.1+
# https://inkscape.org/doc/inkscape-man.html
# https://wiki.inkscape.org/wiki/index.php/Using_the_Command_Line

echo "> Resetting file...";
git -C ../commons-android checkout $SOURCE_GIT_PATH; #start fresh
echo "> Resetting file... DONE";

echo "> Setting file strings...";

if [[ "$#" -eq 3 ]]; then
    sed -i "s/MTAgency/$AGENCY_NAME_1/g" $SOURCE;
else
    sed -i "s/MTAgency1/$AGENCY_NAME_1/g" $SOURCE;
    sed -i "s/MTAgency2/$AGENCY_NAME_2/g" $SOURCE;
fi
sed -i "s/MTCity/$CITY/g" $SOURCE;
sed -i "s/MTStateCountry/$STATE_COUNTRY/g" $SOURCE;
git -C ../commons-android diff $SOURCE_GIT_PATH;
echo "> Setting file strings... DONE";

echo "> Running inkscape...";
inkscape \
--export-area-page \
--export-width=$WIDTH \
--export-height=$HEIGHT \
--export-background=#$COLOR \
--export-type=png \
--export-filename=$DEST \
$SOURCE;
RESULT=$?;
if [[ ${RESULT} -ne 0 ]]; then
    echo "> Error running Inkscape!";
    exit ${RESULT};
fi
echo "> Running inkscape... DONE";

echo "> Resetting file...";
git -C ../commons-android checkout $SOURCE_GIT_PATH; #start fresh
echo "> Resetting file... DONE";

echo ">> Convering Module Featured Graphic SVG to PNG '$@'... DONE";


text:
package main

import "net"
import "fmt"
import "sync/atomic"
import "time"
import "strconv"
import "os"

func client(conn net.Conn, rcounter *int64, wcounter *int64) {
	buf := make([]byte, 2048)
	for {
    // Write
		nwritten, err := conn.Write([]byte("message"))
		if err == nil && 0 < nwritten {
			atomic.AddInt64(wcounter, 1)
		} else {
      panic("")
      return
    }

    // Read
		nread, err := conn.Read(buf)
		if err == nil && 0 < nread {
			atomic.AddInt64(rcounter, 1)
		} else {
      panic("")
      return
    }
	}
}

func main() {
	nb_iter, _ := strconv.ParseInt(os.Args[1], 10, 64)
	var nread int64
	var nwrite int64
	var i int64

	go func(nread *int64, nwrite *int64, nconnected *int64, size int64) {
		latest := time.Now()
		stepDuration := time.Second
		for {
			fmt.Printf("r/s:%9d w/s:%9d clients: %d/%d\n", atomic.SwapInt64(nread, 0)*time.Second.Nanoseconds()/stepDuration.Nanoseconds(), atomic.SwapInt64(nwrite, 0)*time.Second.Nanoseconds()/stepDuration.Nanoseconds(), atomic.LoadInt64(nconnected), size)
			time.Sleep(time.Second)
			current := time.Now()
			stepDuration = current.Sub(latest)
			latest = current
		}
	}(&nread, &nwrite, &i, nb_iter)

	for i < nb_iter {
		conn, err := net.Dial("tcp", "127.0.0.1:8080")
		if err == nil {
			go client(conn, &nread, &nwrite)
			i++
		}
	}

	fmt.Println("Finished launching clients")
	blocker := make(chan int)
	<-blocker
}


text:
{% load url from future %}
{% load i18n %}

{{ widget_output }}

<script type="text/javascript">
if(!window.pybb){
    window.pybb = {};
}
if(!window.pybb.get_markitup_settings){
    window.pybb.get_markitup_settings = function() {
        var mySettings = new Array();
        mySettings['previewParserPath'] = '{% url "pybb:post_ajax_preview" %}';
        mySettings['previewPosition'] = 'before';
        mySettings['resizeHandle'] = true;
        mySettings['markupSet'] = [
            {name:'{% trans "Bold" %}', key:'B', openWith:'[b]', closeWith:'[/b]'},
            {name:'{% trans "Italic" %}', key:'I', openWith:'[i]', closeWith:'[/i]'},
            {name:'{% trans "Underline" %}', key:'U', openWith:'[u]', closeWith:'[/u]'},
            {name:'{% trans "Stroke" %}', key:'S', openWith:'[s]', closeWith:'[/s]'},
            {separator:'---------------' },
            {name:'{% trans "Picture" %}', key:'P', replaceWith:'[img][![Url]!][/img]'},
            {name:'{% trans "Link" %}', key:'L', openWith:'[url=[![Url]!]]', closeWith:'[/url]', placeHolder:'{% trans "Your text to link here..." %}'},
            {separator:'---------------' },
            {name:'{% trans "Bulleted list" %}', openWith:'[list]\n', closeWith:'\n[/list]'},
            {name:'{% trans "Numeric list" %}', openWith:'[list=[![Starting number]!]]\n', closeWith:'\n[/list]'},
            {name:'{% trans "List item" %}', openWith:'[*] '},
            {separator:'---------------' },
            {name:'{% trans "Quotes" %}', openWith:'[quote]', closeWith:'[/quote]'},
            {name:'{% trans "Code" %}', openWith:'[code]', closeWith:'[/code]'},
            {separator:'---------------' },
            {name:'{% trans "Clean" %}', className:"clean", replaceWith:function(markitup) { return markitup.selection.replace(/\[(.*?)\]/g, "") } },
            {name:'{% trans "Preview" %}', className:"preview", call:'preview' }
        ];
        return mySettings ;
    };
}
</script>


text:
$(document).ready(function() {
    $.validate({
        form: '#contactForm',
    });
});


text:
module Yage.Core.Application.LogHandler
    ( module LogHandler
    ) where

import System.Log.Handler as LogHandler


text:
def binaryTree(r):
    return [r, [], []]

def insertLeft(root,newBranch):
    t = root.pop(1)
    if len(t) > 1:
        root.insert(1,[newBranch,t,[]])
    else:
        root.insert(1,[newBranch, [], []])
    return root

def insertRight(root,newBranch):
    t = root.pop(2)
    if len(t) > 1:
        root.insert(2,[newBranch,[],t])
    else:
        root.insert(2,[newBranch,[],[]])
    return root

def getRootVal(root):
    return root[0]

def setRootVal(root,newVal):
    root[0] = newVal

def getLeftChild(root):
    return root[1]

def getRightChild(root):
    return root[2]

def buildTree():
    a = binaryTree('a')
    insertLeft(a, 'b')
    insertRight(a, 'c')
    insertRight(getLeftChild(a), 'd')
    insertLeft(getRightChild(a), 'e')
    insertRight(getRightChild(a), 'f')
    return a

tree = buildTree()
print tree


text:
/***************************************************************************
* Class: Fusion.Layers
*
* Implements Layers for Fusion.
*/

Fusion.Event.MAP_LAYER_TOGGLED = Fusion.Event.lastEventId++;
Fusion.Event.MAP_LAYER_ORDER_CHANGED = Fusion.Event.lastEventId++;
Fusion.Event.LAYER_LOADED = Fusion.Event.lastEventId++;
Fusion.Event.LAYER_LOADING = Fusion.Event.lastEventId++;

Fusion.Layers = OpenLayers.Class(Fusion.Lib.EventMgr, {
    bSingleTile: null,
    bIsBaseLayer: false,     //TODO: set this in AppDef?
    bDisplayInLegend: true,   //TODO: set this in AppDef?
    bExpandInLegend: true,   //TODO: set this in AppDef?
    bMapLoaded: false,
    bIsMapWidgetLayer: true,  //Set this to false for overview map layers
    bLayersReversed: false,     //MGOS returns layers top-most layer first
    sMapResourceId: null,    //pointer to the resource that defines the map (URL, MapFile, MGOS, etc)
    sImageType: 'png',      //TODO: set this in AppDef?
    clientAgent: 'Fusion Viewer',
    noCache: false,
    _sMapTitle: null,
    _sMapname: null,

    initialize: function(map, mapTag, isMapWidgetLayer) {
        // console.log('Fusion.Layers.initialize');

        this.registerEventID(Fusion.Event.MAP_SELECTION_ON);
        this.registerEventID(Fusion.Event.MAP_SELECTION_OFF);
        this.registerEventID(Fusion.Event.MAP_LOADED);
        this.registerEventID(Fusion.Event.LAYER_LOADED);
        this.registerEventID(Fusion.Event.LAYER_LOADING);
        this.registerEventID(Fusion.Event.MAP_LAYER_ORDER_CHANGED);
        this.registerEventID(Fusion.Event.LAYER_PROPERTY_CHANGED);

        this.mapWidget = map;
        this.oSelection = null;
        if (isMapWidgetLayer != null) {
            this.bIsMapWidgetLayer = isMapWidgetLayer;
        }

        this.mapTag = mapTag;
        if (!this.mapTag.layerOptions) {
          this.mapTag.layerOptions = {};
        }
        this.ratio = this.mapTag.layerOptions.MapRatio ? this.extension.MapRatio[0] : 1.0;
        this.bSingleTile = mapTag.singleTile; //this is set in thhe AppDef.Map class
        this.bIsBaseLayer = mapTag.isBaseLayer;
        this.sMapResourceId = mapTag.resourceId ? mapTag.resourceId : '';
        this.mapInfo = mapTag.mapInfo;
        this.layerType = mapTag.type;
    },

    /**
     * Function: loadScaleRanges
     *
     * This function should be called after the map has loaded. It
     * loads the scsle ranges for each layer. I tis for now only
     * used by the legend widget.
     */

    loadScaleRanges: function(userFunc) {
      userFunc();
    },

    getMapName: function() {
        return this._sMapname;
    },

    getMapTitle: function() {
        return this._sMapTitle;
    },

    /**
     * Function: isMapLoaded
     *
     * Returns true if the Map has been laoded succesfully form the server
     */
    isMapLoaded: function() {
        return this.bMapLoaded;
    },

    getMaxExtent: function() {
      var maxExtent = null;
      if (this.oLayerOL) {
        maxExtent = this.oLayerOL.maxExtent;
      }
      return maxExtent;
    },

    hasSelection: function() {
      return this.bSelectionOn;
    },

    /**
     * Returns the number of features selected for this map layer
     */
    getSelectedFeatureCount: function() {
      var total = 0;
      return total;
    },

    /**
     * Returns the number of features selected for this map layer
     */
    getSelectedLayers: function() {
      var layers = [];
      return layers;
    },

    /**
     * Returns the number of features selected for this map layer
     */
    getSelectableLayers: function() {
      var layers = [];
      return layers;
    },

    setSelection: function (selText, zoomTo) {
    },

     /**
     * asynchronously load the current selection.  When the current
     * selection changes, the selection is not loaded because it
     * could be a lengthy process.  The user-supplied function will
     * be called when the selection is available.
     *
     * @param userFunc {Function} a function to call when the
     *        selection has loaded
     *
     * @param layers {string} Optional parameter.  A comma separated
     *        list of layer names (Roads,Parcels). If it is not
     *        given, all the layers that have a selection will be used
     *
     * @param startcount {string} Optional parameter.  A comma separated
     *        list of a statinh index and the number of features to be retured for
     *        each layer given in the layers parameter. Index starts at 0
     *        (eg: 0:4,2:6 : return 4 elements for the first layers starting at index 0 and
     *         six elements for layer 2 starting at index 6). If it is not
     *        given, all the elemsnts will be returned.
     */
    getSelection: function(userFunc, layers, startcount) {
    },

    /**
       Utility function to clear current selection
    */
    clearSelection: function() {
    },

    /**
       Do a query on the map
    */
    query: function(options) {
    },

    processLayerEvents: function(layer, isEnabling) {
        if (this.mapInfo && this.mapInfo.mapEvents.layerEvents[layer.layerName]) {
            var layerEvent = this.mapInfo.mapEvents.layerEvents[layer.layerName];
            var events = isEnabling ? layerEvent.onEnable : layerEvent.onDisable;
            for (var i=0; i<events.length; i++) {
                var o = events[i];
                if (o.type == 'layer') {
                    var l = this.layerRoot.findLayer(o.name);
                    if (l) {
                        if (o.enable) {
                            l.show(true);
                        } else {
                            l.hide(true);
                        }
                    }

                } else if (o.type == 'group') {
                    var g = this.layerRoot.findGroupByAttribute('groupName', o.name);
                    if (g) {
                        if (o.enable) {
                            g.show(true);
                        } else {
                            g.hide(true);
                        }
                    }
                }
            }
        }
    },

    processGroupEvents: function(group, isEnabling) {
        if (this.mapInfo && this.mapInfo.mapEvents.groupEvents[group.groupName]) {
            var groupEvent = this.mapInfo.mapEvents.groupEvents[group.groupName];
            var events = isEnabling ? groupEvent.onEnable : groupEvent.onDisable;
            for (var i=0; i<events.length; i++) {
                var o = events[i];
                if (o.type == 'layer') {
                    var l = this.layerRoot.findLayer(o.name);
                    if (l) {
                        if (o.enable) {
                            l.show(true);
                        } else {
                            l.hide(true);
                        }
                    }

                } else if (o.type == 'group') {
                    var g = this.layerRoot.findGroupByAttribute('groupName', o.name);
                    if (g) {
                        if (o.enable) {
                            g.show(true);
                        } else {
                            g.hide(true);
                        }
                    }
                }
            }
        }
    },

    refreshLayer: function( layer ) {
        this.drawMap();
    },

    setParameter: function(param, value) {
        if (param == 'SelectionType') {
            this.selectionType = value;
        }
    },

    loadStart: function() {
      if (this.bIsMapWidgetLayer) {
        this.mapWidget._addWorker();
      }
    },

    loadEnd: function() {
      if (this.bIsMapWidgetLayer) {
        this.mapWidget._removeWorker();
      }
    },

    getGroupInfoUrl: function(groupName) {
        if (this.mapInfo) {
            var groups = this.mapInfo.links.groups;
            for (var i=0; i<groups.length; i++) {
                if (groups[i].name == groupName) {
                    return groups[i].url;
                }
            }
        }
        return null;
    },
    getLayerInfoUrl: function(layerName) {
        if (this.mapInfo) {
            var layers = this.mapInfo.links.layers;
            for (var i=0; i<layers.length; i++) {
                if (layers[i].name == layerName) {
                    return layers[i].url;
                }
            }
        }
        return null;
    },

    getMapTip: function(mapTipWidget) {}
});

/***************************************************************************
* Class: Fusion.Layers.Group
*
* Implements the map layer groups
 * **********************************************************************/
Fusion.Event.GROUP_PROPERTY_CHANGED = Fusion.Event.lastEventId++;

Fusion.Layers.Group = OpenLayers.Class(Fusion.Lib.EventMgr, {
    name: null,
    groups: null,
    layers: null,
    oMap: null,
    initialize: function(o, oMap) {
        this.uniqueId = o.uniqueId;
        this.name = o.groupName;
        this.groups = [];
        this.layers = [];
        this.oMap = oMap;
        this.groupName = o.groupName;
        this.legendLabel = o.legendLabel;
        this.parentUniqueId = o.parentUniqueId;
        this.groupType = o.groupType;
        this.displayInLegend = o.displayInLegend;
        this.expandInLegend = o.expandInLegend;
        this.visible = o.visible;
        this.initiallyVisible = o.visible;
        this.actuallyVisible = o.actuallyVisible;
        this.isBaseMapGroup = o.isBaseMapGroup;
        this.registerEventID(Fusion.Event.GROUP_PROPERTY_CHANGED);
    },

    show: function(noDraw) {
        if (this.visible) {
            return;
        }
        this.oMap.showGroup(this, noDraw ? true : false);
        this.set('visible', true);
        if (this.legend && this.legend.treeItem && this.legend.treeItem.checkBox) {
            this.legend.treeItem.checkBox.checked = true;
        }
    },

    hide: function(noDraw) {
        if (!this.visible) {
            return;
        }
        this.oMap.hideGroup(this, noDraw ? true : false);
        this.set('visible', false);
        if (this.legend && this.legend.treeItem && this.legend.treeItem.checkBox) {
            this.legend.treeItem.checkBox.checked = false;
        }
    },

    isVisible: function() {
        return this.visible;
    },

    clear: function() {
        for (var i=0; i<this.groups.length; i++) {
            this.groups[i].clear();
        }
        for (var i=0; i<this.layers.length; i++) {
            this.layers[i].clear();
        }
        this.groups = [];
        this.layers = [];
    },

    set: function(property, value) {
        this[property] = value;
        this.triggerEvent(Fusion.Event.GROUP_PROPERTY_CHANGED, this);
    },

    addGroup: function(group,reverse) {
        group.parentGroup = this;
        if (reverse) {
          this.groups.unshift(group);
        } else {
          this.groups.push(group);
        }
    },

    addLayer: function(layer,reverse) {
        layer.parentGroup = this;
        if (reverse) {
          this.layers.unshift(layer);
        } else {
          this.layers.push(layer);
        }
    },

    findGroup: function(name) {
        return this.findGroupByAttribute('name', name);
    },

    findGroupByAttribute: function(attribute, value) {
        if (this[attribute] == value) {
            return this;
        }
        for (var i=0; i<this.groups.length; i++) {
            var group = this.groups[i].findGroupByAttribute(attribute, value);
            if (group) {
                return group;
            }
        }
        return null;
    },

    findLayer: function(name) {
        return this.findLayerByAttribute('name', name);
    },

    findLayerByAttribute: function(attribute, value) {
        for (var i=0; i<this.layers.length; i++) {
            if (this.layers[i][attribute] == value) {
                return this.layers[i];
            }
        }
        for (var i=0; i<this.groups.length; i++) {
            var layer = this.groups[i].findLayerByAttribute(attribute,value);
            if (layer) {
                return layer;
            }
        }
        return null;
    }

});

/***************************************************************************
* Class: Fusion.Layers.Layer
*
* Implements individual map legend layers
 * **********************************************************************/
Fusion.Event.LAYER_PROPERTY_CHANGED = Fusion.Event.lastEventId++;

Fusion.Layers.Layer = OpenLayers.Class(Fusion.Lib.EventMgr, {

    name: null,
    scaleRanges: null,
    oMap: null,

    initialize: function(o, oMap) {
        this.oMap = oMap;
        this.layerName = o.layerName;
        this.uniqueId = o.uniqueId;
        this.resourceId = o.resourceId;
        this.selectedFeatureCount = 0;
        this.layerTypes = [].concat(o.layerTypes);
        this.legendLabel = o.legendLabel;
        this.displayInLegend = o.displayInLegend;
        this.expandInLegend = o.expandInLegend;
        this.actuallyVisible = o.actuallyVisible;
        this.statusDefault = o.statusdefault;
        this.editable = o.editable;
        this.visible = o.visible;
        this.initiallyVisible = o.visible;
        this.selectable = o.selectable;
        this.isBaseMapLayer = o.isBaseMapLayer;

        //determine the layer type so that the correct icon can be displayed in the legend
        this.layerType = null;
        if (this.supportsType(Fusion.Constant.LAYER_RASTER_TYPE)) {   //raster layers
          this.layerType = Fusion.Constant.LAYER_RASTER_TYPE;
        } else if (this.supportsType(Fusion.Constant.LAYER_DWF_TYPE)) {  //DWF layers
          this.layerType = Fusion.Constant.LAYER_DWF_TYPE;
        }

        this.parentGroup = o.parentGroup;
        this.minScale = o.minScale;
        this.maxScale = o.maxScale;
        if (this.maxScale == 'infinity') {
          this.maxScale = 1000000000000;
        }
        this.scaleRanges = [];

        if (o.scaleRanges)
        {
          for (var i=0; i<o.scaleRanges.length; i++) {
            var scaleRange = new Fusion.Layers.ScaleRange(o.scaleRanges[i],
                                                                 this.layerType);
            this.scaleRanges.push(scaleRange);
          }
        }

        //this.registerEventID(Fusion.Event.LAYER_PROPERTY_CHANGED);
    },

    supportsType: function(type) {
        for (var i=0; i<this.layerTypes.length; i++) {
            if (this.layerTypes[i] == type) {
                return true;
            }
        }
        return false;
    },

    getScaleRange: function(fScale) {
        for (var i=0; i<this.scaleRanges.length; i++) {
            if (this.scaleRanges[i].contains(fScale)) {
                return this.scaleRanges[i];
            }
        }
        return null;
    },

    show: function(noDraw) {
        if (this.visible) {
            return;
        }
        this.set('visible', true);
        this.oMap.showLayer(this, noDraw ? true : false);
        if (this.legend && this.legend.treeItem && this.legend.treeItem.checkBox) {
            this.legend.treeItem.checkBox.checked = true;
        }
    },

    hide: function(noDraw) {
        if (!this.visible) {
            return;
        }
        this.set('visible',false);
        this.oMap.hideLayer(this, noDraw ? true : false);
        if (this.legend && this.legend.treeItem && this.legend.treeItem.checkBox) {
            this.legend.treeItem.checkBox.checked = false;
        }
    },

    isVisible: function() {
        return this.visible;
    },

    clear: function() {},

    set: function(property, value) {
        this[property] = value;
        this.oMap.triggerEvent(Fusion.Event.LAYER_PROPERTY_CHANGED, this);
    }

});

/***************************************************************************
* Class: Fusion.Layers.ScaleRange
*
* Implements a scale range object
*/

Fusion.Layers.ScaleRange = OpenLayers.Class({
    styles: null,
    initialize: function(o, layerType, iconOpt) {
        this.minScale = o.minScale;
        this.maxScale = o.maxScale;
        this.isCompressed = o.isCompressed;
        if (this.maxScale == 'infinity' || this.maxScale == 'auto') {
          this.maxScale = Infinity;
        }
        this.styles = [];
        if (!o.styles) {
          var styleItem = new Fusion.Layers.StyleItem({legendLabel:'DWF'}, layerType, iconOpt);
          this.styles.push(styleItem);
          return;
        }
        var staticIcon = o.styles.length>1 ? false : layerType;
        for (var i=0; i<o.styles.length; i++) {
            var styleItem = new Fusion.Layers.StyleItem(o.styles[i], staticIcon, iconOpt);
            if (o.styles[i].imageData)
            {
                styleItem.iconOpt = {
                    url: o.styles[i].imageData,
                    width: iconOpt.width,
                    height: iconOpt.height
                };
            }
            this.styles.push(styleItem);
        }
    },
    contains: function(fScale) {
        var testScale = Math.round(fScale);
        return testScale >= this.minScale && testScale <= this.maxScale;
    }
});

/***************************************************************************
* Class: Fusion.Layers.StyleItem
*
* Implements the legend style items to get a legend icon from the server
*/

Fusion.Layers.StyleItem = OpenLayers.Class({
    clientAgent: 'Fusion Viewer',
    initialize: function(o, staticIcon, iconOpt) {
        this.iconOpt = iconOpt;
        this.iconX = o.icon_x || 0;
        this.iconY = o.icon_y || 0;
        this.legendLabel = o.legendLabel;
        this.filter = o.filter;
        this.geometryType = o.geometryType;
        this.skipRendering = o.skipRendering;
        if (this.geometryType == '') {
            this.geometryType = -1;
        }
        this.categoryIndex = o.categoryIndex;
        if (this.categoryindex == '') {
            this.categoryindex = -1;
        }
        this.index = o.index; //TODO: merge this with categoryIndex?
        this.staticIcon = staticIcon;
    }
});


text:
<?php

namespace ONGR\ElasticsearchBundle\Tests\app\fixture\Acme\TestBundle\Document\Test;

use ONGR\ElasticsearchBundle\Annotation as ES;
use ONGR\ElasticsearchBundle\Document\AbstractDocument;
use ONGR\ElasticsearchBundle\Document\DocumentInterface;
use ONGR\ElasticsearchBundle\Document\DocumentTrait;

/**
 * Document class Item.
 *
 * @ES\Document(create=false)
 */
class Item extends AbstractDocument
{
    /**
     * @var string
     *
     * @ES\Property(name="name", type="string")
     */
    public $name;

    /**
     * @var float
     *
     * @ES\Property(type="float", name="price")
     */
    protected $price;

    /**
     * @var \DateTime
     *
     * @ES\Property(name="created_at", type="date")
     */
    private $createdAt;

    /**
     * @return float
     */
    public function getPrice()
    {
        return $this->price;
    }

    /**
     * @param float $price
     */
    public function setPrice($price)
    {
        $this->price = $price;
    }

    /**
     * @return \DateTime
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * @param \DateTime $createdAt
     */
    public function setCreatedAt($createdAt)
    {
        $this->createdAt = $createdAt;
    }
}


text:
package binarytree

import (
	"bytes"
	"errors"

	"github.com/aiden0z/kit/base"
	"github.com/aiden0z/kit/queue"
	"github.com/aiden0z/kit/stack"
)

// NewBtreeWithInPreOrder create a binary tree based on PRE and IN order
func NewBtreeWithInPreOrder(inOrder, preOrder []base.Comparable) (btree *Btree, err error) {

	defer func() {
		if r := recover(); r != nil {
			switch r.(type) {
			case error:
				err = errors.New("invalid order sequence")
			default:
				err = errors.New("Unknown panic")
			}
		}
	}()

	if err != nil {
		return
	}

	if len(preOrder) == 0 {
		return btree, nil
	}

	if len(preOrder) != len(inOrder) {
		err = errors.New("length of order sequence not equal")
		return
	}

	rootIndex := indexInSlice(preOrder[0], inOrder)

	btree = &Btree{
		Element: preOrder[0],
	}

	node, err := NewBtreeWithInPreOrder(inOrder[:rootIndex], preOrder[1:rootIndex+1])
	if err != nil {
		return nil, err
	}
	btree.Left = node

	node, err = NewBtreeWithInPreOrder(inOrder[1+rootIndex:], preOrder[1+rootIndex:])
	if err != nil {
		return nil, err
	}

	btree.Right = node
	return btree, nil
}

// NewBtreeWithInPostOrder create a binary tree based on POST and IN order
func NewBtreeWithInPostOrder(inOrder, postOrder []base.Comparable) (btree *Btree,
	err error) {

	defer func() {
		if r := recover(); r != nil {
			switch r.(type) {
			case error:
				err = errors.New("invalid order sequence")
			default:
				err = errors.New("Unknown panic")
			}
		}
	}()

	if err != nil {
		return
	}

	if len(postOrder) == 0 {
		return btree, nil
	}

	if len(postOrder) != len(inOrder) {
		err = errors.New("length of order sequence not equal")
		return
	}

	rootIndex := indexInSlice(postOrder[len(postOrder)-1], inOrder)

	btree = &Btree{
		Element: postOrder[len(postOrder)-1],
	}

	node, err := NewBtreeWithInPostOrder(inOrder[:rootIndex], postOrder[:rootIndex])
	if err != nil {
		return nil, err
	}
	btree.Left = node

	node, err = NewBtreeWithInPostOrder(inOrder[1+rootIndex:], postOrder[rootIndex:len(postOrder)-1])
	if err != nil {
		return nil, err
	}

	btree.Right = node
	return btree, nil

}

// PreOrder return the PRE order traversal
func (tree *Btree) PreOrder() (order []*Btree) {
	if tree != nil {
		order = append(order, tree)
		order = append(order, tree.Left.PreOrder()...)
		order = append(order, tree.Right.PreOrder()...)
	}
	return order
}

// PreOrderNonRecursive return the PRE order traversal
func (tree *Btree) PreOrderNonRecursive() (order []*Btree) {
	if tree == nil {
		return
	}

	node := tree
	s := stack.NewStack(10)

	for node != nil || !s.IsEmpty() {
		for node != nil {
			order = append(order, node)
			s.Push(node)
			node = node.Left
		}

		if !s.IsEmpty() {
			node = s.Pop().(*Btree)
			node = node.Right
		}
	}

	return order
}

// PreOrderMorris return the IN order traversal based on threaded binary tree
// In In-Order, the right node of current node's predecessor always is nil
func (tree *Btree) PreOrderMorris() (order []*Btree) {

	current := tree
	var preNode *Btree

	for current != nil {
		if current.Left == nil {
			order = append(order, current)
			current = current.Right
		} else {
			// find the current node's predecessor in In-Order
			preNode = current.Left
			for preNode.Right != nil && preNode.Right != current {
				preNode = preNode.Right
			}

			if preNode.Right == nil {
				// first time visit, link the right node of current node's predecessor to current node
				order = append(order, current)
				preNode.Right = current
				current = current.Left
			} else {
				// second time visit, remove the link set in first time visit
				preNode.Right = nil
				current = current.Right
			}
		}

	}

	return
}

// InOrder return the IN order traversal
func (tree *Btree) InOrder() (order []*Btree) {
	if tree != nil {
		order = append(order, tree.Left.InOrder()...)
		order = append(order, tree)
		order = append(order, tree.Right.InOrder()...)

	}
	return order
}

// InOrderNonRecursive return the IN order traversal
func (tree *Btree) InOrderNonRecursive() (order []*Btree) {
	if tree == nil {
		return
	}

	node := tree
	s := stack.NewStack(10)

	for node != nil || !s.IsEmpty() {
		for node != nil {
			s.Push(node)
			node = node.Left
		}

		if !s.IsEmpty() {
			node = s.Pop().(*Btree)
			order = append(order, node)
			node = node.Right
		}
	}

	return order
}

// InOrderMorris return the IN order traversal based on threaded binary tree.
// In In-Order, the right node of current node's predecessor always is nil
// In In-order traversal, start from root node
// 1. if current node has left child then find its in-order predecessor and
// make root as right child of it and move left of root. [ to find
// predecessor, find the maximum right element in its left subtree ]
// 2. if current node don't have left child , then print data and move right.
//
// The main thing which should be observe is that while performing step 1,
// we'll reach a point where predecessor right child is itself current node,
// this only happen when whole left child turned off and we start printing data from there.
func (tree *Btree) InOrderMorris() (order []*Btree) {

	current := tree
	var preNode *Btree

	for current != nil {
		if current.Left == nil {
			order = append(order, current)
			current = current.Right
		} else {
			// find the current node's predecessor in In-Order
			preNode = current.Left
			for preNode.Right != nil && preNode.Right != current {
				preNode = preNode.Right
			}

			if preNode.Right == nil {
				// first time visit, link the right node of current node's predecessor to current node
				preNode.Right = current
				current = current.Left
			} else {
				// second time visit, remove the link set in first time visit, then output the node
				preNode.Right = nil
				order = append(order, current)
				current = current.Right
			}
		}

	}

	return
}

// PostOrder return the post order traversal
func (tree *Btree) PostOrder() (order []*Btree) {

	if tree != nil {
		order = append(order, tree.Left.PostOrder()...)
		order = append(order, tree.Right.PostOrder()...)
		order = append(order, tree)

	}
	return order
}

// PostOrderMorris return the POST order traversal based on threaded binary tree
func (tree *Btree) PostOrderMorris() (order []*Btree) {

	dummyRoot := new(Btree)
	// why link tree to the dummyRoot.Left ?
	// Because if we assume there is no right child of root then print
	// left child and then root become POST-order traversal
	dummyRoot.Left = tree

	var preNode, first, middle, last *Btree
	current := dummyRoot

	for current != nil {
		if current.Left == nil {
			current = current.Right
		} else {
			// current has a left child, it also has a predecessor
			// find the current's predecessor in IN-order
			preNode = current.Left
			for preNode.Right != nil && preNode.Right != current {
				preNode = preNode.Right
			}

			// link the right child of predecessor to current
			// when predecessor found for first time
			if preNode.Right == nil {
				preNode.Right = current
				current = current.Left

			} else {
				// predecessor found second time
				// reverse the right references in chain from preNode to current node
				first = current
				middle = current.Left
				for middle != current {
					last = middle.Right
					middle.Right = first
					first = middle
					middle = last

				}

				// visit the nodes from preNode to current node
				// again reverse this right references from
				// preNode to current node
				first = current
				middle = preNode
				for middle != current {
					order = append(order, middle)
					last = middle.Right
					middle.Right = first
					first = middle
					middle = last
				}

				preNode.Right = nil
				current = current.Right

			}

		}

	}

	return
}

// PostOrderNonRecursive return the post order traversal
func (tree *Btree) PostOrderNonRecursive() (order []*Btree) {
	if tree == nil {
		return
	}

	current := tree

	var lastVisited *Btree

	s := stack.NewStack(10)

	// push all left child into the stack firstly
	for current != nil {
		s.Push(current)
		current = current.Left
	}

	for !s.IsEmpty() {
		current = s.Peek().(*Btree)
		// hand the root node
		if current.Right == nil || current.Right == lastVisited {
			order = append(order, current)
			lastVisited = current
			s.Pop()
		} else {
			// handle the right tree
			current = current.Right
			for current != nil {
				s.Push(current)
				current = current.Left
			}
		}
	}
	return
}

// PostOrderNonRecursiveV1 return the post order traversal
func (tree *Btree) PostOrderNonRecursiveV1() (order []*Btree) {
	if tree == nil {
		return
	}

	current := tree

	var lastVisited *Btree

	s := stack.NewStack(10)

	// push the root node into stack firstly
	s.Push(current)

	for !s.IsEmpty() {
		current = s.Peek().(*Btree)

		// root node
		if (current.Left == nil && current.Right == nil) || (lastVisited != nil && (lastVisited == current.Left || lastVisited == current.Right)) {
			order = append(order, current)
			s.Pop()
			lastVisited = current
		} else {
			// then push the right tree
			if current.Right != nil {
				s.Push(current.Right)
			}
			// pus the left tree
			if current.Left != nil {
				s.Push(current.Left)

			}
		}
	}
	return
}

// PostOrderNonRecursiveV2 return the post order traversal
func (tree *Btree) PostOrderNonRecursiveV2() (order []*Btree) {

	if tree == nil {
		return
	}

	s1 := stack.NewStack(10)
	s2 := stack.NewStack(10)

	current := tree
	s1.Push(current)

	// push order: root node -> left tree -> right tree
	for !s1.IsEmpty() {

		current = s1.Pop().(*Btree)
		s2.Push(current)

		if current.Left != nil {
			s1.Push(current.Left)

		}

		if current.Right != nil {
			s1.Push(current.Right)
		}
	}

	// reverse the s1, right tree -> left tree -> root node, get the POST traversal order
	for !s2.IsEmpty() {

		order = append(order, s2.Pop().(*Btree))
	}

	return
}

// LevelOrder return the level order traversal
func (tree *Btree) LevelOrder() (order []*Btree) {

	if tree == nil {
		return

	}

	queue := queue.NewQueue()

	current := tree

	queue.Enqueue(current)

	for !queue.IsEmpty() {

		current = queue.Dequeue().(*Btree)
		order = append(order, current)

		if current.Left != nil {

			queue.Enqueue(current.Left)
		}

		if current.Right != nil {
			queue.Enqueue(current.Right)
		}
	}

	return
}

// Depth return depth of the tree.
func (tree *Btree) Depth() int {
	if tree == nil {
		return 0
	}

	return maxInt(tree.Right.Depth(), tree.Left.Depth()) + 1
}

// VerticalPretty print the tree in vertical format.
func (tree *Btree) VerticalPretty() *bytes.Buffer {

	if tree == nil {
		return nil
	}

	return vertical([]*Btree{tree}, 1, tree.Depth())
}

func (tree *Btree) horizontal(isRight bool, indent string) (buffer *bytes.Buffer) {

	buffer = new(bytes.Buffer)

	if tree == nil {
		return
	}

	if tree.Right != nil {
		var rIndent string
		if isRight {
			rIndent = indent + "       "
		} else {
			rIndent = indent + " |     "
		}
		tree.Right.horizontal(true, rIndent).WriteTo(buffer)
	}

	buffer.WriteString(indent)
	if isRight {
		buffer.WriteString(" /")
	} else {
		buffer.WriteString(" \\")
	}
	buffer.WriteString("---- ")
	buffer.WriteString(tree.Element.String() + "\n")

	if tree.Left != nil {
		var lIndent string
		if isRight {
			lIndent = indent + " |     "
		} else {
			lIndent = indent + "       "
		}
		tree.Left.horizontal(false, lIndent).WriteTo(buffer)
	}

	return
}

// HorizontalPretty print the tree in horizontal pretty format.
func (tree *Btree) HorizontalPretty() (buffer *bytes.Buffer) {

	if tree == nil {
		return
	}

	buffer = new(bytes.Buffer)

	if tree.Right != nil {
		tree.Right.horizontal(true, "").WriteTo(buffer)
	}

	buffer.WriteString(tree.Element.String() + "\n")

	if tree.Left != nil {
		tree.Left.horizontal(false, "").WriteTo(buffer)
	}

	return
}


text:
#pragma once

#include <Cacophony/config.hpp>
#include <Cacophony/types.hpp>
#include <Cacophony/traits.hpp>
#include <Cacophony/utility.hpp>

#include <type_traits>

namespace Cacophony {
//namespace support {

// Forward declarations
template<class T>
struct sequence;

/**
	@addtogroup support
	@{
*/

/**
	Sequence of objects.

	@note Serialization:
	-# elements

	@tparam T Value type.
*/
template<class T>
struct sequence final {
	static_assert(
		!std::is_void<T>::value,
		"T must be a non-void type"
	);

	/** Value type. */
	using value_type = T;

	/** Pointer to sequence. */
	value_type* ptr;
	/** Number of elements. */
	std::size_t size;
};

/**
	Make sequence.

	@param ptr Pointer to sequence.
	@param size Number of elements.
*/
template<
	class T
>
inline sequence<T>
make_sequence(
	T* const ptr,
	std::size_t const size
) noexcept {
	return {ptr, size};
}

/** @cond INTERNAL */

template<class Ser, class T>
inline enable_ser<
	!is_binary_serializable<bare_type<T>>::value
>
serialize(
	tag_serialize,
	Ser& ser,
	sequence<T>& seq
) {
	auto& self = const_safe<Ser>(seq);
	T const* const end = self.ptr + self.size;
	for (auto* it = self.ptr; end > it; ++it) {
		ser(*it);
	}
}

/** @endcond */ // INTERNAL

/** @} */ // end of doc-group support

//} // namespace support
} // namespace Cacophony


text:
package org.apache.geronimo.management.stats;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import javax.management.j2ee.statistics.Statistic;
import javax.management.j2ee.statistics.Stats;

/**
 * Geronimo implementation of the JSR-77 Stats interface.  Dynamically tracks
 * available statistics for its subclasses, to make it easy to iterate
 * available statistics without knowing exactly what kind of class you're
 * looking at.
 *
 * @version $Rev$ $Date$
 */

public class StatsImpl implements Stats, Serializable {
    private final Map <String,StatisticImpl> stats = new HashMap<String,StatisticImpl>();

    public StatsImpl() {
    }

    protected void addStat(String name, StatisticImpl value) {
        stats.put(name, value);
    }

    /**
     * Used when the available statistics are dynamic (e.g. depend on the
     * current clients of the service, etc.).
     *
     * @param name The statistic to remove
     */
    protected void removeStat(String name) {
        stats.remove(name);
    }

    /**
     * Set the startTime for all statistics to System.currentTimeMillis()
     */
    public void setStartTime() {
        long now = System.currentTimeMillis();
        for (StatisticImpl item : stats.values()) {
            item.setStartTime(now);
        }
    }

    /**
     * Set the startTime for all statistics to the given value
     * @param time
     */
    public void setStartTime(long time) {
        for (StatisticImpl item : stats.values()) {
            item.setStartTime(time);
        }
    }

    /**
     * Set the lastSampleTime for all statistics to System.currentTimeMillis()
     */
    public void setLastSampleTime() {
        long now = System.currentTimeMillis();
        for (StatisticImpl item : stats.values()) {
            item.setLastSampleTime(now);
        }
    }

    /*
     * Gets a Statistic by name
     * @see javax.management.j2ee.statistics.Stats#getStatistic(java.lang.String)
     */
    public Statistic getStatistic(String statisticName) {
        return (Statistic)stats.get(statisticName);
    }

    /*
     * Returns a list of names of statistics
     * @see javax.management.j2ee.statistics.Stats#getStatisticNames()
     */
    public String[] getStatisticNames() {
        return (String[]) stats.keySet().toArray(new String[stats.size()]);
    }

    /*
     * Returns a list of all the Statistic objects supported by this Stats object
     * @see javax.management.j2ee.statistics.Stats#getStatistics()
     */
    public Statistic[] getStatistics() {
        String[] names = getStatisticNames();
        Statistic[] result = new Statistic[names.length];
        for (int i = 0; i < names.length; i++) {
            result[i] = (Statistic) stats.get(names[i]);
        }
        return result;
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>StorableResource (River-Internet vtrunk API Documentation)</title>
<meta name="date" content="2016-03-28">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.river.outrigger

Interface StorableResource<T extends LeasedResource>

Type Parameters:

T - the type of the StorableObject

All Superinterfaces:

LeasedResource, StorableObject<T>

public interface StorableResource<T extends LeasedResource>
extends StorableObject<T>, LeasedResource

Sub-interface of StorableObject that must be implemented by
 objects that represent leased resources and must persist their state.

Since:

2.0

Author:

Sun Microsystems, Inc.

See Also:

LogOps

Method Summary

Methods inherited from interface org.apache.river.outrigger.StorableObject

restore, store

Methods inherited from interface org.apache.river.landlord.LeasedResource

getCookie, getExpiration, setExpiration

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright 2007-2013, multiple authors.
Licensed under the Apache License, Version 2.0, see the NOTICE file for attributions.