text:
/* Includes ------------------------------------------------------------------*/
#include "stm32l1xx_hal.h"

/** @addtogroup STM32L1xx_HAL_Driver
  * @{
  */

/** @defgroup OPAMPEx OPAMPEx
  * @brief OPAMP Extended HAL module driver.
  * @{
  */

#ifdef HAL_OPAMP_MODULE_ENABLED

#if defined (STM32L151xCA) || defined (STM32L151xD) || defined (STM32L152xCA) || defined (STM32L152xD) || defined (STM32L162xCA) || defined (STM32L162xD) || defined (STM32L151xE) || defined (STM32L152xE) || defined (STM32L162xE) || defined (STM32L162xC) || defined (STM32L152xC) || defined (STM32L151xC)

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/

/** @addtogroup OPAMPEx_Exported_Functions OPAMPEx Exported Functions
  * @{
  */

/** @addtogroup OPAMPEx_Exported_Functions_Group1
  * @brief    Extended operation functions
  *
@verbatim
 ===============================================================================
              ##### Extended IO operation functions #####
 ===============================================================================
  [..]
      (+) OPAMP Self calibration.

@endverbatim
  * @{
  */

#if defined (STM32L151xD) || defined (STM32L152xD) || defined (STM32L162xD)

/*  3 OPAMPS available */
/*  3 OPAMPS can be calibrated in parallel */

