text:
/*
 *    Description:
 *      This file...
 *
 */

#include <stdio.h>
#include <stdlib.h>

#define NLPLATFORM_INTERRUPT_FUNCTIONS
#define CALLING_NL_PRODUCT_INIT
#include <nlplatform.h>
#undef CALLING_NL_PRODUCT_INIT
#undef NLPLATFORM_INTERRUPT_FUNCTIONS

#include <nlplatform/nlfault.h>
#include <nlplatform/nlflash.h>
#include <nlplatform/nlflash_spi.h>
#include <nlplatform/nlfs.h>
#include <nlplatform/nlgpio.h>
#include <nlplatform/nlmpu.h>
#include <nlplatform/nltimer.h>
#include <nlplatform/nluart.h>
#include <nlplatform/nlwatchdog.h>
#include <nlplatform/nlwatchpoint.h>

#if defined(BUILD_FEATURE_NL_PROFILE) && !defined(NL_NO_RTOS)
#include <nlplatform/nlprofile.h>
#endif

#include <nlplatform_nrf52x/nrf52x_gpio.h>
#include <nlplatform_nrf52x/nlflash_nrf52x.h>
#if defined(BUILD_FEATURE_SW_TIMER) && !defined(NL_NO_RTOS)
#include <nlplatform/nlswtimer.h>
#include <nlertime.h>
#endif

#include <FreeRTOS.h>
#include <task.h>
#include <portmacro.h>

#include <nlassert.h>

#if defined(BUILD_FEATURE_SW_TIMER) && !defined(NL_NO_RTOS)
static uint32_t blk_sleep_tmr_cb(nl_swtimer_t *timer, void *arg);
static struct block_sleep_tmr_s
{
    nl_swtimer_t timer;
    nl_time_native_t end;
} s_blk_sleep_tmr;
#endif

// Assert that FreeRTOS ATOMIC_PRIORITY_LEVEL is same as PRODUCT_INTERRUPT_DISABLE_BASE_PRIORITY
#ifdef PRODUCT_INTERRUPT_DISABLE_BASE_PRIORITY
nlSTATIC_ASSERT(ATOMIC_PRIORITY_LEVEL == PRODUCT_INTERRUPT_DISABLE_BASE_PRIORITY);
nlSTATIC_ASSERT(configMAX_SYSCALL_INTERRUPT_PRIORITY == PRODUCT_INTERRUPT_DISABLE_BASE_PRIORITY_VALUE);
#endif

/* Allow product to define the RTC PRESCALER value, which determines the FreeRTOS
 * tick frequency. If not defined, we default to a 4MS (really 3.9978ms) tick
 */
#ifndef NRF_RTC_PRESCALER_VALUE
#define NRF_RTC_PRESCALER_VALUE 130 /* Gives a frequency of 250.1374046Hz, 3.9978ms tick */
#endif

static uint32_t sCachedRebootCause;

static int sBlockSleepCount = 0;

/* nrf52x has 4 watchpoint comparators.  We use the last one for
 * guarding task stacks.
 */
#define TASK_STACK_WATCHPOINT_INDEX 3

/* guard 256 bytes at 0x0. could guard more, but I think this
 * is sufficient to catch most NULL ptr use cases. this
 * covers the vector table.
 */
#define ADDRESS_ZERO_GUARD_SIZE 256

/* MPU defines, don't seem to be in CMSIS */
#define MPU_RASR_AP_NO_ACCESS 0
#define MPU_RASR_AP_READ_ONLY 7
#define MPU_RASR_TEX_NORMAL   1

static void guard_cstack_and_address_0(void)
{
    // We generally prefer to use the watchpoint block to catch stack
    // overflow instead of the MPU because the MPU would prevent
    // all writes, including the pushing of fault context (if we want
    // to catch interrupt handlers causing stack overflows, we have to
    // enable the read-only access in privileged mode as well as unprivileged
    // mode). The watchpoint catches writes after the fact, and still allows
    // the pushing of context by the HW on fault, so we can get a full
    // context and backtrace of the faulting instruction.

    // So a watchpoint is used for guarding the current task stack, which
    // we update on every context switch. However, there are very few
    // watchpoints (4 on a typical cortex-m3 and m4) so we don't want
    // to use more than one. We use the MPU to guard the CSTACK, which
    // should be much less likely to overflow. We set up the protection
    // once at boot.
    extern uint32_t const __GUARD_REGION__start;
    extern uint32_t const __GUARD_REGION__size;

    // this function is called before .bss and .data are initialized,
    // so must be careful about any globals that may be used by
    // any functions called. the only global known to be accessed
    // is int_lock_count, when nl_mpu_request_region() uses
    // nlplatform_interrupt_disable() and nlplatform_interrupt_enable().
    // set int_lock_count to 0 manually here.
    int_lock_count = 0;

    nl_mpu_init();
    nl_mpu_request_region((unsigned)&__GUARD_REGION__start, (unsigned)&__GUARD_REGION__size,
                          MPU_RASR_XN_Msk |
                          MPU_RASR_AP_READ_ONLY << MPU_RASR_AP_Pos | // privileged and unprivileged read-only, so backtrace attempts don't fault when reading the area
                          MPU_RASR_TEX_NORMAL << MPU_RASR_TEX_Pos); // normal memory, outer and inner non-cacheable, not shared
#ifdef NL_BOOTLOADER
    if (SCB->VTOR == 0x0)
    {
        // for the bootloader, set address 0 guard to read only
        // so fault handling still works
        nl_mpu_request_region(0x0, ADDRESS_ZERO_GUARD_SIZE,
                              MPU_RASR_XN_Msk |
                              MPU_RASR_AP_READ_ONLY << MPU_RASR_AP_Pos | // privileged and unprivileged read-only, so fault handling still works
                              MPU_RASR_TEX_NORMAL << MPU_RASR_TEX_Pos); // normal memory, outer and inner non-cacheable, not shared

    }
    else
    {
        // for aupd, we've already switched vector table so set the
        // the address 0 guard to no access. note that if aupd
        // wants to update the bootloader, it needs to disable
        // the mpu, and then reenable it afterwards.
        nl_mpu_request_region(0x0, ADDRESS_ZERO_GUARD_SIZE,
                              MPU_RASR_XN_Msk |
                              MPU_RASR_AP_NO_ACCESS << MPU_RASR_AP_Pos | // privileged and unprivileged no access
                              MPU_RASR_TEX_NORMAL << MPU_RASR_TEX_Pos); // normal memory, outer and inner non-cacheable, not shared
    }
#else
    // for regular apps, set the address 0 guard to no access
    // to catch NULL ptr usage
    nl_mpu_request_region(0x0, ADDRESS_ZERO_GUARD_SIZE,
                          MPU_RASR_XN_Msk |
                          MPU_RASR_AP_NO_ACCESS << MPU_RASR_AP_Pos | // privileged and unprivileged no access
                          MPU_RASR_TEX_NORMAL << MPU_RASR_TEX_Pos); // normal memory, outer and inner non-cacheable, not shared
#endif
    nl_mpu_enable(true, true, true);
}

/* There are three variants of nlplatform_init().  One for the bootloader,
 * one for aupd, and one app/shell.
 *
 * The bootloader calls nlplatform_init on every boot, and so do the apps
 * (aupd and full app).  To make boot time faster, we want to avoid
 * repeating any initialization in the app that was done already by
 * the bootloader.
 *
 * aupd differs from the full app because it has no FreeRTOS, making it
 * more like the bootloader in this regard.  We compile two versions of
 * nlplatform_soc, one with FreeRTOS and one without FreeRTOS.  However,
 * since aupd and the bootloader both use the non-FreeRTOS version, but
 * we want them to do different things at boot time, we use the linker
 * script to select which function to use (rather than building three
 * library variants).
 */
#ifdef NL_BOOTLOADER

/* used by the bootloader */
void nlplatform_init(void)
{
    sCachedRebootCause = NRF_POWER->RESETREAS;
    // don't clear reset reason so app can read it too

#ifdef BUILD_FEATURE_WATCHPOINT_STACK_GUARD
    // disable watchpoint used for stack guarding so any stack init routines
    // don't trip the watchpoint during early boot
    nl_watchpoint_disable(TASK_STACK_WATCHPOINT_INDEX);
#endif

    /* start LF clock */
    NRF_CLOCK->EVENTS_LFCLKSTARTED = 0;
    /* For radio to work, need to use configure LFCLKSRC */
#ifdef PRODUCT_NRF_LFCLKSRC
    /* use product defined clock source */
    NRF_CLOCK->LFCLKSRC = PRODUCT_NRF_LFCLKSRC;
#else
    /* default clock source is normal xtal operation */
    NRF_CLOCK->LFCLKSRC = (CLOCK_LFCLKSRC_SRC_Xtal << CLOCK_LFCLKSRC_SRC_Pos);
#endif
    NRF_CLOCK->TASKS_LFCLKSTART = 1;
    /* Wait for LFCLK to start */
    while (NRF_CLOCK->EVENTS_LFCLKSTARTED == 0) {}

    nltimer_init();

    nltimer_request(NLTIMER_DELAY);

    nlgpio_init();

    // not needed in the bootloader
    //nluart_init();

    nlwatchdog_init();

    nlplatform_crypto_init();

    /* set SEVONPEND so interrupts wake from WFE */
    SCB->SCR |= SCB_SCR_SEVONPEND_Msk;
}

void nlplatform_init_aupd(void);
void nlplatform_init_aupd(void)
{
    sCachedRebootCause = NRF_POWER->RESETREAS;
    // clear reset reasons so next read of the register doesn't have stale data
    NRF_POWER->RESETREAS = 0xffffffff;

#ifdef BUILD_FEATURE_WATCHPOINT_STACK_GUARD
    // use the last watchpoint to guard the first 32-bytes of the AUPD CSTACK
    extern uint32_t const __CSTACK__start;
    nl_watchpoint_enable(TASK_STACK_WATCHPOINT_INDEX, (uint32_t)&__CSTACK__start, WATCHPOINT_ON_WRITE, 0x5);
#endif

    nltimer_init();

    // Though bootloader did watchdog_init(), we have to run
    // again in the app since we need to check debugger state.
    nlwatchdog_init();

    nltimer_request(NLTIMER_DELAY);

    /* everything else was initialized by bootloader */
}

void nlplatform_cstartup_init(void)
{
#ifdef PRODUCT_NRF_DCDCEN
    /* use product defined regulator configuration */
    NRF_POWER->DCDCEN = PRODUCT_NRF_DCDCEN;
#else
    // enable DCDC buck, which is more efficient than the LDO that we boot with.
    // assumes external LC components are present to support DCDC.
    NRF_POWER->DCDCEN = POWER_DCDCEN_DCDCEN_Enabled << POWER_DCDCEN_DCDCEN_Pos;
#endif

    // enable instruction cache, profiling disabled
    NRF_NVMC->ICACHECNF = NVMC_ICACHECNF_CACHEEN_Msk;

    // enable ITM/DWT and debug monitor, which is used by watchpoint module,
    // nlwatchdog, and swo_vuart
    CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk | CoreDebug_DEMCR_MON_EN_Msk;

    guard_cstack_and_address_0();

#ifdef BUILD_FEATURE_WATCHPOINT_STACK_GUARD
    // disable watchpoint used for stack guarding so any stack init routines
    // don't trip the watchpoint during early boot
    nl_watchpoint_disable(TASK_STACK_WATCHPOINT_INDEX);
#endif
}

#else /* NL_BOOTLOADER */

#if defined(BUILD_FEATURE_WATCHDOG) && defined(BUILD_FEATURE_SW_TIMER)
static nl_swtimer_t watchdog_late_timer;
static uint32_t late_watchdog_timer_expiry(nl_swtimer_t *timer, void *arg)
{
    // No need to do anything, the wakeup alone should be enough to
    // expire the watchdog
    return 0;
}
#endif

/* used by apps */
void nlplatform_init(void)
{
    sCachedRebootCause = NRF_POWER->RESETREAS;
    // clear reset reasons so next read of the register doesn't have stale data
    NRF_POWER->RESETREAS = 0xffffffff;

    /* seed rand() */
    srand(nlplatform_get_random_number());

#ifdef BUILD_FEATURE_NO_INIT_FROM_BOOTLOADER
    /* If using the Nest bootloader then gpio init from
     * bootloader is sufficient, no need to repeat here. */
    nlgpio_init();
#endif

    // Though bootloader did watchdog_init(), we have to run
    // again in the app since we need to check debugger state.
    nlwatchdog_init();

    nltimer_init();

    // Configure timer we use for delays to be 32-bit, free running
    // and auto-repeating when it hits max uint32.
    // We turn it on and off as needed in nlplatform_delay_us().
    nltimer_request(NLTIMER_DELAY);
    nltimer_set(NLTIMER_DELAY, 0xffffffff, NULL, NULL, true);

    nluart_init(); /* needed to allocate semaphores per controller */

#if defined(BUILD_FEATURE_WATCHDOG) && defined(BUILD_FEATURE_SW_TIMER)
    nl_swtimer_init(&watchdog_late_timer, late_watchdog_timer_expiry, NULL);
#endif

#if defined(BUILD_FEATURE_SW_TIMER)
    nl_swtimer_init(&s_blk_sleep_tmr.timer, blk_sleep_tmr_cb, NULL);
#endif

    nlplatform_crypto_init();
}

