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

#ifdef __cplusplus
 extern "C" {
#endif

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

/** @addtogroup STM32L0xx_HAL_Driver
  * @{
  */

/** @defgroup ADC ADC
  * @{
  */

/** @defgroup ADC_Exported_Types ADC Exported Types
  * @{
  */

/* Exported types ------------------------------------------------------------*/
/**
  * @brief  HAL ADC state machine: ADC states definition (bitfields)
  */
/* States of ADC global scope */
#define HAL_ADC_STATE_RESET             ((uint32_t)0x00000000)    /*!< ADC not yet initialized or disabled */
#define HAL_ADC_STATE_READY             ((uint32_t)0x00000001)    /*!< ADC peripheral ready for use */
#define HAL_ADC_STATE_BUSY_INTERNAL     ((uint32_t)0x00000002)    /*!< ADC is busy to internal process (initialization, calibration) */
#define HAL_ADC_STATE_TIMEOUT           ((uint32_t)0x00000004)    /*!< TimeOut occurrence */

/* States of ADC errors */
#define HAL_ADC_STATE_ERROR_INTERNAL    ((uint32_t)0x00000010)    /*!< Internal error occurrence */
#define HAL_ADC_STATE_ERROR_CONFIG      ((uint32_t)0x00000020)    /*!< Configuration error occurrence */
#define HAL_ADC_STATE_ERROR_DMA         ((uint32_t)0x00000040)    /*!< DMA error occurrence */

/* States of ADC group regular */
#define HAL_ADC_STATE_REG_BUSY          ((uint32_t)0x00000100)    /*!< A conversion on group regular is ongoing or can occur (either by continuous mode,
                                                                       external trigger, low power auto power-on, multimode ADC master control) */
#define HAL_ADC_STATE_REG_EOC           ((uint32_t)0x00000200)    /*!< Conversion data available on group regular */
#define HAL_ADC_STATE_REG_OVR           ((uint32_t)0x00000400)    /*!< Overrun occurrence */
#define HAL_ADC_STATE_REG_EOSMP         ((uint32_t)0x00000800)    /*!< Not available on STM32F0 device: End Of Sampling flag raised  */

/* States of ADC group injected */
#define HAL_ADC_STATE_INJ_BUSY          ((uint32_t)0x00001000)    /*!< Not available on STM32F0 device: A conversion on group injected is ongoing or can occur (either by auto-injection mode,
                                                                       external trigger, low power auto power-on, multimode ADC master control) */
#define HAL_ADC_STATE_INJ_EOC           ((uint32_t)0x00002000)    /*!< Not available on STM32F0 device: Conversion data available on group injected */
#define HAL_ADC_STATE_INJ_JQOVF         ((uint32_t)0x00004000)    /*!< Not available on STM32F0 device: Not available on STM32F0 device: Injected queue overflow occurrence */

/* States of ADC analog watchdogs */
#define HAL_ADC_STATE_AWD1              ((uint32_t)0x00010000)    /*!< Out-of-window occurrence of analog watchdog 1 */
#define HAL_ADC_STATE_AWD2              ((uint32_t)0x00020000)    /*!< Not available on STM32F0 device: Out-of-window occurrence of analog watchdog 2 */
#define HAL_ADC_STATE_AWD3              ((uint32_t)0x00040000)    /*!< Not available on STM32F0 device: Out-of-window occurrence of analog watchdog 3 */

/* States of ADC multi-mode */
#define HAL_ADC_STATE_MULTIMODE_SLAVE   ((uint32_t)0x00100000)    /*!< Not available on STM32F0 device: ADC in multimode slave state, controlled by another ADC master ( */

/**
  * @brief  ADC Oversampler structure definition
  */
typedef struct
{
  uint32_t Ratio;                         /*!< Configures the oversampling ratio.
                                               This parameter can be a value of @ref ADC_Oversampling_Ratio */
  uint32_t RightBitShift;                 /*!< Configures the division coefficient for the Oversampler.
                                               This parameter can be a value of @ref ADC_Right_Bit_Shift */
  uint32_t TriggeredMode;                 /*!< Selects the regular triggered oversampling mode
                                               This parameter can be a value of @ref ADC_Triggered_Oversampling_Mode */

}ADC_OversamplingTypeDef;

/**
  * @brief  ADC Init structure definition
  * @note   The setting of these parameters with function HAL_ADC_Init() is conditioned by the ADC state.
  *         If ADC is not in the appropriate state to modify some parameters, these parameters setting is bypassed
  *         without error reporting (as it can be the expected behaviour in case of intended action to update antother parameter (which fullfills the ADC state condition) on the fly).
  */
typedef struct
{
  uint32_t OversamplingMode;             /*!< Specifies whether the oversampling feature is enabled or disabled
                                              This parameter can be set to ENABLE or DISABLE.
                                              Note: This parameter can be modified only if there is no conversion is ongoing. */
  ADC_OversamplingTypeDef  Oversample;   /*!< Specifies the Oversampling parameters
                                              Note: This parameter can be modified only if there is no conversion is ongoing. */
  uint32_t ClockPrescaler;               /*!< Selects the ADC clock frequency.
                                              This parameter can be a value of @ref ADC_ClockPrescaler
                                              Note: This parameter can be modified only if ADC is disabled.
                                              Note: In case of Synchronous clock mode divided by 1, this configuration must be enabled only
                                              if PCLK has a 50% duty clock cycle (APB prescaler configured inside the RCC
                                              must be bypassed and the system clock must by 50% duty cycle). Refer to reference manual for details */
  uint32_t Resolution;                   /*!< Configures the ADC resolution mode.
                                              This parameter can be a value of @ref ADC_Resolution
                                              Note: This parameter can be modified only if ADC is disabled. */
  uint32_t SamplingTime;                 /*!< The sample time value to be set for all channels.
                                              This parameter can be a value of @ref ADC_sampling_times
                                              Note: This parameter can be modified only if there is no conversion ongoing. */
  uint32_t ScanConvMode;                  /*!< The scan sequence direction.
                                              If several channels are set:  Conversions are performed in sequence mode
                                              (ranks defined by each channel number: channel 0 fixed on rank 0,
                                              channel 1 fixed on rank1, ...).
                                              This parameter can be a value of @ref ADC_Scan_mode
                                              Note: This parameter can be modified only if there is no conversion is ongoing. */
  uint32_t DataAlign;                    /*!< Specifies whether the ADC data  alignment is left or right.
                                              This parameter can be a value of @ref ADC_data_align
                                              Note: This parameter can be modified only if there is no conversion is ongoing. */
  uint32_t ContinuousConvMode;           /*!< Specifies whether the conversion is performed in Continuous or Single mode.
                                              This parameter can be set to ENABLE or DISABLE.
                                              Note: This parameter can be modified only if there is no conversion is ongoing. */
  uint32_t DiscontinuousConvMode;        /*!< Specifies whether the conversion is performed
                                              in Complete-sequence/Discontinuous-sequence.
                                              Discontinuous mode can be enabled only if continuous mode is disabled.
                                              This parameter can be set to ENABLE or DISABLE.
                                              Note: This parameter can be modified only if there is no conversion is ongoing. */
  uint32_t ExternalTrigConv;             /*!< Select the external event used to trigger the start of conversion.
                                              If set to ADC_SOFTWARE_START, external triggers are disabled.
                                              This parameter can be a value of @ref ADC_External_trigger_Source
                                              Note: This parameter can be modified only if there is no conversion is ongoing. */
  uint32_t ExternalTrigConvEdge;         /*!< Select the external trigger edge and enable the trigger.
                                              If trigger is set to ADC_SOFTWARE_START, this parameter is discarded.
                                              This parameter can be a value of @ref ADC_Regular_External_Trigger_Source_Edge
                                              Note: This parameter can be modified only if there is no conversion is ongoing. */
  uint32_t DMAContinuousRequests;        /*!< Specifies whether the DMA requests are performed in one shot mode (DMA transfer stop when number of conversions is reached)
                                              or in Continuous mode (DMA transfer unlimited, whatever number of conversions).
                                              Note: In continuous mode, DMA must be configured in circular mode. Otherwise an overrun will be triggered when DMA buffer max pointer is reached.
                                              This parameter can be set to ENABLE or DISABLE.
                                              Note: This parameter can be modified only if there is no conversion is ongoing. */
  uint32_t EOCSelection;                 /*!< Specifies what EOC (End Of Conversion) flag is used for conversion polling and interruption:
                                              end of single channel conversion or end of channels conversions sequence.
                                              This parameter can be a value of @ref ADC_EOCSelection */
  uint32_t Overrun;                      /*!< Select the behaviour in case of overrun: data preserved or overwritten
                                              This parameter has an effect on regular channels only, including in DMA mode.
                                              This parameter can be a value of @ref ADC_Overrun
                                              Note: This parameter can be modified only if there is no conversion is ongoing. */
  uint32_t LowPowerAutoWait;             /*!< Specifies the usage of dynamic low power Auto Delay: new conversion start only
                                              when the previous conversion (for regular channel) is completed.
                                              This avoids risk of overrun for low frequency application.
                                              This parameter can be set to ENABLE or DISABLE.
                                              Note: This parameter can be modified only if there is no conversion is ongoing. */
  uint32_t LowPowerFrequencyMode;        /*!< When selecting an analog ADC clock frequency lower than 2.8MHz,
                                              it is mandatory to first enable the Low Frequency Mode.
                                              This parameter can be set to ENABLE or DISABLE.
                                              Note: This parameter can be modified only if there is no conversion is ongoing. */
  uint32_t LowPowerAutoPowerOff;         /*!< When setting the AutoOff feature, the ADC is always powered off when not converting and automatically
                                              wakes-up when a conversion is started (by software or hardware trigger).
                                              This parameter can be set to ENABLE or DISABLE.
                                              Note: This parameter can be modified only if there is no conversion is ongoing. */
}ADC_InitTypeDef;

/**
  * @brief  ADC handle Structure definition
  */
typedef struct
{
  ADC_TypeDef                   *Instance;              /*!< Register base address */

  ADC_InitTypeDef               Init;                   /*!< ADC required parameters */

  DMA_HandleTypeDef             *DMA_Handle;            /*!< Pointer DMA Handler */

  HAL_LockTypeDef               Lock;                   /*!< ADC locking object */

  __IO uint32_t                 State;                  /*!< ADC communication state (bitmap of ADC states) */

  __IO uint32_t                 ErrorCode;              /*!< ADC Error code */
}ADC_HandleTypeDef;

/**
  * @brief  ADC Configuration regular Channel structure definition
  */
typedef struct
{
  uint32_t Channel;                /*!< the ADC channel to configure
                                        This parameter can be a value of @ref ADC_channels */

  uint32_t Rank;                   /*!< Add or remove the channel from ADC regular group sequencer.
                                        On STM32L0 devices,  number of ranks in the sequence is defined by number of channels enabled, rank of each channel is defined by channel number
                                        (channel 0 fixed on rank 0, channel 1 fixed on rank1, ...).
                                        Despite the channel rank is fixed, this parameter allow an additional possibility: to remove the selected rank (selected channel) from sequencer.
                                        This parameter can be a value of @ref ADC_rank */
}ADC_ChannelConfTypeDef;

/**
  * @brief   ADC Configuration analog watchdog definition
  */
typedef struct
{
  uint32_t WatchdogMode;      /*!< Configures the ADC analog watchdog mode: single/all channels.
                                   This parameter can be a value of @ref ADC_analog_watchdog_mode */
  uint32_t Channel;           /*!< Selects which ADC channel to monitor by analog watchdog.
                                   This parameter has an effect only if watchdog mode is configured on single channel (parameter WatchdogMode)
                                   This parameter can be a value of @ref ADC_channels */
  uint32_t ITMode;            /*!< Specifies whether the analog watchdog is configured in interrupt or polling mode.
                                   This parameter can be set to ENABLE or DISABLE */
  uint32_t HighThreshold;     /*!< Configures the ADC analog watchdog High threshold value.
                                   Depending of ADC resolution selected (12, 10, 8 or 6 bits),
                                   this parameter must be a number between Min_Data = 0x000 and Max_Data = 0xFFF, 0x3FF, 0xFF or 0x3F respectively. */
  uint32_t LowThreshold;      /*!< Configures the ADC analog watchdog High threshold value.
                                   Depending of ADC resolution selected (12, 10, 8 or 6 bits),
                                   this parameter must be a number between Min_Data = 0x000 and Max_Data = 0xFFF, 0x3FF, 0xFF or 0x3F respectively. */
}ADC_AnalogWDGConfTypeDef;