/**
  * @brief  Run the self calibration of the 3 OPAMPs in parallel.
  * @note   Trimming values (PMOS & NMOS) are updated and user trimming is
  *         enabled is calibration is succesful.
  * @note   Calibration is performed in the mode specified in OPAMP init
  *         structure (mode normal or low-power). To perform calibration for
  *         both modes, repeat this function twice after OPAMP init structure
  *         accordingly updated.
  * @note   Calibration runs about 10 ms (5 dichotmy steps, repeated for P
  *         and N transistors: 10 steps with 1 ms for each step).
  * @param  hopamp1 handle
  * @param  hopamp2 handle
  * @param  hopamp3 handle
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_OPAMPEx_SelfCalibrateAll(OPAMP_HandleTypeDef *hopamp1, OPAMP_HandleTypeDef *hopamp2, OPAMP_HandleTypeDef *hopamp3)
{
  HAL_StatusTypeDef status = HAL_OK;

  uint32_t* opamp1_trimmingvalue = 0;
  uint32_t opamp1_trimmingvaluen = 0;
  uint32_t opamp1_trimmingvaluep = 0;

  uint32_t* opamp2_trimmingvalue = 0;
  uint32_t opamp2_trimmingvaluen = 0;
  uint32_t opamp2_trimmingvaluep = 0;

  uint32_t* opamp3_trimmingvalue = 0;
  uint32_t opamp3_trimmingvaluen = 0;
  uint32_t opamp3_trimmingvaluep = 0;

  uint32_t trimming_diff_pair = 0;          /* Selection of differential transistors pair high or low */

  __IO uint32_t* tmp_opamp1_reg_trimming;   /* Selection of register of trimming depending on power mode: OTR or LPOTR */
  __IO uint32_t* tmp_opamp2_reg_trimming;
  __IO uint32_t* tmp_opamp3_reg_trimming;
  uint32_t tmp_opamp1_otr_otuser = 0;       /* Selection of bit OPAMP_OTR_OT_USER depending on trimming register pointed: OTR or LPOTR */
  uint32_t tmp_opamp2_otr_otuser = 0;
  uint32_t tmp_opamp3_otr_otuser = 0;

  uint32_t tmp_Opa1calout_DefaultSate = 0;  /* Bit OPAMP_CSR_OPA1CALOUT default state when trimming value is 00000b. Used to detect the bit toggling */
  uint32_t tmp_Opa2calout_DefaultSate = 0;  /* Bit OPAMP_CSR_OPA2CALOUT default state when trimming value is 00000b. Used to detect the bit toggling */
  uint32_t tmp_Opa3calout_DefaultSate = 0;  /* Bit OPAMP_CSR_OPA3CALOUT default state when trimming value is 00000b. Used to detect the bit toggling */

  uint32_t tmp_OpaxSwitchesContextBackup = 0;

  uint8_t trimming_diff_pair_iteration_count = 0;
  uint8_t delta = 0;

  /* Check the OPAMP handle allocation */
  /* Check if OPAMP locked */
  if((hopamp1 == HAL_NULL) || (hopamp1->State == HAL_OPAMP_STATE_BUSYLOCKED) ||
     (hopamp2 == HAL_NULL) || (hopamp2->State == HAL_OPAMP_STATE_BUSYLOCKED) ||
     (hopamp3 == HAL_NULL) || (hopamp3->State == HAL_OPAMP_STATE_BUSYLOCKED)   )
  {
    status = HAL_ERROR;
  }
  else
  {

    /* Check if OPAMP in calibration mode and calibration not yet enable */
    if((hopamp1->State == HAL_OPAMP_STATE_READY) &&
       (hopamp2->State == HAL_OPAMP_STATE_READY) &&
       (hopamp3->State == HAL_OPAMP_STATE_READY)   )
    {
      /* Check the parameter */
      assert_param(IS_OPAMP_ALL_INSTANCE(hopamp1->Instance));
      assert_param(IS_OPAMP_ALL_INSTANCE(hopamp2->Instance));
      assert_param(IS_OPAMP_ALL_INSTANCE(hopamp3->Instance));
      assert_param(IS_OPAMP_POWERMODE(hopamp1->Init.PowerMode));
      assert_param(IS_OPAMP_POWERMODE(hopamp2->Init.PowerMode));
      assert_param(IS_OPAMP_POWERMODE(hopamp3->Init.PowerMode));

      /* Update OPAMP state */
      hopamp1->State = HAL_OPAMP_STATE_CALIBBUSY;
      hopamp2->State = HAL_OPAMP_STATE_CALIBBUSY;
      hopamp3->State = HAL_OPAMP_STATE_CALIBBUSY;

      /* Backup of switches configuration to restore it at the end of the     */
      /* calibration.                                                         */
      tmp_OpaxSwitchesContextBackup = READ_BIT(OPAMP->CSR, OPAMP_CSR_ALL_SWITCHES_ALL_OPAMPS);

      /* Open all switches on non-inverting input, inverting input and output */
      /* feedback.                                                            */
      CLEAR_BIT(OPAMP->CSR, OPAMP_CSR_ALL_SWITCHES_ALL_OPAMPS);

      /* Set calibration mode to user programmed trimming values */
      SET_BIT(OPAMP->OTR, OPAMP_OTR_OT_USER);

      /* Select trimming settings depending on power mode */
      if (hopamp1->Init.PowerMode == OPAMP_POWERMODE_NORMAL)
      {
        tmp_opamp1_otr_otuser = OPAMP_OTR_OT_USER;
        tmp_opamp1_reg_trimming = &OPAMP->OTR;
      }
      else
      {
        tmp_opamp1_otr_otuser = 0x00000000;
        tmp_opamp1_reg_trimming = &OPAMP->LPOTR;
      }

      if (hopamp2->Init.PowerMode == OPAMP_POWERMODE_NORMAL)
      {
        tmp_opamp2_otr_otuser = OPAMP_OTR_OT_USER;
        tmp_opamp2_reg_trimming = &OPAMP->OTR;
      }
      else
      {
        tmp_opamp2_otr_otuser = 0x00000000;
        tmp_opamp2_reg_trimming = &OPAMP->LPOTR;
      }

      if (hopamp3->Init.PowerMode == OPAMP_POWERMODE_NORMAL)
      {
        tmp_opamp3_otr_otuser = OPAMP_OTR_OT_USER;
        tmp_opamp3_reg_trimming = &OPAMP->OTR;
      }
      else
      {
        tmp_opamp3_otr_otuser = 0x00000000;
        tmp_opamp3_reg_trimming = &OPAMP->LPOTR;
      }

      /* Enable the selected opamp */
      CLEAR_BIT (OPAMP->CSR, OPAMP_CSR_OPAXPD_ALL);

      /* Perform trimming for both differential transistors pair high and low */
      for (trimming_diff_pair_iteration_count = 0; trimming_diff_pair_iteration_count <=1; trimming_diff_pair_iteration_count++)
      {
        if (trimming_diff_pair_iteration_count == 0)
        {
          /* Calibration of transistors differential pair high (NMOS) */
          trimming_diff_pair = OPAMP_FACTORYTRIMMING_N;
          opamp1_trimmingvalue = &opamp1_trimmingvaluen;
          opamp2_trimmingvalue = &opamp2_trimmingvaluen;
          opamp3_trimmingvalue = &opamp3_trimmingvaluen;

          /* Set bit OPAMP_CSR_OPAXCALOUT default state when trimming value   */
          /* is 00000b. Used to detect the bit toggling during trimming.      */
          tmp_Opa1calout_DefaultSate = RESET;
          tmp_Opa2calout_DefaultSate = RESET;
          tmp_Opa3calout_DefaultSate = RESET;

          /* Enable calibration for N differential pair */
          MODIFY_REG(OPAMP->CSR, OPAMP_CSR_OPAXCAL_L_ALL,
                                 OPAMP_CSR_OPAXCAL_H_ALL);
        }
        else /* (trimming_diff_pair_iteration_count == 1) */
        {
          /* Calibration of transistors differential pair low (PMOS) */
          trimming_diff_pair = OPAMP_FACTORYTRIMMING_P;
          opamp1_trimmingvalue = &opamp1_trimmingvaluep;
          opamp2_trimmingvalue = &opamp2_trimmingvaluep;
          opamp3_trimmingvalue = &opamp3_trimmingvaluep;

          /* Set bit OPAMP_CSR_OPAXCALOUT default state when trimming value   */
          /* is 00000b. Used to detect the bit toggling during trimming.      */
          tmp_Opa1calout_DefaultSate = __OPAMP_CSR_OPAXCALOUT(hopamp1);
          tmp_Opa2calout_DefaultSate = __OPAMP_CSR_OPAXCALOUT(hopamp2);
          tmp_Opa3calout_DefaultSate = __OPAMP_CSR_OPAXCALOUT(hopamp3);

          /* Enable calibration for P differential pair */
          MODIFY_REG(OPAMP->CSR, OPAMP_CSR_OPAXCAL_H_ALL,
                                 OPAMP_CSR_OPAXCAL_L_ALL);
        }

        /* Perform calibration parameter search by dichotomy sweep */
        /*  - Delta initial value 16: for 5 dichotomy steps: 16 for the       */
        /*    initial range, then successive delta sweeps (8, 4, 2, 1).       */
        /*    can extend the search range to +/- 15 units.                    */
        /*  - Trimming initial value 15: search range will go from 0 to 30    */
        /*    (Trimming value 31 is forbidden).                               */
        *opamp1_trimmingvalue = 15;
        *opamp2_trimmingvalue = 15;
        *opamp3_trimmingvalue = 15;
        delta = 16;

        while (delta != 0)
        {
          /* Set candidate trimming */

          MODIFY_REG(*tmp_opamp1_reg_trimming, __OPAMP_OFFSET_TRIM_SET(hopamp1, trimming_diff_pair, OPAMP_TRIM_VALUE_MASK) ,
                                               __OPAMP_OFFSET_TRIM_SET(hopamp1, trimming_diff_pair, *opamp1_trimmingvalue) | tmp_opamp1_otr_otuser);

          MODIFY_REG(*tmp_opamp2_reg_trimming, __OPAMP_OFFSET_TRIM_SET(hopamp2, trimming_diff_pair, OPAMP_TRIM_VALUE_MASK) ,
                                               __OPAMP_OFFSET_TRIM_SET(hopamp2, trimming_diff_pair, *opamp2_trimmingvalue) | tmp_opamp2_otr_otuser);

          MODIFY_REG(*tmp_opamp3_reg_trimming, __OPAMP_OFFSET_TRIM_SET(hopamp3, trimming_diff_pair, OPAMP_TRIM_VALUE_MASK) ,
                                               __OPAMP_OFFSET_TRIM_SET(hopamp3, trimming_diff_pair, *opamp3_trimmingvalue) | tmp_opamp3_otr_otuser);

          /* Offset trimming time: during calibration, minimum time needed    */
          /* between two steps to have 1 mV accuracy.                         */
          HAL_Delay(OPAMP_TRIMMING_DELAY);

          /* Divide range by 2 to continue dichotomy sweep */
          delta >>= 1;

          /* Set trimming values for next iteration in function of trimming   */
          /* result toggle (versus initial state).                            */
          /* Trimming values update with dichotomy delta of previous          */
          /* iteration.                                                       */
          if (READ_BIT(OPAMP->CSR, __OPAMP_CSR_OPAXCALOUT(hopamp1)) != tmp_Opa1calout_DefaultSate)
          {
            /* If calibration output is has toggled, try lower trimming */
            *opamp1_trimmingvalue -= delta;
          }
          else
          {
            /* If calibration output is has not toggled, try higher trimming */
            *opamp1_trimmingvalue += delta;
          }

          /* Set trimming values for next iteration in function of trimming   */
          /* result toggle (versus initial state).                            */
          /* Trimming values update with dichotomy delta of previous          */
          /* iteration.                                                       */
          if (READ_BIT(OPAMP->CSR, __OPAMP_CSR_OPAXCALOUT(hopamp2)) != tmp_Opa2calout_DefaultSate)
          {
            /* If calibration output is has toggled, try lower trimming */
            *opamp2_trimmingvalue -= delta;
          }
          else
          {
            /* If calibration output is has not toggled, try higher trimming */
            *opamp2_trimmingvalue += delta;
          }

          /* Set trimming values for next iteration in function of trimming   */
          /* result toggle (versus initial state).                            */
          /* Trimming values update with dichotomy delta of previous          */
          /* iteration.                                                       */
          if (READ_BIT(OPAMP->CSR, __OPAMP_CSR_OPAXCALOUT(hopamp3)) != tmp_Opa3calout_DefaultSate)
          {
            /* If calibration output is has toggled, try lower trimming */
            *opamp3_trimmingvalue -= delta;
          }
          else
          {
            /* If calibration output is has not toggled, try higher trimming */
            *opamp3_trimmingvalue += delta;
          }

        }
      }

      /* Disable calibration for P and N differential pairs */
      /* Disable the selected opamp */
      CLEAR_BIT (OPAMP->CSR, (OPAMP_CSR_OPAXCAL_H_ALL |
                              OPAMP_CSR_OPAXCAL_L_ALL |
                              OPAMP_CSR_OPAXPD_ALL     ));

      /* Backup of switches configuration to restore it at the end of the     */
      /* calibration.                                                         */
      SET_BIT(OPAMP->CSR, tmp_OpaxSwitchesContextBackup);

      /* Self calibration is successful */
      /* Store calibration (user trimming) results in init structure. */

      /* Set user trimming mode */
      hopamp1->Init.UserTrimming = OPAMP_TRIMMING_USER;
      hopamp2->Init.UserTrimming = OPAMP_TRIMMING_USER;
      hopamp3->Init.UserTrimming = OPAMP_TRIMMING_USER;

      /* Affect calibration parameters depending on mode normal/low power */
      if (hopamp1->Init.PowerMode != OPAMP_POWERMODE_LOWPOWER)
      {
        /* Write calibration result N */
        hopamp1->Init.TrimmingValueN = opamp1_trimmingvaluen;
        /* Write calibration result P */
        hopamp1->Init.TrimmingValueP = opamp1_trimmingvaluep;
      }
      else
      {
        /* Write calibration result N */
        hopamp1->Init.TrimmingValueNLowPower = opamp1_trimmingvaluen;
        /* Write calibration result P */
        hopamp1->Init.TrimmingValuePLowPower = opamp1_trimmingvaluep;
      }

      if (hopamp2->Init.PowerMode != OPAMP_POWERMODE_LOWPOWER)
      {
        /* Write calibration result N */
        hopamp2->Init.TrimmingValueN = opamp2_trimmingvaluen;
        /* Write calibration result P */
        hopamp2->Init.TrimmingValueP = opamp2_trimmingvaluep;
      }
      else
      {
        /* Write calibration result N */
        hopamp2->Init.TrimmingValueNLowPower = opamp2_trimmingvaluen;
        /* Write calibration result P */
        hopamp2->Init.TrimmingValuePLowPower = opamp2_trimmingvaluep;
      }

      if (hopamp3->Init.PowerMode != OPAMP_POWERMODE_LOWPOWER)
      {
        /* Write calibration result N */
        hopamp3->Init.TrimmingValueN = opamp3_trimmingvaluen;
        /* Write calibration result P */
        hopamp3->Init.TrimmingValueP = opamp3_trimmingvaluep;
      }
      else
      {
        /* Write calibration result N */
        hopamp3->Init.TrimmingValueNLowPower = opamp3_trimmingvaluen;
        /* Write calibration result P */
        hopamp3->Init.TrimmingValuePLowPower = opamp3_trimmingvaluep;
      }

      /* Update OPAMP state */
      hopamp1->State = HAL_OPAMP_STATE_READY;
      hopamp2->State = HAL_OPAMP_STATE_READY;
      hopamp3->State = HAL_OPAMP_STATE_READY;

    }
    else
    {
      /* OPAMP can not be calibrated from this mode */
      status = HAL_ERROR;
    }
  }

  return status;
}

