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

/** @addtogroup STM32F1xx_HAL_Driver
  * @{
  */

#ifdef HAL_RCC_MODULE_ENABLED

/** @defgroup RCCEx RCCEx
  * @brief RCC Extension HAL module driver.
  * @{
  */

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/** @defgroup RCCEx_Private_Constants RCCEx Private Constants
 * @{
 */
/**
  * @}
  */

/* Private macro -------------------------------------------------------------*/
/** @defgroup RCCEx_Private_Macros RCCEx Private Macros
 * @{
 */
/**
  * @}
  */

/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/

/** @defgroup RCCEx_Exported_Functions RCCEx Exported Functions
  * @{
  */

/** @defgroup RCCEx_Exported_Functions_Group1 Peripheral Control functions
 *  @brief  Extended Peripheral Control functions
 *
@verbatim
 ===============================================================================
                ##### Extended Peripheral Control functions  #####
 ===============================================================================
    [..]
    This subsection provides a set of functions allowing to control the RCC Clocks
    frequencies.
    [..]
    (@) Important note: Care must be taken when HAL_RCCEx_PeriphCLKConfig() is used to
        select the RTC clock source; in this case the Backup domain will be reset in
        order to modify the RTC Clock source, as consequence RTC registers (including
        the backup registers) and RCC_BDCR register are set to their reset values.

@endverbatim
  * @{
  */

/**
  * @brief  Initializes the RCC extended peripherals clocks according to the specified parameters in the
  *         RCC_PeriphCLKInitTypeDef.
  * @param  PeriphClkInit pointer to an RCC_PeriphCLKInitTypeDef structure that
  *         contains the configuration information for the Extended Peripherals clocks(RTC clock).
  *
  * @note   Care must be taken when HAL_RCCEx_PeriphCLKConfig() is used to select
  *         the RTC clock source; in this case the Backup domain will be reset in
  *         order to modify the RTC Clock source, as consequence RTC registers (including
  *         the backup registers) are set to their reset values.
  *
  * @note   In case of STM32F105xC or STM32F107xC devices, PLLI2S will be enabled if requested on
  *         one of 2 I2S interfaces. When PLLI2S is enabled, you need to call HAL_RCCEx_DisablePLLI2S to
  *         manually disable it.
  *
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef  *PeriphClkInit)
{
  uint32_t tickstart = 0, temp_reg = 0;
#if defined(STM32F105xC) || defined(STM32F107xC)
  uint32_t  pllactive = 0;
#endif /* STM32F105xC || STM32F107xC */

  /* Check the parameters */
  assert_param(IS_RCC_PERIPHCLOCK(PeriphClkInit->PeriphClockSelection));

  /*------------------------------- RTC/LCD Configuration ------------------------*/
  if ((((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_RTC) == RCC_PERIPHCLK_RTC))
  {
    /* check for RTC Parameters used to output RTCCLK */
    assert_param(IS_RCC_RTCCLKSOURCE(PeriphClkInit->RTCClockSelection));

    /* Enable Power Clock*/
    __HAL_RCC_PWR_CLK_ENABLE();

    /* Enable write access to Backup domain */
    SET_BIT(PWR->CR, PWR_CR_DBP);

    /* Wait for Backup domain Write protection disable */
    tickstart = HAL_GetTick();

    while((PWR->CR & PWR_CR_DBP) == RESET)
    {
      if((HAL_GetTick() - tickstart) > RCC_DBP_TIMEOUT_VALUE)
      {
        return HAL_TIMEOUT;
      }
    }

    /* Reset the Backup domain only if the RTC Clock source selection is modified */
    if((RCC->BDCR & RCC_BDCR_RTCSEL) != (PeriphClkInit->RTCClockSelection & RCC_BDCR_RTCSEL))
    {
      /* Store the content of BDCR register before the reset of Backup Domain */
      temp_reg = (RCC->BDCR & ~(RCC_BDCR_RTCSEL));
      /* RTC Clock selection can be changed only if the Backup Domain is reset */
      __HAL_RCC_BACKUPRESET_FORCE();
      __HAL_RCC_BACKUPRESET_RELEASE();
      /* Restore the Content of BDCR register */
      RCC->BDCR = temp_reg;

      /* Wait for LSERDY if LSE was enabled */
      if (HAL_IS_BIT_SET(temp_reg, RCC_BDCR_LSERDY))
      {
        /* Get timeout */
        tickstart = HAL_GetTick();

        /* Wait till LSE is ready */
        while(__HAL_RCC_GET_FLAG(RCC_FLAG_LSERDY) == RESET)
        {
          if((HAL_GetTick() - tickstart) > RCC_LSE_TIMEOUT_VALUE)
          {
            return HAL_TIMEOUT;
          }
        }
      }
      __HAL_RCC_RTC_CONFIG(PeriphClkInit->RTCClockSelection);
    }
  }

  /*------------------------------ ADC clock Configuration ------------------*/
  if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_ADC) == RCC_PERIPHCLK_ADC)
  {
    /* Check the parameters */
    assert_param(IS_RCC_ADCPLLCLK_DIV(PeriphClkInit->AdcClockSelection));

    /* Configure the ADC clock source */
    __HAL_RCC_ADC_CONFIG(PeriphClkInit->AdcClockSelection);
  }

#if defined(STM32F105xC) || defined(STM32F107xC)
  /*------------------------------ I2S2 Configuration ------------------------*/
  if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2S2) == RCC_PERIPHCLK_I2S2)
  {
    /* Check the parameters */
    assert_param(IS_RCC_I2S2CLKSOURCE(PeriphClkInit->I2s2ClockSelection));

    /* Configure the I2S2 clock source */
    __HAL_RCC_I2S2_CONFIG(PeriphClkInit->I2s2ClockSelection);
  }

  /*------------------------------ I2S3 Configuration ------------------------*/
  if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2S3) == RCC_PERIPHCLK_I2S3)
  {
    /* Check the parameters */
    assert_param(IS_RCC_I2S3CLKSOURCE(PeriphClkInit->I2s3ClockSelection));

    /* Configure the I2S3 clock source */
    __HAL_RCC_I2S3_CONFIG(PeriphClkInit->I2s3ClockSelection);
  }

  /*------------------------------ PLL I2S Configuration ----------------------*/
  /* Check that PLLI2S need to be enabled */
  if (HAL_IS_BIT_SET(RCC->CFGR2, RCC_CFGR2_I2S2SRC) || HAL_IS_BIT_SET(RCC->CFGR2, RCC_CFGR2_I2S3SRC))
  {
    /* Update flag to indicate that PLL I2S should be active */
    pllactive = 1;
  }

  /* Check if PLL I2S need to be enabled */
  if (pllactive == 1)
  {
    /* Enable PLL I2S only if not active */
    if (HAL_IS_BIT_CLR(RCC->CR, RCC_CR_PLL3ON))
    {
      /* Check the parameters */
      assert_param(IS_RCC_PLLI2S_MUL(PeriphClkInit->PLLI2S.PLLI2SMUL));
      assert_param(IS_RCC_HSE_PREDIV2(PeriphClkInit->PLLI2S.HSEPrediv2Value));

      /* Prediv2 can be written only when the PLL2 is disabled. */
      /* Return an error only if new value is different from the programmed value */
      if (HAL_IS_BIT_SET(RCC->CR,RCC_CR_PLL2ON) && \
        (__HAL_RCC_HSE_GET_PREDIV2() != PeriphClkInit->PLLI2S.HSEPrediv2Value))
      {
        return HAL_ERROR;
      }

      /* Configure the HSE prediv2 factor --------------------------------*/
      __HAL_RCC_HSE_PREDIV2_CONFIG(PeriphClkInit->PLLI2S.HSEPrediv2Value);

      /* Configure the main PLLI2S multiplication factors. */
      __HAL_RCC_PLLI2S_CONFIG(PeriphClkInit->PLLI2S.PLLI2SMUL);

      /* Enable the main PLLI2S. */
      __HAL_RCC_PLLI2S_ENABLE();

      /* Get Start Tick*/
      tickstart = HAL_GetTick();

      /* Wait till PLLI2S is ready */
      while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLI2SRDY)  == RESET)
      {
        if((HAL_GetTick() - tickstart ) > PLLI2S_TIMEOUT_VALUE)
        {
          return HAL_TIMEOUT;
        }
      }
    }
    else
    {
      /* Return an error only if user wants to change the PLLI2SMUL whereas PLLI2S is active */
      if (READ_BIT(RCC->CFGR2, RCC_CFGR2_PLL3MUL) != PeriphClkInit->PLLI2S.PLLI2SMUL)
      {
          return HAL_ERROR;
      }
    }
  }
#endif /* STM32F105xC || STM32F107xC */

#if defined(STM32F102x6) || defined(STM32F102xB) || defined(STM32F103x6)\
 || defined(STM32F103xB) || defined(STM32F103xE) || defined(STM32F103xG)\
 || defined(STM32F105xC) || defined(STM32F107xC)
  /*------------------------------ USB clock Configuration ------------------*/
  if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_USB) == RCC_PERIPHCLK_USB)
  {
    /* Check the parameters */
    assert_param(IS_RCC_USBPLLCLK_DIV(PeriphClkInit->UsbClockSelection));

    /* Configure the USB clock source */
    __HAL_RCC_USB_CONFIG(PeriphClkInit->UsbClockSelection);
  }
#endif /* STM32F102x6 || STM32F102xB || STM32F103x6 || STM32F103xB || STM32F103xE || STM32F103xG || STM32F105xC || STM32F107xC */

  return HAL_OK;
}

/**
  * @brief  Get the PeriphClkInit according to the internal
  * RCC configuration registers.
  * @param  PeriphClkInit pointer to an RCC_PeriphCLKInitTypeDef structure that
  *         returns the configuration information for the Extended Peripherals clocks(RTC, I2S, ADC clocks).
  * @retval None
  */
void HAL_RCCEx_GetPeriphCLKConfig(RCC_PeriphCLKInitTypeDef  *PeriphClkInit)
{
  uint32_t srcclk = 0;

  /* Set all possible values for the extended clock type parameter------------*/
  PeriphClkInit->PeriphClockSelection = RCC_PERIPHCLK_RTC;

  /* Get the RTC configuration -----------------------------------------------*/
  srcclk = __HAL_RCC_GET_RTC_SOURCE();
  /* Source clock is LSE or LSI*/
  PeriphClkInit->RTCClockSelection = srcclk;

  /* Get the ADC clock configuration -----------------------------------------*/
  PeriphClkInit->PeriphClockSelection |= RCC_PERIPHCLK_ADC;
  PeriphClkInit->AdcClockSelection = __HAL_RCC_GET_ADC_SOURCE();

#if defined(STM32F105xC) || defined(STM32F107xC)
  /* Get the I2S2 clock configuration -----------------------------------------*/
  PeriphClkInit->PeriphClockSelection |= RCC_PERIPHCLK_I2S2;
  PeriphClkInit->I2s2ClockSelection = __HAL_RCC_GET_I2S2_SOURCE();

  /* Get the I2S3 clock configuration -----------------------------------------*/
  PeriphClkInit->PeriphClockSelection |= RCC_PERIPHCLK_I2S3;
  PeriphClkInit->I2s3ClockSelection = __HAL_RCC_GET_I2S3_SOURCE();

#endif /* STM32F105xC || STM32F107xC */

#if defined(STM32F103xE) || defined(STM32F103xG)
  /* Get the I2S2 clock configuration -----------------------------------------*/
  PeriphClkInit->PeriphClockSelection |= RCC_PERIPHCLK_I2S2;
  PeriphClkInit->I2s2ClockSelection = RCC_I2S2CLKSOURCE_SYSCLK;

  /* Get the I2S3 clock configuration -----------------------------------------*/
  PeriphClkInit->PeriphClockSelection |= RCC_PERIPHCLK_I2S3;
  PeriphClkInit->I2s3ClockSelection = RCC_I2S3CLKSOURCE_SYSCLK;

#endif /* STM32F103xE || STM32F103xG */

#if defined(STM32F102x6) || defined(STM32F102xB) || defined(STM32F103x6)\
 || defined(STM32F103xB) || defined(STM32F103xE) || defined(STM32F103xG)\
 || defined(STM32F105xC) || defined(STM32F107xC)
  /* Get the USB clock configuration -----------------------------------------*/
  PeriphClkInit->PeriphClockSelection |= RCC_PERIPHCLK_USB;
  PeriphClkInit->UsbClockSelection = __HAL_RCC_GET_USB_SOURCE();
#endif /* STM32F102x6 || STM32F102xB || STM32F103x6 || STM32F103xB || STM32F103xE || STM32F103xG || STM32F105xC || STM32F107xC */
}