/**
  * @}
  */

/* Exported constants --------------------------------------------------------*/

/** @defgroup ADC_Exported_Constants ADC Exported Constants
  * @{
  */

/** @defgroup ADC_Error_Code ADC Error Code
  * @{
  */
#define HAL_ADC_ERROR_NONE        ((uint32_t)0x00)   /*!< No error           */
#define HAL_ADC_ERROR_INTERNAL    ((uint32_t)0x01)   /*!< ADC IP internal error: if problem of clocking,
                                                          enable/disable, erroneous state */
#define HAL_ADC_ERROR_OVR         ((uint32_t)0x02)   /*!< OVR error          */
#define HAL_ADC_ERROR_DMA         ((uint32_t)0x04)   /*!< DMA transfer error */
/**
  * @}
  */

/** @defgroup ADC_TimeOut_Values ADC TimeOut Values
  * @{
  */

  /* Fixed timeout values for ADC calibration, enable settling time, disable  */
  /* settling time.                                                           */
  /* Values defined to be higher than worst cases: low clocks freq,           */
  /* maximum prescalers.                                                      */
  /* Unit: ms                                                                 */
#define ADC_ENABLE_TIMEOUT            10
#define ADC_DISABLE_TIMEOUT           10
#define ADC_STOP_CONVERSION_TIMEOUT   10

  /* Delay of 10us fixed to worst case: maximum CPU frequency 180MHz to have  */
  /* the minimum number of CPU cycles to fulfill this delay                   */
  #define ADC_DELAY_10US_MIN_CPU_CYCLES         1800
/**
  * @}
  */

/** @defgroup ADC_ClockPrescaler ADC Clock Prescaler
  * @{
  */
#define ADC_CLOCK_ASYNC_DIV1              ((uint32_t)0x00000000)                                /*!< ADC Asynchronous clock mode divided by 1 */
#define ADC_CLOCK_ASYNC_DIV2              (ADC_CCR_PRESC_0)                                     /*!< ADC Asynchronous clock mode divided by 2 */
#define ADC_CLOCK_ASYNC_DIV4              (ADC_CCR_PRESC_1)                                     /*!< ADC Asynchronous clock mode divided by 2 */
#define ADC_CLOCK_ASYNC_DIV6              (ADC_CCR_PRESC_1 | ADC_CCR_PRESC_0)                   /*!< ADC Asynchronous clock mode divided by 2 */
#define ADC_CLOCK_ASYNC_DIV8              (ADC_CCR_PRESC_2)                                     /*!< ADC Asynchronous clock mode divided by 2 */
#define ADC_CLOCK_ASYNC_DIV10             (ADC_CCR_PRESC_2 | ADC_CCR_PRESC_0)                   /*!< ADC Asynchronous clock mode divided by 2 */
#define ADC_CLOCK_ASYNC_DIV12             (ADC_CCR_PRESC_2 | ADC_CCR_PRESC_1)                   /*!< ADC Asynchronous clock mode divided by 2 */
#define ADC_CLOCK_ASYNC_DIV16             (ADC_CCR_PRESC_2 | ADC_CCR_PRESC_1 | ADC_CCR_PRESC_0) /*!< ADC Asynchronous clock mode divided by 2 */
#define ADC_CLOCK_ASYNC_DIV32             (ADC_CCR_PRESC_3)                                     /*!< ADC Asynchronous clock mode divided by 2 */
#define ADC_CLOCK_ASYNC_DIV64             (ADC_CCR_PRESC_3 | ADC_CCR_PRESC_0)                   /*!< ADC Asynchronous clock mode divided by 2 */
#define ADC_CLOCK_ASYNC_DIV128            (ADC_CCR_PRESC_3 | ADC_CCR_PRESC_1)                   /*!< ADC Asynchronous clock mode divided by 2 */
#define ADC_CLOCK_ASYNC_DIV256            (ADC_CCR_PRESC_3 | ADC_CCR_PRESC_1 | ADC_CCR_PRESC_0) /*!< ADC Asynchronous clock mode divided by 2 */

#define ADC_CLOCK_SYNC_PCLK_DIV1         ((uint32_t)ADC_CFGR2_CKMODE)    /*!< Synchronous clock mode divided by 1
                                                                               This configuration must be enabled only if PCLK has a 50%
                                                                               duty clock cycle (APB prescaler configured inside the RCC must be bypassed and the system clock
                                                                               must by 50% duty cycle)*/
#define ADC_CLOCK_SYNC_PCLK_DIV2         ((uint32_t)ADC_CFGR2_CKMODE_0)  /*!< Synchronous clock mode divided by 2 */
#define ADC_CLOCK_SYNC_PCLK_DIV4         ((uint32_t)ADC_CFGR2_CKMODE_1)  /*!< Synchronous clock mode divided by 4 */

/**
  * @}
  */

/** @defgroup ADC_Resolution ADC Resolution
  * @{
  */
#define ADC_RESOLUTION_12B      ((uint32_t)0x00000000)          /*!<  ADC 12-bit resolution */
#define ADC_RESOLUTION_10B      ((uint32_t)ADC_CFGR1_RES_0)      /*!<  ADC 10-bit resolution */
#define ADC_RESOLUTION_8B       ((uint32_t)ADC_CFGR1_RES_1)      /*!<  ADC 8-bit resolution */
#define ADC_RESOLUTION_6B       ((uint32_t)ADC_CFGR1_RES)        /*!<  ADC 6-bit resolution */
/**
  * @}
  */

/** @defgroup ADC_data_align ADC Data Align
  * @{
  */
#define ADC_DATAALIGN_RIGHT      ((uint32_t)0x00000000)
#define ADC_DATAALIGN_LEFT       ((uint32_t)ADC_CFGR1_ALIGN)

/**
  * @}
  */

/** @defgroup ADC_Regular_External_Trigger_Source_Edge ADC External Trigger Source Edge for Regular Group
  * @{
  */
#define ADC_EXTERNALTRIGCONVEDGE_NONE           ((uint32_t)0x00000000)
#define ADC_EXTERNALTRIGCONVEDGE_RISING         ((uint32_t)ADC_CFGR1_EXTEN_0)
#define ADC_EXTERNALTRIGCONVEDGE_FALLING        ((uint32_t)ADC_CFGR1_EXTEN_1)
#define ADC_EXTERNALTRIGCONVEDGE_RISINGFALLING  ((uint32_t)ADC_CFGR1_EXTEN)
/**
  * @}
  */

/** @defgroup ADC_EOCSelection ADC EOC Selection
  * @{
  */
#define ADC_EOC_SINGLE_CONV         ((uint32_t) ADC_ISR_EOC)
#define ADC_EOC_SEQ_CONV            ((uint32_t) ADC_ISR_EOS)
#define ADC_EOC_SINGLE_SEQ_CONV     ((uint32_t)(ADC_ISR_EOC | ADC_ISR_EOS))  /*!< reserved for future use */
/**
  * @}
  */

/** @defgroup ADC_Overrun ADC Overrun
  * @{
  */
#define ADC_OVR_DATA_PRESERVED              ((uint32_t)0x00000000)
#define ADC_OVR_DATA_OVERWRITTEN            ((uint32_t)ADC_CFGR1_OVRMOD)
/**
  * @}
  */

/** @defgroup ADC_rank ADC rank
  * @{
  */
#define ADC_RANK_CHANNEL_NUMBER                 ((uint32_t)0x00001000)  /*!< Enable the rank of the selected channels. Number of ranks in the sequence is defined by number of channels enabled, rank of each channel is defined by channel number (channel 0 fixed on rank 0, channel 1 fixed on rank1, ...) */
#define ADC_RANK_NONE                           ((uint32_t)0x00001001)  /*!< Disable the selected rank (selected channel) from sequencer */
/**
  * @}
  */

/** @defgroup ADC_channels ADC_Channels
  * @{
  */
#define ADC_CHANNEL_0           ((uint32_t)(ADC_CHSELR_CHSEL0))
#define ADC_CHANNEL_1           ((uint32_t)(ADC_CHSELR_CHSEL1) | ADC_CFGR1_AWDCH_0)
#define ADC_CHANNEL_2           ((uint32_t)(ADC_CHSELR_CHSEL2) | ADC_CFGR1_AWDCH_1)
#define ADC_CHANNEL_3           ((uint32_t)(ADC_CHSELR_CHSEL3)| ADC_CFGR1_AWDCH_1 | ADC_CFGR1_AWDCH_0)
#define ADC_CHANNEL_4           ((uint32_t)(ADC_CHSELR_CHSEL4)| ADC_CFGR1_AWDCH_2)
#define ADC_CHANNEL_5           ((uint32_t)(ADC_CHSELR_CHSEL5)| ADC_CFGR1_AWDCH_2| ADC_CFGR1_AWDCH_0)
#define ADC_CHANNEL_6           ((uint32_t)(ADC_CHSELR_CHSEL6)| ADC_CFGR1_AWDCH_2| ADC_CFGR1_AWDCH_1)
#define ADC_CHANNEL_7           ((uint32_t)(ADC_CHSELR_CHSEL7)| ADC_CFGR1_AWDCH_2| ADC_CFGR1_AWDCH_1 | ADC_CFGR1_AWDCH_0)
#define ADC_CHANNEL_8           ((uint32_t)(ADC_CHSELR_CHSEL8)| ADC_CFGR1_AWDCH_3)
#define ADC_CHANNEL_9           ((uint32_t)(ADC_CHSELR_CHSEL9)| ADC_CFGR1_AWDCH_3| ADC_CFGR1_AWDCH_0)
#define ADC_CHANNEL_10          ((uint32_t)(ADC_CHSELR_CHSEL10)| ADC_CFGR1_AWDCH_3| ADC_CFGR1_AWDCH_1)
#define ADC_CHANNEL_11          ((uint32_t)(ADC_CHSELR_CHSEL11)| ADC_CFGR1_AWDCH_3| ADC_CFGR1_AWDCH_1| ADC_CFGR1_AWDCH_0)
#define ADC_CHANNEL_12          ((uint32_t)(ADC_CHSELR_CHSEL12)| ADC_CFGR1_AWDCH_3| ADC_CFGR1_AWDCH_2)
#define ADC_CHANNEL_13          ((uint32_t)(ADC_CHSELR_CHSEL13)| ADC_CFGR1_AWDCH_3| ADC_CFGR1_AWDCH_2| ADC_CFGR1_AWDCH_0)
#define ADC_CHANNEL_14          ((uint32_t)(ADC_CHSELR_CHSEL14)| ADC_CFGR1_AWDCH_3| ADC_CFGR1_AWDCH_2| ADC_CFGR1_AWDCH_1)
#define ADC_CHANNEL_15          ((uint32_t)(ADC_CHSELR_CHSEL15)| ADC_CFGR1_AWDCH_3| ADC_CFGR1_AWDCH_2| ADC_CFGR1_AWDCH_1| ADC_CFGR1_AWDCH_0)
#define ADC_CHANNEL_16          ((uint32_t)(ADC_CHSELR_CHSEL16)| ADC_CFGR1_AWDCH_4)
#define ADC_CHANNEL_17          ((uint32_t)(ADC_CHSELR_CHSEL17)| ADC_CFGR1_AWDCH_4| ADC_CFGR1_AWDCH_0)
#define ADC_CHANNEL_18          ((uint32_t)(ADC_CHSELR_CHSEL18)| ADC_CFGR1_AWDCH_4| ADC_CFGR1_AWDCH_1)

/* Internal channels */
#if defined (STM32L053xx) || defined (STM32L063xx) || defined (STM32L073xx) || defined (STM32L083xx)
#define ADC_CHANNEL_VLCD         ADC_CHANNEL_16
#endif
#define ADC_CHANNEL_VREFINT      ADC_CHANNEL_17
#define ADC_CHANNEL_TEMPSENSOR   ADC_CHANNEL_18
/**
  * @}
  */

/** @defgroup ADC_Channel_AWD_Masks ADC Channel Masks
  * @{
  */