#else

/*  2 OPAMPS available */
/*  2 OPAMPS can be calibrated in parallel */

/**
  * @brief  Run the self calibration of the 2 OPAMPs in parallel.
  * @note   Trimming values (PMOS & NMOS) are updated and user trimming is
  *         enabled is calibration is succesful.
  * @note   Calibration is performed in the mode specified in OPAMP init
  *         structure (mode normal or low-power). To perform calibration for
  *         both modes, repeat this function twice after OPAMP init structure
  *         accordingly updated.
  * @note   Calibration runs about 10 ms (5 dichotmy steps, repeated for P
  *         and N transistors: 10 steps with 1 ms for each step).
  * @param  hopamp1 handle
  * @param  hopamp2 handle
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_OPAMPEx_SelfCalibrateAll(OPAMP_HandleTypeDef *hopamp1, OPAMP_HandleTypeDef *hopamp2)
{
  HAL_StatusTypeDef status = HAL_OK;

  uint32_t* opamp1_trimmingvalue = 0;
  uint32_t opamp1_trimmingvaluen = 0;
  uint32_t opamp1_trimmingvaluep = 0;

  uint32_t* opamp2_trimmingvalue = 0;
  uint32_t opamp2_trimmingvaluen = 0;
  uint32_t opamp2_trimmingvaluep = 0;

  uint32_t trimming_diff_pair = 0;          /* Selection of differential transistors pair high or low */

  __IO uint32_t* tmp_opamp1_reg_trimming;   /* Selection of register of trimming depending on power mode: OTR or LPOTR */
  __IO uint32_t* tmp_opamp2_reg_trimming;
  uint32_t tmp_opamp1_otr_otuser = 0;       /* Selection of bit OPAMP_OTR_OT_USER depending on trimming register pointed: OTR or LPOTR */
  uint32_t tmp_opamp2_otr_otuser = 0;

  uint32_t tmp_Opa1calout_DefaultSate = 0;  /* Bit OPAMP_CSR_OPA1CALOUT default state when trimming value is 00000b. Used to detect the bit toggling */
  uint32_t tmp_Opa2calout_DefaultSate = 0;  /* Bit OPAMP_CSR_OPA2CALOUT default state when trimming value is 00000b. Used to detect the bit toggling */

  uint32_t tmp_OpaxSwitchesContextBackup = 0;

  uint8_t trimming_diff_pair_iteration_count = 0;
  uint8_t delta = 0;

  /* Check the OPAMP handle allocation */
  /* Check if OPAMP locked */
  if((hopamp1 == HAL_NULL) || (hopamp1->State == HAL_OPAMP_STATE_BUSYLOCKED) ||
     (hopamp2 == HAL_NULL) || (hopamp2->State == HAL_OPAMP_STATE_BUSYLOCKED)   )
  {
    status = HAL_ERROR;
  }
  else
  {

    /* Check if OPAMP in calibration mode and calibration not yet enable */
    if((hopamp1->State == HAL_OPAMP_STATE_READY) &&
       (hopamp2->State == HAL_OPAMP_STATE_READY)   )
    {
      /* Check the parameter */
      assert_param(IS_OPAMP_ALL_INSTANCE(hopamp1->Instance));
      assert_param(IS_OPAMP_ALL_INSTANCE(hopamp2->Instance));
      assert_param(IS_OPAMP_POWERMODE(hopamp1->Init.PowerMode));
      assert_param(IS_OPAMP_POWERMODE(hopamp2->Init.PowerMode));

      /* Update OPAMP state */
      hopamp1->State = HAL_OPAMP_STATE_CALIBBUSY;
      hopamp2->State = HAL_OPAMP_STATE_CALIBBUSY;

      /* Backup of switches configuration to restore it at the end of the     */
      /* calibration.                                                         */
      tmp_OpaxSwitchesContextBackup = READ_BIT(OPAMP->CSR, OPAMP_CSR_ALL_SWITCHES_ALL_OPAMPS);

      /* Open all switches on non-inverting input, inverting input and output */
      /* feedback.                                                            */
      CLEAR_BIT(OPAMP->CSR, OPAMP_CSR_ALL_SWITCHES_ALL_OPAMPS);

      /* Set calibration mode to user programmed trimming values */
      SET_BIT(OPAMP->OTR, OPAMP_OTR_OT_USER);

      /* Select trimming settings depending on power mode */
      if (hopamp1->Init.PowerMode == OPAMP_POWERMODE_NORMAL)
      {
        tmp_opamp1_otr_otuser = OPAMP_OTR_OT_USER;
        tmp_opamp1_reg_trimming = &OPAMP->OTR;
      }
      else
      {
        tmp_opamp1_otr_otuser = 0x00000000;
        tmp_opamp1_reg_trimming = &OPAMP->LPOTR;
      }

      if (hopamp2->Init.PowerMode == OPAMP_POWERMODE_NORMAL)
      {
        tmp_opamp2_otr_otuser = OPAMP_OTR_OT_USER;
        tmp_opamp2_reg_trimming = &OPAMP->OTR;
      }
      else
      {
        tmp_opamp2_otr_otuser = 0x00000000;
        tmp_opamp2_reg_trimming = &OPAMP->LPOTR;
      }

      /* Enable the selected opamp */
      CLEAR_BIT (OPAMP->CSR, OPAMP_CSR_OPAXPD_ALL);

      /* Perform trimming for both differential transistors pair high and low */
      for (trimming_diff_pair_iteration_count = 0; trimming_diff_pair_iteration_count <=1; trimming_diff_pair_iteration_count++)
      {
        if (trimming_diff_pair_iteration_count == 0)
        {
          /* Calibration of transistors differential pair high (NMOS) */
          trimming_diff_pair = OPAMP_FACTORYTRIMMING_N;
          opamp1_trimmingvalue = &opamp1_trimmingvaluen;
          opamp2_trimmingvalue = &opamp2_trimmingvaluen;

          /* Set bit OPAMP_CSR_OPAXCALOUT default state when trimming value   */
          /* is 00000b. Used to detect the bit toggling during trimming.      */
          tmp_Opa1calout_DefaultSate = RESET;
          tmp_Opa2calout_DefaultSate = RESET;

          /* Enable calibration for N differential pair */
          MODIFY_REG(OPAMP->CSR, OPAMP_CSR_OPAXCAL_L_ALL,
                                 OPAMP_CSR_OPAXCAL_H_ALL);
        }
        else /* (trimming_diff_pair_iteration_count == 1) */
        {
          /* Calibration of transistors differential pair low (PMOS) */
          trimming_diff_pair = OPAMP_FACTORYTRIMMING_P;
          opamp1_trimmingvalue = &opamp1_trimmingvaluep;
          opamp2_trimmingvalue = &opamp2_trimmingvaluep;

          /* Set bit OPAMP_CSR_OPAXCALOUT default state when trimming value   */
          /* is 00000b. Used to detect the bit toggling during trimming.      */
          tmp_Opa1calout_DefaultSate = __OPAMP_CSR_OPAXCALOUT(hopamp1);
          tmp_Opa2calout_DefaultSate = __OPAMP_CSR_OPAXCALOUT(hopamp2);

          /* Enable calibration for P differential pair */
          MODIFY_REG(OPAMP->CSR, OPAMP_CSR_OPAXCAL_H_ALL,
                                 OPAMP_CSR_OPAXCAL_L_ALL);
        }

        /* Perform calibration parameter search by dichotomy sweep */
        /*  - Delta initial value 16: for 5 dichotomy steps: 16 for the       */
        /*    initial range, then successive delta sweeps (8, 4, 2, 1).       */
        /*    can extend the search range to +/- 15 units.                    */
        /*  - Trimming initial value 15: search range will go from 0 to 30    */
        /*    (Trimming value 31 is forbidden).                               */
        *opamp1_trimmingvalue = 15;
        *opamp2_trimmingvalue = 15;
        delta = 16;

        while (delta != 0)
        {
          /* Set candidate trimming */

          MODIFY_REG(*tmp_opamp1_reg_trimming, __OPAMP_OFFSET_TRIM_SET(hopamp1, trimming_diff_pair, OPAMP_TRIM_VALUE_MASK) ,
                                               __OPAMP_OFFSET_TRIM_SET(hopamp1, trimming_diff_pair, *opamp1_trimmingvalue) | tmp_opamp1_otr_otuser);

          MODIFY_REG(*tmp_opamp2_reg_trimming, __OPAMP_OFFSET_TRIM_SET(hopamp2, trimming_diff_pair, OPAMP_TRIM_VALUE_MASK) ,
                                               __OPAMP_OFFSET_TRIM_SET(hopamp2, trimming_diff_pair, *opamp2_trimmingvalue) | tmp_opamp2_otr_otuser);

          /* Offset trimming time: during calibration, minimum time needed    */
          /* between two steps to have 1 mV accuracy.                         */
          HAL_Delay(OPAMP_TRIMMING_DELAY);

          /* Divide range by 2 to continue dichotomy sweep */
          delta >>= 1;

          /* Set trimming values for next iteration in function of trimming   */
          /* result toggle (versus initial state).                            */
          if (READ_BIT(OPAMP->CSR, __OPAMP_CSR_OPAXCALOUT(hopamp1)) != tmp_Opa1calout_DefaultSate)
          {
            /* If calibration output is has toggled, try lower trimming */
            *opamp1_trimmingvalue -= delta;
          }
          else
          {
            /* If calibration output is has not toggled, try higher trimming */
            *opamp1_trimmingvalue += delta;
          }

          /* Set trimming values for next iteration in function of trimming   */
          /* result toggle (versus initial state).                            */
          if (READ_BIT(OPAMP->CSR, __OPAMP_CSR_OPAXCALOUT(hopamp2)) != tmp_Opa2calout_DefaultSate)
          {
            /* If calibration output is has toggled, try lower trimming */
            *opamp2_trimmingvalue -= delta;
          }
          else
          {
            /* If calibration output is has not toggled, try higher trimming */
            *opamp2_trimmingvalue += delta;
          }

        }
      }

      /* Disable calibration for P and N differential pairs */
      /* Disable the selected opamp */
      CLEAR_BIT (OPAMP->CSR, (OPAMP_CSR_OPAXCAL_H_ALL |
                              OPAMP_CSR_OPAXCAL_L_ALL |
                              OPAMP_CSR_OPAXPD_ALL     ));

      /* Backup of switches configuration to restore it at the end of the     */
      /* calibration.                                                         */
      SET_BIT(OPAMP->CSR, tmp_OpaxSwitchesContextBackup);

      /* Self calibration is successful */
      /* Store calibration (user trimming) results in init structure. */

      /* Set user trimming mode */
      hopamp1->Init.UserTrimming = OPAMP_TRIMMING_USER;
      hopamp2->Init.UserTrimming = OPAMP_TRIMMING_USER;

      /* Affect calibration parameters depending on mode normal/low power */
      if (hopamp1->Init.PowerMode != OPAMP_POWERMODE_LOWPOWER)
      {
        /* Write calibration result N */
        hopamp1->Init.TrimmingValueN = opamp1_trimmingvaluen;
        /* Write calibration result P */
        hopamp1->Init.TrimmingValueP = opamp1_trimmingvaluep;
      }
      else
      {
        /* Write calibration result N */
        hopamp1->Init.TrimmingValueNLowPower = opamp1_trimmingvaluen;
        /* Write calibration result P */
        hopamp1->Init.TrimmingValuePLowPower = opamp1_trimmingvaluep;
      }

      if (hopamp2->Init.PowerMode != OPAMP_POWERMODE_LOWPOWER)
      {
        /* Write calibration result N */
        hopamp2->Init.TrimmingValueN = opamp2_trimmingvaluen;
        /* Write calibration result P */
        hopamp2->Init.TrimmingValueP = opamp2_trimmingvaluep;
      }
      else
      {
        /* Write calibration result N */
        hopamp2->Init.TrimmingValueNLowPower = opamp2_trimmingvaluen;
        /* Write calibration result P */
        hopamp2->Init.TrimmingValuePLowPower = opamp2_trimmingvaluep;
      }

      /* Update OPAMP state */
      hopamp1->State = HAL_OPAMP_STATE_READY;
      hopamp2->State = HAL_OPAMP_STATE_READY;

    }
    else
    {
      /* OPAMP can not be calibrated from this mode */
      status = HAL_ERROR;
    }
  }

  return status;
}