void nlplatform_cstartup_init(void)
{
    // re-initialize the MPU and request a region to guard the CSTACK.
    // our GUARD_REGION might be different than the one in bootloader.
    guard_cstack_and_address_0();

    // watchpoint should already be disabled by bootloader so it won't
    // interfere with .data or .bss initialization
}

#endif /* NL_BOOTLOADER */

void nlplatform_reset(nl_reset_reason_t reset_reason)
{
#ifdef BUILD_FEATURE_RESET_INFO
    nl_reset_info_prepare_reset(reset_reason, NULL);
#endif

    // Run any product-specific reset hooks
    nlproduct_prepare_reset(reset_reason);

    // clear HW resetreas so it doesn't have stale info
    NRF_POWER->RESETREAS = 0xffffffff;

    NVIC_SystemReset();
}

int nlplatform_get_unique_id(const uint8_t **uid, size_t *len)
{
    *uid = (uint8_t *)&NRF_FICR->DEVICEID[0];
    *len = 8;

    return 0;
}

#if !defined(NL_BOOTLOADER)
void nlplatform_print_reset_cause(void)
{
    uint32_t uiX, uiY, uiZ;
    /**
     * Scan through the reset events and print out descriptors for
     * any of them which are set (on some hardware it is possible to
     * get multiple reset events, not sure about the EM35x, but may as
     * well check them all).
     *
     * The WatchDog is a special case where we'll also print out the
     * last flag state in order to determine which tasks (if any)
     * instigated the reset.
     */
    uiY = 0;
    uiZ = sCachedRebootCause;
    printf("Reset Event(s) : ");
    for (uiX = 0; uiX < ARRAY_SIZE(reset_evMasks); uiX++)
    {
        if (uiZ & reset_evMasks[uiX])
        {
            if (uiY > 0)
            {
                printf(", ");
            }
            uiY++;

            printf("%s", reset_evDescs[uiX]);
            if (POWER_RESETREAS_DOG_Msk == reset_evMasks[uiX])
            {
                printf(" (Flags $%08lx)", nl_watchDog_lastFlags);
            }
        }
    }
    printf("\n");
}

void nlplatform_print_wakeup_cause(void)
{
    // We're not using System OFF mode, just System ON low power,
    // and there's no special HW support for determining what
    // event/interrupt caused us to exit idle.  We don't try
    // to determine the wakeup cause
    printf("Wakeup cause unknown\n");
}
#endif /* !defined(NL_BOOTLOADER) */

static uint32_t rand32(void)
{
    uint32_t result;
    uint8_t *p8 = (uint8_t*)&result;
    uint8_t *p8end = (uint8_t*)(&result + 1);

    /* Enable bias correction.  Slower result but more uniformly distributed. */
    NRF_RNG->CONFIG = RNG_CONFIG_DERCEN_Enabled;
    /* Start */
    NRF_RNG->TASKS_START = 1;
    /* Collect 4 samples */
    while (p8 < p8end)
    {
        /* Clear VALRDY event status */
        NRF_RNG->EVENTS_VALRDY = 0;
        /* Wait for value to be ready */
        while (NRF_RNG->EVENTS_VALRDY == 0);
        /* Add to result */
        *p8++ = NRF_RNG->VALUE;
    }
    /* Stop to save power */
    NRF_RNG->TASKS_STOP = 1;
    return result;
}

uint32_t nlplatform_get_random_number(void)
{
#ifdef NL_BOOTLOADER
    return rand32();
#else
    uint32_t result;
    // disable interrupts while collecting random number to make it thread safe
    nlplatform_interrupt_disable();
    result = rand32();
    nlplatform_interrupt_enable();
    return result;
#endif
}

int nlplatform_get_entropy(unsigned char *outEntropy, size_t inSize)
{
    unsigned char *entropy;
    uint32_t      idx;
    uint32_t      rval;

    do
    {
        rval = (int)nlplatform_get_random_number();

        entropy = (unsigned char *)&rval;

        for (idx = 0; (idx < sizeof(int)) && (inSize > 0); idx++, inSize--)
            *outEntropy++ = *entropy++;
    }
    while (inSize > 0);

    return 0;
}

#ifdef NL_BOOTLOADER

/* No RTOS version doesn't need the complexity of thread-safety
 * so keep the code smaller and simpler.
 */
void nlplatform_delay_ms(unsigned delay_ms)
{
    // long delays might indicate a problem so assert to catch these.
    // also since HW timer is in microseconds and max 32-bit, this
    // catches value being too large.
    assert(delay_ms < 1000);
    nlplatform_delay_us(delay_ms * 1000);
}

void nlplatform_delay_us(unsigned delay_us)
{
    // long delays might indicate a problem so assert to catch these
    assert(delay_us < 1000000);
    // The Nordic reference code just delays by looping
    // with NOPS.  It says it's not very accurate since instruction
    // execution rate can vary based on clock and whether the code
    // is running from RAM, FLASH, or instruction cached FLASH.
    //
    // For now, we use a HW TIMER to do the delay, and then turn
    // it off to save power.

    // Configure for one-shot, auto-stop, no callback (we'll
    // just poll)
    nltimer_set(NLTIMER_DELAY, delay_us, NULL, NULL, false);
    nltimer_start(NLTIMER_DELAY);
    while (nltimer_active(NLTIMER_DELAY)) {};
    // Although stopped, call nltimer_stop() to shutdown and save power
    nltimer_stop(NLTIMER_DELAY);
}

#else /* NL_BOOTLOADER */

void nlplatform_delay_ms(unsigned delay_ms)
{
    while (delay_ms > 0) {
        nlplatform_delay_us(1000);
        delay_ms--;
    }
}

void nlplatform_delay_us(unsigned delay_us)
{
    // long delays might indicate a problem so assert to catch these
    assert(delay_us < 1000000);
    // The Nordic reference code just delays by looping
    // with NOPS.  It says it's not very accurate since instruction
    // execution rate can vary based on clock and whether the code
    // is running from RAM, FLASH, or instruction cached FLASH.
    //
    // For now, we use a HW TIMER to do the delay, and then turn
    // it off to save power.

    static uint8_t s_active_delays;
    uint32_t time_at_start;

    // increment the s_active_delays counter inside a critical section
    nlplatform_interrupt_disable();
    if (s_active_delays++ == 0)
    {
        // Start the HW timer
        time_at_start = 0;
        nltimer_start(NLTIMER_DELAY);
    }
    else
    {
        // Timer is already running, record start time
        time_at_start = nltimer_elapsed(NLTIMER_DELAY);
    }
    // while we wait, enable interrupts so we don't keep interrupts
    // off too long.
    nlplatform_interrupt_enable();

    // loop until the elapsed time reaches the target. HW timer
    // should wrap.
    while ((nltimer_elapsed(NLTIMER_DELAY) - time_at_start) < delay_us) {};

    // decrement the s_active_delays counter inside a critical section
    nlplatform_interrupt_disable();
    if (--s_active_delays == 0)
    {
        // we can shut off the timer now
        nltimer_stop(NLTIMER_DELAY);
    }
    nlplatform_interrupt_enable();
}

#endif /* NL_BOOTLOADER */

uint32_t nlplatform_get_last_reset_cause(void)
{
    return sCachedRebootCause;
}

nl_reset_reason_t nlplatform_get_reset_reason(void)
{
    static nl_reset_reason_t sCachedResetReason = NL_RESET_REASON_UNSPECIFIED;

    if (sCachedResetReason == NL_RESET_REASON_UNSPECIFIED)
    {
#ifdef BUILD_FEATURE_RESET_INFO
        nl_reset_reason_t reason;
#endif

        sCachedResetReason = NL_RESET_REASON_UNKNOWN;

        if (sCachedRebootCause & POWER_RESETREAS_RESETPIN_Msk)
        {
            // TODO: Uncomment this line once this constant is
            // introduced into nlplatform
            //sCachedResetReason = NL_RESET_REASON_EXTERNAL;
        }

#ifdef BUILD_FEATURE_RESET_INFO
        else if ((reason = nl_reset_info_get_reset_reason()) != NL_RESET_REASON_UNKNOWN)
        {
            sCachedResetReason = reason;
        }
        else if (IS_VALID_FAULT_REASON(g_reset_info.fault_info.reason))
        {
            sCachedResetReason = g_reset_info.fault_info.reason;
        }
#endif

        else if (sCachedRebootCause & POWER_RESETREAS_LOCKUP_Msk)
        {
            sCachedResetReason = NL_RESET_REASON_HARD_FAULT;
        }
        else if ((sCachedRebootCause & POWER_RESETREAS_OFF_Msk)    ||
                 (sCachedRebootCause & POWER_RESETREAS_LPCOMP_Msk) ||
                 (sCachedRebootCause & POWER_RESETREAS_DIF_Msk)    ||
                 (sCachedRebootCause & POWER_RESETREAS_NFC_Msk)    ||
                 (sCachedRebootCause & POWER_RESETREAS_VBUS_Msk))
        {
            sCachedResetReason = NL_RESET_REASON_UNKNOWN;
        }
        else if (sCachedRebootCause & POWER_RESETREAS_DOG_Msk)
        {
            sCachedResetReason = NL_RESET_REASON_WATCHDOG;
        }
        else if (sCachedRebootCause & POWER_RESETREAS_SREQ_Msk)
        {
            sCachedResetReason = NL_RESET_REASON_SW_REQUESTED;
        }
        else
        {
            // TODO: Uncomment this line once this constant is
            // introduced into nlplatform
            //sCachedResetReason = NL_RESET_REASON_POWER_ON;
        }
    }

    return sCachedResetReason;
}

void nlplatform_reset_info_init_done(void)
{
}

void nlplatform_quiesce_on_fault(void)
{
#if !defined(NL_BOOTLOADER)
    /**
     * If we're NOT targeting a bootloader build the UART will be in
     * asynchronous mode and requires a switch into FORCED SYNC MODE
     * prior to any further activity (i.e. printing) in the fault handler.
     */
    nluart_force_sync(CONSOLE_UART_ID);

    /**
     * Suspend task switching so that NLER logging calls do not try to
     * run scheduler.
     */
    vTaskSuspendAll();
#endif
#if (defined(NL_DISABLE_WATCHDOG_OPERATION) || defined(NL_WATCHDOG_REQUIRE_ENROLLMENT))
    /**
     * If compiled to not enable watchdog by default, enable it here so that we don't
     * hang in fault handler.
     */
    nlwatchdog_set_enable(true);
#endif
}

// Define a scratch buffer to be used for things like env
// Make sure it's word aligned.
uint8_t flash_activity_buffer[FLASH_BUFFER_SIZE] __attribute__((aligned(4))) __attribute__((used)) = {0};

// In diags mode or if explicitly allowing sysenv writes, define a large temp buffer to be used by
// env-dump, flash-exttest, sysenv writes, and env-unittest.
#if defined(BUILD_CONFIG_DIAGNOSTICS) || defined(BUILD_FEATURE_SYSENV_WRITES_ALLOWED)
uint8_t diags_temp_buffer[DIAGS_TEMP_RAM_SIZE] __attribute__((aligned(4))) __attribute__((used)) = {0};
// also define a small buffer
uint8_t diags_small_temp_buffer[DIAGS_SMALL_TEMP_RAM_SIZE] __attribute__((aligned(4))) __attribute__((used)) = {0};
#endif

// used by nlflash.c
const nlflash_func_table_t g_flash_device_table[NL_NUM_FLASH_IDS] =
{
    // flash_nrf52840 internal flash
    {
        // the bootloader doesn't need these but AUPD does.
        // rather than compiling three variants of this library
        // (normal, bootloader, aupd), we only compile two
        // and leave these hooks in.
        .init = NULL,
        .request = NULL,
        .release = NULL,
        .flush = NULL,
        .read_id = NULL,
        .get_info = nlflash_nrf52x_get_info,
        .erase = nlflash_nrf52x_erase,
        .read = nlflash_nrf52x_read,
        .write = nlflash_nrf52x_write,
    },
#ifndef BUILD_FEATURE_NO_SPI_FLASH
    // flash_spi
    {
        .init = NULL,
        .request = nlflash_spi_request,
        .release = nlflash_spi_release,
        .flush = nlflash_spi_flush,
        .read_id = nlflash_spi_read_id,
        .get_info = nlflash_spi_get_info,
        .erase = nlflash_spi_erase,
        .read = nlflash_spi_read,
        .write = nlflash_spi_write,
    },
#endif
};

void nlplatform_block_sleep(bool block)
{
    nlplatform_interrupt_disable();
    if (block)
    {
#if defined(BUILD_FEATURE_NL_PROFILE) && !defined(NL_NO_RTOS)
        if (sBlockSleepCount == 0)
        {
            nl_profile_start(NL_PROFILE_DEEP_SLEEP_BLOCKED);
        }
#endif
        sBlockSleepCount++;
    }
    else
    {
        sBlockSleepCount--;
        nlASSERT(sBlockSleepCount >= 0);
#if defined(BUILD_FEATURE_NL_PROFILE) && !defined(NL_NO_RTOS)
        if (sBlockSleepCount == 0)
        {
            nl_profile_stop(NL_PROFILE_DEEP_SLEEP_BLOCKED);
        }
#endif
    }
    nlplatform_interrupt_enable();
}