#define ADC_CHANNEL_MASK        ((uint32_t)0x0007FFFF)
#define ADC_CHANNEL_AWD_MASK    ((uint32_t)0x7C000000)
/**
  * @}
  */

/** @defgroup ADC_sampling_times ADC Sampling Cycles
  * @{
  */

#define ADC_SAMPLETIME_1CYCLE_5       ((uint32_t)0x00000000)                          /*!<  ADC sampling time 1.5 cycle */
#define ADC_SAMPLETIME_7CYCLES_5      ((uint32_t)ADC_SMPR_SMPR_0)                     /*!<  ADC sampling time 7.5 CYCLES */
#define ADC_SAMPLETIME_13CYCLES_5     ((uint32_t)ADC_SMPR_SMPR_1)                     /*!<  ADC sampling time 13.5 CYCLES */
#define ADC_SAMPLETIME_28CYCLES_5     ((uint32_t)(ADC_SMPR_SMPR_1 | ADC_SMPR_SMPR_0)) /*!<  ADC sampling time 28.5 CYCLES */
#define ADC_SAMPLETIME_41CYCLES_5     ((uint32_t)ADC_SMPR_SMPR_2)                     /*!<  ADC sampling time 41.5 CYCLES */
#define ADC_SAMPLETIME_55CYCLES_5     ((uint32_t)(ADC_SMPR_SMPR_2 | ADC_SMPR_SMPR_0)) /*!<  ADC sampling time 55.5 CYCLES */
#define ADC_SAMPLETIME_71CYCLES_5     ((uint32_t)(ADC_SMPR_SMPR_2 | ADC_SMPR_SMPR_1)) /*!<  ADC sampling time 71.5 CYCLES */
#define ADC_SAMPLETIME_239CYCLES_5    ((uint32_t)ADC_SMPR_SMPR)                       /*!<  ADC sampling time 239.5 CYCLES */
/**
  * @}
  */

/** @defgroup ADC_Scan_mode ADC Scan mode
  * @{
  */
/* Note: Scan mode values must be compatible with other STM32 devices having  */
/*       a configurable sequencer.                                            */
/*       Scan direction setting values are defined by taking in account       */
/*       already defined values for other STM32 devices:                      */
/*         ADC_SCAN_DISABLE         ((uint32_t)0x00000000)                    */
/*         ADC_SCAN_ENABLE          ((uint32_t)0x00000001)                    */
/*       Scan direction forward is considered as default setting equivalent   */
/*       to scan enable.                                                      */
/*       Scan direction backward is considered as additional setting.         */
/*       In case of migration from another STM32 device, the user will be     */
/*       warned of change of setting choices with assert check.               */
#define ADC_SCAN_DIRECTION_FORWARD        ((uint32_t)0x00000001)        /*!< Scan direction forward: from channel 0 to channel 18 */
#define ADC_SCAN_DIRECTION_BACKWARD       ((uint32_t)0x00000002)        /*!< Scan direction backward: from channel 18 to channel 0 */

#define ADC_SCAN_ENABLE         ADC_SCAN_DIRECTION_FORWARD             /* For compatibility with other STM32 devices */
/**
  * @}
  */

/** @defgroup ADC_Oversampling_Ratio ADC Oversampling Ratio
  * @{
  */

#define ADC_OVERSAMPLING_RATIO_2                    ((uint32_t)0x00000000)  /*!<  ADC Oversampling ratio 2x */
#define ADC_OVERSAMPLING_RATIO_4                    ((uint32_t)0x00000004)  /*!<  ADC Oversampling ratio 4x */
#define ADC_OVERSAMPLING_RATIO_8                    ((uint32_t)0x00000008)  /*!<  ADC Oversampling ratio 8x */
#define ADC_OVERSAMPLING_RATIO_16                   ((uint32_t)0x0000000C)  /*!<  ADC Oversampling ratio 16x */
#define ADC_OVERSAMPLING_RATIO_32                   ((uint32_t)0x00000010)  /*!<  ADC Oversampling ratio 32x */
#define ADC_OVERSAMPLING_RATIO_64                   ((uint32_t)0x00000014)  /*!<  ADC Oversampling ratio 64x */
#define ADC_OVERSAMPLING_RATIO_128                  ((uint32_t)0x00000018)  /*!<  ADC Oversampling ratio 128x */
#define ADC_OVERSAMPLING_RATIO_256                  ((uint32_t)0x0000001C)  /*!<  ADC Oversampling ratio 256x */
/**
  * @}
  */

/** @defgroup ADC_Right_Bit_Shift ADC Right Bit Shift
  * @{
  */
#define ADC_RIGHTBITSHIFT_NONE                       ((uint32_t)0x00000000)  /*!<  ADC No bit shift for oversampling */
#define ADC_RIGHTBITSHIFT_1                          ((uint32_t)0x00000020)  /*!<  ADC 1 bit shift for oversampling */
#define ADC_RIGHTBITSHIFT_2                          ((uint32_t)0x00000040)  /*!<  ADC 2 bits shift for oversampling */
#define ADC_RIGHTBITSHIFT_3                          ((uint32_t)0x00000060)  /*!<  ADC 3 bits shift for oversampling */
#define ADC_RIGHTBITSHIFT_4                          ((uint32_t)0x00000080)  /*!<  ADC 4 bits shift for oversampling */
#define ADC_RIGHTBITSHIFT_5                          ((uint32_t)0x000000A0)  /*!<  ADC 5 bits shift for oversampling */
#define ADC_RIGHTBITSHIFT_6                          ((uint32_t)0x000000C0)  /*!<  ADC 6 bits shift for oversampling */
#define ADC_RIGHTBITSHIFT_7                          ((uint32_t)0x000000E0)  /*!<  ADC 7 bits shift for oversampling */
#define ADC_RIGHTBITSHIFT_8                          ((uint32_t)0x00000100)  /*!<  ADC 8 bits shift for oversampling */
/**
  * @}
  */

/** @defgroup ADC_Triggered_Oversampling_Mode ADC Triggered Oversampling Mode
  * @{
  */
#define ADC_TRIGGEREDMODE_SINGLE_TRIGGER            ((uint32_t)0x00000000)  /*!<  ADC No bit shift for oversampling */
#define ADC_TRIGGEREDMODE_MULTI_TRIGGER             ((uint32_t)0x00000200)  /*!<  ADC No bit shift for oversampling */
/**
  * @}
  */

/** @defgroup ADC_analog_watchdog_mode ADC Analog Watchdog Mode
  * @{
  */
#define ADC_ANALOGWATCHDOG_NONE                     ((uint32_t) 0x00000000)
#define ADC_ANALOGWATCHDOG_SINGLE_REG               ((uint32_t)(ADC_CFGR1_AWDSGL | ADC_CFGR1_AWDEN))
#define ADC_ANALOGWATCHDOG_ALL_REG                  ((uint32_t) ADC_CFGR1_AWDEN)
/**
  * @}
  */

/** @defgroup ADC_conversion_type ADC Conversion Group
  * @{
  */
#define ADC_REGULAR_GROUP                         ((uint32_t)(ADC_FLAG_EOC | ADC_FLAG_EOS))
/**
  * @}
  */

/** @defgroup ADC_Event_type ADC Event
  * @{
  */
#define ADC_AWD_EVENT              ((uint32_t)ADC_FLAG_AWD)
#define ADC_OVR_EVENT              ((uint32_t)ADC_FLAG_OVR)
/**
  * @}
  */

/** @defgroup ADC_interrupts_definition ADC Interrupts Definition
  * @{
  */
#define ADC_IT_RDY           ADC_IER_ADRDYIE     /*!< ADC Ready (ADRDY) interrupt source */
#define ADC_IT_EOSMP         ADC_IER_EOSMPIE     /*!< ADC End of Sampling interrupt source */
#define ADC_IT_EOC           ADC_IER_EOCIE       /*!< ADC End of Regular Conversion interrupt source */
#define ADC_IT_EOS           ADC_IER_EOSEQIE     /*!< ADC End of Regular sequence of Conversions interrupt source */
#define ADC_IT_OVR           ADC_IER_OVRIE       /*!< ADC overrun interrupt source */
#define ADC_IT_AWD           ADC_IER_AWDIE       /*!< ADC Analog watchdog 1 interrupt source */
#define ADC_IT_EOCAL         ADC_IER_EOCALIE     /*!< ADC End of Calibration interrupt source */
/**
  * @}
  */

/** @defgroup ADC_flags_definition ADC Flags Definition
  * @{
  */
#define ADC_FLAG_RDY           ADC_ISR_ADRDY    /*!< ADC Ready (ADRDY) flag */
#define ADC_FLAG_EOSMP         ADC_ISR_EOSMP    /*!< ADC End of Sampling flag */
#define ADC_FLAG_EOC           ADC_ISR_EOC      /*!< ADC End of Regular Conversion flag */
#define ADC_FLAG_EOS           ADC_ISR_EOSEQ    /*!< ADC End of Regular sequence of Conversions flag */
#define ADC_FLAG_OVR           ADC_ISR_OVR      /*!< ADC overrun flag */
#define ADC_FLAG_AWD           ADC_ISR_AWD      /*!< ADC Analog watchdog flag */
#define ADC_FLAG_EOCAL         ADC_ISR_EOCAL    /*!< ADC Enf Of Calibration flag */

#define ADC_FLAG_ALL    (ADC_FLAG_RDY | ADC_FLAG_EOSMP | ADC_FLAG_EOC | ADC_FLAG_EOS |  \
                         ADC_FLAG_OVR | ADC_FLAG_AWD   | ADC_FLAG_EOCAL)
/**
  * @}
  */

/**
  * @}
  */
/* Exported macro ------------------------------------------------------------*/

/** @defgroup ADC_Exported_Macro ADC Exported Macro
  * @{
  */
/** @brief Reset ADC handle state
  * @param  __HANDLE__: ADC handle
  * @retval None
  */
#define __HAL_ADC_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_ADC_STATE_RESET)

/**
  * @brief Enable the ADC peripheral
  * @param __HANDLE__: ADC handle
  * @retval None
  */
#define __HAL_ADC_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= ADC_CR_ADEN)

/**
  * @brief Verification of hardware constraints before ADC can be enabled
  * @param __HANDLE__: ADC handle
  * @retval SET (ADC can be enabled) or RESET (ADC cannot be enabled)
  */
#define ADC_ENABLING_CONDITIONS(__HANDLE__)           \
       (( ( ((__HANDLE__)->Instance->CR) &                  \
            (ADC_CR_ADCAL | ADC_CR_ADSTP | ADC_CR_ADSTART | \
             ADC_CR_ADDIS | ADC_CR_ADEN )                   \
           ) == RESET                                       \
        ) ? SET : RESET)

/**
  * @brief Disable the ADC peripheral
  * @param __HANDLE__: ADC handle
  * @retval None
  */
#define __HAL_ADC_DISABLE(__HANDLE__)                                          \
  do{                                                                          \
         (__HANDLE__)->Instance->CR |= ADC_CR_ADDIS;                           \
          __HAL_ADC_CLEAR_FLAG((__HANDLE__), (ADC_FLAG_EOSMP | ADC_FLAG_RDY)); \
  } while(0)

/**
  * @brief Verification of hardware constraints before ADC can be disabled
  * @param __HANDLE__: ADC handle
  * @retval SET (ADC can be disabled) or RESET (ADC cannot be disabled)
  */
#define ADC_DISABLING_CONDITIONS(__HANDLE__)                             \
       (( ( ((__HANDLE__)->Instance->CR) &                                     \
            (ADC_CR_ADSTART | ADC_CR_ADEN)) == ADC_CR_ADEN   \
        ) ? SET : RESET)

/**
  * @brief Verification of ADC state: enabled or disabled
  * @param __HANDLE__: ADC handle
  * @retval SET (ADC enabled) or RESET (ADC disabled)
  */
#define ADC_IS_ENABLE(__HANDLE__)                                                    \
       (( ((((__HANDLE__)->Instance->CR) & (ADC_CR_ADEN | ADC_CR_ADDIS)) == ADC_CR_ADEN) && \
          ((((__HANDLE__)->Instance->ISR) & ADC_FLAG_RDY) == ADC_FLAG_RDY)                  \
        ) ? SET : RESET)

/**
  * @brief Returns resolution bits in CFGR register: RES[1:0]. Return value among parameter to @ref ADC_Resolution.
  * @param __HANDLE__: ADC handle
  * @retval None
  */