#endif /* STM32L151xD || STM32L152xD || STM32L162xD */

/**
  * @}
  */

/** @defgroup OPAMPEx_Exported_Functions_Group2 Extended Peripheral Control functions
 *  @brief   Extended control functions
 *
@verbatim
 ===============================================================================
             ##### Peripheral Control functions #####
 ===============================================================================
    [..]
      (+) OPAMP unlock.

@endverbatim
  * @{
  */

/**
  * @brief  Unlock the selected opamp configuration.
  *         This function must be called only when OPAMP is in state "locked".
  * @param  hopamp: OPAMP handle
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_OPAMPEx_Unlock(OPAMP_HandleTypeDef* hopamp)
{
  HAL_StatusTypeDef status = HAL_OK;

  /* Check the OPAMP handle allocation */
  /* Check if OPAMP locked */
  if((hopamp == HAL_NULL) || (hopamp->State == HAL_OPAMP_STATE_RESET)
                      || (hopamp->State == HAL_OPAMP_STATE_READY)
                      || (hopamp->State == HAL_OPAMP_STATE_CALIBBUSY)
                      || (hopamp->State == HAL_OPAMP_STATE_BUSY))

  {
    status = HAL_ERROR;
  }
  else
  {
    /* Check the parameter */
    assert_param(IS_OPAMP_ALL_INSTANCE(hopamp->Instance));

   /* OPAMP state changed to locked */
    hopamp->State = HAL_OPAMP_STATE_BUSY;
  }
  return status;
}

/**
  * @}
  */

/**
  * @}
  */

#endif /* STM32L151xCA || STM32L151xD || STM32L152xCA || STM32L152xD || STM32L162xCA || STM32L162xD || STM32L151xE || STM32L152xE || STM32L162xE || STM32L162xC || STM32L152xC || STM32L151xC */

#endif /* HAL_OPAMP_MODULE_ENABLED */
/**
  * @}
  */

/**
  * @}
  */

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


text:
import os

import commonTools.common as common
import commonTools.utils as utils
from commonTools.config import QuickConfig
import commonTools.folderQuery as folderQuery
import pipeCore.folderPaths as folderPaths

import pipeCore.common as pcCommon
import pipeCore.config as pcConfig
import pipeCore.dbAccessor as dbAccessor
from pipeCore.readAssets import ReadAssets