bool nlplatform_is_sleep_blocked(void)
{
    return (sBlockSleepCount != 0);
}

#if defined(BUILD_FEATURE_SW_TIMER) && !defined(NL_NO_RTOS)
static uint32_t blk_sleep_tmr_cb(nl_swtimer_t *timer, void *arg)
{
    nlplatform_block_sleep(false);
    return 0;
}

void nlplatform_block_sleep_ms(unsigned ms)
{
    nl_time_native_t curr;
    nl_time_native_t block_time_ticks;
    nl_time_native_t end;

    block_time_ticks = nl_time_ms_to_delay_time_native(ms);

    /* Use a critical section so that the timer cannot expire nor system time
     * elapse while its determined whether a timer restart is needed. */
    nlplatform_interrupt_disable();

    curr = xTaskGetTickCount();
    end = curr + block_time_ticks;

    if (nl_swtimer_is_active(&s_blk_sleep_tmr.timer))
    {
        if (block_time_ticks > (s_blk_sleep_tmr.end - curr))
        {
            /* A longer duration of sleep-blocking than currently scheduled is
             * needed. */
            s_blk_sleep_tmr.end = end;
            nl_swtimer_cancel(&s_blk_sleep_tmr.timer);
            nl_swtimer_start(&s_blk_sleep_tmr.timer, ms);
        }

    }
    else
    {
        nlplatform_block_sleep(true);
        s_blk_sleep_tmr.end = end;
        nl_swtimer_start(&s_blk_sleep_tmr.timer, ms);
    }

    nlplatform_interrupt_enable();
}
#endif

/* For FreeRTOS V10.0.1, the base of the stack is
 * at offset 48 into the TCB:
 *     (gdb) p/d &((tskTCB *)0)->pxStack
 *     $16 = 48
 */
#define TCB_OFFSET_PX_STACK 48

#if !defined(NL_BOOTLOADER)
void nlplatform_soc_dump_context(void)
{
    printf("- SOC context: -\n");

#ifdef BUILD_FEATURE_WATCHPOINT_STACK_GUARD
    // Dump watchpoint state
    TaskHandle_t currentTaskHandle = xTaskGetCurrentTaskHandle();
    if (currentTaskHandle)
    {
        uint32_t stackBaseAddress = *(uint32_t*)((uint32_t)(currentTaskHandle) + TCB_OFFSET_PX_STACK);
        printf("CurrentTask = '%s', stackBase = 0x%x\n", pcTaskGetName(currentTaskHandle), stackBaseAddress);
    }

    printf("DWT->COMP3 = 0x%08x\n", DWT->COMP3);
    printf("DWT->MASK3 = 0x%08x\n", DWT->MASK3);
    printf("DWT->FUNCTION3 = 0x%08x\n", DWT->FUNCTION3);
#endif

    // Dump additional debug halt reason registers
    printf("DEMCR = 0x%x\n", CoreDebug->DEMCR);
}

void nlplatform_configure_stack_guard(void)
{
    TaskHandle_t currentTaskHandle = xTaskGetCurrentTaskHandle();
    uint32_t stackBaseAddress = *(uint32_t*)((uint32_t)(currentTaskHandle) + TCB_OFFSET_PX_STACK);
    (void)stackBaseAddress;
#ifdef BUILD_FEATURE_MPU_STACK_GUARD
    halInternalSetMPUStackGuardRegionStart(stackBaseAddress);
#endif
#ifdef BUILD_FEATURE_WATCHPOINT_STACK_GUARD
    // double check that the stackBaseAddress is 32-byte aligned, so the mask we
    // pass to nl_watchpoint_enable() actually works in guarding the first 32 bytes
    // of the task stack
    assert((stackBaseAddress % 32) == 0);

    // use the last watchpoint to guard the first 32-bytes of the current task stack
    nl_watchpoint_enable(TASK_STACK_WATCHPOINT_INDEX, stackBaseAddress, WATCHPOINT_ON_WRITE, 0x5);
#endif
}
#endif /* !defined(NL_BOOTLOADER) */

#if !defined(NL_BOOTLOADER)

/* Implementation of system tick and vPortSuppressTicksAndSleep() ported from Nordic SDK.
 * The FreeRTOS port uses the RTC and not SysTick as the tick source.
 * I believe this is because the RTC keeps running during SOC sleep
 * whereas SysTick does not.
 *
 * RTC is a 24-bit counter, which we're configuring to run at 250Hz (4ms tick).
 */

/* Count of extra ticks slept.  Particularly when stepping through there
 * sleep code in a debugger, the count of ticks slept can be much higher
 * than waht was requested.  FreeRTOS is unhappy if vTaskStepTick() is
 * given a count that is higher than it requested.  So, we keep track
 * of the extra ticks in this global and feed them back to the kernel
 * over time in subsequent tick irqs.
 */
static uint32_t extra_sleep_ticks;

extern void xPortSysTickHandler(void);

void nlrtc1_isr ( void );
void nlrtc1_isr ( void )
{
    NRF_RTC1->EVENTS_TICK = 0;
    NRF_RTC1->EVENTS_COMPARE[0] = 0;

    xPortSysTickHandler();

    /* Feed one extra sleep tick, if any.
     * Note we do not read the counter register and try to see
     * if any ticks were missed due to late/delayed RTC1_IRQ.
     * It's not expected to have interrupt latency over 4ms (the
     * default tick - some systems might have an even longer tick
     * like 10ms), and it's somewhat expensive to read the COUNTER
     * register due to need for synchronization between the CPU clock
     * and the lfclk that drives the RTC
     */
    if (extra_sleep_ticks > 0)
    {
        extra_sleep_ticks--;
        xPortSysTickHandler();
    }
}

/*
 * Setup the RTC to generate the tick interrupts at the required
 * frequency, overriding weak definition in freertos
 */
void vPortSetupTimerInterrupt( void );
void vPortSetupTimerInterrupt( void )
{
    /* Configure RTC1 to interrupt at the requested rate. */
    NRF_RTC1->PRESCALER = NRF_RTC_PRESCALER_VALUE;
    NRF_RTC1->INTENSET = (RTC_INTENSET_TICK_Set << RTC_INTENSET_TICK_Pos);
    NRF_RTC1->TASKS_CLEAR = 1;
    NRF_RTC1->TASKS_START = 1;

    NVIC_EnableIRQ(RTC1_IRQn);
}

// Maximum tick count at 24-bits
#define portNRF_RTC_MAXTICKS ((1 << 24) - 1)

// Set to 1 to get some info about events before and after WFE
#define DEBUG_SLEEP_EVENTS 0

static void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime )
{
    /*
     * Implementation note:
     *
     * To help debugging the option configUSE_TICKLESS_IDLE_SIMPLE_DEBUG was presented.
     * This option would make sure that even if program execution was stopped inside
     * this function no more than expected number of ticks would be skipped.
     *
     * Normally RTC works all the time even if firmware execution was stopped
     * and that may lead to skipping too much of ticks.
     */
    TickType_t enterTime;

    /* We don't support a delay of 1 because the HW counter is free running and
     * there could be a race where the counter is incremented after we read the
     * current value, causing the CC value we set to be invalid (would never
     * trigger an interrupt until counter rolled over).
     */
    assert(xExpectedIdleTime > 1);

    /* Make sure the SysTick reload value does not overflow the counter. */
    if ( xExpectedIdleTime > portNRF_RTC_MAXTICKS - configEXPECTED_IDLE_TIME_BEFORE_SLEEP )
    {
        xExpectedIdleTime = portNRF_RTC_MAXTICKS - configEXPECTED_IDLE_TIME_BEFORE_SLEEP;
    }
    /* Block all the interrupts globally */
#ifdef SOFTDEVICE_PRESENT
    do{
        uint8_t dummy = 0;
        uint32_t err_code = sd_nvic_critical_region_enter(&dummy);
        APP_ERROR_CHECK(err_code);
    }while(0);
#else
    nlplatform_interrupt_disable();
#endif

    enterTime = NRF_RTC1->COUNTER;

    if ( eTaskConfirmSleepModeStatus() != eAbortSleep )
    {
        TickType_t xModifiableIdleTime;
        TickType_t wakeupTime = (enterTime + xExpectedIdleTime) & portNRF_RTC_MAXTICKS;

        /* Stop tick events */
        NRF_RTC1->INTENCLR = RTC_INTENCLR_TICK_Clear;

        /* Configure compare interrupt for our wakeupTime */
        NRF_RTC1->CC[0] = wakeupTime;
        NRF_RTC1->EVENTS_COMPARE[0] = 0;
        NRF_RTC1->INTENSET = (RTC_INTENSET_COMPARE0_Set << RTC_INTENSET_COMPARE0_Pos);

        /* CryptoCell appears to be setting a pending interrupt bit in ISPR, even though we
         * don't enable it. Clear it to prevent it from keeping us from sleeping.
         */
        if (NVIC_GetPendingIRQ(CRYPTOCELL_IRQn))
        {
            NVIC_ClearPendingIRQ(CRYPTOCELL_IRQn);
        }

        /* Suspend uart */
        nluart_suspend();

#if DEBUG_SLEEP_EVENTS
        uint32_t pre_wfe_ispr0;
        uint32_t pre_wfe_ispr1;
        uint32_t post_wfe_ispr0;
        uint32_t post_wfe_ispr1;
        uint32_t wfe_count = 0;
#endif

        __DSB();

        /* Sleep until something happens.  configPRE_SLEEP_PROCESSING() can
         * set its parameter to 0 to indicate that its implementation contains
         * its own wait for interrupt or wait for event instruction, and so wfi
         * should not be executed again.  However, the original expected idle
         * time variable must remain unmodified, so a copy is taken. */
        xModifiableIdleTime = xExpectedIdleTime;
        configPRE_SLEEP_PROCESSING( xModifiableIdleTime );

#if DEBUG_SLEEP_EVENTS
        pre_wfe_ispr0 = NVIC->ISPR[0];
        pre_wfe_ispr1 = NVIC->ISPR[1];
#endif
        if ( xModifiableIdleTime > 0 )
        {
            bool enable_ITM_DWT_after_sleep = false;

            // disable MPU that was guarding main stack to save power
            nl_mpu_enable(false, false, false);

#ifdef BUILD_FEATURE_WATCHPOINT_STACK_GUARD
            // suspend task stack guard watchpoint to save power
            nl_watchpoint_disable(TASK_STACK_WATCHPOINT_INDEX);
#endif

            if (!(CoreDebug->DHCSR & CoreDebug_DHCSR_C_DEBUGEN_Msk))
            {
                /* no debugger connected, disable ITM/DWT to save power.
                 * note that other users of ITM/DWT are:
                 *  - watchpoint, which is the most common user, but
                 *    we just disabled it
                 *  - virtual uart, which should be okay to suspend
                 *    in sleep
                 *  - CYCCNT for watchdog when debugger is connected,
                 *    but we know debugger is not connected so CYCCNT
                 *    should not be in use
                 */
                if (CoreDebug->DEMCR & (CoreDebug_DEMCR_TRCENA_Msk | CoreDebug_DEMCR_MON_EN_Msk))
                {
                    enable_ITM_DWT_after_sleep = true;
                    CoreDebug->DEMCR &= ~(CoreDebug_DEMCR_TRCENA_Msk | CoreDebug_DEMCR_MON_EN_Msk);
                }
            }

            // note: instruction cache is automatically powered down in sleep

            do
            {
#if DEBUG_SLEEP_EVENTS
                wfe_count++;
#endif
                __WFE();
            } while (0 == (NVIC->ISPR[0] | NVIC->ISPR[1]));

            // enable ITM/DWT if we had disabled it during sleep
            if (enable_ITM_DWT_after_sleep)
            {
                CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk | CoreDebug_DEMCR_MON_EN_Msk;
            }

#ifdef BUILD_FEATURE_WATCHPOINT_STACK_GUARD
            // restore watchpoint that is guarding task stack
            nl_watchpoint_set_type(TASK_STACK_WATCHPOINT_INDEX, WATCHPOINT_ON_WRITE);
#endif

            // enable MPU guarding main stack
            nl_mpu_enable(true, true, true);
        }
#if DEBUG_SLEEP_EVENTS
        post_wfe_ispr0 = NVIC->ISPR[0];
        post_wfe_ispr1 = NVIC->ISPR[1];
#endif

        configPOST_SLEEP_PROCESSING( xExpectedIdleTime );
        NRF_RTC1->INTENCLR = (RTC_INTENCLR_COMPARE0_Clear << RTC_INTENCLR_COMPARE0_Pos);
        NRF_RTC1->EVENTS_COMPARE[0] = 0;

        /* resume_uart */
        nluart_resume();

#if DEBUG_SLEEP_EVENTS
        printf("%s: after WFE (count = %u), pre_wfe_ispr0 = 0x%08x, pre_wfe_ispr1 = 0x%08x, post_wfe_ispr0 = 0x%08x, post_wfe_ispr1 = 0x%08x\n",
            __func__, wfe_count, pre_wfe_ispr0, pre_wfe_ispr1, post_wfe_ispr0, post_wfe_ispr1);
#endif

        /* Reenable tick interrupt and update tick count after sleep */
        {
            TickType_t diff;
            TickType_t exitTime;

            NRF_RTC1->EVENTS_TICK = 0;
            NRF_RTC1->INTENSET = (RTC_INTENSET_TICK_Set << RTC_INTENSET_TICK_Pos);

            exitTime = NRF_RTC1->COUNTER;

            // TickType_t is 32-bit, but register is 24-bit, so handle
            // wrapping by & with max 24-bit value
            diff = (exitTime - enterTime) & portNRF_RTC_MAXTICKS;

            /* It is important that we clear pending here so that our
             * corrections are latest and in sync with tick_interrupt handler.
             * Otherwise we could immediately get a IRQ and add an extra tick
             * after sleep.
             */
            NVIC_ClearPendingIRQ(RTC1_IRQn);

#if DEBUG_SLEEP_EVENTS
            printf("%s: sleep resumed after %u ticks\n", __func__, diff);
#endif

            if (diff > 0)
            {
                /* FreeRTOS asserts if the actual sleep time was longer than
                 * requested. This can happen when using a debugger.
                 * Save the extra ticks in a global that we feed back
                 * to FreeRTOS in the RTC IRQHandler.
                 */
                if (diff > xExpectedIdleTime)
                {
                    extra_sleep_ticks += diff - (xExpectedIdleTime - 1);
                    diff = xExpectedIdleTime - 1;
                    /* Pend the nlrtc1_isr() immediately to start
                     * processing the extra ticks
                     */
                    NVIC_SetPendingIRQ(RTC1_IRQn);
                }
                vTaskStepTick(diff);
            }
        }
    }
#ifdef SOFTDEVICE_PRESENT
    uint32_t err_code = sd_nvic_critical_region_exit(0);
    APP_ERROR_CHECK(err_code);
#else
    nlplatform_interrupt_enable();
#endif
}