#define ADC_GET_RESOLUTION(__HANDLE__) (((__HANDLE__)->Instance->CFGR1) & ADC_CFGR1_RES)
/**
  * @brief Test if conversion trigger of regular group is software start
  *        or external trigger.
  * @param __HANDLE__: ADC handle
  * @retval SET (software start) or RESET (external trigger)
  */
#define ADC_IS_SOFTWARE_START_REGULAR(__HANDLE__)                              \
  (((__HANDLE__)->Instance->CFGR1 & ADC_CFGR1_EXTEN) == RESET)

/**
  * @brief Check if no conversion on going on regular group
  * @param __HANDLE__: ADC handle
  * @retval SET (conversion is on going) or RESET (no conversion is on going)
  */
#define ADC_IS_CONVERSION_ONGOING_REGULAR(__HANDLE__)                          \
  (( (((__HANDLE__)->Instance->CR) & ADC_CR_ADSTART) == RESET                  \
  ) ? RESET : SET)

/**
  * @brief Enable ADC continuous conversion mode.
  * @param _CONTINUOUS_MODE_: Continuous mode.
  * @retval None
  */
#define ADC_CONTINUOUS(_CONTINUOUS_MODE_) ((_CONTINUOUS_MODE_) << 13)

/**
  * @brief Enable ADC scan mode to convert multiple ranks with sequencer.
  * @param _SCAN_MODE_: Scan conversion mode.
  * @retval None
  */
#define ADC_SCANDIR(_SCAN_MODE_)                                   \
  ( ( (_SCAN_MODE_) == (ADC_SCAN_DIRECTION_BACKWARD)                           \
    )? (ADC_CFGR1_SCANDIR) : (0x00000000)                                      \
  )

/**
  * @brief Configures the number of discontinuous conversions for the regular group channels.
  * @param _NBR_DISCONTINUOUS_CONV_: Number of discontinuous conversions.
  * @retval None
  */
#define __HAL_ADC_CFGR1_DISCONTINUOUS_NUM(_NBR_DISCONTINUOUS_CONV_) (((_NBR_DISCONTINUOUS_CONV_) - 1) << 17)

/**
  * @brief Enable the ADC DMA continuous request.
  * @param _DMAContReq_MODE_: DMA continuous request mode.
  * @retval None
  */
#define ADC_DMACONTREQ(_DMAContReq_MODE_) ((_DMAContReq_MODE_) << 1)

/**
  * @brief Enable the ADC Auto Delay.
  * @param _AutoDelay_: Auto delay bit enable or disable.
  * @retval None
  */
#define __HAL_ADC_CFGR1_AutoDelay(_AutoDelay_) ((_AutoDelay_) << 14)

/**
  * @brief Enable the ADC LowPowerAutoPowerOff.
  * @param _AUTOFF_: AutoOff bit enable or disable.
  * @retval None
  */
#define __HAL_ADC_CFGR1_AUTOFF(_AUTOFF_) ((_AUTOFF_) << 15)

/**
  * @brief Configure the analog watchdog high threshold into registers TR1, TR2 or TR3.
  * @param _Threshold_: Threshold value
  * @retval None
  */
#define ADC_TRX_HIGHTHRESHOLD(_Threshold_) ((_Threshold_) << 16)

/**
  * @brief Enable the ADC Low Frequency mode.
  * @param _LOW_FREQUENCY_MODE_: Low Frequency mode.
  * @retval None
  */
#define __HAL_ADC_CCR_LOWFREQUENCY(_LOW_FREQUENCY_MODE_) ((_LOW_FREQUENCY_MODE_) << 25)

/**
  * @brief Shift the offset in function of the selected ADC resolution.
  *        Offset has to be left-aligned on bit 11, the LSB (right bits) are set to 0
  *        If resolution 12 bits, no shift.
  *        If resolution 10 bits, shift of 2 ranks on the right.
  *        If resolution 8 bits, shift of 4 ranks on the right.
  *        If resolution 6 bits, shift of 6 ranks on the right.
  *        therefore, shift = (12 - resolution) = 12 - (12- (((RES[1:0]) >> 3)*2))
  * @param __HANDLE__: ADC handle.
  * @param _Offset_: Value to be shifted
  * @retval None
  */
#define ADC_OFFSET_SHIFT_RESOLUTION(__HANDLE__, _Offset_) \
        ((_Offset_) << ((((__HANDLE__)->Instance->CFGR & ADC_CFGR1_RES) >> 3)*2))

/**
  * @brief Shift the AWD1 threshold in function of the selected ADC resolution.
  *        Thresholds have to be left-aligned on bit 11, the LSB (right bits) are set to 0
  *        If resolution 12 bits, no shift.
  *        If resolution 10 bits, shift of 2 ranks on the right.
  *        If resolution 8 bits, shift of 4 ranks on the right.
  *        If resolution 6 bits, shift of 6 ranks on the right.
  *        therefore, shift = (12 - resolution) = 12 - (12- (((RES[1:0]) >> 3)*2))
  * @param __HANDLE__: ADC handle.
  * @param _Threshold_: Value to be shifted
  * @retval None
  */
#define ADC_AWD1THRESHOLD_SHIFT_RESOLUTION(__HANDLE__, _Threshold_) \
        ((_Threshold_) << ((((__HANDLE__)->Instance->CFGR1 & ADC_CFGR1_RES) >> 3)*2))

/**
  * @brief Shift the value on the left, less significant are set to 0.
  * @param _Value_: Value to be shifted
  * @param _Shift_: Number of shift to be done
  * @retval None
  */
#define __HAL_ADC_Value_Shift_left(_Value_, _Shift_) ((_Value_) << (_Shift_))

/**
  * @brief Enable the ADC end of conversion interrupt.
  * @param __HANDLE__: ADC handle.
  * @param __INTERRUPT__: ADC Interrupt.
  * @retval None
  */
#define __HAL_ADC_ENABLE_IT(__HANDLE__, __INTERRUPT__)  \
  (((__HANDLE__)->Instance->IER) |= (__INTERRUPT__))

/**
  * @brief Disable the ADC end of conversion interrupt.
  * @param __HANDLE__: ADC handle.
  * @param __INTERRUPT__: ADC interrupt.
  * @retval None
  */
#define __HAL_ADC_DISABLE_IT(__HANDLE__, __INTERRUPT__) \
  (((__HANDLE__)->Instance->IER) &= ~(__INTERRUPT__))

/** @brief  Checks if the specified ADC interrupt source is enabled or disabled.
  * @param __HANDLE__: ADC handle
  * @param __INTERRUPT__: ADC interrupt source to check
  *            @arg ...
  *            @arg ...
  * @retval State of interruption (TRUE or FALSE)
  */
#define __HAL_ADC_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__)                     \
  (((__HANDLE__)->Instance->IER & (__INTERRUPT__)) == (__INTERRUPT__))

/**
  * @brief Clear the ADC's pending flags
  * @param __HANDLE__: ADC handle.
  * @param __FLAG__: ADC flag.
  * @retval None
  */
/* Note: bit cleared bit by writing 1 */
#define __HAL_ADC_CLEAR_FLAG(__HANDLE__, __FLAG__) \
  (((__HANDLE__)->Instance->ISR) = (__FLAG__))

/**
  * @brief Get the selected ADC's flag status.
  * @param __HANDLE__: ADC handle.
  * @param __FLAG__: ADC flag.
  * @retval None
  */
#define __HAL_ADC_GET_FLAG(__HANDLE__, __FLAG__) \
  ((((__HANDLE__)->Instance->ISR) & (__FLAG__)) == (__FLAG__))

/**
  * @brief Simultaneously clears and sets specific bits of the handle State
  * @note: ADC_STATE_CLR_SET() macro is merely aliased to generic macro MODIFY_REG(),
  *        the first parameter is the ADC handle State, the second parameter is the
  *        bit field to clear, the third and last parameter is the bit field to set.
  * @retval None
  */
#define ADC_STATE_CLR_SET MODIFY_REG

/**
  * @brief Clear ADC error code (set it to error code: "no error")
  * @param __HANDLE__: ADC handle
  * @retval None
  */
#define ADC_CLEAR_ERRORCODE(__HANDLE__)                                        \
  ((__HANDLE__)->ErrorCode = HAL_ADC_ERROR_NONE)

/**
  * @brief Configuration of ADC clock & prescaler: clock source PCLK or Asynchronous with selectable prescaler
  * @param __HANDLE__: ADC handle
  * @retval None
  */

#define __HAL_ADC_CLOCK_PRESCALER(__HANDLE__)                                       \
  do{                                                                               \
      if ((((__HANDLE__)->Init.ClockPrescaler) == ADC_CLOCK_SYNC_PCLK_DIV1) ||  \
          (((__HANDLE__)->Init.ClockPrescaler) == ADC_CLOCK_SYNC_PCLK_DIV2) ||  \
          (((__HANDLE__)->Init.ClockPrescaler) == ADC_CLOCK_SYNC_PCLK_DIV4))    \
      {                                                                             \
        (__HANDLE__)->Instance->CFGR2 &= ~(ADC_CFGR2_CKMODE);                       \
        (__HANDLE__)->Instance->CFGR2 |=  (__HANDLE__)->Init.ClockPrescaler;        \
      }                                                                             \
      else                                                                          \
      {                                                                             \
        /* CKMOD bits must be reset */                                              \
        (__HANDLE__)->Instance->CFGR2 &= ~(ADC_CFGR2_CKMODE);                       \
        ADC->CCR &= ~(ADC_CCR_PRESC);                                               \
        ADC->CCR |=  (__HANDLE__)->Init.ClockPrescaler;                             \
      }                                                                             \
  } while(0)

#define IS_ADC_CLOCKPRESCALER(ADC_CLOCK) (((ADC_CLOCK) == ADC_CLOCK_ASYNC_DIV1) ||\
                                          ((ADC_CLOCK) == ADC_CLOCK_SYNC_PCLK_DIV1) ||\
                                          ((ADC_CLOCK) == ADC_CLOCK_SYNC_PCLK_DIV2) ||\
                                          ((ADC_CLOCK) == ADC_CLOCK_SYNC_PCLK_DIV4) ||\
                                          ((ADC_CLOCK) == ADC_CLOCK_ASYNC_DIV1  ) ||\
                                          ((ADC_CLOCK) == ADC_CLOCK_ASYNC_DIV2  ) ||\
                                          ((ADC_CLOCK) == ADC_CLOCK_ASYNC_DIV4  ) ||\
                                          ((ADC_CLOCK) == ADC_CLOCK_ASYNC_DIV6  ) ||\
                                          ((ADC_CLOCK) == ADC_CLOCK_ASYNC_DIV8  ) ||\
                                          ((ADC_CLOCK) == ADC_CLOCK_ASYNC_DIV10 ) ||\
                                          ((ADC_CLOCK) == ADC_CLOCK_ASYNC_DIV12 ) ||\
                                          ((ADC_CLOCK) == ADC_CLOCK_ASYNC_DIV16 ) ||\
                                          ((ADC_CLOCK) == ADC_CLOCK_ASYNC_DIV32 ) ||\
                                          ((ADC_CLOCK) == ADC_CLOCK_ASYNC_DIV64 ) ||\
                                          ((ADC_CLOCK) == ADC_CLOCK_ASYNC_DIV128 ) ||\
                                          ((ADC_CLOCK) == ADC_CLOCK_ASYNC_DIV256))

#define IS_ADC_RESOLUTION(RESOLUTION) (((RESOLUTION) == ADC_RESOLUTION_12B) || \
                                       ((RESOLUTION) == ADC_RESOLUTION_10B) || \
                                       ((RESOLUTION) == ADC_RESOLUTION_8B) || \
                                       ((RESOLUTION) == ADC_RESOLUTION_6B))

#define IS_ADC_RESOLUTION_8_6_BITS(RESOLUTION) (((RESOLUTION) == ADC_RESOLUTION_8B) || \
                                                ((RESOLUTION) == ADC_RESOLUTION_6B))

#define IS_ADC_DATA_ALIGN(ALIGN) (((ALIGN) == ADC_DATAALIGN_RIGHT) || \
                                  ((ALIGN) == ADC_DATAALIGN_LEFT))