AVID_DIRS = {
	pcCommon.WORK_MODE_ANIMATION: '03_ANI',
	pcCommon.WORK_MODE_EFX: '08_EFX',
	pcCommon.WORK_MODE_RENDERING: '03_ANI'
}

def _isTimeCode(timeCode):
	parts = timeCode.split(':')
	if len(parts) != 4:
		return False
	for part in parts:
		if len(part) != 2 or not part.isdigit():
			return False
	return True

def _framesFromTimeCode(timeCode, fps, minusTenHours=True):
	hours, minutes, seconds, frames = timeCode.split(':')
	hours = int(hours)
	minutes = int(minutes)
	seconds = int(seconds)
	frames = int(frames)
	if minusTenHours and hours >= 10:
		# This is a convention to start from exactly 10 hours (10:00:00:00) instead of frame 1 (00:00:00:01)
		# For our purposes we need to convert to the latter format
		hours -= 10
		frames += 1
	minutes = minutes + 60 * hours
	seconds = seconds + 60 * minutes
	return frames + fps * seconds

def _findPlayblastInfoFromName(client, project, sequence, shot, playblastName):
	for workMode in AVID_DIRS.keys():
		avidDir = '%s/07_To_Avid/%s' % (ReadAssets().getProjectRootDir(client, project), AVID_DIRS[workMode])
		avidShotDir = '%s/SEQ%s/SH%s' % (avidDir, sequence, shot)
		if not os.path.isdir(avidShotDir):
			break
		subFiles = [subFile.upper() for subFile in folderQuery.getSubFiles(avidShotDir)]
		if playblastName in subFiles:
			infoFileName = playblastName.split('.')[0] + '_INFO'
			if infoFileName in subFiles:
				return '%s/%s' % (avidShotDir, infoFileName)
	return None

def _rangesOverlap(start1, end1, start2, end2):
    return end1 > start2 > start1 or end1 > end2 > start1 or end2 > start1 > start2 or end2 > end1 > start2

def publishPlayblast(client, project, sequence, shot, workMode, inFrame, outFrame, movPath):
	""" Publish the given .mov file to Avid for the given shot
	Args:
		client (str): The client name
		project (str): The project name
		sequence (str): The sequence name
		shot (str): The shot name
		workMode (int): The working mode of the user publishing the playblast
		inFrame (int): The in frame of the shot
		outFrame (int): The out frame of the shot
		movPath (str): The path to the .mov file to publish
	"""
	movName = movPath.split('/')[-1].split('.')[0]
	avidDir = '%s/07_To_Avid/%s' % (ReadAssets().getProjectRootDir(client, project), AVID_DIRS[workMode])

	if not os.path.isdir(avidDir):
		os.makedirs(avidDir)
	avidShotDir = '%s/SEQ%s/SH%s' % (avidDir, sequence, shot)
	if not os.path.isdir(avidShotDir):
		raise Exception("Avid folder for shot doesn't exist- %s" % avidShotDir)
	utils.copyFile(movPath, [avidShotDir])

	copiedMovFile = '%s/%s.mov' % (avidShotDir, movName)
	configFile = '%s/%s_INFO' % (avidShotDir, movName)
	config = QuickConfig(configPath=configFile, clear=True)
	config.writeValueToConfig('details', 'user', common.USER_NAME)
	config.writeValueToConfig('details', 'inFrame', inFrame)
	config.writeValueToConfig('details', 'outFrame', outFrame)

	# Send an email to the Editing team to say a new clip has been published
	inFrameDB, outFrameDB = dbAccessor.Database().getShotInAndOutFrame(client, project, sequence, shot)
	messageSubject = '%s/%s Shot %s : %s Updated' % (client, project, sequence, shot)
	copiedMovFile = copiedMovFile.replace('/', '\\')
	messageBody = 'The %s/%s ANIM clip for Sequence %s : Shot %s has been published as a new file here:\n\n  %s\n\nThe frame range is %s - %s' % (client, project, sequence, shot, copiedMovFile, inFrame, outFrame)
	if (inFrameDB, outFrameDB) != (inFrame, outFrame):
		messageSubject = '%s With New Frame Range' % messageSubject
		messageBody = '%s\nThis is a change from the current range of %s - %s' % (messageBody, inFrameDB, outFrameDB)
	messageBody = '%s\n\nThis is ready to be added to the edit.\n\nPlease do not respond to this mail.\n\nThanks\n' % messageBody
	pcConfig.sendEditInfoEmail(client, project, messageSubject, messageBody)

	common.logInfo('Published playlast to Avid DIR - %s' % avidShotDir)

def getFrameRangeForShot(clientName, projectName, sequence, shot):
	""" Gets any frame range registered from AVID for the given shot
	This checks the "editDataInfo" file which is kept up to date by the "checkForShotFrameRangeUpdate" method
	Args:
		clientName (str): The client name
		projectName (str): The project name
		sequence (str): The sequence name
		shot (str): The shot name
	Returns:
		inFrame (int): The in frame registered or None
		outFrame (int): The out frame registered or None
	"""
	inFrame, outFrame = None, None
	editDataFile = '%s/editDataInfo' % folderPaths.getEditDataDir(clientName, projectName)
	if os.path.isfile(editDataFile):
		config = QuickConfig(configPath=editDataFile)
		inFrame = config.readIntFromConfig('inFrame', '%s|%s' % (sequence, shot))
		outFrame = config.readIntFromConfig('outFrame', '%s|%s' % (sequence, shot))
		if None not in (inFrame, outFrame):
			return inFrame, outFrame
	return inFrame, outFrame