void nlplatform_suppress_ticks_and_sleep(uint32_t xExpectedIdleTime);
void nlplatform_suppress_ticks_and_sleep(uint32_t xExpectedIdleTime)
{
#ifdef BUILD_FEATURE_SW_TIMER_USES_RTOS_TICK
    bool timer_sleep_ok;
    TickType_t before_sleep_tick_count;
#endif

#ifdef BUILD_FEATURE_SW_TIMER_USES_RTOS_TICK
    timer_sleep_ok = nl_swtimer_pre_sleep(&before_sleep_tick_count, &xExpectedIdleTime);
    // FreeRTOS imposes a minimum tick time before sleep of configEXPECTED_IDLE_TIME_BEFORE_SLEEP
    // (defaults to 2, but could be higher), but nl_swtimer_pre_sleep()
    // might have changed xExpectedIdleTime to be less than that. We want to still
    // enforce the FreeRTOS configured minimum. It's expecially bad if the value
    // is 1 because there could be a race when computing the wakeup time if
    // the underlying HW counter increments right after we read the current
    // value because the setting for the wakeup interrupt might miss the
    // counter increment and we won't get the CC match until the counter
    // wraps!
    if (timer_sleep_ok && !nlplatform_is_sleep_blocked() && xExpectedIdleTime > configEXPECTED_IDLE_TIME_BEFORE_SLEEP)
    {
#endif

#if defined(BUILD_FEATURE_NL_PROFILE) && !defined(NL_NO_RTOS)
        nl_profile_start(NL_PROFILE_DEEP_SLEEP);
#endif
        vPortSuppressTicksAndSleep(xExpectedIdleTime);
#if defined(BUILD_FEATURE_NL_PROFILE) && !defined(NL_NO_RTOS)
        nl_profile_stop(NL_PROFILE_DEEP_SLEEP);
#endif

#ifdef BUILD_FEATURE_SW_TIMER_USES_RTOS_TICK
    }
    nl_swtimer_post_sleep(before_sleep_tick_count);
#endif
}
#endif // NL_BOOTLOADER

bool nlplatform_bootloader_is_locked(void)
{
    // a value of 0x00 for APPROTECT means the bootloader is locked
    return (NRF_UICR->APPROTECT == 0x00);
}

void nlplatform_acl_configure(nlacl_id_t acl_id, unsigned region_start_addr, unsigned region_size, unsigned permission)
{
    assert(acl_id <= MAX_ACL_ID);
    // assert that region start addr is aligned on flash page boundary
    assert((region_start_addr & (NRF52X_INTERNAL_FLASH_ERASE_SIZE - 1)) == 0);
    // assert that region_size is not zero and is a multiple of the flash page size
    assert((region_size > 0) && ((region_size & (NRF52X_INTERNAL_FLASH_ERASE_SIZE - 1)) == 0));
    // assert that permission is valid. since 0 is no protection, which is already the
    // default, it's probably an error to request that so don't allow no protection
    assert((permission == NL_ACL_PERMISSION_BLOCK_WRITE_ERASE) ||
           (permission == NL_ACL_PERMISSION_BLOCK_EXECUTE_READ) ||
           (permission == NL_ACL_PERMISSION_BLOCK_ALL));
    // all registers are write-once per boot so check that they are currently in reset state
    assert(NRF_ACL->ACL[acl_id].ADDR == 0);
    assert(NRF_ACL->ACL[acl_id].SIZE == 0);
    assert(NRF_ACL->ACL[acl_id].PERM == 0);

    // now do the actual writes to the configuration registers
    NRF_ACL->ACL[acl_id].ADDR = region_start_addr;
    NRF_ACL->ACL[acl_id].SIZE = region_size;
    NRF_ACL->ACL[acl_id].PERM = permission;

    // Do two dummy reads to so new permissions are enforced by the time function returns.
    // OPS says enforcement takes two clock cycles after last register is written.
    (void)NRF_ACL->ACL[acl_id].ADDR;
    (void)NRF_ACL->ACL[acl_id].ADDR;
}

// If APPROTECT is enabled, disable it by erasing UICR. We backup
// and restore to the UICR all other fields except the APPROTECT,
// and also set the CUSTOMER[UNLOCK_UICR_CUSTOMER_INDEX] to indicate
// we're now in a pesistent unlocked state (so that next call
// of nlplatform_external_debugger_access_disable() will do nothing)
void nlplatform_external_debugger_access_enable(void *scratch_buffer, size_t scratch_buffer_size)
{
    if (NRF_UICR->APPROTECT == UICR_APPROTECT_PALL_Enabled)
    {
        // enable external debugger access by erasing UICR and restoring
        // all contents of the UICR except set APPROTECT to disabled and
        // set CUSTOMER[UNLOCK_UICR_CUSTOMER_INDEX] to UNLOCK_VALUE_UNLOCK_TOKEN_RECEIVED
        int retval;
        size_t retlen;
        NRF_UICR_Type *uicr_backup_buf = (NRF_UICR_Type*)scratch_buffer;
        assert(scratch_buffer_size >= NRF52X_INTERNAL_FLASH_ERASE_SIZE);

        // copy current UICR to RAM buffer
        memcpy(uicr_backup_buf, NRF_UICR, NRF52X_INTERNAL_FLASH_ERASE_SIZE);

        // set APPROTECT in the backup to disabled
        uicr_backup_buf->APPROTECT = UICR_APPROTECT_PALL_Disabled;

        // set CUSTOMER[UNLOCK_UICR_CUSTOMER_INDEX] to UNLOCK_VALUE_UNLOCK_TOKEN_RECEIVED
        uicr_backup_buf->CUSTOMER[UNLOCK_UICR_CUSTOMER_INDEX] = UNLOCK_VALUE_UNLOCK_TOKEN_RECEIVED;

        // enable erase
        NRF_NVMC->CONFIG = NVMC_CONFIG_WEN_Een;
        // erase UICR
        NRF_NVMC->ERASEUICR = NVMC_ERASEUICR_ERASEUICR_Erase;
        // wait for erase to finish
        while (NRF_NVMC->READY == NVMC_READY_READY_Busy);
        // go back to read enable
        NRF_NVMC->CONFIG = NVMC_CONFIG_WEN_Ren;

        // write UICR we saved/modified earlier
        retval = nlflash_write(NLFLASH_INTERNAL, NRF_UICR_BASE, NRF52X_INTERNAL_FLASH_ERASE_SIZE,
                               &retlen, (const uint8_t*)uicr_backup_buf, NULL);
        (void)retval;
        assert(retval == 0);
    }
}

// checks the APPROTECT register in UICR. If it is not enabled and the UICR
// customer register we use to indicate a device is in a persisent
// unlocked state is not set (i.e. device was sent an unlock token)
// then enable APPROTECT and reboot to enforce new APPROTECT setting
// (according to Nordic OPS manual, changes to UICR only take effect after a reset).
void nlplatform_external_debugger_access_disable(void)
{
    if ((NRF_UICR->APPROTECT != UICR_APPROTECT_PALL_Enabled) &&
        (NRF_UICR->CUSTOMER[UNLOCK_UICR_CUSTOMER_INDEX] == UNLOCK_VALUE_NO_UNLOCK_TOKEN_RECEIVED))
    {
        // APPROTECT not enabled and not set to unlock, enable it now by
        // setting APPROTECT to UICR_APPROTECT_PALL_Enabled

        // Enable write access to UICR/internal FLASH
        NRF_NVMC->CONFIG = NVMC_CONFIG_WEN_Wen;
        // Set APPROTECT to enable (which blocks out external debuggers)
        NRF_UICR->APPROTECT = UICR_APPROTECT_PALL_Enabled;
        // Wait for write to finish
        while (NRF_NVMC->READY == NVMC_READY_READY_Busy);
        // Reset so new value is applied
        nlplatform_reset(NL_RESET_REASON_SW_REQUESTED);
        // Never gets here
    }
}

bool nlplatform_get_external_debugger_access(void)
{
    return NRF_UICR->APPROTECT != UICR_APPROTECT_PALL_Enabled;
}


text:
<Type Name="CTRunDelegate" FullName="MonoMac.CoreText.CTRunDelegate">
  <TypeSignature Language="C#" Value="public class CTRunDelegate : MonoMac.CoreFoundation.CFType" />
  <TypeSignature Language="ILAsm" Value=".class public auto ansi beforefieldinit CTRunDelegate extends MonoMac.CoreFoundation.CFType" />
  <AssemblyInfo>
    <AssemblyName>MonoMac</AssemblyName>
    <AssemblyVersion>0.0.0.0</AssemblyVersion>
  </AssemblyInfo>
  <Base>
    <BaseTypeName>MonoMac.CoreFoundation.CFType</BaseTypeName>
  </Base>
  <Interfaces>
  </Interfaces>
  <Attributes>
    <Attribute>
      <AttributeName>MonoMac.ObjCRuntime.Since(3, 2)</AttributeName>
    </Attribute>
  </Attributes>
  <Docs>
    To be added.
    <remarks>To be added.</remarks>
  </Docs>
  <Members>
    <Member MemberName=".ctor">
      <MemberSignature Language="C#" Value="public CTRunDelegate (MonoMac.CoreText.CTRunDelegateOperations operations);" />
      <MemberSignature Language="ILAsm" Value=".method public hidebysig specialname rtspecialname instance void .ctor(class MonoMac.CoreText.CTRunDelegateOperations operations) cil managed" />
      <MemberType>Constructor</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>0.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <Parameters>
        <Parameter Name="operations" Type="MonoMac.CoreText.CTRunDelegateOperations" />
      </Parameters>
      <Docs>
        <param name="operations">To be added.</param>
        To be added.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="Finalize">
      <MemberSignature Language="C#" Value="~CTRunDelegate ();" />
      <MemberSignature Language="ILAsm" Value=".method familyhidebysig virtual instance void Finalize() cil managed" />
      <MemberType>Method</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>0.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.Void</ReturnType>
      </ReturnValue>
      <Parameters />
      <Docs>
        Finalizer for the CTRunDelegate object
        <remarks>
        </remarks>
      </Docs>
    </Member>
    <Member MemberName="Operations">
      <MemberSignature Language="C#" Value="public MonoMac.CoreText.CTRunDelegateOperations Operations { get; }" />
      <MemberSignature Language="ILAsm" Value=".property instance class MonoMac.CoreText.CTRunDelegateOperations Operations" />
      <MemberType>Property</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>0.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>MonoMac.CoreText.CTRunDelegateOperations</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
        <value>To be added.</value>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
  </Members>
</Type>

redpajama_set_name: RedPajamaGithub


text:
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// IPC messages for the Cast transport API.
// Multiply-included message file, hence no include guard.

#include "ipc/ipc_message_macros.h"
#include "media/cast/cast_sender.h"
#include "media/cast/logging/logging_defines.h"
#include "media/cast/rtcp/rtcp_defines.h"
#include "media/cast/transport/cast_transport_sender.h"
#include "net/base/ip_endpoint.h"
#include "net/base/net_util.h"

#undef IPC_MESSAGE_EXPORT
#define IPC_MESSAGE_EXPORT
#define IPC_MESSAGE_START CastMsgStart