#define IS_ADC_EXTTRIG_EDGE(EDGE) (((EDGE) == ADC_EXTERNALTRIGCONVEDGE_NONE) || \
                                   ((EDGE) == ADC_EXTERNALTRIGCONVEDGE_RISING) || \
                                   ((EDGE) == ADC_EXTERNALTRIGCONVEDGE_FALLING) || \
                                   ((EDGE) == ADC_EXTERNALTRIGCONVEDGE_RISINGFALLING))

#define IS_ADC_EOC_SELECTION(EOC_SELECTION) (((EOC_SELECTION) == ADC_EOC_SINGLE_CONV)   || \
                                             ((EOC_SELECTION) == ADC_EOC_SEQ_CONV)      || \
                                             ((EOC_SELECTION) == ADC_EOC_SINGLE_SEQ_CONV))

#define IS_ADC_OVERRUN(OVR) (((OVR) == ADC_OVR_DATA_PRESERVED) || \
                             ((OVR) == ADC_OVR_DATA_OVERWRITTEN))

#define IS_ADC_RANK(WATCHDOG) (((WATCHDOG) == ADC_RANK_CHANNEL_NUMBER) || \
                               ((WATCHDOG) == ADC_RANK_NONE))

#if defined (STM32L053xx) || defined (STM32L063xx) || defined (STM32L073xx) || defined (STM32L083xx)
#define IS_ADC_CHANNEL(CHANNEL) (((CHANNEL) == ADC_CHANNEL_0)           || \
                                 ((CHANNEL) == ADC_CHANNEL_1)           || \
                                 ((CHANNEL) == ADC_CHANNEL_2)           || \
                                 ((CHANNEL) == ADC_CHANNEL_3)           || \
                                 ((CHANNEL) == ADC_CHANNEL_4)           || \
                                 ((CHANNEL) == ADC_CHANNEL_5)           || \
                                 ((CHANNEL) == ADC_CHANNEL_6)           || \
                                 ((CHANNEL) == ADC_CHANNEL_7)           || \
                                 ((CHANNEL) == ADC_CHANNEL_8)           || \
                                 ((CHANNEL) == ADC_CHANNEL_9)           || \
                                 ((CHANNEL) == ADC_CHANNEL_10)          || \
                                 ((CHANNEL) == ADC_CHANNEL_11)          || \
                                 ((CHANNEL) == ADC_CHANNEL_12)          || \
                                 ((CHANNEL) == ADC_CHANNEL_13)          || \
                                 ((CHANNEL) == ADC_CHANNEL_14)          || \
                                 ((CHANNEL) == ADC_CHANNEL_15)          || \
                                 ((CHANNEL) == ADC_CHANNEL_TEMPSENSOR)  || \
                                 ((CHANNEL) == ADC_CHANNEL_VREFINT)     || \
                                 ((CHANNEL) == ADC_CHANNEL_VLCD))
#else
#define IS_ADC_CHANNEL(CHANNEL) (((CHANNEL) == ADC_CHANNEL_0)           || \
                                 ((CHANNEL) == ADC_CHANNEL_1)           || \
                                 ((CHANNEL) == ADC_CHANNEL_2)           || \
                                 ((CHANNEL) == ADC_CHANNEL_3)           || \
                                 ((CHANNEL) == ADC_CHANNEL_4)           || \
                                 ((CHANNEL) == ADC_CHANNEL_5)           || \
                                 ((CHANNEL) == ADC_CHANNEL_6)           || \
                                 ((CHANNEL) == ADC_CHANNEL_7)           || \
                                 ((CHANNEL) == ADC_CHANNEL_8)           || \
                                 ((CHANNEL) == ADC_CHANNEL_9)           || \
                                 ((CHANNEL) == ADC_CHANNEL_10)          || \
                                 ((CHANNEL) == ADC_CHANNEL_11)          || \
                                 ((CHANNEL) == ADC_CHANNEL_12)          || \
                                 ((CHANNEL) == ADC_CHANNEL_13)          || \
                                 ((CHANNEL) == ADC_CHANNEL_14)          || \
                                 ((CHANNEL) == ADC_CHANNEL_15)          || \
                                 ((CHANNEL) == ADC_CHANNEL_TEMPSENSOR)  || \
                                 ((CHANNEL) == ADC_CHANNEL_VREFINT))
#endif

#define IS_ADC_SAMPLE_TIME(TIME) (((TIME) == ADC_SAMPLETIME_1CYCLE_5   ) || \
                                  ((TIME) == ADC_SAMPLETIME_7CYCLES_5  ) || \
                                  ((TIME) == ADC_SAMPLETIME_13CYCLES_5 ) || \
                                  ((TIME) == ADC_SAMPLETIME_28CYCLES_5 ) || \
                                  ((TIME) == ADC_SAMPLETIME_41CYCLES_5 ) || \
                                  ((TIME) == ADC_SAMPLETIME_55CYCLES_5 ) || \
                                  ((TIME) == ADC_SAMPLETIME_71CYCLES_5 ) || \
                                  ((TIME) == ADC_SAMPLETIME_239CYCLES_5))

#define IS_ADC_SCAN_MODE(SCAN_MODE) (((SCAN_MODE) == ADC_SCAN_DIRECTION_FORWARD) || \
                                     ((SCAN_MODE) == ADC_SCAN_DIRECTION_BACKWARD))

#define IS_ADC_OVERSAMPLING_RATIO(RATIO)          (((RATIO) == ADC_OVERSAMPLING_RATIO_2   ) || \
                                                   ((RATIO) == ADC_OVERSAMPLING_RATIO_4   ) || \
                                                   ((RATIO) == ADC_OVERSAMPLING_RATIO_8   ) || \
                                                   ((RATIO) == ADC_OVERSAMPLING_RATIO_16  ) || \
                                                   ((RATIO) == ADC_OVERSAMPLING_RATIO_32  ) || \
                                                   ((RATIO) == ADC_OVERSAMPLING_RATIO_64  ) || \
                                                   ((RATIO) == ADC_OVERSAMPLING_RATIO_128 ) || \
                                                   ((RATIO) == ADC_OVERSAMPLING_RATIO_256 ))

#define IS_ADC_RIGHT_BIT_SHIFT(SHIFT)               (((SHIFT) == ADC_RIGHTBITSHIFT_NONE) || \
                                                     ((SHIFT) == ADC_RIGHTBITSHIFT_1   ) || \
                                                     ((SHIFT) == ADC_RIGHTBITSHIFT_2   ) || \
                                                     ((SHIFT) == ADC_RIGHTBITSHIFT_3   ) || \
                                                     ((SHIFT) == ADC_RIGHTBITSHIFT_4   ) || \
                                                     ((SHIFT) == ADC_RIGHTBITSHIFT_5   ) || \
                                                     ((SHIFT) == ADC_RIGHTBITSHIFT_6   ) || \
                                                     ((SHIFT) == ADC_RIGHTBITSHIFT_7   ) || \
                                                     ((SHIFT) == ADC_RIGHTBITSHIFT_8   ))

#define IS_ADC_TRIGGERED_OVERSAMPLING_MODE(MODE)     (((MODE) == ADC_TRIGGEREDMODE_SINGLE_TRIGGER) || \
                                                      ((MODE) == ADC_TRIGGEREDMODE_MULTI_TRIGGER) )

#define IS_ADC_ANALOG_WATCHDOG_MODE(WATCHDOG)     (((WATCHDOG) == ADC_ANALOGWATCHDOG_NONE      )   || \
                                                   ((WATCHDOG) == ADC_ANALOGWATCHDOG_SINGLE_REG)   || \
                                                   ((WATCHDOG) == ADC_ANALOGWATCHDOG_ALL_REG   ))

#define IS_ADC_CONVERSION_GROUP(CONVERSION)   ((CONVERSION) == ADC_REGULAR_GROUP)

#define IS_ADC_EVENT_TYPE(EVENT) (((EVENT) == ADC_AWD_EVENT) || \
                                  ((EVENT) == ADC_OVR_EVENT))

/** @defgroup ADC_range_verification ADC Range Verification
  * in function of ADC resolution selected (12, 10, 8 or 6 bits)
  * @{
  */
#define IS_ADC_RANGE(RESOLUTION, ADC_VALUE)                                     \
   ((((RESOLUTION) == ADC_RESOLUTION_12B) && ((ADC_VALUE) <= ((uint32_t)0x0FFF))) || \
    (((RESOLUTION) == ADC_RESOLUTION_10B) && ((ADC_VALUE) <= ((uint32_t)0x03FF))) || \
    (((RESOLUTION) == ADC_RESOLUTION_8B)  && ((ADC_VALUE) <= ((uint32_t)0x00FF))) || \
    (((RESOLUTION) == ADC_RESOLUTION_6B)  && ((ADC_VALUE) <= ((uint32_t)0x003F))))
/**
  * @}
  */

/** @defgroup ADC_regular_nb_conv_verification ADC Regular Nb Conversion Verification
  * @{
  */
#define IS_ADC_REGULAR_NB_CONV(LENGTH) (((LENGTH) >= ((uint32_t)1)) && ((LENGTH) <= ((uint32_t)16)))
/**
  * @}
  */

 /**
  * @}
  */

/* Include ADC HAL Extension module */
#include "stm32l0xx_hal_adc_ex.h"

/* Exported functions --------------------------------------------------------*/
/** @defgroup ADC_Exported_Functions ADC Exported Functions
  * @{
  */
/* Initialization and de-initialization functions  **********************************/
/** @defgroup ADC_Exported_Functions_Group1 Initialization and de-initialization functions
 *  @brief    Initialization and de-initialization functions
 * @{
  */
HAL_StatusTypeDef    HAL_ADC_Init(ADC_HandleTypeDef* hadc);
HAL_StatusTypeDef    HAL_ADC_DeInit(ADC_HandleTypeDef *hadc);
void                 HAL_ADC_MspInit(ADC_HandleTypeDef* hadc);
void                 HAL_ADC_MspDeInit(ADC_HandleTypeDef* hadc);
/**
  * @}
  */

/* IO operation functions  *****************************************************/
/** @defgroup ADC_Exported_Functions_Group2 I/O operation functions
  * @{
  */
/* Blocking mode: Polling */
HAL_StatusTypeDef    HAL_ADC_Start(ADC_HandleTypeDef* hadc);
HAL_StatusTypeDef    HAL_ADC_Stop(ADC_HandleTypeDef* hadc);
HAL_StatusTypeDef    HAL_ADC_PollForConversion(ADC_HandleTypeDef* hadc, uint32_t Timeout);
HAL_StatusTypeDef    HAL_ADC_PollForEvent(ADC_HandleTypeDef* hadc, uint32_t EventType, uint32_t Timeout);

/* Non-blocking mode: Interruption */
HAL_StatusTypeDef    HAL_ADC_Start_IT(ADC_HandleTypeDef* hadc);
HAL_StatusTypeDef    HAL_ADC_Stop_IT(ADC_HandleTypeDef* hadc);

/* Non-blocking mode: DMA */
HAL_StatusTypeDef    HAL_ADC_Start_DMA(ADC_HandleTypeDef* hadc, uint32_t* pData, uint32_t Length);
HAL_StatusTypeDef    HAL_ADC_Stop_DMA(ADC_HandleTypeDef* hadc);

/* ADC retrieve conversion value intended to be used with polling or interruption */
uint32_t             HAL_ADC_GetValue(ADC_HandleTypeDef* hadc);

/* ADC IRQHandler and Callbacks used in non-blocking modes (Interruption and DMA) */
void                 HAL_ADC_IRQHandler(ADC_HandleTypeDef* hadc);
void                 HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc);
void                 HAL_ADC_ConvHalfCpltCallback(ADC_HandleTypeDef* hadc);
void                 HAL_ADC_LevelOutOfWindowCallback(ADC_HandleTypeDef* hadc);
void                 HAL_ADC_ErrorCallback(ADC_HandleTypeDef *hadc);
/**
  * @}
  */

/* Peripheral Control functions ***********************************************/
/** @defgroup ADC_Exported_Functions_Group3 Peripheral Control functions
  * @{
  */
HAL_StatusTypeDef    HAL_ADC_ConfigChannel(ADC_HandleTypeDef* hadc, ADC_ChannelConfTypeDef* sConfig);
HAL_StatusTypeDef    HAL_ADC_AnalogWDGConfig(ADC_HandleTypeDef* hadc, ADC_AnalogWDGConfTypeDef* AnalogWDGConfig);
/**
  * @}
  */