def checkForShotFrameRangeUpdate(clientName, projectName, updateDatabase=True):
	""" This checks the AVID folder for any change to the frame ranges and update the database
	Args:
		clientName (str): The name of the client of the shot
		projectName (str): The name of the project of the shot
	"""
	editDataDir = folderPaths.getEditDataDir(clientName, projectName)
	avidDir = '%s/From_Avid' % editDataDir
	avidFileNamePrefix = '_'.join([clientName, projectName, ''])
	# Check all .edl files that they begin with prefix followed by a num?
	latestEdl = utils.findLatestVersionedFileNameUnderDir(avidDir, avidFileNamePrefix, '.edl') if os.path.isdir(avidDir) else None
	if not latestEdl:
		# No EDLs published from Avid yet
		return False
	outOfDate = True
	editDataFile = '%s/editDataInfo' % editDataDir
	if os.path.isfile(editDataFile):
		config = QuickConfig(configPath=editDataFile)
		sourceEdl = config.readValueFromConfig('details', 'sourceEdl')
		if sourceEdl == latestEdl:
			# The latest EDL has already been processed
			return False
	# The latest EDL file hasn't yet been processed
	avidFile = '%s/%s' % (avidDir, latestEdl)
	lines = []
	with open(avidFile) as f:
		lines = f.readlines()
	badFormattingLines = []
	error = ''
	newShotInOutFrames = {}
	numClipLines = 0
	dummyFile = len(lines) > 1 and 'dummyFile' in lines[0]
	for line in lines:
		line = line.strip()
		parts = [part.strip().upper() for part in line.split(' ') if part]
		if len(parts) > 2 and parts[0].isdigit() and parts[1].endswith('.MOV') and parts[2] == 'V':
			numClipLines += 1
			# This looks like a video clip line
			if len(parts) < 7:
				badFormattingLines.append(line)
				error = 'Expecting at least 7 parts to the line eg: 001 MY_CLIP.MOV V TIME_CODE_1 TIME_CODE_2 TIME_CODE_3 TIME_CODE_4'
				continue
			editStart = parts[-2]
			editEnd = parts[-1]
			clipStart = parts[-4]
			clipEnd = parts[-3]
			badFormat = False
			for timeCode in (editStart, editEnd, clipStart, clipEnd):
				if not _isTimeCode(timeCode):
					badFormattingLines.append(line)
					error = 'The last 4 parts of the line should be timeCodes of the format 00:00:00:00 - Unexpected format: "%s"' % timeCode
					badFormat = True
					break
			if badFormat:
				continue
			playblastName = parts[1]
			prefix = '%s_%s_' % (clientName, projectName)
			if not playblastName.startswith(prefix):
				badFormattingLines.append(line)
				error = 'The name of the clip should begin with "%s" - Unexpected clip name: %s' % (prefix, playblastName)
				continue
			playblastParts = playblastName[len(prefix):].split('_')
			if len(playblastParts) < 2:
				badFormattingLines.append(line)
				error = 'The name of the clip should contain the names of client, project, sequence and shot, separated by "_" - Unexpecxted clip name: %s' % playblastName
				continue
			sequence, shot = playblastParts[0], playblastParts[1]
			playblastInfo = _findPlayblastInfoFromName(clientName, projectName, sequence, shot, playblastName)
			if not playblastInfo:
				common.logError('Could not find an info file for the given clip file: %s' % playblastName)
				continue
			# Convert time codes into frames
			fps = dbAccessor.Database().getProjectFpsAsInt(clientName, projectName)
			editStartFrame = _framesFromTimeCode(editStart, fps)
			clipStartFrame = _framesFromTimeCode(clipStart, fps)
			# Have to minus 1 from the end frame becuase Avid gives the next frame as the one the clip goes up to
			editEndFrame = _framesFromTimeCode(editEnd, fps) - 1
			clipEndFrame = _framesFromTimeCode(clipEnd, fps) - 1

			if editEndFrame - editStartFrame != clipEndFrame - clipStartFrame:
				common.logError('Frame range in clip (1st time-code pair) is different size to range in edit (2nd time-code pair): %s' % line)
				continue

			clipConfig = QuickConfig(configPath=playblastInfo)
			clipInFrame = int(clipConfig.readFloatFromConfig('details', 'inFrame'))
			clipOutFrame = int(clipConfig.readFloatFromConfig('details', 'outFrame'))
			numFrames = (clipOutFrame - clipInFrame) + 1
			if clipStartFrame > numFrames:
				common.logError("EDL (%s) timecode (%s) out of clip's (%s) frame range" % (latestEdl, clipStart, playblastName))
				continue
			if clipEndFrame > numFrames:
				common.logError("EDL (%s) timecode (%s) out of clip's (%s) frame range" % (latestEdl, clipEnd, playblastName))
				continue
			framesCutFromStart = clipStartFrame - 1
			framesCutFromEnd = numFrames - clipEndFrame
			inFrame = clipInFrame + clipStartFrame - 1
			outFrame = clipInFrame + clipEndFrame - 1

			# The clip may be in the EDL many times (due to layers or just reuse) so we keep a list
			newShotInOutFrames.setdefault((sequence, shot), [])
			mergeEventsOn = True

			##########################################################################################################################################
			# This code will iterate over any previous instances of this clip and remove any that this instance overlaps with in the edit
			# This shouldn't actually be necessary because the EDL should have been produced with the "Merge events on selected video tracks to one track" setting
			# switched on, meaning it just gives us the cut clips in the order shown, with none overlapping
			# However if it wasn't switched on then we try to remove overlapping clips from different layers- higher layers will be shown and should appear later in the EDL
			shotInOutFrames = []
			for prevFrames in newShotInOutFrames[(sequence, shot)]:
				inFramePrev, outFramePrev, editStartFramePrev, editEndFramePrev = prevFrames
				if not _rangesOverlap(editStartFrame, editEndFrame, editStartFramePrev, editEndFramePrev):
					# This instance and the previous one overlap
					# We assume this means they are on different layers and we take the most recent layer (this one)
					shotInOutFrames.append(prevFrames)
					mergeEventsOn = False
			newShotInOutFrames[(sequence, shot)] = shotInOutFrames
			##########################################################################################################################################

			# Add the clip instance to the list
			newShotInOutFrames[(sequence, shot)].append((inFrame, outFrame, editStartFrame, editEndFrame))
	if badFormattingLines:
		common.logError('Error reading lines from EDL:\n  %s\n%s' % (badFormattingLines[-1], error))
		messageBody = 'The following EDL has lines that have an unexpected format:\n\n  %s\n\nThe following lines have errors:\n\n  %s\n\n ERROR: \'%s\'\n\nPlease do not reply to this email\n' % (avidFile, '\n  '.join(badFormattingLines), error)
		pcConfig.sendEditInfoEmail(clientName, projectName, '## No Reply ## -  Error reading EDL', messageBody)
	elif not numClipLines and not dummyFile:
		messageBody = 'The following EDL has no lines with the expected format:\n\n  %s\n\nExample expected format: "000001  CLIENT_PROJECT_010_010_ANIM_PT01_TK01_002_2.MOV V     C        10:00:00:00 10:00:02:10 10:00:00:00 10:00:02:10"\n\nPlease do not reply to this email\n' % avidFile
		common.logError(messageBody)
		pcConfig.sendEditInfoEmail(clientName, projectName, '## No Reply ## -  Error reading EDL', messageBody)

	# Write the frame information into the config file
	config = QuickConfig(configPath=editDataFile, clear=True)
	for sequence, shot in newShotInOutFrames:
		minInFrame = 999999
		maxOutFrame = -999999
		# We need to iterate over all instances of the clip (it may be reused) and ensure we keep all required frames
		for inFrame, outFrame, editStartFrame, editEndFrame in newShotInOutFrames[(sequence, shot)]:
			minInFrame = min(minInFrame, inFrame)
			maxOutFrame = max(maxOutFrame, outFrame)
		config.writeValueToConfig('inFrame', '%s|%s' % (sequence, shot), minInFrame)
		config.writeValueToConfig('outFrame', '%s|%s' % (sequence, shot), maxOutFrame)
		if updateDatabase:
			dbAccessor.Database().setShotInAndOutFrame(clientName, projectName, sequence, shot, minInFrame, maxOutFrame)
	config.writeValueToConfig('details', 'sourceEdl', latestEdl)

redpajama_set_name: RedPajamaGithub


text:
package org.hsqldb.persist;

import org.hsqldb.Database;
import org.hsqldb.error.Error;
import org.hsqldb.error.ErrorCode;

/**
 * Parser and container for text table settings.
 *
 * @author Bob Preston (sqlbob@users dot sourceforge.net)
 * @author Fred Toussi (fredt@users dot sourceforge.net)
 * @version 2.3.0
 * @since 2.2.6
 */
public class TextFileSettings {

    //state of Cache
    public static final String NL = System.getProperty("line.separator");
    public String              fs;
    public String              vs;
    public String              lvs;
    public String              stringEncoding;
    public boolean             isQuoted;
    public boolean             isAllQuoted;
    public boolean             ignoreFirst;

    //
    Database database;
    String   dataFileName;
    int      maxCacheRows;
    int      maxCacheBytes;

    //
    static final byte[] BYTES_LINE_SEP    = NL.getBytes();
    static final char   DOUBLE_QUOTE_CHAR = '\"';
    static final char   BACKSLASH_CHAR    = '\\';
    static final char   LF_CHAR           = '\n';
    static final char   CR_CHAR           = '\r';