/**
  * @brief  Returns the peripheral clock frequency
  * @note   Returns 0 if peripheral clock is unknown
  * @param  PeriphClk Peripheral clock identifier
  *         This parameter can be one of the following values:
  *            @arg @ref RCC_PERIPHCLK_RTC  RTC peripheral clock
  *            @arg @ref RCC_PERIPHCLK_ADC  ADC peripheral clock
  @if STM32F103xE
  *            @arg @ref RCC_PERIPHCLK_I2S2 I2S2 peripheral clock
  *            @arg @ref RCC_PERIPHCLK_I2S3 I2S3 peripheral clock
  *            @arg @ref RCC_PERIPHCLK_I2S3 I2S3 peripheral clock
  @endif
  @if STM32F103xG
  *            @arg @ref RCC_PERIPHCLK_I2S2 I2S2 peripheral clock
  *            @arg @ref RCC_PERIPHCLK_I2S3 I2S3 peripheral clock
  *            @arg @ref RCC_PERIPHCLK_I2S3 I2S3 peripheral clock
  *            @arg @ref RCC_PERIPHCLK_I2S2 I2S2 peripheral clock
  @endif
  @if STM32F105xC
  *            @arg @ref RCC_PERIPHCLK_I2S2 I2S2 peripheral clock
  *            @arg @ref RCC_PERIPHCLK_I2S3 I2S3 peripheral clock
  *            @arg @ref RCC_PERIPHCLK_I2S3 I2S3 peripheral clock
  *            @arg @ref RCC_PERIPHCLK_I2S2 I2S2 peripheral clock
  *            @arg @ref RCC_PERIPHCLK_I2S3 I2S3 peripheral clock
  *            @arg @ref RCC_PERIPHCLK_I2S3 I2S3 peripheral clock
  *            @arg @ref RCC_PERIPHCLK_I2S2 I2S2 peripheral clock
  *            @arg @ref RCC_PERIPHCLK_USB  USB peripheral clock
  @endif
  @if STM32F107xC
  *            @arg @ref RCC_PERIPHCLK_I2S2 I2S2 peripheral clock
  *            @arg @ref RCC_PERIPHCLK_I2S3 I2S3 peripheral clock
  *            @arg @ref RCC_PERIPHCLK_I2S3 I2S3 peripheral clock
  *            @arg @ref RCC_PERIPHCLK_I2S2 I2S2 peripheral clock
  *            @arg @ref RCC_PERIPHCLK_I2S3 I2S3 peripheral clock
  *            @arg @ref RCC_PERIPHCLK_I2S3 I2S3 peripheral clock
  *            @arg @ref RCC_PERIPHCLK_I2S2 I2S2 peripheral clock
  *            @arg @ref RCC_PERIPHCLK_USB  USB peripheral clock
  @endif
  @if STM32F102xx
  *            @arg @ref RCC_PERIPHCLK_USB  USB peripheral clock
  @endif
  @if STM32F103xx
  *            @arg @ref RCC_PERIPHCLK_USB  USB peripheral clock
  @endif
  * @retval Frequency in Hz (0: means that no available frequency for the peripheral)
  */
uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk)
{
#if defined(STM32F102x6) || defined(STM32F102xB) || defined(STM32F103x6)\
 || defined(STM32F103xB) || defined(STM32F103xE) || defined(STM32F103xG)\
 || defined(STM32F105xC) || defined(STM32F107xC)
#if defined(STM32F105xC) || defined(STM32F107xC)
  const uint8_t aPLLMULFactorTable[12] = {0, 0, 4,  5,  6,  7,  8,  9, 0, 0, 0, 13};
  const uint8_t aPredivFactorTable[16] = { 1, 2,  3,  4,  5,  6,  7,  8, 9,10, 11, 12, 13, 14, 15, 16};
#else
  const uint8_t aPLLMULFactorTable[16] = { 2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 16};
  const uint8_t aPredivFactorTable[2] = { 1, 2};
#endif
#endif
  uint32_t temp_reg = 0, frequency = 0;
#if defined(STM32F102x6) || defined(STM32F102xB) || defined(STM32F103x6)\
 || defined(STM32F103xB) || defined(STM32F103xE) || defined(STM32F103xG)\
 || defined(STM32F105xC) || defined(STM32F107xC)
  uint32_t prediv1 = 0, pllclk = 0, pllmul = 0;
#endif /* STM32F102x6 || STM32F102xB || STM32F103x6 || STM32F103xB || STM32F103xE || STM32F103xG || STM32F105xC || STM32F107xC */
#if defined(STM32F105xC) || defined(STM32F107xC)
  uint32_t pll2mul = 0, pll3mul = 0, prediv2 = 0;
#endif /* STM32F105xC || STM32F107xC */

  /* Check the parameters */
  assert_param(IS_RCC_PERIPHCLOCK(PeriphClk));

  switch (PeriphClk)
  {
#if defined(STM32F102x6) || defined(STM32F102xB) || defined(STM32F103x6)\
 || defined(STM32F103xB) || defined(STM32F103xE) || defined(STM32F103xG)\
 || defined(STM32F105xC) || defined(STM32F107xC)
  case RCC_PERIPHCLK_USB:
    {
      /* Get RCC configuration ------------------------------------------------------*/
      temp_reg = RCC->CFGR;

      /* Check if PLL is enabled */
      if (HAL_IS_BIT_SET(RCC->CR,RCC_CR_PLLON))
      {
        pllmul = aPLLMULFactorTable[(uint32_t)(temp_reg & RCC_CFGR_PLLMULL) >> POSITION_VAL(RCC_CFGR_PLLMULL)];
        if ((temp_reg & RCC_CFGR_PLLSRC) != RCC_PLLSOURCE_HSI_DIV2)
        {
#if defined(STM32F105xC) || defined(STM32F107xC) || defined(STM32F100xB)\
 || defined(STM32F100xE)
          prediv1 = aPredivFactorTable[(uint32_t)(RCC->CFGR2 & RCC_CFGR2_PREDIV1) >> POSITION_VAL(RCC_CFGR2_PREDIV1)];
#else
          prediv1 = aPredivFactorTable[(uint32_t)(RCC->CFGR & RCC_CFGR_PLLXTPRE) >> POSITION_VAL(RCC_CFGR_PLLXTPRE)];
#endif /* STM32F105xC || STM32F107xC || STM32F100xB || STM32F100xE */

#if defined(STM32F105xC) || defined(STM32F107xC)
          if(HAL_IS_BIT_SET(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC))
          {
            /* PLL2 selected as Prediv1 source */
            /* PLLCLK = PLL2CLK / PREDIV1 * PLLMUL with PLL2CLK = HSE/PREDIV2 * PLL2MUL */
            prediv2 = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> POSITION_VAL(RCC_CFGR2_PREDIV2)) + 1;
            pll2mul = ((RCC->CFGR2 & RCC_CFGR2_PLL2MUL) >> POSITION_VAL(RCC_CFGR2_PLL2MUL)) + 2;
            pllclk = (uint32_t)((((HSE_VALUE / prediv2) * pll2mul) / prediv1) * pllmul);
          }
          else
          {
            /* HSE used as PLL clock source : PLLCLK = HSE/PREDIV1 * PLLMUL */
            pllclk = (uint32_t)((HSE_VALUE / prediv1) * pllmul);
          }

          /* If PLLMUL was set to 13 means that it was to cover the case PLLMUL 6.5 (avoid using float) */
          /* In this case need to divide pllclk by 2 */
          if (pllmul == aPLLMULFactorTable[(uint32_t)(RCC_CFGR_PLLMULL6_5) >> POSITION_VAL(RCC_CFGR_PLLMULL)])
          {
              pllclk = pllclk / 2;
          }
#else
          if ((temp_reg & RCC_CFGR_PLLSRC) != RCC_PLLSOURCE_HSI_DIV2)
          {
            /* HSE used as PLL clock source : PLLCLK = HSE/PREDIV1 * PLLMUL */
            pllclk = (uint32_t)((HSE_VALUE / prediv1) * pllmul);
          }
#endif /* STM32F105xC || STM32F107xC */
        }
        else
        {
          /* HSI used as PLL clock source : PLLCLK = HSI/2 * PLLMUL */
          pllclk = (uint32_t)((HSI_VALUE >> 1) * pllmul);
        }

        /* Calcul of the USB frequency*/
#if defined(STM32F105xC) || defined(STM32F107xC)
        /* USBCLK = PLLVCO = (2 x PLLCLK) / USB prescaler */
        if (__HAL_RCC_GET_USB_SOURCE() == RCC_USBCLKSOURCE_PLL_DIV2)
        {
          /* Prescaler of 2 selected for USB */
          frequency = pllclk;
        }
        else
        {
          /* Prescaler of 3 selected for USB */
          frequency = (2 * pllclk) / 3;
        }
#else
        /* USBCLK = PLLCLK / USB prescaler */
        if (__HAL_RCC_GET_USB_SOURCE() == RCC_USBCLKSOURCE_PLL)
        {
          /* No prescaler selected for USB */
          frequency = pllclk;
        }
        else
        {
          /* Prescaler of 1.5 selected for USB */
          frequency = (pllclk * 2) / 3;
        }
#endif
      }
      break;
    }
#endif /* STM32F102x6 || STM32F102xB || STM32F103x6 || STM32F103xB || STM32F103xE || STM32F103xG || STM32F105xC || STM32F107xC */
#if defined(STM32F103xE) || defined(STM32F103xG) || defined(STM32F105xC)\
 || defined(STM32F107xC)
  case RCC_PERIPHCLK_I2S2:
    {
#if defined(STM32F103xE) || defined(STM32F103xG)
      /* SYSCLK used as source clock for I2S2 */
      frequency = HAL_RCC_GetSysClockFreq();
#else
      if (__HAL_RCC_GET_I2S2_SOURCE() == RCC_I2S2CLKSOURCE_SYSCLK)
      {
        /* SYSCLK used as source clock for I2S2 */
        frequency = HAL_RCC_GetSysClockFreq();
      }
      else
      {
         /* Check if PLLI2S is enabled */
        if (HAL_IS_BIT_SET(RCC->CR, RCC_CR_PLL3ON))
        {
          /* PLLI2SVCO = 2 * PLLI2SCLK = 2 * (HSE/PREDIV2 * PLL3MUL) */
          prediv2 = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> POSITION_VAL(RCC_CFGR2_PREDIV2)) + 1;
          pll3mul = ((RCC->CFGR2 & RCC_CFGR2_PLL3MUL) >> POSITION_VAL(RCC_CFGR2_PLL3MUL)) + 2;
          frequency = (uint32_t)(2 * ((HSE_VALUE / prediv2) * pll3mul));
        }
      }
#endif /* STM32F103xE || STM32F103xG */
      break;
    }
  case RCC_PERIPHCLK_I2S3:
    {
#if defined(STM32F103xE) || defined(STM32F103xG)
      /* SYSCLK used as source clock for I2S3 */
      frequency = HAL_RCC_GetSysClockFreq();
#else
      if (__HAL_RCC_GET_I2S3_SOURCE() == RCC_I2S3CLKSOURCE_SYSCLK)
      {
        /* SYSCLK used as source clock for I2S3 */
        frequency = HAL_RCC_GetSysClockFreq();
      }
      else
      {
         /* Check if PLLI2S is enabled */
        if (HAL_IS_BIT_SET(RCC->CR, RCC_CR_PLL3ON))
        {
          /* PLLI2SVCO = 2 * PLLI2SCLK = 2 * (HSE/PREDIV2 * PLL3MUL) */
          prediv2 = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> POSITION_VAL(RCC_CFGR2_PREDIV2)) + 1;
          pll3mul = ((RCC->CFGR2 & RCC_CFGR2_PLL3MUL) >> POSITION_VAL(RCC_CFGR2_PLL3MUL)) + 2;
          frequency = (uint32_t)(2 * ((HSE_VALUE / prediv2) * pll3mul));
        }
      }