/* Peripheral State functions *************************************************/
/** @defgroup ADC_Exported_Functions_Group4 Peripheral State functions
  * @{
  */
uint32_t             HAL_ADC_GetState(ADC_HandleTypeDef* hadc);
uint32_t             HAL_ADC_GetError(ADC_HandleTypeDef *hadc);
/**
  * @}
  */

/**
  * @}
  */

/* Define the private group ***********************************/
/**************************************************************/
/** @defgroup ADC_Private ADC Private
  * @{
  */
/**
  * @}
  */
/**************************************************************/

/**
  * @}
  */

/**
  * @}
  */

#ifdef __cplusplus
}
#endif

#endif /*__STM32L0xx_ADC_H */

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


text:
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE chapter SYSTEM "chapter.dtd">

<chapter>

    <copyright>
      <year>2004</year><year>2013</year>
      <holder>Ericsson AB. All Rights Reserved.</holder>
    </copyright>
    <legalnotice>
      Licensed under the Apache License, Version 2.0 (the "License");
      you may not use this file except in compliance with the License.
      You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

      Unless required by applicable law or agreed to in writing, software
      distributed under the License is distributed on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      See the License for the specific language governing permissions and
      limitations under the License.

    </legalnotice>

    <title>OTP_Mibs Release Notes</title>
    <prepared>otp_appnotes</prepared>
    <docno>nil</docno>
    <date>nil</date>
    <rev>nil</rev>
    <file>notes.xml</file>

This document describes the changes made to the OTP_Mibs
    application.

<title>Otp_Mibs 1.1</title>

<title>Improvements and New Features</title>
      <list>
        <item>

	    Change license text from Erlang Public License to Apache
	    Public License v2

	    Own Id: OTP-12845

        </item>
      </list>

<title>Otp_Mibs 1.0.10</title>

<title>Fixed Bugs and Malfunctions</title>
      <list>
        <item>

	    Make sure the clean rule for ssh, ssl, eunit and otp_mibs
	    actually removes generated files.

	    Own Id: OTP-12200

        </item>
      </list>

<title>Otp_Mibs 1.0.9</title>

<title>Fixed Bugs and Malfunctions</title>
      <list>
        <item>

	    Add type based integer value truncation/reset.

	    This fixes errors when querying e.g. the
	    erlNodeReductions, erlNodeInBytes and erlNodeOutBytes
	    objects in long-running Erlang/OTP systems.

	    Update types of applicable MIB objects to 64bit based
	    types.

	    Potential incompatibility: Type change of Counter32 to
	    Counter64 in OTP-MIB.mib

	    (Thanks to Tobias Schlager)

	    *** POTENTIAL INCOMPATIBILITY ***

	    Own Id: OTP-11203

        </item>
        <item>

	    Application upgrade (appup) files are corrected for the
	    following applications:

	    <c>asn1, common_test, compiler, crypto, debugger,
	    dialyzer, edoc, eldap, erl_docgen, et, eunit, gs, hipe,
	    inets, observer, odbc, os_mon, otp_mibs, parsetools,
	    percept, public_key, reltool, runtime_tools, ssh,
	    syntax_tools, test_server, tools, typer, webtool, wx,
	    xmerl</c>

	    A new test utility for testing appup files is added to
	    test_server. This is now used by most applications in
	    OTP.

	    (Thanks to Tobias Schlager)

	    Own Id: OTP-11744

        </item>
      </list>

<title>Otp_Mibs 1.0.8</title>

<title>Improvements and New Features</title>
      <list>
        <item>

	    Misc build updates

	    Own Id: OTP-10784

        </item>
      </list>

<title>Otp_Mibs 1.0.7</title>

<title>Improvements and New Features</title>
      <list>
        <item>

	    Tuple funs (a two-element tuple with a module name and a
	    function) are now officially deprecated and will be
	    removed in R16. Use '<c>fun M:F/A</c>' instead. To make
	    you aware that your system uses tuple funs, the very
	    first time a tuple fun is applied, a warning will be sent
	    to the error logger.

	    Own Id: OTP-9649

        </item>
      </list>

<title>Otp_Mibs 1.0.6</title>

<title>Improvements and New Features</title>
      <list>
        <item>

	    The documentation is now built with open source tools
	    (xsltproc and fop) that exists on most platforms. One
	    visible change is that the frames are removed.

	    Own Id: OTP-8201

        </item>
      </list>

<title>Otp_Mibs 1.0.5</title>

<title>Improvements and New Features</title>
      <list>
        <item>

The copyright notices have been updated.

	    Own Id: OTP-7851

        </item>
      </list>

    <title>Otp_Mibs 1.0.4.1</title>

      <title>Improvements and New Features</title>
      <list type="bulleted">
        <item>

Minor Makefile changes.

Own Id: OTP-6689

        </item>
      </list>

    <title>OTP_Mibs 1.0.4</title>

      <title>Improvements and New Features</title>
      <list type="bulleted">
        <item>

Replaced calls to deprecated functions in <c>snmp</c>
            with calls to the equivalent functions in <c>snmpa</c>.

Own Id: OTP-6112

        </item>
      </list>

    <title>OTP_Mibs 1.0.3</title>

      <title>Improvements and New Features</title>
      <list type="bulleted">
        <item>

The <c>otp_mib</c> module has been cleaned up to improve the
            maintainability. It should have no effect on the
            functionality of the OTP_Mibs application.

Own Id: OTP-4982

        </item>
      </list>

    <title>OTP_Mibs 1.0.2</title>

      <title>Fixed Bugs and Malfunctions</title>
      <list type="bulleted">
        <item>

Incorrect <c>.app</c> file (missing mandatory
            <c>registered</c>).

Own Id: OTP-4823 Aux Id: Seq8145, OTP-4801

        </item>
      </list>

    <title>OTP_Mibs 1.0.1</title>

      <title>Fixed Bugs and Malfunctions</title>
      <list type="bulleted">
        <item>

Missing <c>.app</c> and <c>appup</c> files in <c>ebin</c>.

Own Id: OTP-4801 Aux Id: Seq8145

        </item>
      </list>

    <title>OTP_Mibs 1.0</title>

The OTP mibs that where included in the SASL application
      have been moved to this new application OTP_Mibs. The OTP
      mibs had no real connection to SASL and it is desirable that
      the core of Erlang/OTP is not dependent on SNMP.

Own Id: OTP-4686

</chapter>

redpajama_set_name: RedPajamaGithub


text:
package org.terasology.engine.input.events;

import org.terasology.input.ButtonState;
import org.terasology.input.Input;
import org.terasology.input.Keyboard;

public final class KeyDownEvent extends KeyEvent {

    private static KeyDownEvent event = new KeyDownEvent(Keyboard.Key.NONE, 0);

    private KeyDownEvent(Input key, float delta) {
        super(key, ButtonState.DOWN, delta);
    }

    public static KeyDownEvent create(Input key, float delta) {
        event.reset(delta);
        event.setKey(key);
        return event;
    }

    public static KeyDownEvent createCopy(KeyDownEvent toBeCopied) {
        return new KeyDownEvent(toBeCopied.getKey(), toBeCopied.getDelta());
    }
}


text:
package org.apache.geode.internal.process;

/**
 * A PidUnavailableException is thrown when the pid cannot be parsed from the RuntimeMXBean name or
 * otherwise determined.
 *
 * @since GemFire 7.0
 */
public class PidUnavailableException extends Exception {
  private static final long serialVersionUID = -1660269538268828059L;

  /**
   * Creates a new {@code PidUnavailableException}.
   */
  public PidUnavailableException(final String message) {
    super(message);
  }

  /**
   * Creates a new {@code PidUnavailableException} that was caused by a given exception
   */
  public PidUnavailableException(final String message, final Throwable cause) {
    super(message, cause);
  }

  /**
   * Creates a new {@code PidUnavailableException} that was caused by a given exception
   */
  public PidUnavailableException(final Throwable cause) {
    super(cause.getMessage(), cause);
  }
}