IPC_ENUM_TRAITS_MAX_VALUE(
    media::cast::transport::EncodedFrame::Dependency,
    media::cast::transport::EncodedFrame::DEPENDENCY_LAST)
IPC_ENUM_TRAITS_MAX_VALUE(media::cast::transport::Codec,
                          media::cast::transport::CODEC_LAST)
IPC_ENUM_TRAITS_MAX_VALUE(media::cast::transport::CastTransportStatus,
                          media::cast::transport::CAST_TRANSPORT_STATUS_LAST)
IPC_ENUM_TRAITS_MAX_VALUE(media::cast::CastLoggingEvent,
                          media::cast::kNumOfLoggingEvents)
IPC_ENUM_TRAITS_MAX_VALUE(media::cast::EventMediaType,
                          media::cast::EVENT_MEDIA_TYPE_LAST)

IPC_STRUCT_TRAITS_BEGIN(media::cast::transport::EncodedFrame)
  IPC_STRUCT_TRAITS_MEMBER(dependency)
  IPC_STRUCT_TRAITS_MEMBER(frame_id)
  IPC_STRUCT_TRAITS_MEMBER(referenced_frame_id)
  IPC_STRUCT_TRAITS_MEMBER(rtp_timestamp)
  IPC_STRUCT_TRAITS_MEMBER(reference_time)
  IPC_STRUCT_TRAITS_MEMBER(data)
IPC_STRUCT_TRAITS_END()

IPC_STRUCT_TRAITS_BEGIN(media::cast::transport::RtcpDlrrReportBlock)
  IPC_STRUCT_TRAITS_MEMBER(last_rr)
  IPC_STRUCT_TRAITS_MEMBER(delay_since_last_rr)
IPC_STRUCT_TRAITS_END()

IPC_STRUCT_TRAITS_BEGIN(media::cast::transport::CastTransportRtpConfig)
  IPC_STRUCT_TRAITS_MEMBER(ssrc)
  IPC_STRUCT_TRAITS_MEMBER(rtp_payload_type)
  IPC_STRUCT_TRAITS_MEMBER(stored_frames)
  IPC_STRUCT_TRAITS_MEMBER(aes_key)
  IPC_STRUCT_TRAITS_MEMBER(aes_iv_mask)
IPC_STRUCT_TRAITS_END()

IPC_STRUCT_TRAITS_BEGIN(media::cast::transport::SendRtcpFromRtpSenderData)
  IPC_STRUCT_TRAITS_MEMBER(packet_type_flags)
  IPC_STRUCT_TRAITS_MEMBER(sending_ssrc)
  IPC_STRUCT_TRAITS_MEMBER(c_name)
  IPC_STRUCT_TRAITS_MEMBER(ntp_seconds)
  IPC_STRUCT_TRAITS_MEMBER(ntp_fraction)
  IPC_STRUCT_TRAITS_MEMBER(rtp_timestamp)
IPC_STRUCT_TRAITS_END()

IPC_STRUCT_TRAITS_BEGIN(media::cast::PacketEvent)
  IPC_STRUCT_TRAITS_MEMBER(rtp_timestamp)
  IPC_STRUCT_TRAITS_MEMBER(frame_id)
  IPC_STRUCT_TRAITS_MEMBER(max_packet_id)
  IPC_STRUCT_TRAITS_MEMBER(packet_id)
  IPC_STRUCT_TRAITS_MEMBER(size)
  IPC_STRUCT_TRAITS_MEMBER(timestamp)
  IPC_STRUCT_TRAITS_MEMBER(type)
  IPC_STRUCT_TRAITS_MEMBER(media_type)
IPC_STRUCT_TRAITS_END()

// Cast messages sent from the browser to the renderer.

IPC_MESSAGE_CONTROL2(CastMsg_ReceivedPacket,
                     int32 /* channel_id */,
                     media::cast::Packet /* packet */)

IPC_MESSAGE_CONTROL2(
    CastMsg_NotifyStatusChange,
    int32 /* channel_id */,
    media::cast::transport::CastTransportStatus /* status */)

IPC_MESSAGE_CONTROL2(CastMsg_RawEvents,
                     int32 /* channel_id */,
                     std::vector<media::cast::PacketEvent> /* packet_events */)

// Cast messages sent from the renderer to the browser.

IPC_MESSAGE_CONTROL2(
  CastHostMsg_InitializeAudio,
  int32 /*channel_id*/,
  media::cast::transport::CastTransportRtpConfig /*config*/)

IPC_MESSAGE_CONTROL2(
  CastHostMsg_InitializeVideo,
  int32 /*channel_id*/,
  media::cast::transport::CastTransportRtpConfig /*config*/)

IPC_MESSAGE_CONTROL2(
    CastHostMsg_InsertCodedAudioFrame,
    int32 /* channel_id */,
    media::cast::transport::EncodedFrame /* audio_frame */)

IPC_MESSAGE_CONTROL2(
    CastHostMsg_InsertCodedVideoFrame,
    int32 /* channel_id */,
    media::cast::transport::EncodedFrame /* video_frame */)

IPC_MESSAGE_CONTROL3(
    CastHostMsg_SendRtcpFromRtpSender,
    int32 /* channel_id */,
    media::cast::transport::SendRtcpFromRtpSenderData /* data */,
    media::cast::transport::RtcpDlrrReportBlock /* dlrr */)

IPC_MESSAGE_CONTROL5(
    CastHostMsg_ResendPackets,
    int32 /* channel_id */,
    bool /* is_audio */,
    media::cast::MissingFramesAndPacketsMap /* missing_packets */,
    bool /* cancel_rtx_if_not_in_list */,
    base::TimeDelta /* dedupe_window */)

IPC_MESSAGE_CONTROL2(
    CastHostMsg_New,
    int32 /* channel_id */,
    net::IPEndPoint /*remote_end_point*/)

IPC_MESSAGE_CONTROL1(
    CastHostMsg_Delete,
    int32 /* channel_id */)


text:
data:
  title: "Supported platforms"
  description: All platforms supported by drift, and how to use them
template: layouts/docs/single
---

Being built on top of the sqlite3 database, drift can run on almost every Dart platform.
Since the initial release, the Dart and Flutter ecosystems have changed a lot.
To clear confusion about different drift packages and when to use them, this document
lists all supported platforms and how to use drift when building apps for them.

To achieve platform independence, drift separates its core apis from a platform-specific
database implementation. The core apis are pure-Dart and run on all Dart platforms, even
outside of Flutter. When writing drift apps, prefer to mainly use the apis in
`package:drift/drift.dart` as they are guaranteed to work across all platforms.
Depending on your platform, you can choose a different `QueryExecutor`.

## Mobile (Android and iOS)

There are two drift implementations for mobile that you can use:

### using `moor_flutter`