#endif /* STM32F103xE || STM32F103xG */
      break;
    }
#endif /* STM32F103xE || STM32F103xG || STM32F105xC || STM32F107xC */
  case RCC_PERIPHCLK_RTC:
    {
      /* Get RCC BDCR configuration ------------------------------------------------------*/
      temp_reg = RCC->BDCR;

      /* Check if LSE is ready if RTC clock selection is LSE */
      if (((temp_reg & RCC_BDCR_RTCSEL) == RCC_RTCCLKSOURCE_LSE) && (HAL_IS_BIT_SET(temp_reg, RCC_BDCR_LSERDY)))
      {
        frequency = LSE_VALUE;
      }
      /* Check if LSI is ready if RTC clock selection is LSI */
      else if (((temp_reg & RCC_BDCR_RTCSEL) == RCC_RTCCLKSOURCE_LSI) && (HAL_IS_BIT_SET(RCC->CSR, RCC_CSR_LSIRDY)))
      {
        frequency = LSI_VALUE;
      }
      else if (((temp_reg & RCC_BDCR_RTCSEL) == RCC_RTCCLKSOURCE_HSE_DIV128) && (HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSERDY)))
      {
        frequency = HSE_VALUE / 128;
      }
      /* Clock not enabled for RTC*/
      else
      {
        frequency = 0;
      }
      break;
    }
  case RCC_PERIPHCLK_ADC:
    {
      frequency = HAL_RCC_GetPCLK2Freq() / (((__HAL_RCC_GET_ADC_SOURCE() >> POSITION_VAL(RCC_CFGR_ADCPRE_DIV4)) + 1) * 2);
      break;
    }
  default:
    {
      break;
    }
  }
  return(frequency);
}

/**
  * @}
  */

#if defined(STM32F105xC) || defined(STM32F107xC)
/** @defgroup RCCEx_Exported_Functions_Group2 PLLI2S Management function
 *  @brief  PLLI2S Management functions
 *
@verbatim
 ===============================================================================
                ##### Extended PLLI2S Management functions  #####
 ===============================================================================
    [..]
    This subsection provides a set of functions allowing to control the PLLI2S
    activation or deactivation
@endverbatim
  * @{
  */

/**
  * @brief  Enable PLLI2S
  * @param  PLLI2SInit pointer to an RCC_PLLI2SInitTypeDef structure that
  *         contains the configuration information for the PLLI2S
  * @note   The PLLI2S configuration not modified if used by I2S2 or I2S3 Interface.
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_RCCEx_EnablePLLI2S(RCC_PLLI2SInitTypeDef  *PLLI2SInit)
{
  uint32_t tickstart = 0;

  /* Check that PLL I2S has not been already enabled by I2S2 or I2S3*/
  if (HAL_IS_BIT_CLR(RCC->CFGR2, RCC_CFGR2_I2S2SRC) && HAL_IS_BIT_CLR(RCC->CFGR2, RCC_CFGR2_I2S3SRC))
  {
    /* Check the parameters */
    assert_param(IS_RCC_PLLI2S_MUL(PLLI2SInit->PLLI2SMUL));
    assert_param(IS_RCC_HSE_PREDIV2(PLLI2SInit->HSEPrediv2Value));

    /* Prediv2 can be written only when the PLL2 is disabled. */
    /* Return an error only if new value is different from the programmed value */
    if (HAL_IS_BIT_SET(RCC->CR,RCC_CR_PLL2ON) && \
      (__HAL_RCC_HSE_GET_PREDIV2() != PLLI2SInit->HSEPrediv2Value))
    {
      return HAL_ERROR;
    }

    /* Disable the main PLLI2S. */
    __HAL_RCC_PLLI2S_DISABLE();

    /* Get Start Tick*/
    tickstart = HAL_GetTick();

    /* Wait till PLLI2S is ready */
    while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLI2SRDY)  != RESET)
    {
      if((HAL_GetTick() - tickstart ) > PLLI2S_TIMEOUT_VALUE)
      {
        return HAL_TIMEOUT;
      }
    }

    /* Configure the HSE prediv2 factor --------------------------------*/
    __HAL_RCC_HSE_PREDIV2_CONFIG(PLLI2SInit->HSEPrediv2Value);

    /* Configure the main PLLI2S multiplication factors. */
    __HAL_RCC_PLLI2S_CONFIG(PLLI2SInit->PLLI2SMUL);

    /* Enable the main PLLI2S. */
    __HAL_RCC_PLLI2S_ENABLE();

    /* Get Start Tick*/
    tickstart = HAL_GetTick();

    /* Wait till PLLI2S is ready */
    while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLI2SRDY)  == RESET)
    {
      if((HAL_GetTick() - tickstart ) > PLLI2S_TIMEOUT_VALUE)
      {
        return HAL_TIMEOUT;
      }
    }
  }
  else
  {
    /* PLLI2S cannot be modified as already used by I2S2 or I2S3 */
    return HAL_ERROR;
  }

  return HAL_OK;
}

/**
  * @brief  Disable PLLI2S
  * @note   PLLI2S is not disabled if used by I2S2 or I2S3 Interface.
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_RCCEx_DisablePLLI2S(void)
{
  uint32_t tickstart = 0;

  /* Disable PLL I2S as not requested by I2S2 or I2S3*/
  if (HAL_IS_BIT_CLR(RCC->CFGR2, RCC_CFGR2_I2S2SRC) && HAL_IS_BIT_CLR(RCC->CFGR2, RCC_CFGR2_I2S3SRC))
  {
    /* Disable the main PLLI2S. */
    __HAL_RCC_PLLI2S_DISABLE();

    /* Get Start Tick*/
    tickstart = HAL_GetTick();

    /* Wait till PLLI2S is ready */
    while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLI2SRDY)  != RESET)
    {
      if((HAL_GetTick() - tickstart ) > PLLI2S_TIMEOUT_VALUE)
      {
        return HAL_TIMEOUT;
      }
    }
  }
  else
  {
    /* PLLI2S is currently used by I2S2 or I2S3. Cannot be disabled.*/
    return HAL_ERROR;
  }

  return HAL_OK;
}

/**
  * @}
  */

/** @defgroup RCCEx_Exported_Functions_Group3 PLL2 Management function
 *  @brief  PLL2 Management functions
 *
@verbatim
 ===============================================================================
                ##### Extended PLL2 Management functions  #####
 ===============================================================================
    [..]
    This subsection provides a set of functions allowing to control the PLL2
    activation or deactivation
@endverbatim
  * @{
  */

/**
  * @brief  Enable PLL2
  * @param  PLL2Init pointer to an RCC_PLL2InitTypeDef structure that
  *         contains the configuration information for the PLL2
  * @note   The PLL2 configuration not modified if used indirectly as system clock.
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_RCCEx_EnablePLL2(RCC_PLL2InitTypeDef  *PLL2Init)
{
  uint32_t tickstart = 0;

  /* This bit can not be cleared if the PLL2 clock is used indirectly as system
    clock (i.e. it is used as PLL clock entry that is used as system clock). */
  if((__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSE) && \
        (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) && \
        ((READ_BIT(RCC->CFGR2,RCC_CFGR2_PREDIV1SRC)) == RCC_CFGR2_PREDIV1SRC_PLL2))
  {
    return HAL_ERROR;
  }
  else
  {
    /* Check the parameters */
    assert_param(IS_RCC_PLL2_MUL(PLL2Init->PLL2MUL));
    assert_param(IS_RCC_HSE_PREDIV2(PLL2Init->HSEPrediv2Value));

    /* Prediv2 can be written only when the PLLI2S is disabled. */
    /* Return an error only if new value is different from the programmed value */
    if (HAL_IS_BIT_SET(RCC->CR,RCC_CR_PLL3ON) && \
      (__HAL_RCC_HSE_GET_PREDIV2() != PLL2Init->HSEPrediv2Value))
    {
      return HAL_ERROR;
    }

    /* Disable the main PLL2. */
    __HAL_RCC_PLL2_DISABLE();

    /* Get Start Tick*/
    tickstart = HAL_GetTick();

    /* Wait till PLL2 is disabled */
    while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLL2RDY) != RESET)
    {
      if((HAL_GetTick() - tickstart ) > PLL2_TIMEOUT_VALUE)
      {
        return HAL_TIMEOUT;
      }
    }

    /* Configure the HSE prediv2 factor --------------------------------*/
    __HAL_RCC_HSE_PREDIV2_CONFIG(PLL2Init->HSEPrediv2Value);

    /* Configure the main PLL2 multiplication factors. */
    __HAL_RCC_PLL2_CONFIG(PLL2Init->PLL2MUL);

    /* Enable the main PLL2. */
    __HAL_RCC_PLL2_ENABLE();

    /* Get Start Tick*/
    tickstart = HAL_GetTick();

    /* Wait till PLL2 is ready */
    while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLL2RDY)  == RESET)
    {
      if((HAL_GetTick() - tickstart ) > PLL2_TIMEOUT_VALUE)
      {
        return HAL_TIMEOUT;
      }
    }
  }

  return HAL_OK;
}

/**
  * @brief  Disable PLL2
  * @note   PLL2 is not disabled if used indirectly as system clock.
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_RCCEx_DisablePLL2(void)
{
  uint32_t tickstart = 0;

  /* This bit can not be cleared if the PLL2 clock is used indirectly as system
    clock (i.e. it is used as PLL clock entry that is used as system clock). */
  if((__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSE) && \
        (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) && \
        ((READ_BIT(RCC->CFGR2,RCC_CFGR2_PREDIV1SRC)) == RCC_CFGR2_PREDIV1SRC_PLL2))
  {
    return HAL_ERROR;
  }
  else
  {
    /* Disable the main PLL2. */
    __HAL_RCC_PLL2_DISABLE();

    /* Get Start Tick*/
    tickstart = HAL_GetTick();

    /* Wait till PLL2 is disabled */
    while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLL2RDY)  != RESET)
    {
      if((HAL_GetTick() - tickstart ) > PLL2_TIMEOUT_VALUE)
      {
        return HAL_TIMEOUT;
      }
    }
  }

  return HAL_OK;
}