    /**
     *  The source string for a cached table is evaluated and the parameters
     *  are used to open the source file.<p>
     *
     *  Settings are used in this order: (1) settings specified in the
     *  source string for the table (2) global database settings
     *  (3) program defaults
     */
    TextFileSettings(Database database, String fileSettingsString) {

        this.database = database;

        HsqlProperties tableprops =
            HsqlProperties.delimitedArgPairsToProps(fileSettingsString, "=",
                ";", "textdb");
        HsqlDatabaseProperties dbProps = database.getProperties();

        switch (tableprops.errorCodes.length) {

            case 0 :
                // no source file name
                this.dataFileName = null;
                break;

            case 1 :

                // source file name is the only key without a value
                this.dataFileName = tableprops.errorKeys[0].trim();
                break;

            default :
                throw Error.error(ErrorCode.X_S0502);
        }

        //-- Get separators: from database properties, then from table properties
        fs  = dbProps.getStringProperty(HsqlDatabaseProperties.textdb_fs);
        fs  = tableprops.getProperty(HsqlDatabaseProperties.textdb_fs, fs);
        vs  = dbProps.getStringProperty(HsqlDatabaseProperties.textdb_vs);
        vs  = tableprops.getProperty(HsqlDatabaseProperties.textdb_vs, vs);
        lvs = dbProps.getStringProperty(HsqlDatabaseProperties.textdb_lvs);
        lvs = tableprops.getProperty(HsqlDatabaseProperties.textdb_lvs, lvs);

        if (vs == null) {
            vs = fs;
        }

        if (lvs == null) {
            lvs = fs;
        }

        fs  = translateSep(fs);
        vs  = translateSep(vs);
        lvs = translateSep(lvs);

        if (fs.length() == 0 || vs.length() == 0 || lvs.length() == 0) {
            throw Error.error(ErrorCode.X_S0503);
        }

        //-- Get booleans
        ignoreFirst =
            dbProps.isPropertyTrue(HsqlDatabaseProperties.textdb_ignore_first);
        ignoreFirst = tableprops.isPropertyTrue(
            HsqlDatabaseProperties.textdb_ignore_first, ignoreFirst);
        isQuoted =
            dbProps.isPropertyTrue(HsqlDatabaseProperties.textdb_quoted);
        isQuoted =
            tableprops.isPropertyTrue(HsqlDatabaseProperties.textdb_quoted,
                                      isQuoted);
        isAllQuoted =
            dbProps.isPropertyTrue(HsqlDatabaseProperties.textdb_all_quoted);
        isAllQuoted =
            tableprops.isPropertyTrue(HsqlDatabaseProperties.textdb_all_quoted,
                                      isAllQuoted);
        stringEncoding =
            dbProps.getStringProperty(HsqlDatabaseProperties.textdb_encoding);
        stringEncoding =
            tableprops.getProperty(HsqlDatabaseProperties.textdb_encoding,
                                   stringEncoding);

        //-- get size and scale
        int cacheScale = dbProps.getIntegerProperty(
            HsqlDatabaseProperties.textdb_cache_scale);

        cacheScale = tableprops.getIntegerProperty(
            HsqlDatabaseProperties.textdb_cache_scale, cacheScale);

        int cacheSizeScale = dbProps.getIntegerProperty(
            HsqlDatabaseProperties.textdb_cache_size_scale);

        cacheSizeScale = tableprops.getIntegerProperty(
            HsqlDatabaseProperties.textdb_cache_size_scale, cacheSizeScale);

//
        maxCacheRows = (1 << cacheScale) * 3;
        maxCacheRows = dbProps.getIntegerProperty(
            HsqlDatabaseProperties.textdb_cache_rows, maxCacheRows);
        maxCacheRows = tableprops.getIntegerProperty(
            HsqlDatabaseProperties.textdb_cache_rows, maxCacheRows);
        maxCacheBytes = ((1 << cacheSizeScale) * maxCacheRows) / 1024;

        if (maxCacheBytes < 4) {
            maxCacheBytes = 4;
        }

        maxCacheBytes = dbProps.getIntegerProperty(
            HsqlDatabaseProperties.textdb_cache_size, (int) maxCacheBytes);
        maxCacheBytes = tableprops.getIntegerProperty(
            HsqlDatabaseProperties.textdb_cache_size, (int) maxCacheBytes);
        maxCacheBytes *= 1024;
    }

    String getFileName() {
        return dataFileName;
    }

    int getMaxCacheRows() {
        return maxCacheRows;
    }

    int getMaxCacheBytes() {
        return maxCacheBytes;
    }

    private static String translateSep(String sep) {
        return translateSep(sep, false);
    }

    /**
     * Translates the escaped characters in a separator string and returns
     * the non-escaped string.
     */
    private static String translateSep(String sep, boolean isProperty) {

        if (sep == null) {
            return null;
        }

        int next = sep.indexOf(BACKSLASH_CHAR);

        if (next != -1) {
            int          start    = 0;
            char[]       sepArray = sep.toCharArray();
            char         ch       = 0;
            int          len      = sep.length();
            StringBuffer sb       = new StringBuffer(len);

            do {
                sb.append(sepArray, start, next - start);

                start = ++next;

                if (next >= len) {
                    sb.append(BACKSLASH_CHAR);

                    break;
                }

                if (!isProperty) {
                    ch = sepArray[next];
                }

                if (ch == 'n') {
                    sb.append(LF_CHAR);

                    start++;
                } else if (ch == 'r') {
                    sb.append(CR_CHAR);

                    start++;
                } else if (ch == 't') {
                    sb.append('\t');

                    start++;
                } else if (ch == BACKSLASH_CHAR) {
                    sb.append(BACKSLASH_CHAR);

                    start++;
                } else if (ch == 'u') {
                    start++;

                    sb.append(
                        (char) Integer.parseInt(
                            sep.substring(start, start + 4), 16));

                    start += 4;
                } else if (sep.startsWith("semi", next)) {
                    sb.append(';');

                    start += 4;
                } else if (sep.startsWith("space", next)) {
                    sb.append(' ');

                    start += 5;
                } else if (sep.startsWith("quote", next)) {
                    sb.append(DOUBLE_QUOTE_CHAR);

                    start += 5;
                } else if (sep.startsWith("apos", next)) {
                    sb.append('\'');

                    start += 4;
                } else {
                    sb.append(BACKSLASH_CHAR);
                    sb.append(sepArray[next]);

                    start++;
                }
            } while ((next = sep.indexOf(BACKSLASH_CHAR, start)) != -1);

            sb.append(sepArray, start, len - start);

            sep = sb.toString();
        }

        return sep;
    }
}


text:
require 'test_helper'

class ShowHousePicturesControllerTest < ActionController::TestCase
  setup do
    @show_house_picture = show_house_pictures(:one)
  end

  test "should get index" do
    get :index
    assert_response :success
    assert_not_nil assigns(:show_house_pictures)
  end

  test "should get new" do
    get :new
    assert_response :success
  end

  test "should create show_house_picture" do
    assert_difference('ShowHousePicture.count') do
      post :create, show_house_picture: { brief: @show_house_picture.brief, description: @show_house_picture.description, path: @show_house_picture.path }
    end

    assert_redirected_to show_house_picture_path(assigns(:show_house_picture))
  end

  test "should show show_house_picture" do
    get :show, id: @show_house_picture
    assert_response :success
  end

  test "should get edit" do
    get :edit, id: @show_house_picture
    assert_response :success
  end

  test "should update show_house_picture" do
    put :update, id: @show_house_picture, show_house_picture: { brief: @show_house_picture.brief, description: @show_house_picture.description, path: @show_house_picture.path }
    assert_redirected_to show_house_picture_path(assigns(:show_house_picture))
  end

  test "should destroy show_house_picture" do
    assert_difference('ShowHousePicture.count', -1) do
      delete :destroy, id: @show_house_picture
    end

    assert_redirected_to show_house_pictures_path
  end
end


text:
using System;
using System.Linq;
using EasyNetQ;
using Watcher.DAL;
using Watcher.Messages.Movie;
using Watcher.Messages.Person;
using Watcher.Messages.Show;
using Watcher.Messages.Subscription;

namespace Watcher.Service.Services
{
    class UserSubscriptionService : IMqService
    {
        private readonly IBus _bus;

        public UserSubscriptionService(IBus bus)
        {
            _bus = bus;
        }

        public void HandleRequests()
        {
            _bus.Respond<ShowSubscriptionRequest, ShowSubscriptionListDto>(GetShowSubscriptions);
            _bus.Respond<MovieSubscriptionRequest, MovieSubscriptionListDto>(GetMovieSubscriptions);
            _bus.Respond<PersonSubscriptionRequest, PersonSubscriptionListDto>(GetPersonSubscriptions);
        }