The original [`moor_flutter`](https://pub.dev/packages/moor_flutter) package uses `sqflite` and
only works on Android and iOS.
For new projects, we generally recommend the newer ffi-based implementation, but `moor_flutter`
is still maintained and supported.

### using `drift/native`

The new `package:drift/native.dart` implementation uses `dart:ffi` to bind to sqlite3's native C apis.
This is the recommended approach for newer projects as described in the [getting started]({{ "Getting started/index.md" | pageUrl }}) guide.

To ensure that your app ships with the latest sqlite3 version, also add a dependency to the `sqlite3_flutter_libs`
package when using `package:drift/native.dart`!

{% block "blocks/alert" title="A note on ffi and Android" %}
> `package:drift/native.dart` is the recommended drift implementation for new Android apps.
  However, there are some smaller issues on some devices that you should be aware of:

  - Using `sqlite3_flutter_libs` will include prebuilt binaries for 32-bit `x86` devices which you
    probably won't need. You can apply a [filter](https://github.com/simolus3/sqlite3.dart/tree/master/sqlite3_flutter_libs#included-platforms)
    in your `build.gradle` to remove those binaries.
  - Opening `libsqlite3.so` fails on some Android 6.0.1 devices. This can be fixed by setting
    `android.bundle.enableUncompressedNativeLibs=false` in your `gradle.properties` file.
    Note that this will increase the disk usage of your app. See [this issue](https://github.com/simolus3/moor/issues/895#issuecomment-720195005)
    for details.
  - Out of memory errors for very complex queries: Since the regular tmp directory isn't available on Android, you need to inform
    sqlite3 about the right directory to store temporary data. See [this comment](https://github.com/simolus3/moor/issues/876#issuecomment-710013503)
    for an example on how to do that.
{% endblock %}

## Web

_Main article: [Web]({{ "Other engines/web.md" | pageUrl }})_

For apps that run on the web, you can use drift's experimental web implementation, located
in `package:drift/web.dart`.
As it binds to [sql.js](https://github.com/sql-js/sql.js), special setup is required. Please
read the main article for details.

## Desktop

Drift also supports all major Desktop operating systems where Dart runs on by using the
`NativeDatabase` from `package:drift/native.dart`. Depending on your operating system, further
setup might be required:

### Windows

On Windows, you can [download sqlite](https://www.sqlite.org/download.html) and extract
`sqlite3.dll` into a folder that's in your `PATH` environment variable to use drift.

You can also ship a custom `sqlite3.dll` along with your app. See the section below for
details.

### Linux

On most distributions, `libsqlite3.so` is installed already. If you only need to use drift for
development, you can just install the sqlite3 libraries. On Ubuntu and other Debian-based
distros, you can install the `libsqlite3-dev` package for this. Virtually every other distribution
will also have a prebuilt package for sqlite.

You can also ship a custom `libsqlite3.so` along with your app. See the section below for
details.

### macOS

This one is easy! Just use the `NativeDatabase` from `package:drift/native.dart`. No further setup is
necessary.

If you need a custom sqlite3 library, or want to make sure that your app will always use a
specific sqlite3 version, you can also ship that version with your app.
When depending on `sqlite3_flutter_libs`, drift will automatically use that version which is
usually more recent than the `sqlite3` version that comes with macOS.

### Bundling sqlite with your app

If you don't want to use the `sqlite3` version from the operating system (or if it's not
available), you can also ship `sqlite3` with your app.
The best way to do that depends on how you ship your app. Here, we assume that you can
install the dynamic library for `sqlite` next to your application executable.

This example shows how to do that on Linux, by using a custom `sqlite3.so` that we assume
lives next to your application:

{% assign snippets = 'package:moor_documentation/snippets/platforms.dart.excerpt.json' | readString | json_decode %}
{% include "blocks/snippet" snippets = snippets %}

Be sure to use drift _after_ you set the platform-specific overrides.
When you use drift in [another isolate]({{ 'Advanced Features/isolates.md' | pageUrl }}),
you'll also need to apply the opening overrides on that background isolate.
You can call them in the isolate's entrypoint before using any drift apis.


text:
package org.jvending.huntsville;

import java.io.File;
import java.util.Arrays;
import java.util.Properties;
import java.util.logging.Logger;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

/**
 * Unit test for simple App.
 */
public class ItVerifierTest
    extends TestCase
{
    /**
     * Create the test case
     *
     * @param testName
     *            name of the test case
     */
    public ItVerifierTest( String testName )
    {
        super( testName );
    }

    /**
     * @return the suite of tests being tested
     */
    public static Test suite()
    {
        return new TestSuite( ItVerifierTest.class );
    }

    @Override
    protected void setUp()
        throws Exception
    {
        super.setUp();
        ItVerifier it = new ItVerifier();
        it.clearLog();
    }

    public void testLog()
        throws Exception
    {
        File targetDir = new File( "target/logs" );
        File tempFileDir = new File( "/sdcard" );

        ItVerifier it = new ItVerifier();
        File log = it.saveLog( tempFileDir, targetDir, null );

        Logger.getAnonymousLogger().info( "Saved file:  " + log.getAbsolutePath() );
    }

    public void testReadProperties()
        throws Exception
    {
        ItVerifier it = new ItVerifier();
        Properties p = it.readPropertiesFileFromDevice( new File( "/default.prop" ) );
        assertTrue( p.containsKey( "ro.debuggable" ) );
    }

    public void testFileExists()
        throws Exception
    {
        DeviceAssert.assertFileExists( new File( "/default.prop" ) );
    }

    public void testFileDoesNotExist()
        throws Exception
    {
        DeviceAssert.assertFileDoesNotExist( new File( "/dummy.prop" ) );
    }

    public void testPackageInstalled()
        throws Exception
    {
        DeviceAssert.assertPackageInstalled( "com.android.vending" );
    }

    public void testPackagesInstalled()
        throws Exception
    {
        DeviceAssert.assertPackagesInstalled( Arrays.asList( "com.android.vending", "com.google.android.browser" ) );
    }

    public void testEnvironmentPropertyExists()
        throws Exception
    {
        DeviceAssert.assertEnvironmentPropertyExists( "SHELL" );
    }

    public void testEnvironmentPropertyValue()
        throws Exception
    {
        DeviceAssert.assertEnvironmentPropertyValue( "ANDROID_DATA", "/data" );
    }

    public void testDevicePropertyExists()
        throws Exception
    {
        DeviceAssert.assertDevicePropertyExists( "ro.debuggable" );
    }

    public void testDevicePropertyValue()
        throws Exception
    {
        DeviceAssert.assertDevicePropertyValue( "ro.debuggable", "1" );

    }

    public void testLogContains()
        throws Exception
    {
        DeviceAssert.assertLogContainsMessage( "/" );
    }

    public void testLogDoesNotContain()
        throws Exception
    {
        DeviceAssert.assertLogDoesNotContainMessage( "foobar" );
    }

    public void testTakeScreenshot()
        throws Exception
    {
        File targetDir = new File( "target/screenshots" );
        File tempFileDir = new File( "/sdcard" );

        ItVerifier it = new ItVerifier();
        it.takeScreenshot( new File("foobar-" + System.currentTimeMillis() + ".png"),
                                      targetDir, tempFileDir );
    }

    public void testVmStat() throws Exception
    {
        File targetDir = new File( "target/logs" );
        Performance.vmstat( targetDir, 5 );
    }

    /*
    public void testSetEnvironmentProperty() throws Exception {
        ItVerifier it = new ItVerifier();
        String testName = "test" + System.currentTimeMillis();
        it.setEnvironmentProperty( testName, "testValue" );

        DeviceAssert.assertEnvironmentPropertyExists( testName );
    }
    */
}


text:
<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>

    <display-name>Archetype Created Web Application</display-name>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath:config/applicationContext.xml
        </param-value>
    </context-param>

</web-app>


text:
<title>OGRE: Ogre::HardwareBufferManagerBase::VertexBufferLicense Class Reference - OGRE Documentation</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link type="text/css" rel="stylesheet" href="doxygen.css">
<link type="text/css" rel="stylesheet" href="tabs.css">

Main Page

Related Pages

Modules

Namespaces

Classes

Files

Directories

Class List

Class Index

Class Hierarchy

Class Members

Ogre

Ogre::HardwareBufferManagerBase

Ogre::HardwareBufferManagerBase::VertexBufferLicense

Public Member Functions |
Public Attributes

Ogre::HardwareBufferManagerBase::VertexBufferLicense Class Reference

Struct holding details of a license to use a temporary shared buffer.
More...

#include <OgreHardwareBufferManager.h>

List of all members.

Public Member Functions

 	VertexBufferLicense (HardwareVertexBuffer *orig, BufferLicenseType ltype, size_t delay, HardwareVertexBufferSharedPtr buf, HardwareBufferLicensee *lic)

Public Attributes

HardwareVertexBuffer * 	originalBufferPtr

BufferLicenseType 	licenseType

size_t 	expiredDelay

HardwareVertexBufferSharedPtr 	buffer

HardwareBufferLicensee * 	licensee

Detailed Description

Struct holding details of a license to use a temporary shared buffer.

Definition at line 163 of file OgreHardwareBufferManager.h.

Constructor & Destructor Documentation

          Ogre::HardwareBufferManagerBase::VertexBufferLicense::VertexBufferLicense
          (
          HardwareVertexBuffer *
           orig,

          BufferLicenseType
           ltype,

          size_t
           delay,

          HardwareVertexBufferSharedPtr
           buf,

          HardwareBufferLicensee *
           lic

          )

Definition at line 171 of file OgreHardwareBufferManager.h.

Member Data Documentation

          HardwareVertexBufferSharedPtr Ogre::HardwareBufferManagerBase::VertexBufferLicense::buffer

Definition at line 169 of file OgreHardwareBufferManager.h.

          size_t Ogre::HardwareBufferManagerBase::VertexBufferLicense::expiredDelay

Definition at line 168 of file OgreHardwareBufferManager.h.

          HardwareBufferLicensee* Ogre::HardwareBufferManagerBase::VertexBufferLicense::licensee

Definition at line 170 of file OgreHardwareBufferManager.h.

          BufferLicenseType Ogre::HardwareBufferManagerBase::VertexBufferLicense::licenseType

Definition at line 167 of file OgreHardwareBufferManager.h.

          HardwareVertexBuffer* Ogre::HardwareBufferManagerBase::VertexBufferLicense::originalBufferPtr

Definition at line 166 of file OgreHardwareBufferManager.h.

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

OgreHardwareBufferManager.h

Copyright © 2008 Torus Knot Software Ltd

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.

Last modified Wed Nov 3 2010 19:24:55


text:
package org.olat.modules.webFeed.ui;

import org.olat.core.gui.UserRequest;
import org.olat.core.gui.components.form.flexible.FormItem;
import org.olat.core.gui.components.form.flexible.FormItemContainer;
import org.olat.core.gui.components.form.flexible.elements.TextElement;
import org.olat.core.gui.components.form.flexible.impl.FormBasicController;
import org.olat.core.gui.components.form.flexible.impl.FormEvent;
import org.olat.core.gui.control.Controller;
import org.olat.core.gui.control.WindowControl;
import org.olat.core.gui.translator.Translator;
import org.olat.modules.webFeed.FeedViewHelper;
import org.olat.modules.webFeed.models.Feed;

/**
 * Controller for displaying the feed-url to the students. When the element is
 * clicked, a warning occurs that the url is private.
 *
 *

 * Initial Date: May 20, 2009

 *
 * @author gwassmann
 */
public class DisplayFeedUrlController extends FormBasicController {
	private Feed feed;
	private FeedViewHelper helper;
	private TextElement feedUrl;

	boolean userHasBeenNotifiedOfConfidentialityOfUrl = false;

	/**
	 * Constructor
	 *
	 * @param ureq
	 * @param control
	 * @param feed
	 */
	public DisplayFeedUrlController(UserRequest ureq, WindowControl control, Feed feed, FeedViewHelper helper, Translator translator) {
		super(ureq, control, FormBasicController.LAYOUT_VERTICAL);
		this.feed = feed;
		this.helper = helper;
		setTranslator(translator);
		initForm(ureq);
	}

	/**
	 * @see org.olat.core.gui.components.form.flexible.impl.FormBasicController#doDispose()
	 */
	@Override
	protected void doDispose() {
	// nothing to do
	}

	/**
	 * @see org.olat.core.gui.components.form.flexible.impl.FormBasicController#formInnerEvent(org.olat.core.gui.UserRequest,
	 *      org.olat.core.gui.components.form.flexible.FormItem,
	 *      org.olat.core.gui.components.form.flexible.impl.FormEvent)
	 */
	protected void formInnerEvent(UserRequest ureq, FormItem source, FormEvent event) {
		if (source == feedUrl && event.wasTriggerdBy(FormEvent.ONCLICK)) {
			if (feed.isInternal() && !userHasBeenNotifiedOfConfidentialityOfUrl) {
				showWarning("feed.url.is.personal.warning");
				userHasBeenNotifiedOfConfidentialityOfUrl = true;
			}
		}
	}

	/**
	 * @see org.olat.core.gui.components.form.flexible.impl.FormBasicController#formOK(org.olat.core.gui.UserRequest)
	 */
	@Override
	protected void formOK(UserRequest ureq) {
	// this is actually not a proper form. don't do anything.
	}

	/**
	 * @see org.olat.modules.webFeed.ui.podcast.FeedFormController#initForm(org.olat.core.gui.components.form.flexible.FormItemContainer,
	 *      org.olat.core.gui.control.Controller, org.olat.core.gui.UserRequest)
	 */
	@Override
	protected void initForm(FormItemContainer formLayout, Controller listener, UserRequest ureq) {
		feedUrl = uifactory.addTextAreaElement("feedUrl", "feed.url.label", 5000, 1, 1, true, helper.getFeedUrl(), this.flc);
		// no editing. selecting allowed only
		feedUrl.setEnabled(false);
		feedUrl.addActionListener(this, FormEvent.ONCLICK);
	}

	/**
	 * Sets the URL to display.
	 *
	 * @param url
	 */
	public void setUrl(String url) {
		feedUrl.setValue(url);
	}
}


text:
{% extends "base.html" %}

{% block title %}This experiment uses {{ provider }}{% endblock %}

{% block content %}

Before we begin, we need you to login with {{ provider }}.

{{ provider }} may ask you to grant certain permissions for this experiment to use your data. Please allow these permissions for the experiment to work correctly. If you are using browser extensions which block access to data from other websites, such as Adblock, please add this site to your whitelist, or disable the extension while taking part, as this may interfere with the experiment.

If you have any questions about how we use the data from these services,
please review the participant information, or contact the researcher.

Login to {{ provider }}

{% endblock %}


text:
import psycopg2
import psycopg2.extras
import md5

def getOperator(conn,prefix=None,website=None):
    cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
    if website is None:
        website = 'http://www.example.com'
    if prefix is None:
        prefix = 'DINO'
    cur.execute("""
SELECT DISTINCT ON (branch_nr)
branch_nr as privatecode,
%s||':'||branch_nr as operator_id,
branch_name as name,
%s as url,
'de' as language,
'Europe/Amsterdam' as timezone
FROM branch;""",[prefix,website])
    rows = cur.fetchall()
    operators = {}
    cur.close()
    for row in rows:
        operators[row['privatecode']] = row
    return operators

def getLines(conn,prefix=None):
    cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
    if prefix is None:
        prefix = 'DINO'
    lines = {}
    cur.execute("""
SELECT DISTINCT ON (operator_id,transportmode)
rec_lin_ber.branch_nr as operatorref,
'AVV'||':'||version||':'||line_nr as operator_id,
line_nr as privatecode,
line_name as publiccode,
CASE WHEN (lower(veh_type_text) like '%bus%') THEN 'BUS'
     WHEN (lower(veh_type_text) like '%taxi%') THEN 'BUS'
     WHEN (lower(veh_type_text) like '%bahn%') THEN 'TRAIN'
     WHEN (lower(veh_type_text) like '%zug%') THEN 'TRAIN'
     WHEN (lower(veh_type_text) like '%chiff%') THEN 'BOAT'
     ELSE veh_type_text END as TransportMode,
null AS name,
false as monitored
FROM
rec_lin_ber LEFT JOIN rec_trip USING (version,line_nr)
            LEFT JOIN set_vehicle_type USING (version,veh_type_nr)
ORDER BY operator_id,transportmode
""")
    for row in cur.fetchall():
        lines[row['operator_id']] = row
    cur.close()
    return lines

def getDestinationDisplays(conn,prefix=None):
    cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
    destinationdisplays = {}
    if prefix is None:
        prefix = 'DINO'
    cur.execute("""
SELECT DISTINCT ON (arr.stop_nr)
arr.stop_nr as privatecode,
%s||':'||arr.stop_nr as operator_id,
arr.stop_name as name,
arr.stop_name as shortname
FROM
rec_trip,rec_stop as arr,rec_stop as dep
WHERE
dep_stop_nr = dep.stop_nr AND
arr_stop_nr = arr.stop_nr AND
dep.place = arr.place
UNION
SELECT DISTINCT ON (arr.stop_nr)
arr.stop_nr as privatecode,
%s||':P'||arr.stop_nr as operator_id,
arr.place||', '||arr.stop_name,
arr.place as shortname
FROM
rec_trip,rec_stop as arr,rec_stop as dep
WHERE
dep_stop_nr = dep.stop_nr AND
arr_stop_nr = arr.stop_nr AND
dep.place <> arr.place
""",[prefix]*2)
    for row in cur.fetchall():
        destinationdisplays[row['operator_id']] = row
    cur.close()
    return destinationdisplays

def getStopPoints(conn,prefix=None):
    cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
    if prefix is None:
        prefix = 'DINO'
    stops = {}
    cur.execute("""
SELECT
%s||':'||stop_nr||':'||stopping_point_nr as operator_id,
stop_nr||':'||stopping_point_nr as privatecode,
NULL as publiccode,
%s||':'||stop_nr as stoparearef,
place||', '||stop_name AS name,
place as town,
true as isScheduled,
CAST(CAST(ST_Y(the_geom) AS NUMERIC(9,6)) AS text) AS latitude,
CAST(CAST(ST_X(the_geom) AS NUMERIC(8,6)) AS text) AS longitude,
null as rd_x,
null as rd_y
FROM rec_stop JOIN
              (SELECT *, st_transform(ST_setsrid(st_makepoint(stopping_point_pos_x,stopping_point_pos_y),31466),4326) AS the_geom
               FROM rec_stopping_points) as stopping USING (stop_nr)""",[prefix]*2)
    for row in cur.fetchall():
        stops[row['operator_id']] = row
    cur.close()
    return stops

def getProductCategories(conn,prefix=None):
    cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
    if prefix is None:
        prefix = 'DINO'
    productcategory = {}
    cur.execute("""
SELECT
concat_ws(':',%s,version,str_veh_type) as operator_id,
str_veh_type as privatecode,
veh_type_text as name,
str_veh_type as shortname
FROM
set_vehicle_type""",[prefix])
    for row in cur.fetchall():
        productcategory[row['operator_id']] = row
    cur.close()
    return productcategory

def getAvailabilityConditions(conn,prefix=None):
    cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
    if prefix is None:
        prefix = 'DINO'
    availabilityConditions = {}
    cur.execute("""
SELECT
concat_ws(':',%s,version,day_attribute_nr,restriction) as operator_id,
concat_ws(':',%s,version,day_attribute_nr,restriction) as privatecode,
%s as unitcode,
%s||':'||version as versionref,
NULL::text as name,
min(day) as fromdate,
max(day) as todate,
array_agg(DISTINCT day) as days
FROM
(SELECT DISTINCT
 version,restriction,day_attribute_nr FROM rec_trip) as trips
         JOIN set_day_attribute USING (version,day_attribute_nr)
         JOIN day_type_2_day_attribute USING (version,day_attribute_nr)
         JOIN calendar_of_the_company as cotc USING (version,day_type_nr)
         LEFT JOIN (SELECT version,restriction,unnest(bitcalendar(date_from,('x' || restriction_days) :: bit varying(1024)))::date as day
               FROM service_restriction) as restricted USING (version,restriction,day)
WHERE restricted.day is null
GROUP BY operator_id,privatecode,unitcode,versionref,name;
""",[prefix]*4)
    for row in cur.fetchall():
        row['DAYS'] = {'validdates' : row['days'], 'isavailable' : True, 'availabilityconditionref' : row['operator_id']}
        del(row['days'])
        availabilityConditions[row['operator_id']] = row
    return availabilityConditions

def getStopAreas(conn,prefix=None):
    cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
    if prefix is None:
        prefix = 'DINO'
    stops = {}
    cur.execute("""
SELECT DISTINCT ON (operator_id)
%s||':'||stop_nr as operator_id,
stop_nr as privatecode,
place||', '||stop_name AS name,
place as town,
(avg(ST_Y(the_geom)) OVER (PARTITION BY stop_nr))::NUMERIC(9,6)::text AS latitude,
(avg(ST_X(the_geom)) OVER (PARTITION BY stop_nr))::NUMERIC(8,6)::text AS longitude
FROM rec_stop JOIN
              (SELECT *, st_transform(ST_setsrid(st_makepoint(stopping_point_pos_x,stopping_point_pos_y),31466),4326) AS the_geom
               FROM rec_stopping_points) as stopping USING (stop_nr)
""",[prefix])
    for row in cur.fetchall():
        stops[row['operator_id']] = row
    cur.close()
    return stops

def clusterPatternsIntoRoute(conn,prefix=None):
    if prefix is None:
        prefix = 'DINO'
    cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
    routes = {}
    cur.execute("""
SELECT DISTINCT ON (operator_id)
concat_ws(':',%s,version,line_nr,line_dir_nr,str_line_var) as operator_id,
%s||':'||version||':'||line_nr as lineref
FROM lid_course
""",[prefix]*2)
    for row in cur.fetchall():
        row['POINTS'] = []
        routes[row['operator_id']] = row
    cur.execute("""
SELECT
concat_ws(':',%s,l.version,l.line_nr,l.line_dir_nr,l.str_line_var) as routeref,
%s||':'||l.stop_nr||':'||l.stopping_point_nr as privatecode,
l.line_consec_nr as pointorder,
ST_Y(p.the_geom)::NUMERIC(8,5)::text AS latitude,
ST_X(p.the_geom)::NUMERIC(7,5)::text AS longitude,
coalesce(SUM(st_distance(st_transform(p.the_geom,31466),lp.the_geom)::integer) OVER (PARTITION BY l.version,l.line_nr,l.line_dir_nr,l.str_line_var
                                                                            ORDER BY l.line_consec_nr),0) as distancefromstart
FROM lid_course as l LEFT JOIN (SELECT *, st_transform(ST_setsrid(st_makepoint(stopping_point_pos_x,stopping_point_pos_y),31466),4326) AS the_geom FROM rec_stopping_points) as p USING (version,stop_nr,stop_type_nr,stopping_point_nr)
                     LEFT JOIN (SELECT * FROM lid_course as lp LEFT JOIN (SELECT *, ST_setsrid(st_makepoint(stopping_point_pos_x,stopping_point_pos_y),31466) AS the_geom FROM rec_stopping_points) as po USING (version,stop_nr,stop_type_nr,stopping_point_nr)) as lp
                               ON (l.version = lp.version AND l.line_nr = lp.line_nr AND l.line_dir_nr = lp.line_dir_nr AND l.str_line_var = lp.str_line_var AND lp.line_consec_nr = l.line_consec_nr-1)
ORDER BY routeref,pointorder
""",[prefix]*2)
    for row in cur.fetchall():
        route = routes[row['routeref']]
        route['POINTS'].append(row)
    return routes

def getTimeDemandGroups(conn,prefix=None):
    if prefix is None:
        prefix = 'DINO'
    cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
    timedemandgroups = {}
    cur.execute("""
SELECT
concat_ws(':',%s,version,line_nr,line_dir_nr,str_line_var,line_dir_nr,timing_group_nr) as operator_id,
concat_ws(':',version,line_nr,line_dir_nr,str_line_var,timing_group_nr)  as privatecode,
cast(line_consec_nr  as integer) as pointorder,
tt_rel as drivingtime,
stopping_time as stopwaittime
FROM lid_travel_time_type
ORDER BY operator_id,pointorder
""",[prefix])
    totaldrivetime = 0
    stopwaittime = 0
    for row in cur.fetchall():
        if row['operator_id'] not in timedemandgroups:
            timedemandgroups[row['operator_id']] = {'operator_id' : row['operator_id'], 'privatecode' : row['privatecode'], 'POINTS' : [{'pointorder' : row['pointorder'],'totaldrivetime' : row['drivingtime'], 'stopwaittime' : row['stopwaittime']}]}
            totaldrivetime = row['drivingtime']
            stopwaittime = row['stopwaittime']
        else:
            points = timedemandgroups[row['operator_id']]['POINTS']
            totaldrivetime += row['drivingtime']
            point_dict = {'pointorder' : row['pointorder'],'totaldrivetime' : totaldrivetime, 'stopwaittime' : row['stopwaittime']}
            points.append(point_dict)
            totaldrivetime += row['stopwaittime']
    for key,row in timedemandgroups.items():
        m = md5.new()
        m.update(str(row['POINTS']))
        row['operator_id'] = m.hexdigest()
        row['privatecode'] = row['operator_id']
    return timedemandgroups

def getJourneyPatterns(conn,routes,prefix=None):
    if prefix is None:
        prefix = 'DINO'
    cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
    journeypatterns = {}
    cur.execute("""
SELECT DISTINCT ON (rec_trip.version,line_nr,line_dir_nr,str_line_var,dep_stop_nr,arr_stop_nr,notice)
concat_ws(':',%s,rec_trip.version,rec_trip.line_nr,line_dir_nr,str_line_var,dep_stop_nr,arr_stop_nr,notice) as operator_id,
concat_ws(':',%s,rec_trip.version,rec_trip.line_nr,line_dir_nr,str_line_var) as routeref,
line_dir_nr as directiontype,
CASE WHEN (arr.place = dep.place) THEN 'AVV'||':'||arr.stop_nr
     ELSE %s||':P'||arr.stop_nr END as destinationdisplayref
FROM
rec_trip,rec_stop as arr,rec_stop as dep
WHERE
dep_stop_nr = dep.stop_nr AND
arr_stop_nr = arr.stop_nr
""",[prefix]*3)
    for row in cur.fetchall():
        journeypatterns[row['operator_id']] = row
        journeypatterns[row['operator_id']]['POINTS'] = []
    cur.execute("""
SELECT DISTINCT ON (journeypatternref,pointorder)
concat_ws(':',%s,t.version,jp.line_nr,jp.line_dir_nr,jp.str_line_var,dep_stop_nr,arr_stop_nr,notice) as journeypatternref,
jp.line_consec_nr::integer as pointorder,
null as privatecode,
concat_ws(':',%s,jp.line_nr,jp.line_dir_nr,jp.str_line_var,dep_stop_nr,arr_stop_nr) as operator_id,
%s||':'||jp.stop_nr||':'||jp.stopping_point_nr as pointref,
%s||':'||jpo.stop_nr||':'||jpo.stopping_point_nr as onwardpointref,
NULL as destinationdisplayref,
NULL as noticeassignmentRef,
%s as administrativezoneref,
NULL as iswaitpoint,
0 as waittime,
NULL as requeststop,
true as foralighting,
true as forboarding,
0 as distancefromstartroute,
0 as fareunitspassed
FROM
rec_trip as t LEFT JOIN lid_course as dep USING (version,line_nr,line_dir_nr,str_line_var)
              LEFT JOIN lid_course as arr USING (version,line_nr,line_dir_nr,str_line_var)
              LEFT JOIN lid_course as jp USING (version,line_nr,line_dir_nr,str_line_var)
              LEFT JOIN lid_course as jpo ON (jp.version = jpo.version AND jp.line_nr = jpo.line_nr
                                              AND jp.line_dir_nr = jpo.line_dir_nr AND jp.str_line_var = jpo.str_line_var AND
                                              jp.line_consec_nr = jpo.line_consec_nr + 1)
WHERE
dep.stop_nr = dep_stop_nr AND
dep.stop_type_nr = dep_stop_type_nr AND
dep.stopping_point_nr = dep_stopping_point_nr AND
arr.stop_nr = arr_stop_nr AND
arr.stop_type_nr = arr_stop_type_nr AND
arr.stopping_point_nr = arr_stopping_point_nr AND
jp.line_consec_nr between dep.line_consec_nr AND arr.line_consec_nr
ORDER BY journeypatternref,pointorder
""",[prefix]*5)
    distance = 0
    patternref = None
    for row in cur.fetchall():
        if row['journeypatternref'] != patternref:
            distance = 0
            patternref = row['journeypatternref']
        for point in routes[journeypatterns[row['journeypatternref']]['routeref']]['POINTS']:
            if point['distancefromstart'] >= distance and point['privatecode'] == row['pointref']:
                distance = point['distancefromstart']
                row['distancefromstartroute'] = distance
                break
        row['distancefromstartroute'] = distance
        journeypatterns[row['journeypatternref']]['POINTS'].append(row)
    cur.close()
    return journeypatterns

def getJourneys(conn,prefix=None):
    if prefix is None:
        prefix = 'DINO'
    cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
    cur.execute("""
SELECT
concat_ws(':',%s,version,line_nr,trip_id) as privatecode,
concat_ws(':',%s,version,trip_id,row_number() OVER (PARTITION BY version,trip_id ORDER BY trip_id)) as operator_id,
concat_ws(':',%s,version,day_attribute_nr,restriction) as availabilityconditionRef,
concat_ws(':',%s,version,line_nr,line_dir_nr,str_line_var,dep_stop_nr,arr_stop_nr,notice) as journeypatternref,
concat_ws(':',%s,version,line_nr,line_dir_nr,str_line_var,line_dir_nr,timing_group_nr) as timedemandgroupref,
concat_ws(':',%s,version,str_veh_type) as productCategoryRef,
NULL as noticeassignmentRef,
departuretime,
NULL as blockref,
coalesce(coalesce(trip_id_printing,train_nr),trip_id) as name,
nullif(veh_type_text ilike '%%niederflurbus%%',false) as lowfloor,
NULL as hasLiftOrRamp,
NULL as haswifi,
NULL as bicycleallowed,
(veh_type_text ilike '%%taxi%%' OR veh_type_text ilike '%%rufbus%%')as onDemand
FROM rec_trip LEFT JOIN set_vehicle_type USING (version,veh_type_nr)
""",[prefix]*6)
    journeys = {}
    for row in cur.fetchall():
        journeys[row['operator_id']] = row
    cur.close()
    return journeys

def getVersion(conn,prefix=None,filename=None):
    if prefix is None:
        prefix = 'DINO'
    if filename is None:
        filename = ''
    cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
    cur.execute("""
select '1' as datasourceref, %s||':'||version as operator_id,period_date_from as startdate,period_date_to as enddate,version||':'||%s as privatecode,
version_text as description
from set_version;""",[prefix,filename])
    version = {}
    for row in cur.fetchall():
        version[row['operator_id']] = row
    return version


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="HighlightingAdvisor">
    <option name="SUGGEST_TYPE_AWARE_HIGHLIGHTING" value="false" />
  </component>
</project>


text:
<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="width=device-width,user-scalable=no,maximum-scale=1" />
  </head>
  <body>
    <script>
    document.addEventListener('mousemove', (e) => {
      console.log(`type:${e.type} x:${e.offsetX} y:${e.offsetY}`)
    })
    document.addEventListener('mouseup', (e) => {
      console.log(`type:${e.type} x:${e.offsetX} y:${e.offsetY}`)
    })
    document.addEventListener('mousedown', (e) => {
      console.log(`type:${e.type} x:${e.offsetX} y:${e.offsetY}`)
    })
    function displayTouchEvent(e) {
      if (e.touches && e.touches.length > 0) {
        for ( let i = 0; i < e.touches.length; i++ ) {
          const t = e.touches[i]
          console.log(`type: ${e.type} x: ${t.clientX} y: ${t.clientY}`)
        }
      } else {
        console.log(`type: ${e.type}`)
      }
    }
    document.addEventListener('touchstart', (e) => {
      displayTouchEvent(e)
    })
    document.addEventListener('touchend', (e) => {
      displayTouchEvent(e)
    })
    document.addEventListener('touchmove', (e) => {
      displayTouchEvent(e)
    })
    </script>
  </body>
</html>


text:
package ru.shadam.tarantool.core.mapping;

import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.data.keyvalue.annotation.KeySpace;
import org.springframework.data.keyvalue.core.mapping.KeySpaceResolver;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;

/**
 * @author sala
 */
public enum AnnotationBasedSpaceIdResolver implements KeySpaceResolver {
    INSTANCE;

    @Override
    public String resolveKeySpace(Class<?> type) {
        Assert.notNull(type, "Type for keyspace for null!");

        Class<?> userClass = ClassUtils.getUserClass(type);
        return getKeySpace(userClass);
    }

    private String getKeySpace(Class<?> type) {
        KeySpace keyspace = AnnotatedElementUtils.findMergedAnnotation(type, KeySpace.class);

        if (keyspace != null) {
            return (String) AnnotationUtils.getValue(keyspace);
        }

        return null;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _04.Exam_Shopping
{
    class Program
    {
        static void Main(string[] args)
        {
            var input = Console.ReadLine();
            var shop = new Dictionary<string, int>();

            while (input != "shopping time")
            {
                var itemQuantity = input.Split(' ');
                if (shop.ContainsKey(itemQuantity[1]))
                    shop[itemQuantity[1]] += int.Parse(itemQuantity[2]);
                else
                    shop.Add(itemQuantity[1], int.Parse(itemQuantity[2]));

                input = Console.ReadLine();
            }
            input = Console.ReadLine();
            while (input != "exam time")
            {
                var itemQuantity = input.Split(' ');
                if (shop.ContainsKey(itemQuantity[1]))
                {
                    if (shop[itemQuantity[1]] > 0)
                        shop[itemQuantity[1]] -= int.Parse(itemQuantity[2]);
                    else
                        Console.WriteLine($"{itemQuantity[1]} out of stock");
                }
                else if (!shop.ContainsKey(itemQuantity[1]))
                {
                    Console.WriteLine($"{itemQuantity[1]} doesn't exist");
                }
                input = Console.ReadLine();
            }

            foreach (var kv in shop)
            {
                if (kv.Value > 0)
                    Console.WriteLine($"{kv.Key} -> {kv.Value}");
            }
        }
    }
}


text:
class CreateUserpermissions < ActiveRecord::Migration
  def change
    create_table :userpermissions do |t|
      t.belongs_to :permission, index: true
      t.belongs_to :user, index: true
      t.timestamps
    end
  end
end


text:
using System;
using FluentAssertions;
using NSubstitute;

namespace Assent.Tests.EndToEnd
{
    public class NoApprovedFileScenario : BaseScenario
    {
        private Action _action;
        private readonly string _recievedPath = $@"{GetTestDirectory()}\EndToEnd\{nameof(NoApprovedFileScenario)}.{nameof(WhenTheTestIsRun)}.received.txt";
        private readonly string _approvedPath = $@"{GetTestDirectory()}\EndToEnd\{nameof(NoApprovedFileScenario)}.{nameof(WhenTheTestIsRun)}.approved.txt";

        public void WhenTheTestIsRun()
        {
            _action = () => this.Assent("Foo", Configuration);
        }

        public void ThenAnAssentExceptionIsThrown()
        {
            _action.Should().Throw<AssentFailedException>().WithMessage("Strings differ");
        }

        public void AndThenTheRecievedFileIsWritten()
        {
            var testDirectory = GetTestDirectory();
            ReaderWriter.Files.Keys.Should().Contain(_recievedPath);
        }

        public void AndThenAnApprovedFileIsCreated()
        {
            ReaderWriter.Files.Keys.Should().Contain(_approvedPath);
        }

        public void AndThenTheApprovedFileIsBlank()
        {
            ReaderWriter.Files[_approvedPath].Should().Be(null);
        }

        public void AndThenTheReporterIsLaunched()
        {
            var testDirectory = GetTestDirectory();
            Reporter.Received().Report(_recievedPath, _approvedPath);
        }
        public void AndThenTheRecievedFileWasCleanedUp()
        {
            ReaderWriter.Deleted.Should().Contain(_recievedPath);
        }
    }
}


text:
import {expect} from 'chai';
import {spec} from 'modules/admixerBidAdapter';
import {newBidder} from 'src/adapters/bidderFactory';

const BIDDER_CODE = 'admixer';
const ENDPOINT_URL = '//inv-nets.admixer.net/prebid.1.0.aspx';
const ZONE_ID = '2eb6bd58-865c-47ce-af7f-a918108c3fd2';

describe('AdmixerAdapter', function () {
  const adapter = newBidder(spec);

  describe('inherited functions', function () {
    it('exists and is a function', function () {
      expect(adapter.callBids).to.be.exist.and.to.be.a('function');
    });
  });

  describe('isBidRequestValid', function () {
    let bid = {
      'bidder': BIDDER_CODE,
      'params': {
        'zone': ZONE_ID
      },
      'adUnitCode': 'adunit-code',
      'sizes': [[300, 250], [300, 600]],
      'bidId': '30b31c1838de1e',
      'bidderRequestId': '22edbae2733bf6',
      'auctionId': '1d1a030790a475',
    };

    it('should return true when required params found', function () {
      expect(spec.isBidRequestValid(bid)).to.equal(true);
    });

    it('should return false when required params are not passed', function () {
      let bid = Object.assign({}, bid);
      delete bid.params;
      bid.params = {
        'placementId': 0
      };
      expect(spec.isBidRequestValid(bid)).to.equal(false);
    });
  });

  describe('buildRequests', function () {
    let bidRequests = [
      {
        'bidder': BIDDER_CODE,
        'params': {
          'zone': ZONE_ID
        },
        'adUnitCode': 'adunit-code',
        'sizes': [[300, 250], [300, 600]],
        'bidId': '30b31c1838de1e',
        'bidderRequestId': '22edbae2733bf6',
        'auctionId': '1d1a030790a475',
      }
    ];

    it('should add referrer and imp to be equal bidRequest', function () {
      const request = spec.buildRequests(bidRequests);
      const payload = JSON.parse(request.data.substr(5));
      expect(payload.referrer).to.not.be.undefined;
      expect(payload.imps[0]).to.deep.equal(bidRequests[0]);
    });

    it('sends bid request to ENDPOINT via GET', function () {
      const request = spec.buildRequests(bidRequests);
      expect(request.url).to.equal(ENDPOINT_URL);
      expect(request.method).to.equal('GET');
    });
  });

  describe('interpretResponse', function () {
    let response = {
      body: [{
        'currency': 'USD',
        'cpm': 6.210000,
        'ad': '
ad
',
        'width': 300,
        'height': 600,
        'creativeId': 'ccca3e5e-0c54-4761-9667-771322fbdffc',
        'ttl': 360,
        'netRevenue': false,
        'bidId': '5e4e763b6bc60b'
      }]
    };

    it('should get correct bid response', function () {
      const body = response.body;
      let expectedResponse = [
        {
          'requestId': body[0].bidId,
          'cpm': body[0].cpm,
          'creativeId': body[0].creativeId,
          'width': body[0].width,
          'height': body[0].height,
          'ad': body[0].ad,
          'vastUrl': undefined,
          'currency': body[0].currency,
          'netRevenue': body[0].netRevenue,
          'ttl': body[0].ttl,
        }
      ];

      let result = spec.interpretResponse(response);
      expect(result[0]).to.deep.equal(expectedResponse[0]);
    });

    it('handles nobid responses', function () {
      let response = [];

      let result = spec.interpretResponse(response);
      expect(result.length).to.equal(0);
    });
  });
});


text:
layout: post
title: "Como usar Axios como cliente HTTP"
lang: "pt"
date: 2015-07-15T22:39:43-03:00
translation_id: d41d8cd98f00b204e9800998ecf8427e
author: marlonbernardes
excerpt: >
  Axios é um cliente HTTP que funciona tanto no browser quanto em node.js. Neste post veremos como fazer requisições HTTP utilizando a biblbioteca.
---

## Introdução

Axios é um cliente HTTP, que funciona tanto no browser quanto em node.js. A biblioteca é basicamente uma API que sabe interagir tanto com `XMLHttpRequest` quanto com a interface `http` do node. Isso significa que o mesmo código utilizado para fazer requisições ajax no browser também funciona no servidor. Além disso, as requisições feitas através da biblioteca retornam uma `promise`, compatível com a nova versão do JavaScript - ES6.  *Promissor*, certo? Vamos ver como funciona!

## Instalação

Antes de utilizar axios, primeiro é necessário instalar. Há diversas formas de fazer isso:

1) Usando npm:

```
$ npm install axios
```

2) Usando bower:

```
$ bower install axios
```

3) Download manual:
[https://github.com/mzabriskie/axios/tree/master/dist](https://github.com/mzabriskie/axios/tree/master/dist)

## Primeiros passos

Depois de instalar, utilizar a biblioteca é bastante simples. Neste post, faremos requisições para a API do GitHub:

```js
// Requisições do tipo GET
axios.get('https://api.github.com/users/' + username)
  .then(function(response){
    console.log(response.data); // ex.: { user: 'Your User'}
    console.log(response.status); // ex.: 200
  });

// Requisições POST, note há um parâmetro extra indicando os parâmetros da requisição
axios.post('/save', { firstName: 'Marlon', lastName: 'Bernardes' })
  .then(function(response){
    console.log('salvo com sucesso')
  });
```

Além de `post` e `get`, existem os métodos `delete`, `head`, `put` e `patch`, que fazem requisições com o tipo equivalente em HTTP.

Os método `put` e `patch` são similares ao `post`, e exigem um parâmetro extra contendo os dados que serão enviados.

## Executando múltiplas requisições em paralelo

Para executar múltiplas requisições em paralelo, simplesmente forneça um array para o método `axios.all`. Quando todas as requisições forem concluídas, você receberá um array contendo as respostas na mesma ordem em que estes foram enviados. Uma outra alternativa é utilizar o método `axios.spread`, que converte um array para múltiplos argumentos. Utilizar spread é uma boa alternativa, visto que referenciar os objetos pelo índice do array pode deixar o código confuso.

```js
// Requisições serão executadas em paralelo...
axios.all([
    axios.get('https://api.github.com/users/codeheaven-io');
    axios.get('https://api.github.com/users/codeheaven-io/repos')
  ])
  .then(axios.spread(function (userResponse, reposResponse) {
    //... mas este callback será executada apenas quando todas as requisições concluírem
    console.log('User', userResponse.data);
    console.log('Repositories', reposResponse.data);
  }));
```

## Usando axios em node

Deve ser óbvio agora, mas rodar o código acima no node deve ser bem fácil. Instale axios com `npm` e importe como você já faz com qualquer outra dependência:

```js
var axios = require('axios')
axios.get('https://api.github.com/users/codeheaven-io');
```

## Usando axios no browser

Simplesmente importe axios (através de uma tag `<script>`, browserify, requirejs, webpack, etc)

```html
<script src="./bower_components/axios/dist/axios.js"></script>
<script>
axios.get('https://api.github.com/users/codeheaven-io');
</script>
```

## Enviando headers HTTP customizados

Para enviar headers customizados, forneça um objeto contendo os headers HTTP como último argumento:

```js
var config = {
  headers: {'X-My-Custom-Header': 'Header-Value'}
};

axios.get('https://api.github.com/users/codeheaven-io', config);
axios.post('/save', { firstName: 'Marlon' }, config);
```

Você pode ler mais sobre axios em:
[https://github.com/mzabriskie/axios](https://github.com/mzabriskie/axios)


text:
Ext.define('App.override.field.Field', {
    override: 'Ext.field.Field',

    config: {
        requiredMessage: 'This field is required',

        labelTextAlign: 'right',

        errorTip: {
            anchor: true,
            align: 'l-r?',
            ui: 'tooltip invalid'
        }
    },

    platformConfig: {
        phone: {
            errorTarget: 'under'
        }
    }
});


text:
#include "src/gpu/d3d/GrD3DSemaphore.h"

#include "src/gpu/d3d/GrD3DGpu.h"

std::unique_ptr<GrD3DSemaphore> GrD3DSemaphore::Make(GrD3DGpu* gpu) {
    GrD3DFenceInfo fenceInfo;
    gpu->device()->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fenceInfo.fFence));
    fenceInfo.fValue = 1;

    return std::unique_ptr<GrD3DSemaphore>(new GrD3DSemaphore(fenceInfo));
}

std::unique_ptr<GrD3DSemaphore> GrD3DSemaphore::MakeWrapped(const GrD3DFenceInfo& fenceInfo) {
    return std::unique_ptr<GrD3DSemaphore>(new GrD3DSemaphore(fenceInfo));
}

GrD3DSemaphore::GrD3DSemaphore(const GrD3DFenceInfo& fenceInfo) : fFenceInfo(fenceInfo) {}

GrBackendSemaphore GrD3DSemaphore::backendSemaphore() const {
    GrBackendSemaphore backendSemaphore;
    backendSemaphore.initDirect3D(fFenceInfo);
    return backendSemaphore;
}


text:
package com.blogspot.toomuchcoding.common.assertj;

import org.assertj.core.api.BDDAssertions;

import com.blogspot.toomuchcoding.model.Person;

public class MyBddAssertions extends BDDAssertions {

    public static PersonAssert then(Person actual) {
        return new PersonAssert(actual);
    }

}