/**
  * @}
  */
#endif /* STM32F105xC || STM32F107xC */

/**
  * @}
  */

/**
  * @}
  */

#endif /* HAL_RCC_MODULE_ENABLED */

/**
  * @}
  */

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


text:
@class XCFAuthorDetail;

@interface XCFMyLocateNDescView : UIView

@property (nonatomic, strong) XCFAuthorDetail *authorDetail;

@end

redpajama_set_name: RedPajamaGithub


text:
var wrench = nodeRequire('wrench');
var Path = nodeRequire('path');
var os = nodeRequire('os');
var fs = nodeRequire('fs');
var request = nodeRequire('request');
var Files = require('../../files');

var canvasWidth;
var canvasHeight;
var prevCanvasWidth;
var prevCanvasHeight;

module.exports = {
  newProject: function() {
    //copy the empty project folder to a temporary directory
    var emptyProject = Path.join('mode_assets', 'p5', 'empty_project');
    var tempProject = Path.join(os.tmpdir(), 'p5' + Date.now(), 'Untitled');
    wrench.mkdirSyncRecursive(tempProject);
    wrench.copyDirSyncRecursive(emptyProject, tempProject, {
      excludeHiddenUnix: true,
      inflateSymlinks: true,
      forceDelete: true
    });

    this.projectPath = tempProject;

    //open the project and file
    var self = this;
    this.loadProject(tempProject, function(){
      self.openFile(Path.join(tempProject, 'sketch.js'));
      gui.Window.get().show();
    });

  },

  launchExample: function(examplePath) {
    //copy the empty project folder to a temporary directory
    var emptyProject = 'mode_assets/p5/empty_project';
    var tempProjectPath = Path.join(os.tmpdir(), 'p5' + Date.now(), Files.cleanExampleName(examplePath));
    wrench.mkdirSyncRecursive(tempProjectPath);
    wrench.copyDirSyncRecursive(emptyProject, tempProjectPath, {
      excludeHiddenUnix: true,
      inflateSymlinks: true,
      forceDelete: true
    });
    // replace contents of sketch.js with the requested example
    var sketchContents = fs.readFileSync(examplePath, {encoding: 'utf8'});
    var assets = sketchContents.match(/['"]assets\/(.*?)['"]/g);
    if (assets) {
      var assetsDir = Path.join(tempProjectPath, 'assets');
      wrench.mkdirSyncRecursive(assetsDir);
      assets.forEach(function(a){
        a = a.replace(/(assets\/)|['"]/g, '');
        var originalAsset = Path.join('mode_assets/p5/example_assets', a);
        var destAsset = Path.join(assetsDir, a);
        fs.createReadStream(originalAsset).pipe(fs.createWriteStream(destAsset));
      });
    }
    var destination = Path.join(tempProjectPath, "sketch.js");
    fs.writeFileSync(destination, sketchContents);
    this.openProject(tempProjectPath, true);
  },

  exportProject: function() {
    console.log('hello');
  },

  saveAs: function(path) {
    //save all files
    this.saveAll();

    //copy the folder
    wrench.copyDirSyncRecursive(this.projectPath, path);

    //change file paths
    this.files.forEach(function(file) {
      file.path = Path.join(path, file.name);
    });
    this.tabs.forEach(function(tab){
      tab.path = Path.join(path, tab.name);
    });

    this.$broadcast('save-project-as', path);

    // change the html title tag
    var indexPath = Path.join(path, 'index.html');
    var projectTitle = Path.basename(path);
    var oldProjectTitle = Path.basename(this.projectPath);

    fs.readFile(indexPath, 'utf8', function(err, data){
      if (!err) {
        data = data.replace('<title>' + oldProjectTitle + '</title>', '<title>' + projectTitle + '</title>');
        fs.writeFile(indexPath, data);
      }
    });

    this.projectPath = path;
    this.temp = false;
    this.watch(path);
  },

  run: function() {
    var self = this;
    this.saveAll();
    gui.App.clearCache();

    if (this.outputWindow) {
      if (this.settings.runInBrowser) {
        gui.Shell.openExternal(url);
      } else {
        this.outputWindow.reloadIgnoringCache();
        if(isWin){
          self.outputWindow.hide();
          self.outputWindow.show();
        }
      }
    } else {
      startServer(this.projectPath, this, function(url) {
        if (self.settings.runInBrowser) {
          gui.Shell.openExternal(url);
        } else {
          fs.readFile(Path.join(self.projectPath, 'sketch.js'), function(err, data){
            var matches = (""+data).match(/createCanvas\((.*),(.*)\)/);
            canvasWidth = matches && matches[1] ? +matches[1] : 400;
            canvasHeight = matches && matches[2] ? +matches[2] : 400;

            if (!self.outW) self.outW = canvasWidth;
            if (!self.outH) self.outH = canvasHeight;

            if ((canvasWidth != prevCanvasWidth || canvasHeight != prevCanvasHeight) && !self.resizedOutputWindow) {
              self.outW = canvasWidth;
              self.outH = canvasHeight;
            }

            self.outputWindow = self.newWindow(url, {
              toolbar: true,
              'inject-js-start': 'js/debug-console.js',
              x: self.outX,
              y: self.outY,
              width: self.outW,
              height: self.outH,
              nodejs: false,
              'page-cache': false,
            });

            prevCanvasWidth = canvasWidth;
            prevCanvasHeight = canvasHeight;

            self.outputWindow.on('document-start', function(){
              self.outputWindow.show();
            });

            self.outputWindow.on("close", function(){
              self.outX = self.outputWindow.x;
              self.outY = self.outputWindow.y;
              self.outW = self.outputWindow.width;

              // the "-55" appears to fix the growing window issue,
              // & resulting gasslighting of myself
              self.outH = self.outputWindow.height - 55;
              self.running = false;
              self.outputWindow = null;
              this.close(true);
            });

            self.outputWindow.on('focus', function(){
              self.resetMenu();
            });

            self.outputWindow.on('resize', function() {
              self.resizedOutputWindow = true;
            });
          });
        }
        self.running = true;
      });
    }
  },

  stop: function() {
    if (this.outputWindow) {
      this.outputWindow.close();
    } else {
      this.running = false;
    }
  },

  update: function(callback) {
    var url = 'https://api.github.com/repos/processing/p5.js/releases/latest';
    var libraryPath = Path.join('mode_assets', 'p5', 'empty_project', 'libraries');
    var fileNames = ['p5.js', 'p5.dom.js', 'p5.sound.js'];

    request({url: url, headers: {'User-Agent': 'request'}}, function(error, response, data){
      if (error) return;

      // filter assets to only include the filenames we want
      var assets = JSON.parse(data).assets.filter(function(asset){
        return fileNames.indexOf(asset.name) > -1;
      });

      // if remoteVersion != localVersion, download new version of each asset
      var remoteVersion = JSON.parse(data).tag_name;
      var localPathToP5 = Path.join(libraryPath, 'p5.js');

      var localVersionTag = getVersion(localPathToP5, function(localVersion) {
        if (remoteVersion != localVersion || !localVersion) {
          assets.forEach(function(asset) {
            var localPathToAsset = Path.join(libraryPath, asset.name);
            downloadAsset(asset.browser_download_url, localPathToAsset);
          });
        }
      });

    });

    function downloadAsset(remote, local) {
      request({url: remote, headers: {'User-Agent': 'request'}}, function(error, response, body){
        if (error) return;

        if (body.split('\n')[0].indexOf('/*! p5.') > -1) {
          fs.writeFile(local, body);
        }
      });
    }
  },

  referenceURL: 'http://p5js.org/reference/'

};

var running = false;
var url = '';
var staticServer = nodeRequire('node-static'), server, file;

function startServer(path, app, callback) {
  if (running === false) {
    var portscanner = nodeRequire('portscanner');
    portscanner.findAPortNotInUse(3000, 4000, '127.0.0.1', function(error, port) {
      server = nodeRequire('http').createServer(handler);
      file = new staticServer.Server(path, {cache: false});

      server.listen(port, function(){
        url = 'http://localhost:' + port;
        callback(url);
        running = true;
      });

      function handler(request, response) {
        request.addListener('end', function () {
          file.serve(request, response);
        }).resume();
      }
    });

  } else {
    file = new staticServer.Server(path, {cache: false});
    callback(url);
  }

}

function getVersion(filename, callback) {
  fs.readFile(filename, function (err, data) {
    if (err) throw err;

    var line = data.toString('utf-8').split("\n")[0];
    var version;
    try {
      version = line.match(/v\d+\.\d+\.\d+/)[0].substring(1);
    } catch(e) {
      version = null;
    }
    callback(version);

  });

}


text:
// Copyright © Microsoft Corporation.  All Rights Reserved.
// This code released under the terms of the
// Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TFSIntegrationAdmin.HelpCmd
{
    class HelpCmd : CommandBase
    {
        public override bool PrintHelp
        {
            get
            {
                return true;
            }
            protected set
            {
                base.PrintHelp = value;
            }
        }

        public override bool CanRecognizeArgs(string[] originalCmdLineArgs)
        {
            if (originalCmdLineArgs.Length == 1 &&
                (originalCmdLineArgs[0].Equals(CommandName, StringComparison.OrdinalIgnoreCase)
                || originalCmdLineArgs[0].Equals(Constants.CmdHelpSwitch1, StringComparison.OrdinalIgnoreCase)
                || originalCmdLineArgs[0].Equals(Constants.CmdHelpSwitch2, StringComparison.OrdinalIgnoreCase)
                || originalCmdLineArgs[0].Equals(Constants.CmdHelpSwitch3, StringComparison.OrdinalIgnoreCase)))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public override bool TryParseArgs(string[] cmdSpecificArgs)
        {
            return true;
        }

        public override string CommandName
        {
            get { return "Help"; /* do not localize */ }
        }

        public override TFSIntegrationAdmin.Interfaces.ICommandResult Run()
        {
            return null;
        }

        public override string GetHelpString()
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine("TFS Integration Platform Administration Utility supported commands:");
            sb.AppendLine();

            /*
             * Add a line of brief description for each supported command
             */
            sb.AppendLine("  ExportConfig - export the configuration of a session group");
            sb.AppendLine("  ImportConfig - import a configuration package to create a new session group");
            sb.AppendLine("  DeleteSessionGroup - delete an existing session group");
            sb.AppendLine("  ConfigServiceAccount - add an account to TFS Integration service account");
            sb.AppendLine("  ConfigAccessControl - sets access control of the TFS Integration data folder");
            sb.AppendLine("  PrintStatus - print the status of the integration service");
            sb.AppendLine("  Compress - delete the processed data in the integration platformation Database");

            sb.AppendLine();
            sb.AppendLine();
            sb.AppendLine("To print detailed help of individual command:");
            sb.AppendLine();
            sb.AppendFormat("  {0} <Command> /?", Program.ProgramName);
            return sb.ToString();
        }
    }
}


text:
Page({
  onLoad: function () {
    this.setData({
      savedFilePath: wx.getStorageSync('savedFilePath')
    })
  },
  data: {
    tempFilePath: '',
    savedFilePath: '',
    dialog: {
      hidden: true
    }
  },
  chooseImage: function () {
    var that = this
    wx.chooseImage({
      count: 1,
      success: function (res) {
        that.setData({
          tempFilePath: res.tempFilePaths[0]
        })
      }
    })
  },
  saveFile: function () {
    if (this.data.tempFilePath.length > 0) {
      var that = this
      wx.saveFile({
        tempFilePath: this.data.tempFilePath,
        success: function (res) {
          that.setData({
            savedFilePath: res.savedFilePath
          })
          wx.setStorageSync('savedFilePath', res.savedFilePath)
          that.setData({
            dialog: {
              title: '保存成功',
              content: '下次进入应用时,此文件仍可用',
              hidden: false
            }
          })
        },
        fail: function (res) {
          that.setData({
            dialog: {
              title: '保存失败',
              content: '应该是有 bug 吧',
              hidden: false
            }
          })
        }
      })
    }
  },
  clear: function () {
    wx.setStorageSync('savedFilePath', '')
    this.setData({
      tempFilePath: '',
      savedFilePath: ''
    })
  },
  confirm: function () {
    this.setData({
      'dialog.hidden': true
    })
  }
})


text:
<?php

namespace Comodojo\Exception;

class LdaphException extends \Exception
{
}


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>Scheduler: Scheduler::RoundRobinDiscipline Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

Scheduler

Main Page

Related Pages

Namespaces

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

Scheduler

RoundRobinDiscipline

Public Member Functions |
Static Public Attributes |
List of all members

Scheduler::RoundRobinDiscipline Class Reference

#include <roundRobinDiscipline.h>

Inheritance diagram for Scheduler::RoundRobinDiscipline:

  <map id="Scheduler::RoundRobinDiscipline_map" name="Scheduler::RoundRobinDiscipline_map">
<area href="classScheduler_1_1SchedulingDiscipline.html" alt="Scheduler::SchedulingDiscipline" shape="rect" coords="0,0,199,24"/>
</map>

Public Member Functions

 	RoundRobinDiscipline (std::shared_ptr< SchedulerConfiguration > c)

 	~RoundRobinDiscipline ()

std::shared_ptr< Process > 	selectNextTask (Queue *readyQueue, std::shared_ptr< Process > running, unsigned int)

 	select the best task to run at this point.  More...

std::string 	getName ()

 	returns the name of that discipline  More...

bool 	preempts (TriggeringEvent trigger)

 	returns true if the argument is a scheduling trigger for this specific discipline  More...

 Public Member Functions inherited from Scheduler::SchedulingDiscipline

virtual 	~SchedulingDiscipline ()

 	SchedulingDiscipline (std::shared_ptr< SchedulerConfiguration > c)

virtual void 	end ()

Static Public Attributes

static constexpr const char * 	configKey = "roundRobinDiscipline"

Additional Inherited Members

 Protected Attributes inherited from Scheduler::SchedulingDiscipline

std::shared_ptr< SchedulerConfiguration > 	conf {nullptr}

Detailed Description

Definition at line 22 of file roundRobinDiscipline.h.

Constructor & Destructor Documentation

          Scheduler::RoundRobinDiscipline::RoundRobinDiscipline
          (
          std::shared_ptr< SchedulerConfiguration >
          c	)

inline

Definition at line 27 of file roundRobinDiscipline.h.

          Scheduler::RoundRobinDiscipline::~RoundRobinDiscipline
          (
          	)

inline

Definition at line 28 of file roundRobinDiscipline.h.

Member Function Documentation

          std::string RoundRobinDiscipline::getName
          (
          	)

virtual

returns the name of that discipline

Implements Scheduler::SchedulingDiscipline.

Definition at line 32 of file roundRobinDiscipline.cpp.

          bool RoundRobinDiscipline::preempts
          (
          TriggeringEvent
          trigger	)

virtual

returns true if the argument is a scheduling trigger for this specific discipline

Parameters

trigger	the type of the event that triggered the scheduling invokation

Implements Scheduler::SchedulingDiscipline.

Definition at line 38 of file roundRobinDiscipline.cpp.

          std::shared_ptr< Process > RoundRobinDiscipline::selectNextTask
          (
          Queue *
          readyQueue,

          std::shared_ptr< Process >
          running,

          unsigned
          deadlineMisses

          )

virtual

select the best task to run at this point.

Parameters

readyQueue	the ready queue

running	the currently running task

deadlineMisses

Returns

the next task to be run

Implements Scheduler::SchedulingDiscipline.

Definition at line 21 of file roundRobinDiscipline.cpp.

Member Data Documentation

          constexpr const char* Scheduler::RoundRobinDiscipline::configKey = "roundRobinDiscipline"

static

Definition at line 25 of file roundRobinDiscipline.h.

The documentation for this class was generated from the following files:

src/scheduler/discipline/roundRobinDiscipline.h

src/scheduler/discipline/roundRobinDiscipline.cpp

<address class="footer">
Generated on Sun Nov 26 2017 17:01:37 for Scheduler by

 1.8.11
</address>


text:
require_relative "abstract_unit"

class AssertionsTest < ActiveSupport::TestCase
  def setup
    @object = Class.new do
      attr_accessor :num
      def increment
        self.num += 1
      end

      def decrement
        self.num -= 1
      end
    end.new
    @object.num = 0
  end

  def test_assert_not
    assert_equal true, assert_not(nil)
    assert_equal true, assert_not(false)

    e = assert_raises(Minitest::Assertion) { assert_not true }
    assert_equal "Expected true to be nil or false", e.message

    e = assert_raises(Minitest::Assertion) { assert_not true, "custom" }
    assert_equal "custom", e.message
  end

  def test_assert_no_difference_pass
    assert_no_difference "@object.num" do
      # ...
    end
  end

  def test_assert_no_difference_fail
    error = assert_raises(Minitest::Assertion) do
      assert_no_difference "@object.num" do
        @object.increment
      end
    end
    assert_equal "\"@object.num\" didn't change by 0.\nExpected: 0\n  Actual: 1", error.message
  end

  def test_assert_no_difference_with_message_fail
    error = assert_raises(Minitest::Assertion) do
      assert_no_difference "@object.num", "Object Changed" do
        @object.increment
      end
    end
    assert_equal "Object Changed.\n\"@object.num\" didn't change by 0.\nExpected: 0\n  Actual: 1", error.message
  end

  def test_assert_no_difference_with_multiple_expressions_pass
    another_object = @object.dup
    assert_no_difference ["@object.num", -> { another_object.num }] do
      # ...
    end
  end

  def test_assert_no_difference_with_multiple_expressions_fail
    another_object = @object.dup
    assert_raises(Minitest::Assertion) do
      assert_no_difference ["@object.num", -> { another_object.num }], "Another Object Changed" do
        another_object.increment
      end
    end
  end

  def test_assert_difference
    assert_difference "@object.num", +1 do
      @object.increment
    end
  end

  def test_assert_difference_retval
    incremented = assert_difference "@object.num", +1 do
      @object.increment
    end

    assert_equal incremented, 1
  end

  def test_assert_difference_with_implicit_difference
    assert_difference "@object.num" do
      @object.increment
    end
  end

  def test_arbitrary_expression
    assert_difference "@object.num + 1", +2 do
      @object.increment
      @object.increment
    end
  end

  def test_negative_differences
    assert_difference "@object.num", -1 do
      @object.decrement
    end
  end

  def test_expression_is_evaluated_in_the_appropriate_scope
    silence_warnings do
      local_scope = "foo"
      _ = local_scope  # to suppress unused variable warning
      assert_difference("local_scope; @object.num") { @object.increment }
    end
  end

  def test_array_of_expressions
    assert_difference [ "@object.num", "@object.num + 1" ], +1 do
      @object.increment
    end
  end

  def test_array_of_expressions_identify_failure
    assert_raises(Minitest::Assertion) do
      assert_difference ["@object.num", "1 + 1"] do
        @object.increment
      end
    end
  end

  def test_array_of_expressions_identify_failure_when_message_provided
    assert_raises(Minitest::Assertion) do
      assert_difference ["@object.num", "1 + 1"], 1, "something went wrong" do
        @object.increment
      end
    end
  end

  def test_hash_of_expressions
    assert_difference "@object.num" => 1, "@object.num + 1" => 1 do
      @object.increment
    end
  end

  def test_hash_of_expressions_with_message
    error = assert_raises Minitest::Assertion do
      assert_difference({ "@object.num" => 0 }, "Object Changed") do
        @object.increment
      end
    end
    assert_equal "Object Changed.\n\"@object.num\" didn't change by 0.\nExpected: 0\n  Actual: 1", error.message
  end

  def test_hash_of_lambda_expressions
    assert_difference -> { @object.num } => 1, -> { @object.num + 1 } => 1 do
      @object.increment
    end
  end

  def test_hash_of_expressions_identify_failure
    assert_raises(Minitest::Assertion) do
      assert_difference "@object.num" => 1, "1 + 1" => 1 do
        @object.increment
      end
    end
  end

  def test_assert_changes_pass
    assert_changes "@object.num" do
      @object.increment
    end
  end

  def test_assert_changes_pass_with_lambda
    assert_changes -> { @object.num } do
      @object.increment
    end
  end

  def test_assert_changes_with_from_option
    assert_changes "@object.num", from: 0 do
      @object.increment
    end
  end

  def test_assert_changes_with_from_option_with_wrong_value
    assert_raises Minitest::Assertion do
      assert_changes "@object.num", from: -1 do
        @object.increment
      end
    end
  end

  def test_assert_changes_with_from_option_with_nil
    error = assert_raises Minitest::Assertion do
      assert_changes "@object.num", from: nil do
        @object.increment
      end
    end

    assert_equal "Expected change from nil, got 0", error.message
  end

  def test_assert_changes_with_to_option
    assert_changes "@object.num", to: 1 do
      @object.increment
    end
  end

  def test_assert_changes_with_to_option_but_no_change_has_special_message
    error = assert_raises Minitest::Assertion do
      assert_changes "@object.num", to: 0 do
        # no changes
      end
    end

    assert_equal "\"@object.num\" didn't change. It was already 0.\nExpected 0 to not be equal to 0.", error.message
  end

  def test_assert_changes_with_wrong_to_option
    assert_raises Minitest::Assertion do
      assert_changes "@object.num", to: 2 do
        @object.increment
      end
    end
  end

  def test_assert_changes_with_from_option_and_to_option
    assert_changes "@object.num", from: 0, to: 1 do
      @object.increment
    end
  end

  def test_assert_changes_with_from_and_to_options_and_wrong_to_value
    assert_raises Minitest::Assertion do
      assert_changes "@object.num", from: 0, to: 2 do
        @object.increment
      end
    end
  end

  def test_assert_changes_works_with_any_object
    # Silences: instance variable @new_object not initialized.
    retval = silence_warnings do
      assert_changes :@new_object, from: nil, to: 42 do
        @new_object = 42
      end
    end

    assert_equal 42, retval
  end

  def test_assert_changes_works_with_nil
    oldval = @object

    retval = assert_changes :@object, from: oldval, to: nil do
      @object = nil
    end

    assert_nil retval
  end

  def test_assert_changes_with_to_and_case_operator
    token = nil

    assert_changes -> { token }, to: /\w{32}/ do
      token = SecureRandom.hex
    end
  end

  def test_assert_changes_with_to_and_from_and_case_operator
    token = SecureRandom.hex

    assert_changes -> { token }, from: /\w{32}/, to: /\w{32}/ do
      token = SecureRandom.hex
    end
  end

  def test_assert_changes_with_message
    error = assert_raises Minitest::Assertion do
      assert_changes "@object.num", "@object.num should be 1", to: 1 do
        @object.decrement
      end
    end

    assert_equal "@object.num should be 1.\nExpected change to 1, got -1\n", error.message
  end

  def test_assert_no_changes_pass
    assert_no_changes "@object.num" do
      # ...
    end
  end

  def test_assert_no_changes_with_from_option
    assert_no_changes "@object.num", from: 0 do
      # ...
    end
  end

  def test_assert_no_changes_with_from_option_with_wrong_value
    assert_raises Minitest::Assertion do
      assert_no_changes "@object.num", from: -1 do
        # ...
      end
    end
  end

  def test_assert_no_changes_with_from_option_with_nil
    error = assert_raises Minitest::Assertion do
      assert_no_changes "@object.num", from: nil do
        @object.increment
      end
    end
    assert_equal "Expected initial value of nil", error.message
  end

  def test_assert_no_changes_with_from_and_case_operator
    token = SecureRandom.hex

    assert_no_changes -> { token }, from: /\w{32}/ do
      # ...
    end
  end

  def test_assert_no_changes_with_message
    error = assert_raises Minitest::Assertion do
      assert_no_changes "@object.num", "@object.num should not change" do
        @object.increment
      end
    end

    assert_equal "@object.num should not change.\n\"@object.num\" changed.\nExpected: 0\n  Actual: 1", error.message
  end

  def test_assert_no_changes_with_long_string_wont_output_everything
    lines = "HEY\n" * 12

    error = assert_raises Minitest::Assertion do
      assert_no_changes "lines" do
        lines += "HEY ALSO\n"
      end
    end

    assert_match <<~output, error.message
      "lines" changed.
      --- expected
      +++ actual
      @@ -10,4 +10,5 @@
       HEY
       HEY
       HEY
      +HEY ALSO
       "
    output
  end
end

class ExceptionsInsideAssertionsTest < ActiveSupport::TestCase
  def before_setup
    require "stringio"
    @out = StringIO.new
    self.tagged_logger = ActiveSupport::TaggedLogging.new(Logger.new(@out))
    super
  end

  def test_warning_is_logged_if_caught_internally
    run_test_that_should_pass_and_log_a_warning
    expected = <<~MSG
      ExceptionsInsideAssertionsTest - test_warning_is_logged_if_caught_internally: ArgumentError raised.
      If you expected this exception, use `assert_raises` as near to the code that raises as possible.
      Other block based assertions (e.g. `assert_no_changes`) can be used, as long as `assert_raises` is inside their block.
    MSG
    assert @out.string.include?(expected), @out.string
  end

  def test_warning_is_not_logged_if_caught_correctly_by_user
    run_test_that_should_pass_and_not_log_a_warning
    assert_not @out.string.include?("assert_nothing_raised")
  end

  def test_warning_is_not_logged_if_assertions_are_nested_correctly
    error = assert_raises(Minitest::Assertion) do
      run_test_that_should_fail_but_not_log_a_warning
    end
    assert_not @out.string.include?("assert_nothing_raised")
    assert error.message.include?("(lambda)> changed")
  end

  def test_fails_and_warning_is_logged_if_wrong_error_caught
    error = assert_raises(Minitest::Assertion) do
      run_test_that_should_fail_confusingly
    end
    expected = <<~MSG
      ExceptionsInsideAssertionsTest - test_fails_and_warning_is_logged_if_wrong_error_caught: ArgumentError raised.
      If you expected this exception, use `assert_raises` as near to the code that raises as possible.
      Other block based assertions (e.g. `assert_no_changes`) can be used, as long as `assert_raises` is inside their block.
    MSG
    assert @out.string.include?(expected), @out.string
    assert error.message.include?("ArgumentError: ArgumentError")
    assert error.message.include?("in `block (2 levels) in run_test_that_should_fail_confusingly'")
  end

  private
    def run_test_that_should_pass_and_log_a_warning
      assert_raises(Minitest::UnexpectedError) do # this assertion passes, but it's unlikely to be how anyone writes a test
        assert_no_changes -> { 1 } do # this assertion doesn't run. the error below is caught and the warning logged.
          raise ArgumentError.new
        end
      end
    end

    def run_test_that_should_fail_confusingly
      assert_raises(ArgumentError) do # this assertion fails (confusingly) because it catches a Minitest::UnexpectedError.
        assert_no_changes -> { 1 } do # this assertion doesn't run. the error below is caught and the warning logged.
          raise ArgumentError.new
        end
      end
    end

    def run_test_that_should_pass_and_not_log_a_warning
      assert_no_changes -> { 1 } do # this assertion passes
        assert_raises(ArgumentError) do # this assertion passes
          raise ArgumentError.new
        end
      end
    end

    def run_test_that_should_fail_but_not_log_a_warning
      assert_no_changes -> { rand } do # this assertion fails
        assert_raises(ArgumentError) do # this assertion passes
          raise ArgumentError.new
        end
      end
    end
end

# Setup and teardown callbacks.
class SetupAndTeardownTest < ActiveSupport::TestCase
  setup :reset_callback_record, :foo
  teardown :foo, :sentinel

  def test_inherited_setup_callbacks
    assert_equal [:reset_callback_record, :foo], self.class._setup_callbacks.map(&:filter)
    assert_equal [:foo], @called_back
    assert_equal [:foo, :sentinel], self.class._teardown_callbacks.map(&:filter)
  end

  def setup
  end

  def teardown
  end

  private
    def reset_callback_record
      @called_back = []
    end

    def foo
      @called_back << :foo
    end

    def sentinel
      assert_equal [:foo], @called_back
    end
end

class SubclassSetupAndTeardownTest < SetupAndTeardownTest
  setup :bar
  teardown :bar

  def test_inherited_setup_callbacks
    assert_equal [:reset_callback_record, :foo, :bar], self.class._setup_callbacks.map(&:filter)
    assert_equal [:foo, :bar], @called_back
    assert_equal [:foo, :sentinel, :bar], self.class._teardown_callbacks.map(&:filter)
  end

  private
    def bar
      @called_back << :bar
    end

    def sentinel
      assert_equal [:foo, :bar, :bar], @called_back
    end
end

class TestCaseTaggedLoggingTest < ActiveSupport::TestCase
  def before_setup
    require "stringio"
    @out = StringIO.new
    self.tagged_logger = ActiveSupport::TaggedLogging.new(Logger.new(@out))
    super
  end

  def test_logs_tagged_with_current_test_case
    assert_match "#{self.class}: #{name}\n", @out.string
  end
end

class TestOrderTest < ActiveSupport::TestCase
  def setup
    @original_test_order = ActiveSupport::TestCase.test_order
  end

  def teardown
    ActiveSupport::TestCase.test_order = @original_test_order
  end

  def test_defaults_to_random
    ActiveSupport::TestCase.test_order = nil

    assert_equal :random, ActiveSupport::TestCase.test_order

    assert_equal :random, ActiveSupport.test_order
  end

  def test_test_order_is_global
    ActiveSupport::TestCase.test_order = :sorted

    assert_equal :sorted, ActiveSupport.test_order
    assert_equal :sorted, ActiveSupport::TestCase.test_order
    assert_equal :sorted, self.class.test_order
    assert_equal :sorted, Class.new(ActiveSupport::TestCase).test_order

    ActiveSupport.test_order = :random

    assert_equal :random, ActiveSupport.test_order
    assert_equal :random, ActiveSupport::TestCase.test_order
    assert_equal :random, self.class.test_order
    assert_equal :random, Class.new(ActiveSupport::TestCase).test_order
  end
end

class ConstStubbable
  CONSTANT = 1
end

class TestConstStubbing < ActiveSupport::TestCase
  test "stubbing a constant temporarily replaces it with a new value" do
    stub_const(ConstStubbable, :CONSTANT, 2) do
      assert_equal 2, ConstStubbable::CONSTANT
    end

    assert_equal 1, ConstStubbable::CONSTANT
  end

  test "stubbed constant still reset even if exception is raised" do
    assert_raises(RuntimeError) do
      stub_const(ConstStubbable, :CONSTANT, 2) do
        assert_equal 2, ConstStubbable::CONSTANT
        raise "Exception"
      end
    end

    assert_equal 1, ConstStubbable::CONSTANT
  end
end


text:
package org.deri.iris.queryrewriting;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.deri.iris.api.basics.ILiteral;
import org.deri.iris.api.basics.IRule;
import org.deri.iris.api.factory.IBasicFactory;
import org.deri.iris.api.terms.ITerm;
import org.deri.iris.factory.Factory;
import org.deri.iris.storage.StorageManager;
import org.deri.iris.terms.StringTerm;

import com.google.common.base.Joiner;
import com.google.common.collect.Iterators;

/**
 * A class to produce a SQL Rewriting from a set of datalog queries.
 * @author Giorgio Orsi <orsi@elet.polimi.it> - Politecnico di Milano
 */
public class SQLRewriter {

	private final Logger LOGGER = Logger.getLogger(SQLRewriter.class);

	private final Set<IRule> mRules;

	public SQLRewriter(final Set<IRule> rules) {
		// Store the TGDs to be used for the rewriting
		mRules = rules;
	}

	public String getSQLRewriting(IRule query,final String sqlConstraint, final int nbNodes, final int startedFrom) throws SQLException {
		//LOGGER.debug("Translating " + query);
		final IBasicFactory bf = Factory.BASIC;

		final Map<String, String> aliasMap = new HashMap<String, String>();
		final Set<ITerm> processedTargetTerms = new HashSet<ITerm>();
		final List<String> targetList = new ArrayList<String>();
		final List<String> fromList = new ArrayList<String>();
		final List<String> whereList = new ArrayList<String>();

		// Disambiguate same predicates in the query body
		final Set<ILiteral> body = new LinkedHashSet<ILiteral>();
		int dis = 1;
		for (final ILiteral l : query.getBody()) {
			final String p = l.getAtom().getPredicate().toString();
			String p_alias;
			if (aliasMap.containsValue(p)) {
				p_alias = Joiner.on("").join(p, "_", dis++);
			} else {
				p_alias = p;
			}
			aliasMap.put(p_alias, p);
			body.add(bf.createLiteral(l.isPositive(),
			        bf.createPredicate(p_alias, l.getAtom().getPredicate().getArity()), l.getAtom().getTuple()));
		}
		query = bf.createRule(query.getHead(), body);

		try {
			final StringBuffer out = new StringBuffer();

			// Translate the Query
			for (int i = 0; i < query.getBody().size(); i++) {
				final ILiteral l = Iterators.get(query.getBody().iterator(), i);
				final String p = l.getAtom().getPredicate().getPredicateSymbol();
				fromList.add(p);

				int pos = 0;
				for (final ITerm t : l.getAtom().getTuple()) {
					pos++;
					if (query.getHeadVariables().contains(t) && !processedTargetTerms.contains(t)) {
						// This is a head variable
						targetList.add(Joiner.on("").join(p, ".",
						        StorageManager.getFields(aliasMap.get(p)).get(pos - 1)));
						processedTargetTerms.add(t);
					}
					if (t instanceof StringTerm) {
						if (aliasMap.containsKey(p)) {
							whereList.add(Joiner.on("").join(p, ".",
							        StorageManager.getFields(aliasMap.get(p)).get(pos - 1), "=", t, ""));
						}
					}
					for (int j = i + 1; j < query.getBody().size(); j++) {
						final ILiteral lj = Iterators.get(query.getBody().iterator(), j);
						final String pj = lj.getAtom().getPredicate().toString();
						int posj = 0;
						for (final ITerm jt : lj.getAtom().getTuple()) {
							posj++;
							if (jt.equals(t)) {
								if (p.equalsIgnoreCase("I_CLASS")) {
									final String whereAtom = Joiner.on("").join(p, ".",
									        StorageManager.getFields(aliasMap.get(p)).get(pos - 1), "=", pj, ".",
									        StorageManager.getFields(aliasMap.get(pj)).get(posj - 1));
									whereList.add(whereAtom);
								} else {
									final String whereAtom = Joiner.on("").join(pj, ".",
									        StorageManager.getFields(aliasMap.get(pj)).get(posj - 1), "=", p, ".",
									        StorageManager.getFields(aliasMap.get(p)).get(pos - 1));
									whereList.add(whereAtom);
								}
							}
						}
					}
				}
			}

			// Building the target list
			if (targetList.size() == 0) {
				out.append("SELECT DISTINCT 'true'");
			} else {
				out.append("SELECT DISTINCT ");
				for (int i = 0; i < (targetList.size() - 1); i++) {
					out.append(targetList.get(i)).append(", ");
				}
				out.append(targetList.get(targetList.size() - 1));
			}

			// Building the from list
			out.append(" FROM ");
			final String vendor = StorageManager.getVendor();
			for (int i = 0; i < (fromList.size() - 1); i++) {
				if (aliasMap.get(fromList.get(i)).compareTo(fromList.get(i)) != 0) {
					if (vendor.compareTo("_ORACLE") == 0) {
						out.append(aliasMap.get(fromList.get(i))).append(" ").append(fromList.get(i)).append(", ");
					} else if (vendor.compareTo("_MYSQL") == 0) {
						out.append(aliasMap.get(fromList.get(i))).append(" AS ").append(fromList.get(i)).append(", ");
					} else if (vendor.compareTo("_POSTGRES") == 0) {
						out.append(StorageManager.getSchemaName()).append(".").append(aliasMap.get(fromList.get(i)))
						        .append(" AS ").append(fromList.get(i)).append(", ");
					} else
						throw new SQLException("Unsupported Vendor: " + vendor);
				} else {
					if (vendor.equals("_POSTGRES")) {
						out.append(StorageManager.getSchemaName()).append(".").append(fromList.get(i)).append(", ");
					} else {
						out.append(fromList.get(i)).append(", ");
					}
				}
			}
			if (aliasMap.get(fromList.get(fromList.size() - 1)).compareTo(fromList.get(fromList.size() - 1)) != 0) {
				if (vendor.equals("_ORACLE")) {
					out.append(aliasMap.get(fromList.get(fromList.size() - 1))).append(" ")
					        .append(fromList.get(fromList.size() - 1));
				} else if (vendor.compareTo("_MYSQL") == 0) {
					out.append(aliasMap.get(fromList.get(fromList.size() - 1))).append(" AS ")
					        .append(fromList.get(fromList.size() - 1));
				} else if (vendor.compareTo("_POSTGRES") == 0) {
					out.append(StorageManager.getSchemaName()).append(".")
					        .append(aliasMap.get(fromList.get(fromList.size() - 1))).append(" AS ")
					        .append(fromList.get(fromList.size() - 1));
				} else
					throw new SQLException("Unsupported Vendor: " + vendor);
			} else {
				if (vendor.equals("_POSTGRES")) {
					out.append(StorageManager.getSchemaName()).append(".").append(fromList.get(fromList.size() - 1));
					//out.append(",preferences.business");
				} else {
					out.append(fromList.get(fromList.size() - 1));
				}
			}

			// Building the where list
			if (whereList.size() > 0) {
				out.append(" WHERE ");
				for (int i = 0; i < (whereList.size() - 1); i++) {
					out.append(whereList.get(i)).append(" AND ");
				}
				out.append(whereList.get(whereList.size() - 1));
			//	out.append("and business_categories.bs_id = business.bs_id "+sqlConstraint);

			}
			out.append("  limit "+nbNodes+" offset "+startedFrom);
			//LOGGER.debug("Q " + out.toString());
			return (out.toString());

		} catch (final SQLException e) {
			e.printStackTrace();
		}
		return (null);
	}

	public List<String> getSQLRewritings(final String sqlConstraint, final int nbNodes, final int startedFrom) throws SQLException {
		final List<String> rewritings = new ArrayList<String>();

		// Get each query and compute its rewriting in SQL
		for (final IRule q : mRules) {
			rewritings.add(getSQLRewriting(q,  sqlConstraint,   nbNodes,   startedFrom));
		}

		return (rewritings);
	}

	public String getUCQSQLRewriting(final String sqlConstraint, final int nbNodes, final int startedFrom) throws SQLException {

		final StringBuffer sb = new StringBuffer();
		final List<String> partialRewritings = getSQLRewritings( sqlConstraint,   nbNodes,   startedFrom);

		// Get each query and compute a SQL UCQ
		if (partialRewritings.size() > 0) {
			for (int i = 0; i < (partialRewritings.size() - 1); i++) {
				sb.append(partialRewritings.get(i).toString());
				sb.append(IOUtils.LINE_SEPARATOR);
				sb.append(" UNION ");
				sb.append(IOUtils.LINE_SEPARATOR);
			}
			sb.append(partialRewritings.get(partialRewritings.size() - 1));
		}
		return (sb.toString());

	}

}


text:
package com.planet_ink.coffee_mud.Abilities.Spells;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

public class Spell_Siphon extends Spell
{
	private static Random randomizer = null;
	public Spell_Siphon()
	{
		super();
		if(randomizer==null)
			randomizer = new Random(System.currentTimeMillis());
	}

	@Override
	public String ID()
	{
		return "Spell_Siphon";
	}

	private final static String localizedName = CMLib.lang().L("Siphon");

	@Override
	public String name()
	{
		return localizedName;
	}

	private final static String localizedStaticDisplay = CMLib.lang().L("(Siphon spell)");

	@Override
	public String displayText()
	{
		return localizedStaticDisplay;
	}

	@Override
	public int maxRange()
	{
		return adjustedMaxInvokerRange(1);
	}

	@Override
	public int abstractQuality()
	{
		return Ability.QUALITY_BENEFICIAL_OTHERS;
	}

	@Override
	public int classificationCode()
	{
		return Ability.ACODE_SPELL|Ability.DOMAIN_ENCHANTMENT;
	}

	@Override
	protected int canAffectCode()
	{
		return CAN_MOBS;
	}

	@Override
	protected int canTargetCode()
	{
		return CAN_MOBS;
	}

	@Override
	public boolean invoke(final MOB mob, final List<String> commands, final Physical givenTarget, final boolean auto, final int asLevel)
	{
		final MOB target=getTarget(mob,commands,givenTarget);
		if(target==null)
			return false;

		if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
			return false;

		final boolean success=proficiencyCheck(mob,0,auto);
		if(success)
		{
			final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?L("<T-NAME> feel(s) a thirst for the energy of others."):L("^S<S-NAME> invoke(s) an area deprived of energy around <T-NAMESELF>.^?"));
			if(mob.location().okMessage(mob,msg))
			{
				mob.location().send(mob,msg);
				beneficialAffect(mob,target,asLevel,0);
			}
		}
		else
			beneficialWordsFizzle(mob,target,L("<S-NAME> attempt(s) to invoke an energy thirst, but fail(s)."));

		return success;
	}

	@Override
	public void unInvoke()
	{
		// undo the affects of this spell
		if(!(affected instanceof MOB))
			return;
		final MOB mob=(MOB)affected;
		super.unInvoke();
		if(super.canBeUninvoked())
			mob.tell(L("You no longer feel a thirst for the energy of others."));
	}

	@Override
	public boolean okMessage(final Environmental myHost, final CMMsg msg)
	{
		if(!(affected instanceof MOB))
			return true;

		final MOB mob=(MOB)affected;

		if((msg.amITarget(mob))
		&&(!msg.amISource(mob))
		&&(msg.targetMinor()==CMMsg.TYP_DAMAGE)
		&&((msg.value())>0)
		&&(msg.tool() instanceof Weapon)
		&&(CMLib.dice().rollPercentage()>50)
		&&(msg.source().curState().getMana()>0))
		{
			final MOB sourceM = msg.source();
			final CMMsg msg2=CMClass.getMsg(mob,sourceM,null,CMMsg.MSG_QUIETMOVEMENT,L("<S-NAME> siphon(s) mana from <T-NAME>!"));
			if(mob.location().okMessage(mob,msg2))
			{
				final int maxManaRestore = 3;
				final int curSourceMana = sourceM.curState().getMana();
				int manaDrain = 0;
				if(maxManaRestore <= curSourceMana)
				{
				   manaDrain = maxManaRestore;
				}
				else
				{
				   manaDrain = curSourceMana;
				}
				mob.curState().adjMana(manaDrain, mob.maxState());
				sourceM.curState().adjMana(manaDrain * -1, sourceM.maxState());
				mob.location().send(mob,msg2);
			}
		}
		return super.okMessage(myHost, msg);
	}
}


text:
package com.sc.schat.domain;

import java.io.Serializable;
import java.time.ZonedDateTime;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.Email;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.sc.schat.util.Constants;

/**
 * A user entity
 *
 * @author Saumik
 */
@Entity
@Table(name="user")
public class User extends AbstractAuditingEntity implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator="seq-gen")
    @SequenceGenerator(name="seq-gen",sequenceName="USER_ID_SEQ", initialValue=1, allocationSize=1)
    private Long id;

    @NotNull
    @Pattern(regexp = Constants.USER_NAME_REGEX)
    @Size(min = 1, max = 50)
    @Column(name = "user_name", length = 50, unique = true, nullable = false)
    private String userName;

    @JsonIgnore
    @NotNull
    @Size(min = 60, max = 60)
    @Column(name = "password_hash",length = 60)
    private String password;

    @Size(max = 50)
    @Column(name = "first_name", length = 50)
    private String firstName;

    @Size(max = 50)
    @Column(name = "last_name", length = 50)
    private String lastName;

    @Email
    @Size(max = 100)
    @Column(length = 100, unique = true)
    private String email;

    @Size(max = 20)
    @Column(length = 20, unique = true)
    private String phone;

    @NotNull
    @Column(nullable = false)
    private boolean activated = false;

    @Size(min = 2, max = 5)
    @Column(name = "lang_key", length = 5)
    private String langKey;

    @Size(max = 20)
    @Column(name = "activation_key", length = 20)
    @JsonIgnore
    private String activationKey;

    @Size(max = 20)
    @Column(name = "reset_key", length = 20)
    private String resetKey;

    @Column(name = "reset_date", nullable = true)
    @JsonIgnore
    private ZonedDateTime resetDate = null;

    @JsonIgnore
    @ManyToMany(fetch=FetchType.EAGER)
    @JoinTable(
        name = "user_authority",
        joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")},
        inverseJoinColumns = {@JoinColumn(name = "authority_name", referencedColumnName = "name")})
    private Set<Authority> authorities = new HashSet<>();

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    //Lowercase the UserName before saving it in database
    public void setUserName(String userName) {
        this.userName = userName.toLowerCase(Locale.ENGLISH);
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public boolean getActivated() {
        return activated;
    }

    public void setActivated(boolean activated) {
        this.activated = activated;
    }

    public String getActivationKey() {
        return activationKey;
    }

    public void setActivationKey(String activationKey) {
        this.activationKey = activationKey;
    }

    public String getResetKey() {
        return resetKey;
    }

    public void setResetKey(String resetKey) {
        this.resetKey = resetKey;
    }

    public ZonedDateTime getResetDate() {
       return resetDate;
    }

    public void setResetDate(ZonedDateTime resetDate) {
       this.resetDate = resetDate;
    }

    public String getLangKey() {
        return langKey;
    }

    public void setLangKey(String langKey) {
        this.langKey = langKey;
    }

    public Set<Authority> getAuthorities() {
        return authorities;
    }

    public void setAuthorities(Set<Authority> authorities) {
        this.authorities = authorities;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        User user = (User) o;

        if (!userName.equals(user.userName)) {
            return false;
        }

        return true;
    }

    @Override
    public int hashCode() {
        return userName.hashCode();
    }

    @Override
    public String toString() {
        return "User{" +
            "userName='" + userName + '\'' +
            ", firstName='" + firstName + '\'' +
            ", lastName='" + lastName + '\'' +
            ", email='" + email + '\'' +
            ", activated='" + activated + '\'' +
            ", langKey='" + langKey + '\'' +
            ", activationKey='" + activationKey + '\'' +
            "}";
    }
}


text: MongoDB persistence layer module for Xublit


text:
from hubcheck.pageobjects.po_generic_page import GenericPage

class MembersProfilePage(GenericPage):
    """members profile page"""

    def __init__(self,browser,catalog,memberid='myaccount'):
        super(MembersProfilePage,self).__init__(browser,catalog)
        self.memberid = memberid
        self.path = "/members/%s/profile" % (str(self.memberid))

        # load hub's classes
        MembersProfilePage_Locators = self.load_class('MembersProfilePage_Locators')
        MembersProfileForm          = self.load_class('MembersProfileForm')
        MembersPageMenu             = self.load_class('MembersPageMenu')

        # update this object's locator
        self.locators.update(MembersProfilePage_Locators.locators)

        # setup page object's components
        self.form = MembersProfileForm(self,{'base':'form'})
        self.menu = MembersPageMenu(self,{'base':'menu'})

class MembersProfilePage_Locators_Base(object):
    """locators for MembersProfilePage object"""

    locators = {
        'form' : "css=#profile",
        'menu' : "css=#page_menu",
    }


text:
package org.docksidestage.dockside.dbflute.allcommon.cbean.coption;

import org.dbflute.cbean.coption.LikeSearchOption;
import org.dbflute.utflute.core.PlainTestCase;

/**
 * The test of likeSearchOption for Basic Example.
 * @author jflute
 * @since 0.5.9 (2007/12/20 Thursday)
 */
public class LikeSearchOptionTest extends PlainTestCase {

    // ===================================================================================
    //                                                                         Rear Option
    //                                                                         ===========
    public void test_getRearOption() throws Exception {
        // ## Arrange ##
        final LikeSearchOption option = new LikeSearchOption();
        option.escapeByPipeLine();

        // ## Act ##
        final String rearOption = option.getRearOption();

        // ## Assert ##
        assertEquals("escape '|'", rearOption.trim());
    }

    // ===================================================================================
    //                                                                          Real Value
    //                                                                          ==========
    public void test_generateRealValue() throws Exception {
        final String inputValue = "abc%def_ghi";
        {
            // ## Arrange ##
            final LikeSearchOption option = new LikeSearchOption();
            option.escapeByPipeLine();

            // ## Act ##
            final String realValue = option.generateRealValue(inputValue);

            // ## Assert ##
            log("realValue=" + realValue);
            assertEquals("abc|%def|_ghi", realValue);
        }
        {
            // ## Arrange ##
            final LikeSearchOption option = new LikeSearchOption();
            option.likePrefix().escapeBySlash();

            // ## Act ##
            final String realValue = option.generateRealValue(inputValue);

            // ## Assert ##
            log("realValue=" + realValue);
            assertEquals("abc/%def/_ghi%", realValue);
        }
        {
            // ## Arrange ##
            final LikeSearchOption option = new LikeSearchOption();
            option.likeContain().escapeByAtMark();

            // ## Act ##
            final String realValue = option.generateRealValue(inputValue);

            // ## Assert ##
            log("realValue=" + realValue);
            assertEquals("%abc@%def@_ghi%", realValue);
        }
        {
            // ## Arrange ##
            final LikeSearchOption option = new LikeSearchOption();
            option.likeSuffix().escapeByBackSlash();

            // ## Act ##
            final String realValue = option.generateRealValue(inputValue);

            // ## Assert ##
            log("realValue=" + realValue);
            assertEquals("%abc\\%def\\_ghi", realValue);
        }
        {
            // ## Arrange ##
            final LikeSearchOption option = new LikeSearchOption();
            option.escapeByPipeLine();

            // ## Act ##
            final String realValue = option.generateRealValue(inputValue + "jk|l");

            // ## Assert ##
            log("realValue=" + realValue);
            assertEquals("abc|%def|_ghijk||l", realValue);
        }
    }
}


text:
<?php

namespace Tackk\Cartographer;

class ChangeFrequency
{
    const ALWAYS  = 'always';
    const HOURLY  = 'hourly';
    const DAILY   = 'daily';
    const WEEKLY  = 'weekly';
    const MONTHLY = 'monthly';
    const YEARLY  = 'yearly';
    const NEVER   = 'never';
}

class Sitemap extends AbstractSitemap
{
    protected function getRootNodeName()
    {
        return 'urlset';
    }

    protected function getNodeName()
    {
        return 'url';
    }

    /**
     * Adds the URL to the urlset.
     * @param  string     $loc
     * @param  string|int $lastmod
     * @param  string     $changefreq
     * @param  float      $priority
     * @return $this
     */
    public function add($loc, $lastmod = null, $changefreq = null, $priority = null)
    {
        $loc     = $this->escapeString($loc);
        $lastmod = !is_null($lastmod) ? $this->formatDate($lastmod) : null;

        return $this->addUrlToDocument(compact('loc', 'lastmod', 'changefreq', 'priority'));
    }
}


text:
module Vagrant
  class Action
    module Box
      autoload :Destroy,   'vagrant/action/box/destroy'
      autoload :Download,  'vagrant/action/box/download'
      autoload :Package,   'vagrant/action/box/package'
      autoload :Unpackage, 'vagrant/action/box/unpackage'
      autoload :Verify,    'vagrant/action/box/verify'
    end
  end
end


text:
/*
	SObjectizer 5 Transport.
*/

#include <algorithm>

#include <so_5/rt/h/mbox.hpp>

#include <so_5/h/log_err.hpp>

#include <so_5_transport/h/a_transport_agent.hpp>

namespace so_5_transport
{

//
// a_transport_agent_t
//

a_transport_agent_t::a_transport_agent_t(
	so_5::rt::so_environment_t & env )
	:
		base_type_t( env ),
		m_failed_state( self_ptr() ),
		m_self_mbox( env.create_local_mbox() )
{
}

a_transport_agent_t::~a_transport_agent_t()
{
}

void
a_transport_agent_t::so_define_agent()
{
	so_subscribe( m_self_mbox )
		.event( &a_transport_agent_t::evt_channel_created );

	so_subscribe( m_self_mbox )
		.event( &a_transport_agent_t::evt_channel_lost );
}

void
a_transport_agent_t::so_evt_finish()
{
	std::for_each(
		m_controllers.begin(),
		m_controllers.end(),
		[]( channel_controller_ref_t ctrl ){
			ctrl->close();
		} );
}

void
a_transport_agent_t::evt_channel_created(
	const so_5::rt::event_data_t< msg_channel_created > & msg )
{
	m_controllers.insert( msg->m_controller );
}

void
a_transport_agent_t::evt_channel_lost(
	const so_5::rt::event_data_t< msg_channel_lost > & msg )
{
	m_controllers.erase( msg->m_controller );

	// Extra handling.
	on_lost( *msg );
}

void
a_transport_agent_t::on_lost( const msg_channel_lost & )
{
	// Default implementation does nothing.
}

//
// a_server_transport_agent_t
//

a_server_transport_agent_t::a_server_transport_agent_t(
	so_5::rt::so_environment_t & env,
	acceptor_controller_unique_ptr_t acceptor_controller )
	:
		base_type_t( env ),
		m_acceptor_controller( std::move( acceptor_controller ) )
{
}

a_server_transport_agent_t::~a_server_transport_agent_t()
{
}

void
a_server_transport_agent_t::so_evt_start()
{
	bool succeed_res = true;
	if( 0 != m_acceptor_controller->create( m_self_mbox ) )
	{
		ACE_ERROR(
			(LM_ERROR,
			SO_5_LOG_FMT( "a_server_transport_agent: create acceptor failed" ) ) );

		m_acceptor_controller.reset();
		so_change_state( m_failed_state );

		succeed_res = false;
	}

	m_self_mbox->deliver_message(
		std::unique_ptr< msg_create_server_socket_result >(
			new msg_create_server_socket_result( succeed_res ) ) );
}

void
a_server_transport_agent_t::so_evt_finish()
{
	m_acceptor_controller.reset();
	base_type_t::so_evt_finish();
}

//
// client_reconnect_params_t
//

client_reconnect_params_t::client_reconnect_params_t(
	unsigned int on_lost_reconnect_timeout,
	unsigned int on_failed_reconnect_timeout,
	bool do_reconnect )
	:
		m_on_lost_reconnect_timeout( on_lost_reconnect_timeout ),
		m_on_failed_reconnect_timeout( on_failed_reconnect_timeout ),
		m_do_reconnect( do_reconnect )
{
}

//
// a_client_transport_agent_t
//

a_client_transport_agent_t::a_client_transport_agent_t(
	so_5::rt::so_environment_t & env,
	connector_controller_unique_ptr_t connector_controller,
	const client_reconnect_params_t & client_reconnect_params )
	:
		base_type_t( env ),
		m_connector_controller( std::move( connector_controller ) ),
		m_client_reconnect_params( client_reconnect_params )
{
}

a_client_transport_agent_t::~a_client_transport_agent_t()
{
}

void
a_client_transport_agent_t::so_define_agent()
{
	base_type_t::so_define_agent();

	// Subscribe on reconnect if necessary.
	if( m_client_reconnect_params.m_do_reconnect )
		so_subscribe( m_self_mbox )
			.event( &a_client_transport_agent_t::evt_reconnect );
}

void
a_client_transport_agent_t::so_evt_start()
{
	do_reconnect();
}

void
a_client_transport_agent_t::so_evt_finish()
{
	m_connector_controller.reset();
	base_type_t::so_evt_finish();
}

void
a_client_transport_agent_t::evt_reconnect(
	const so_5::rt::event_data_t< signal_reconnect > & )
{
	do_reconnect();
}

void
a_client_transport_agent_t::on_lost( const msg_channel_lost & )
{
	if( m_client_reconnect_params.m_do_reconnect )
		so_environment().single_timer< signal_reconnect >(
			m_self_mbox,
			m_client_reconnect_params.m_on_lost_reconnect_timeout );
}

void
a_client_transport_agent_t::do_reconnect()
{
	if( !try_to_connect() )
	{
		if( m_client_reconnect_params.m_do_reconnect )
			so_environment().single_timer< signal_reconnect >(
				m_self_mbox,
				m_client_reconnect_params.m_on_failed_reconnect_timeout );
		else
		{
			m_connector_controller.reset();
			// If no reconnect switch to failed state.
			so_change_state( m_failed_state );
		}
	}
}

bool
a_client_transport_agent_t::try_to_connect()
{
	if( 0 != m_connector_controller->connect( m_self_mbox ) )
	{
		ACE_ERROR( (
			LM_ERROR,
			SO_5_LOG_FMT( "a_client_transport_agent: connect failed" ) ) );

		return false;
	}

	return true;
}

} /* namespace so_5_transport */