        private PersonSubscriptionListDto GetPersonSubscriptions(PersonSubscriptionRequest request)
        {
            using var context = new WatcherDbContext();
            var user = context.Users.FirstOrDefault(x => x.Email == request.Email);

            if (user != null)
            {
                var subscriptions = user.UserPersons.Select(x => new PersonSubscriptionsDto
                    {
                        Id = x.Person.Id,
                        Name = x.Person.Name,
                        ProductionName = x.Person.ProductionName,
                        ReleaseDate = x.Person.ReleaseDate,
                        PosterPath = x.Person.PosterPath
                    })
                    .OrderByDescending(x => x.ReleaseDate)
                    .Skip(request.Skip)
                    .Take(request.Take)
                    .ToList();

                return new PersonSubscriptionListDto
                {
                    Subscriptions = subscriptions,
                    Total = user.UserPersons.Count
                };
            }

            return new PersonSubscriptionListDto();
        }

        private ShowSubscriptionListDto GetShowSubscriptions(ShowSubscriptionRequest request)
        {
            using var context = new WatcherDbContext();
            var user = context.Users.FirstOrDefault(x => x.Email == request.Email);

            if (user != null)
            {
                var shows = user.UserShows
                    .Skip(request.Skip)
                    .Take(request.Take)
                    .Select(x => new ShowSubscriptionsDto
                    {
                        Id = x.Show.Id,
                        Name = x.Show.Name,
                        ReleaseDate = x.Show.ReleaseNextEpisode ?? new DateTime(1),
                        EpisodeNumber = x.Show.NextEpisode,
                        CurrentSeason = x.Show.CurrentSeason,
                        RemainingEpisodes = x.Show.EpisodeCount - x.Show.NextEpisode + 1, // also count next episode
                        PosterPath = x.Show.PosterPath
                    })
                    .ToList();

                return new ShowSubscriptionListDto
                {
                    Subscriptions = shows,
                    Total = user.UserShows.Count
                };
            }

            return new ShowSubscriptionListDto();
        }

        private MovieSubscriptionListDto GetMovieSubscriptions(MovieSubscriptionRequest request)
        {
            using var context = new WatcherDbContext();
            var user = context.Users.FirstOrDefault(x => x.Email == request.Email);

            if (user != null)
            {
                var movies = user.UserMovies.Select(x => new MovieSubscriptionsDto
                    {
                        Id = x.Movie.Id,
                        Name = x.Movie.Name,
                        ReleaseDate = x.Movie.ReleaseDate ?? DateTime.MinValue,
                        PosterPath = x.Movie.PosterPath
                    })
                    .Skip(request.Skip)
                    .Take(request.Take)
                    .ToList();

                return new MovieSubscriptionListDto
                {
                    Subscriptions = movies,
                    Total = user.UserMovies.Count
                };
            }

            return new MovieSubscriptionListDto();
        }
    }
}


text:
body {
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
}

.layout-aside {
    position: relative;
    min-height: 400px;
}

.layout-aside .layout-sider {
    width: 200px;
    background: #404040;
    position: absolute;
    overflow: auto;
    padding-bottom: 24px;
    height: 100%;
}

.layout-aside .layout-logo {
    height: 32px;
    margin: 16px 24px;
    text-align: center;
    color: #F0F0F0;
    font-size: 18px;
}

.layout-aside .layout-sider > .menu {
    margin-bottom: 20px;
}

.layout-aside .layout-header {
    background: #fff;
    height: 64px;
    border-bottom: 1px solid #e9e9e9;
}

.layout-aside .layout-header .logout {
    float: right;
    font-size: 16px;
    margin-right: 20px;
    line-height: 64px;
}

.layout-aside .layout-main {
    margin-left: 200px;
    height: 100%;
    overflow-y: auto;
    overflow-x: hidden;
}

.layout-aside .layout-container {
    margin: 12px 16px 24px;
    min-height: 400px;

}

.layout-aside .layout-content {
    background: #fff;
    padding: 24px;
    margin-top: 12px;
    margin-bottom: 64px;
    border-radius: 4px;
}

.layout-aside .layout-footer {
    height: 64px;
    line-height: 64px;
    text-align: center;
    font-size: 12px;
    color: #999;
    background: #fff;
    border-top: 1px solid #e9e9e9;
    width: 100%;
}


text:
package org.jaudiotagger.audio.flac.metadatablock;

/**
 * Metadata Block
 *
 * <p>A FLAC bitstream consists of the "fLaC" marker at the beginning of the stream,
 * followed by a mandatory metadata block (called the STREAMINFO block), any number of other metadata blocks,
 * then the audio frames.
 */
public class MetadataBlock
{
    private MetadataBlockHeader mbh;
    private MetadataBlockData mbd;

    public MetadataBlock(MetadataBlockHeader mbh, MetadataBlockData mbd)
    {
        this.mbh = mbh;
        this.mbd = mbd;
    }

    public MetadataBlockHeader getHeader()
    {
        return mbh;
    }

    public MetadataBlockData getData()
    {
        return mbd;
    }

    public int getLength()
    {
        return MetadataBlockHeader.HEADER_LENGTH + mbh.getDataLength();
    }
}


text:
class CefContextMenuParamsImpl
    : public CefValueBase<CefContextMenuParams, content::ContextMenuParams> {
 public:
  explicit CefContextMenuParamsImpl(content::ContextMenuParams* value);

  // CefContextMenuParams methods.
  virtual int GetXCoord() OVERRIDE;
  virtual int GetYCoord() OVERRIDE;
  virtual TypeFlags GetTypeFlags() OVERRIDE;
  virtual CefString GetLinkUrl() OVERRIDE;
  virtual CefString GetUnfilteredLinkUrl() OVERRIDE;
  virtual CefString GetSourceUrl() OVERRIDE;
  virtual bool IsImageBlocked() OVERRIDE;
  virtual CefString GetPageUrl() OVERRIDE;
  virtual CefString GetFrameUrl() OVERRIDE;
  virtual CefString GetFrameCharset() OVERRIDE;
  virtual MediaType GetMediaType() OVERRIDE;
  virtual MediaStateFlags GetMediaStateFlags() OVERRIDE;
  virtual CefString GetSelectionText() OVERRIDE;
  virtual bool IsEditable() OVERRIDE;
  virtual bool IsSpeechInputEnabled() OVERRIDE;
  virtual EditStateFlags GetEditStateFlags() OVERRIDE;

  DISALLOW_COPY_AND_ASSIGN(CefContextMenuParamsImpl);
};

#endif  // CEF_LIBCEF_BROWSER_CONTEXT_MENU_PARAMS_IMPL_H_


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace glassfactory.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Title = "Home Page";

            return View();
        }
    }
}


text:
module OrganizedAudit
  VERSION = "0.1.0"
end


text:
flowclass:
  - Application
  - Experience
  - Edge 1.0.0
description: Learn more about the Losant Function Node.
---

# Function Node

The Function Node allows a user defined JavaScript to operate on the current payload.

![Function Node](/images/workflows/logic/function-node.png "Function Node")

## Configuration

The Function Node has a single configuration block - the user defined JavaScript code to execute. Only base JavaScript functionality is available for the execution of this code - no external libraries or modules are available for use. The current payload of the workflow is available at the variable `payload`, and can be treated as a normal JavaScript object.

![Function Node Config](/images/workflows/logic/function-node-config.png "Function Node Config")

In the above example, the Function Node is averaging the values of an array of data, and storing that average in the payload field `data.average`.

## Payload Modification

There are two ways a Function Node can modify the current workflow payload.

First, if a return statement is hit and something is returned, that returned value is used as the new payload. For example:

```javascript
return { value: "Total Replacement" };
```

If that were the entire contents of a Function Node, no matter what the original payload was, the payload after the execution of the Function Node would always be the object:

```json
{ "value": "Total Replacement" }
```

The other way to change the payload is to modify the existing payload object. If a return statement is used but no value is returned, or if no return statement is used at all in the node, the value of the `payload` variable at the end of the node's execution is used as the new payload. So, with the example Function Node code of:

```javascript
payload.data.newItem = "Something Special";
payload.data.oldNumber = payload.oldNumber + 1;
```

And an example payload of:

```json
{
  ...
  "data":{
    "oldNumber": 5
  }
  ...
}
```

The payload after the execution of that Function Node would be:

```json
{
  ...
  "data":{
    "newItem": "Something Special",
    "oldNumber": 6
  }
  ...
}
```