text:
function zoomDirective($document, $timeout) {
	'ngInject';

	return {
		restrict: 'C',
		scope: {},
		link: linkFn,
		template: `

		`
	};

	function linkFn(scope, element, attrs, fn) {
		var body = $document.find('body')[0],
		overlay = angular.element('

'),
		clone = element.clone(true).attr('src', attrs.large);

		scope.match = function(el, target) {
			var rect = target[0].getBoundingClientRect();
			el.css('height', rect.height + 'px');
			el.css('left', rect.left + 'px');
			el.css('top', rect.top + 'px');
			el.css('width', rect.width + 'px');
		};

		scope.scaleDown = function(el) {
			el.css('transform', 'scale(1) translateX(0px) translateY(0px)');
		};

		scope.scaleUp = function(el) {
			var rect = el[0].getBoundingClientRect(),
			scaleW = (window.innerWidth / rect.width),
			scaleH = (window.innerHeight / rect.height),
			scale = scaleW < scaleH ? scaleW : scaleH,
			x = (((window.innerWidth / 2) - rect.left) / scale) - ((rect.width / 2)),
			y = (((window.innerHeight / 2) - rect.top) / scale) - ((rect.height / 2));
			el.css('transform', 'scale(' + scale + ') translateX(' + x + 'px) translateY(' + y + 'px)');
		};

		overlay.append(clone);
		overlay.bind('click', function() {
			scope.match(clone, element);
			overlay.removeClass('show');
			scope.scaleDown(clone);
			$timeout(function() {
				body.removeChild(overlay[0]);
			}, 500);
		});

		element.bind('click', function() {
			scope.match(clone, element);
			body.appendChild(overlay[0]);
			$timeout(function() {
				overlay.addClass('show');
				scope.scaleUp(clone);
			}, 10);
		});
	}
}

export default zoomDirective;


text:
package greycat.internal.heap;

import greycat.Constants;
import greycat.internal.CoreConstants;
import greycat.struct.Buffer;
import greycat.struct.IntIntMap;
import greycat.struct.IntIntMapCallBack;
import greycat.utility.Base64;
import greycat.utility.HashHelper;

import java.util.Arrays;

@SuppressWarnings("Duplicates")
public class HeapIntIntMap implements IntIntMap {
    private final HeapContainer parent;

    private int mapSize = 0;
    private int capacity = 0;

    private int[] keys = null;
    private int[] values = null;

    private int[] nexts = null;
    private int[] hashs = null;

    HeapIntIntMap(final HeapContainer p_listener) {
        this.parent = p_listener;
    }

    private int key(int i) {
        return keys[i];
    }

    private void setKey(int i, int newValue) {
        keys[i] = newValue;
    }

    private int value(int i) {
        return values[i];
    }

    private void setValue(int i, int newValue) {
        values[i] = newValue;
    }

    private int next(int i) {
        return nexts[i];
    }

    private void setNext(int i, int newValue) {
        nexts[i] = newValue;
    }

    private int hash(int i) {
        return hashs[i];
    }

    private void setHash(int i, int newValue) {
        hashs[i] = newValue;
    }

    void reallocate(int newCapacity) {
        if (newCapacity > capacity) {
            //extend keys
            int[] new_keys = new int[newCapacity];
            if (keys != null) {
                System.arraycopy(keys, 0, new_keys, 0, capacity);
            }
            keys = new_keys;
            //extend values
            int[] new_values = new int[newCapacity];
            if (values != null) {
                System.arraycopy(values, 0, new_values, 0, capacity);
            }
            values = new_values;

            int[] new_nexts = new int[newCapacity];
            int[] new_hashes = new int[newCapacity * 2];
            Arrays.fill(new_nexts, 0, newCapacity, -1);
            Arrays.fill(new_hashes, 0, (newCapacity * 2), -1);
            hashs = new_hashes;
            nexts = new_nexts;
            for (int i = 0; i < mapSize; i++) {
                int new_key_hash = (int) HashHelper.longHash(key(i), newCapacity * 2);
                setNext(i, hash(new_key_hash));
                setHash(new_key_hash, i);
            }
            capacity = newCapacity;
        }
    }

    HeapIntIntMap cloneFor(HeapContainer newParent) {
        HeapIntIntMap cloned = new HeapIntIntMap(newParent);
        cloned.mapSize = mapSize;
        cloned.capacity = capacity;
        if (keys != null) {
            int[] cloned_keys = new int[capacity];
            System.arraycopy(keys, 0, cloned_keys, 0, capacity);
            cloned.keys = cloned_keys;
        }
        if (values != null) {
            int[] cloned_values = new int[capacity];
            System.arraycopy(values, 0, cloned_values, 0, capacity);
            cloned.values = cloned_values;
        }
        if (nexts != null) {
            int[] cloned_nexts = new int[capacity];
            System.arraycopy(nexts, 0, cloned_nexts, 0, capacity);
            cloned.nexts = cloned_nexts;
        }
        if (hashs != null) {
            int[] cloned_hashs = new int[capacity * 2];
            System.arraycopy(hashs, 0, cloned_hashs, 0, capacity * 2);
            cloned.hashs = cloned_hashs;
        }
        return cloned;
    }

    public final int get(final int requestKey) {
        int result = Constants.NULL_INT;
        synchronized (parent) {
            if (keys != null) {
                final int hashIndex = HashHelper.intHash(requestKey, capacity * 2);
                int m = hash(hashIndex);
                while (m >= 0) {
                    if (requestKey == key(m)) {
                        result = value(m);
                        break;
                    }
                    m = next(m);
                }
            }
        }
        return result;
    }

    public final void each(IntIntMapCallBack callback) {
        synchronized (parent) {
            unsafe_each(callback);
        }
    }

    void unsafe_each(IntIntMapCallBack callback) {
        for (int i = 0; i < mapSize; i++) {
            callback.on(key(i), value(i));
        }
    }

    public int size() {
        int result;
        synchronized (parent) {
            result = mapSize;
        }
        return result;
    }

    public final void remove(final int requestKey) {
        synchronized (parent) {
            if (keys != null && mapSize != 0) {
                int hashCapacity = capacity * 2;
                int hashIndex = HashHelper.intHash(requestKey, hashCapacity);
                int m = hash(hashIndex);
                int found = -1;
                while (m >= 0) {
                    if (requestKey == key(m)) {
                        found = m;
                        break;
                    }
                    m = next(m);
                }
                if (found != -1) {
                    //first remove currentKey from hashChain
                    int toRemoveHash = HashHelper.intHash(requestKey, hashCapacity);
                    m = hash(toRemoveHash);
                    if (m == found) {
                        setHash(toRemoveHash, next(m));
                    } else {
                        while (m != -1) {
                            int next_of_m = next(m);
                            if (next_of_m == found) {
                                setNext(m, next(next_of_m));
                                break;
                            }
                            m = next_of_m;
                        }
                    }
                    final int lastIndex = mapSize - 1;
                    if (lastIndex == found) {
                        //easy, was the last element
                        mapSize--;
                    } else {
                        //less cool, we have to unchain the last value of the map
                        final int lastKey = key(lastIndex);
                        setKey(found, lastKey);
                        setValue(found, value(lastIndex));
                        setNext(found, next(lastIndex));
                        int victimHash = HashHelper.intHash(lastKey, hashCapacity);
                        m = hash(victimHash);
                        if (m == lastIndex) {
                            //the victim was the head of hashing list
                            setHash(victimHash, found);
                        } else {
                            //the victim is in the next, reChain it
                            while (m != -1) {
                                int next_of_m = next(m);
                                if (next_of_m == lastIndex) {
                                    setNext(m, found);
                                    break;
                                }
                                m = next_of_m;
                            }
                        }
                        mapSize--;
                    }
                    parent.declareDirty();
                }
            }
        }
    }

    public final IntIntMap put(final int insertKey, final int insertValue) {
        synchronized (parent) {
            if (keys == null) {
                reallocate(Constants.MAP_INITIAL_CAPACITY);
                setKey(0, insertKey);
                setValue(0, insertValue);
                setHash(HashHelper.intHash(insertKey, capacity * 2), 0);
                setNext(0, -1);
                mapSize++;
            } else {
                int hashCapacity = capacity * 2;
                int insertKeyHash = HashHelper.intHash(insertKey, hashCapacity);
                int currentHash = hash(insertKeyHash);
                int m = currentHash;
                int found = -1;
                while (m >= 0) {
                    if (insertKey == key(m)) {
                        found = m;
                        break;
                    }
                    m = next(m);
                }
                if (found == -1) {
                    final int lastIndex = mapSize;
                    if (lastIndex == capacity) {
                        reallocate(capacity * 2);
                        hashCapacity = capacity * 2;
                        insertKeyHash = HashHelper.intHash(insertKey, hashCapacity);
                        currentHash = hash(insertKeyHash);
                    }
                    setKey(lastIndex, insertKey);
                    setValue(lastIndex, insertValue);
                    setHash(HashHelper.intHash(insertKey, capacity * 2), lastIndex);
                    setNext(lastIndex, currentHash);
                    mapSize++;
                    parent.declareDirty();
                } else {
                    if (value(found) != insertValue) {
                        setValue(found, insertValue);
                        parent.declareDirty();
                    }
                }
            }
        }
        return this;
    }

    public final void save(final Buffer buffer) {
        if (mapSize != 0) {
            Base64.encodeIntToBuffer(mapSize, buffer);
            for (int j = 0; j < mapSize; j++) {
                buffer.write(CoreConstants.CHUNK_VAL_SEP);
                Base64.encodeIntToBuffer(keys[j], buffer);
                buffer.write(CoreConstants.CHUNK_VAL_SEP);
                Base64.encodeIntToBuffer(values[j], buffer);
            }
        } else {
            Base64.encodeIntToBuffer(0, buffer);
        }
    }

    public final long load(final Buffer buffer, final long offset, final long max) {
        long cursor = offset;
        byte current = buffer.read(cursor);
        boolean isFirst = true;
        long previous = offset;
        int previousKey = -1;
        boolean waitingVal = false;
        while (cursor < max && current != Constants.CHUNK_SEP && current != Constants.BLOCK_CLOSE) {
            if (current == Constants.CHUNK_VAL_SEP) {
                if (isFirst) {
                    reallocate(Base64.decodeToIntWithBounds(buffer, previous, cursor));
                    isFirst = false;
                } else {
                    if (!waitingVal) {
                        previousKey = Base64.decodeToIntWithBounds(buffer, previous, cursor);
                        waitingVal = true;
                    } else {
                        waitingVal = false;
                        put(previousKey, Base64.decodeToIntWithBounds(buffer, previous, cursor));
                    }
                }
                previous = cursor + 1;
            }
            cursor++;
            if (cursor < max) {
                current = buffer.read(cursor);
            }
        }
        if (isFirst) {
            reallocate(Base64.decodeToIntWithBounds(buffer, previous, cursor));
        } else {
            if (waitingVal) {
                put(previousKey, Base64.decodeToIntWithBounds(buffer, previous, cursor));
            }
        }
        return cursor;
    }
}


text:
function sil = silhouette_width(data,labels,distfun)
%SILHOUETTE_WIDTH Wraper for SILHOUETTE function to get average width.
%
% SYNOPSIS: ws = silhouette_width(data,labels);
%           ws = silhouette_width(data,labels,distfun);
%
% If distfun is not provided, uses euclidiean as default
%
% xies@mit.edu

if nargin == 2, distfun = @nan_eucdist; end

sil = silhouette(data,labels,distfun);
sil = nanmean(sil);

end


text:
from metakernel import Magic, option

try:
    from calysto_scheme import scheme
except:
    scheme = None

class SchemeMagic(Magic):
    def __init__(self, kernel):
        super(SchemeMagic, self).__init__(kernel)
        self.retval = None

    def line_scheme(self, *args):
        """
        %scheme CODE - evaluate code as Scheme

        This line magic will evaluate the CODE (either expression or
        statement) as Scheme code.

        Examples:
            %scheme (define x 42)
            %scheme (import "math")
            %scheme (+ x + math.pi)

        """
        code = " ".join(args)
        self.retval = self.eval(code)

    def eval(self, code):
        if scheme:
            return scheme.execute_string_rm(code.strip())
        else:
            raise Exception("calysto_scheme is required")

    @option(
        "-e", "--eval_output", action="store_true", default=False,
        help="Use the retval value from the Scheme cell as code in the kernel language."
    )
    def cell_scheme(self, eval_output=False):
        """
        %%scheme - evaluate contents of cell as Scheme

        This cell magic will evaluate the cell (either expression or
        statement) as Scheme code.

        The -e or --eval_output flag signals that the retval value expression
        will be used as code for the cell to be evaluated by the host
        language.

        Examples:
            %%scheme
            (define x 42)

            %%scheme
            (import "math")
            (define retval (+ x math.pi))

            %%scheme -e
            (define retval "this = code")

            %%scheme -e
            "this = code"
        """
        if self.code.strip():
            if eval_output:
                self.code = self.eval(self.code)
                self.evaluate = True
            else:
                self.retval = self.eval(self.code)
                self.evaluate = False

    def post_process(self, retval):
        if retval is not None:
            return retval
        else:
            return self.retval

def register_magics(kernel):
    kernel.register_magics(SchemeMagic)

def register_ipython_magics():
    from metakernel import IPythonKernel
    from IPython.core.magic import register_line_magic, register_cell_magic
    kernel = IPythonKernel()
    magic = SchemeMagic(kernel)

    @register_line_magic
    def scheme(line):
        magic.line_scheme(line)
        return magic.retval

    @register_cell_magic
    def scheme(line, cell):
        magic.code = cell
        magic.cell_scheme()
        return magic.retval


text:
<?php /* CassandraDynamicRemoveDealWithHeaderCommonDynamic.php */ ?>
<?php ?>
<?php /* CassandraDynamicRemoveDealWithHeaderSearchRelatedIndex.php */ ?>
<?php ?>
<?php /* CassandraDynamicRemoveDealWithHeaderAutoCompleteIndex.php */ ?>
<?php ?>
<?php /* CassandraDynamicRemoveDealWithProgCheckCommonDynamic.php */ ?>
<?php ?>
<?php /* CassandraDynamicRemoveDealWithProgCheckSearchRelatedIndex.php */ ?>
<?php ?>
<?php /* CassandraDynamicRemoveDealWithProgCheckAutoCompleteIndex.php */ ?>
<?php ?>
<?php /* CassandraDynamicRemoveDealWithProgCheckTwoCommonDynamic.php */ ?>
<?php ?>
<?php /* CassandraDynamicRemoveDealWithProgCheckTwoSearchRelatedIndex.php */ ?>
<?php ?>
<?php /* CassandraDynamicRemoveDealWithProgCheckTwoAutoCompleteIndex.php */ ?>
<?php ?>
<?php /* CassandraDynamicRemoveDealWithProgSetCommonDynamic.php */ ?>
<?php ?>
<?php /* CassandraDynamicRemoveDealWithProgSetSearchRelatedIndex.php */ ?>
<?php ?>
<?php /* CassandraDynamicRemoveDealWithProgSetAutoCompleteIndex.php */ ?>
<?php ?>
<?php /* CassandraDynamicRemoveDealWithProgPostCommonDynamic.php */ ?>
<?php ?>
<?php /* CassandraDynamicRemoveDealWithProgPostSearchRelatedIndex.php */ ?>
<?php ?>
<?php /* CassandraDynamicRemoveDealWithProgPostAutoCompleteIndex.php */ ?>
<?php ?>
<?php
function RemoveAutoCompleteIndexDealWith(&$key_id,  &$column_names,  &$params_orig,  &$result,  &$params) {
  global $NoSQL;
  $DEBUG_FILENAME = "#" . __FILE__ . "@" . __FUNCTION__;

  /* CassandraDynamicRemoveDealWithProgCheckCommonDynamic.php */

  /* CassandraDynamicRemoveDealWithProgCheckSearchRelatedIndex.php */

  /* CassandraDynamicRemoveDealWithProgCheckAutoCompleteIndex.php */

  /* CassandraDynamicRemoveDealWithProgCheckTwoCommonDynamic.php */

  /* CassandraDynamicRemoveDealWithProgCheckTwoSearchRelatedIndex.php */

  /* CassandraDynamicRemoveDealWithProgCheckTwoAutoCompleteIndex.php */

  /* CassandraDynamicRemoveDealWithProgSetCommonDynamic.php */

  /* CassandraDynamicRemoveDealWithProgSetSearchRelatedIndex.php */

  /* CassandraDynamicRemoveDealWithProgSetAutoCompleteIndex.php */

  /* CassandraDynamicRemoveDealWithProgPostCommonDynamic.php */

  /* CassandraDynamicRemoveDealWithProgPostSearchRelatedIndex.php */

  /* CassandraDynamicRemoveDealWithProgPostAutoCompleteIndex.php */

}
?>


text:
=========
lexicrypt
=========

Beta Site
=========

http://lexicrypt.com

What it is
==========

Token-based message distribution using encryption.

Installation
============

Install MongoDB or set up an account at http://mongohq.com

::

    $ pip install -r requirements.txt
    $ mkdir lexicrypt/tmp
    $ cp lexicrypt/setings.py-local lexicrypt/settings.py

Then edit ``lexicrypt/settings.py``.

Message Flow
============

.. image:: http://dl.dropbox.com/u/1913694/lexicrypt-flow.png

Screenshots
===========

.. image:: http://dl.dropbox.com/u/1913694/lexicrypt_sample_1.png

.. image:: http://dl.dropbox.com/u/1913694/lexicrypt_sample_2.png

.. image:: http://dl.dropbox.com/u/1913694/lexicrypt_sample_3.png

.. image:: http://dl.dropbox.com/u/1913694/lexicrypt_sample_4.png

Todo
====

* Allow regeneration of api keys
* Allow long messages to be converted to parts

Completed Items
===============

* Auto-generate image filenames
* If a visitor's api key matches one in the char_array's list, provide
  a browser notification that this image can be decrypted
* Save self.char_array to a database, such that: author[messages:
  [message: accessors: [api_key_1, api_key_2, api_key_n]]]
* Allow them to decrypt by providing a link to the image
* Allow removal of access tokens from message list

Running the Tests
=================

In the top level of the project, run the following::

    $ python -m lexicrypt.tests.test

Additional Notes
================

* Api keys are tied to a user's email address
* Each user has an generated AES secret for their data. If this key is
  reset, all previous images will be regenerated


text:
layout: post
title: "Revisão de álgebra linear em Python"
date: 2019-06-21 22:50:00
categories: [ Algebra Linear ]
tags: [numpy, vetores, matriz, distancia, euclidiana]
image: assets/images/posts/2019-06-21-revisao-algebra-linear-python.png
excerpt: Veja uma revisão de alguns conceitos importantes de Álgebra Linear e como usar em Python com a biblioteca NumPy.
---

# Numpy

A biblioteca de computação científica [NumPy](http://www.numpy.org) facilita muito a manipulação algébrica de matrizes de **n** dimensões.

Para importar a biblioteca numpy:

``` python
import numpy as np
```

No site do NumPy também tem um tutorial de como começar a usar.

O tipo básico de dados é o **ndarray** que representa um array multidimensional.

``` python
notas = np.array([7.8, 9.1, 8.6, 7.4])
aptos = np.array([104, 515, 1], [140, 635, 1], [50, 210, 0])
```

# Álgebra Linear

## Vetores

Vetores podem ser entendidos como pontos no espaço e podemos representar os dados usando vetores.
Exemplo: os dados que representam um apartamento, as notas de um aluno, os valores que compõem o preço de um produto, entre outros, podem ser armazenados em um vetor.

No Python representamos um vetor como um **array** do NumPy, então se temos apenas a informação da quantidade de m², temos um vetor com um eixo:

``` python
apto = np.array([67])
```

Adicionando a informação do valor do apartamento no vetor, teremos um vetor com dois eixos:

``` python
apto = np.array([67, 250])
```

Se continuarmos incluindo mais uma informação como a quantidade de quartos, teremos um vetor três eixos:

``` python
apto = np.array([67, 250, 2])
```

E podemos continuar adicionando informações no vetor e a cada novo valor aumentamos um eixo do vetor.

A **Figura 1** mostra como um vetor pode ser representado visualmente até o terceiro eixo.

\\
**Figura 1:** Visualizando um vetor de 1, 2 e 3 dimensões.

## Métodos úteis da np.array

``` python
x = np.array([1, 2, 3, 4])
x.sum() # soma dos valores do vetor = 10
x.min() # menor valor do vetor = 1
x.max() # maior valor do vetor = 4
```

## Soma de vetores

Dois ou mais vetores (de tamanho igual) podem ser somados e para isso é calculado a soma de cada elemento nas mesmas posições do vetor, exemplo:

Exemplo: quando temos um vetor com valores de almoço e outro vetor com valores de gorjetas, podemos somar os dois vetores para obter o valor total de cada refeição.

``` python
x = np.array([1, 2, 3, 4])
y = np.array([5, 6, 7, 8])
soma = x + y  #[6, 8, 10, 12]
```

## Soma escalar

Também é possível fazer a soma escalar (com um número) no vetor, então um valor é somado a cada elemento do vetor.
Exemplo, suponha um conjunto de média de notas dos alunos, e o professor bonzinho resolve dar 0.5 pontos para cada aluno:

``` python
notas = np.array([6.5, 8.0, 7.5, 4.5, 9.0, 6.5, 6.0, 5.5, 7.0, 8.0, 6.5, 7.5])
soma = notas + 0.5  #[7.0, 8.5, 8.0, 5.0, 9.5, 7.0, 6.5, 6.0, 7.5, 8.5, 7.0, 8.0]
```

## Operações do array no Numpy

Com o novo vetor de notas, queremos saber quais os alunos obtiveram nota maior ou igual a 7.0 e foram aprovados. Para isso, podemos aplicar uma comparação a cada elemento do vetor, exemplo:

``` python
aprovados = soma >= 7.0
# o resultado é um vetor de booleanos:
# array([True, True, True, False, True, True, False, False, True, True, True, True], dtype=bool)
# que indica com True as notas que são maior ou igual a 7,0 e False as notas menores que 7,0.
```

E contar quantos valores são **True**, portanto tem nota maior ou igual a **7,0**:

``` python
qtdAprovados = sum(soma >= 7.0)  #9
```

O mesmo pode ser feito para saber quantos alunos tiveram a nota menor que **7,0** e foram reprovados. Podemos aplicar uma comparação a cada elemento do vetor, exemplo:

``` python
reprovados = soma < 7.0
# array([False, False, False, True, False, False, True, True, False, False, False, False], dtype=bool)
```

E contar quantos valores são **True**, portanto tem nota menor que **7,0**:

``` python
qtdReprovados = sum(soma < 7.0)  # 3
```

## Multiplicação de vetores

Dois ou mais vetores podem ser multiplicados e para isso é calculado a multiplicação de cada elemento nas mesmas posições do vetor, exemplo:

``` python
x = np.array([1, 2, 3, 4])
y = np.array([5, 6, 7, 8])
mult = x * y  #[5, 12, 21, 32]
```

Se temos um vetor com as notas de um aluno:

``` python
notas = np.array([8.0, 7.0, 7.5, 9.5, 10.0])
```

E temos um vetor com o peso que representa cada uma das notas na disciplina:

``` python
pesos = np.array([0.2, 0.1, 0.1, 0.3, 0.3])
```

Se multiplicarmos os dois vetores e somar seus valores, temos como resultado a nota que este aluno teve na disciplina:

``` python
notaFinal = sum(notas * pesos)
```

## Multiplicação de escalar

Também é possível fazer a multiplicação escalar (com um número) no vetor, então um valor é multiplicado a cada elemento do vetor.
Exemplo, suponha que temos um vetor os valores pagos com comida em um restaurante:

``` python
valores = np.array([18.0, 16.5, 17.0, 19.5, 18.5])
```

E queremos calcular 10% de gorjeta para cada um dos valores:

``` python
gorjeta = valores * 0.1  #[1.8, 1.65, 1.7, 1.95, 1.85]
```

Se quiser saber o total de gorjeta é só somar o vetor **sum(gorjeta)**.

## Produto escalar de vetores

A **Figura 2** mostra o produto escalar de dois vetores.

\\
**Figura 2:** Equação do produto escalar de dois vetores.

sendo **x** e **y**, dois vetores de tamanho iguais e **n** o tamanho dos vetores, o produto escalar é a somatória da multiplicação de dois vetores, exemplo:

``` python
x = np.array([1, 2, 3, 4])
y = np.array([5, 6, 7, 8])
prod = np.dot(x, y)  # 70
```

Para calcular a soma dos quadrados de um vetor, também podemos usar o produto escalar como mostrado na **Figura 3**.

\\
**Figura 3:** Soma dos quadrados de um vetor.

``` python
x = np.array([1, 2, 3, 4])
prod = np.dot(x, x)  # 30
```

Porque obtemos como resultado a soma da multiplicação do vetor **x** por ele mesmo.

## Distância entre vetores

Na **Figura 4** temos o vetor **[1,4] (quadrado verde)** e um vetor **[2,1] (quadrado azul)**. Temos um novo vetor **[4,2] (triângulo vermelho)**, mas gostaríamos de classificar este novo vetor como quadrado verde ou azul. Para isso podemos verificar qual o quadrado mais próximo e usar a mesma cor, mas qual quadrado está mais perto do triângulo?

\\
**Figura 4:** Distância entre vetores.

Na **Figura 5** podemos perceber que o quadrado azul está mais próximo do triângulo vermelho, então podemos classificar este novo vetor como um quadrado azul.

\\
**Figura 5:** Distância entre vetores.

Uma das formas de calcular a distância entre vetores é usando a **Distância Euclidiana**, que é dada pela equação da **Figura 6**.

\\
**Figura 6:** Distância Euclidiana.

Então, na **Figura 7** calculamos o distância euclidiana entre o vetor **[1,4] (quadrado verde)** com o vetor **[4,2] (triângulo vermelho)**.

\\
**Figura 7:** Distância Euclidiana.

E na **Figura 8** calculamos distância euclidiana entre o vetor **[2,1] (quadrado azul)** com o vetor **[4,2] (triângulo vermelho)**.

\\
**Figura 8:** Distância Euclidiana.

Portanto, sabemos que a menor distância é em relação ao quadrado azul.

Usando o Python, podemos calcular a distância entre os vetores:

``` python
qv = np.array([1,4])    # Quadrado verde
qa = np.array([2,1])    # Quadrado azul
tv = np.array([4,2])    # Triângulo vermelho
```

com:

``` python
distanciaQuadradoVerde = np.sqrt(sum((qv - tv) ** 2)) #3.6055
distanciaQuadradoAzul  = np.sqrt(sum((qa - tv) ** 2)) #2.2360
```

Obs: O ** é utilizado para calcular o número da esquerda elevado ao número da direita. Exemplo 5² é calculado como 5 ** 2.

# Matrizes

Matriz é formada por um conjunto de vetores, normalmente representada em maiúsculo, como **A[m, n]** que tem **m** linhas por **n** colunas. O Numpy tem o objeto **matrix** que representa uma matriz, exemplo:

``` python
A = np.matrix([[1, 2, 3, 4],
               [5, 6, 7, 8]])
```

Nesse caso dizemos que a matriz **A** tem tamanho **[2, 4]**, ou duas linhas e quatro colunas. Para acessar uma determinada posição da matriz precisamos informar os valores da linha e coluna, lembrando que os índices começam com **zero**, o valor da posição **A[1, 3]** é **8**.

## Soma de matrizes

A soma de matrizes:

``` python
A = np.matrix([[1, 2, 3, 4],
               [5, 6, 7, 8]])
B = np.matrix([[1, 2, 3, 4],
               [5, 6, 7, 8]])

SOMA = A + B
# [[ 2,  4,  6,  8],
#  [10, 12, 14, 16]]
```

## Transposta

Com o Numpy podemos obter facilmente a transposta de uma matriz:

``` python
A = np.matrix([[1, 2, 3, 4],
               [5, 6, 7, 8]])
A.T    # [[1, 5],
       #  [2, 6],
       #  [3, 7],
       #  [4, 8]]
```

## Multiplicação de matrizes

Para multiplicar duas matrizes é necessário que uma matriz **A** tenha dimensão **m x n** enquanto que a matriz **B** tenha a dimensão **n x m**, como resultado temos uma matriz de dimensão **m x m**.

``` python
A = np.matrix([[1, 2, 3, 4],
               [5, 6, 7, 8]])
B = np.matrix([[1, 2],
               [3, 4],
               [5, 6],
               [7, 8]])
mult = A * B  # [[ 50,  60],
              # [114, 140]]
```