text:
#include <stdint.h>
#include <stdio.h>
#include <string.h>

#include "py/runtime.h"
#include "py/objlist.h"
#include "py/stream.h"
#include "py/mphal.h"
#include "shared/runtime/interrupt_char.h"
#include "inc/hw_types.h"
#include "inc/hw_ints.h"
#include "inc/hw_memmap.h"
#include "inc/hw_uart.h"
#include "rom_map.h"
#include "interrupt.h"
#include "prcm.h"
#include "uart.h"
#include "pybuart.h"
#include "mpirq.h"
#include "pybsleep.h"
#include "osi.h"
#include "utils.h"
#include "pin.h"
#include "pybpin.h"
#include "pins.h"
#include "moduos.h"

/// \moduleref pyb
/// \class UART - duplex serial communication bus

/******************************************************************************
 DEFINE CONSTANTS
 *******-***********************************************************************/
#define PYBUART_FRAME_TIME_US(baud)             ((11 * 1000000) / baud)
#define PYBUART_2_FRAMES_TIME_US(baud)          (PYBUART_FRAME_TIME_US(baud) * 2)
#define PYBUART_RX_TIMEOUT_US(baud)             (PYBUART_2_FRAMES_TIME_US(baud) * 8) // we need at least characters in the FIFO

#define PYBUART_TX_WAIT_US(baud)                ((PYBUART_FRAME_TIME_US(baud)) + 1)
#define PYBUART_TX_MAX_TIMEOUT_MS               (5)

#define PYBUART_RX_BUFFER_LEN                   (256)

// interrupt triggers
#define UART_TRIGGER_RX_ANY                     (0x01)
#define UART_TRIGGER_RX_HALF                    (0x02)
#define UART_TRIGGER_RX_FULL                    (0x04)
#define UART_TRIGGER_TX_DONE                    (0x08)

/******************************************************************************
 DECLARE PRIVATE FUNCTIONS
 ******************************************************************************/
STATIC void uart_init (pyb_uart_obj_t *self);
STATIC bool uart_rx_wait (pyb_uart_obj_t *self);
STATIC void uart_check_init(pyb_uart_obj_t *self);
STATIC mp_obj_t uart_irq_new (pyb_uart_obj_t *self, byte trigger, mp_int_t priority, mp_obj_t handler);
STATIC void UARTGenericIntHandler(uint32_t uart_id);
STATIC void UART0IntHandler(void);
STATIC void UART1IntHandler(void);
STATIC void uart_irq_enable (mp_obj_t self_in);
STATIC void uart_irq_disable (mp_obj_t self_in);

/******************************************************************************
 DEFINE PRIVATE TYPES
 ******************************************************************************/
struct _pyb_uart_obj_t {
    mp_obj_base_t base;
    pyb_uart_id_t uart_id;
    uint reg;
    uint baudrate;
    uint config;
    uint flowcontrol;
    byte *read_buf;                     // read buffer pointer
    volatile uint16_t read_buf_head;    // indexes first empty slot
    uint16_t read_buf_tail;             // indexes first full slot (not full if equals head)
    byte peripheral;
    byte irq_trigger;
    bool irq_enabled;
    byte irq_flags;
};

/******************************************************************************
 DECLARE PRIVATE DATA
 ******************************************************************************/
STATIC pyb_uart_obj_t pyb_uart_obj[PYB_NUM_UARTS] = { {.reg = UARTA0_BASE, .baudrate = 0, .read_buf = NULL, .peripheral = PRCM_UARTA0},
                                                      {.reg = UARTA1_BASE, .baudrate = 0, .read_buf = NULL, .peripheral = PRCM_UARTA1} };
STATIC const mp_irq_methods_t uart_irq_methods;

STATIC const mp_obj_t pyb_uart_def_pin[PYB_NUM_UARTS][2] = { {&pin_GP1, &pin_GP2}, {&pin_GP3, &pin_GP4} };

/******************************************************************************
 DEFINE PUBLIC FUNCTIONS
 ******************************************************************************/
void uart_init0 (void) {
    // save references of the UART objects, to prevent the read buffers from being trashed by the gc
    MP_STATE_PORT(pyb_uart_objs)[0] = &pyb_uart_obj[0];
    MP_STATE_PORT(pyb_uart_objs)[1] = &pyb_uart_obj[1];
}

uint32_t uart_rx_any(pyb_uart_obj_t *self) {
    if (self->read_buf_tail != self->read_buf_head) {
        // buffering  via irq
        return (self->read_buf_head > self->read_buf_tail) ? self->read_buf_head - self->read_buf_tail :
                PYBUART_RX_BUFFER_LEN - self->read_buf_tail + self->read_buf_head;
    }
    return MAP_UARTCharsAvail(self->reg) ? 1 : 0;
}

int uart_rx_char(pyb_uart_obj_t *self) {
    if (self->read_buf_tail != self->read_buf_head) {
        // buffering via irq
        int data = self->read_buf[self->read_buf_tail];
        self->read_buf_tail = (self->read_buf_tail + 1) % PYBUART_RX_BUFFER_LEN;
        return data;
    } else {
        // no buffering
        return MAP_UARTCharGetNonBlocking(self->reg);
    }
}

bool uart_tx_char(pyb_uart_obj_t *self, int c) {
    uint32_t timeout = 0;
    while (!MAP_UARTCharPutNonBlocking(self->reg, c)) {
        if (timeout++ > ((PYBUART_TX_MAX_TIMEOUT_MS * 1000) / PYBUART_TX_WAIT_US(self->baudrate))) {
            return false;
        }
        UtilsDelay(UTILS_DELAY_US_TO_COUNT(PYBUART_TX_WAIT_US(self->baudrate)));
    }
    return true;
}

bool uart_tx_strn(pyb_uart_obj_t *self, const char *str, uint len) {
    for (const char *top = str + len; str < top; str++) {
        if (!uart_tx_char(self, *str)) {
            return false;
        }
    }
    return true;
}

/******************************************************************************
 DEFINE PRIVATE FUNCTIONS
 ******************************************************************************/
// assumes init parameters have been set up correctly
STATIC void uart_init (pyb_uart_obj_t *self) {
    // Enable the peripheral clock
    MAP_PRCMPeripheralClkEnable(self->peripheral, PRCM_RUN_MODE_CLK | PRCM_SLP_MODE_CLK);

    // Reset the uart
    MAP_PRCMPeripheralReset(self->peripheral);

    // re-allocate the read buffer after resetting the uart (which automatically disables any irqs)
    self->read_buf_head = 0;
    self->read_buf_tail = 0;
    self->read_buf = MP_OBJ_NULL; // free the read buffer before allocating again
    self->read_buf = m_new(byte, PYBUART_RX_BUFFER_LEN);

    // Initialize the UART
    MAP_UARTConfigSetExpClk(self->reg, MAP_PRCMPeripheralClockGet(self->peripheral),
                            self->baudrate, self->config);

    // Enable the FIFO
    MAP_UARTFIFOEnable(self->reg);

    // Configure the FIFO interrupt levels
    MAP_UARTFIFOLevelSet(self->reg, UART_FIFO_TX4_8, UART_FIFO_RX4_8);

    // Configure the flow control mode
    UARTFlowControlSet(self->reg, self->flowcontrol);
}

// Waits at most timeout microseconds for at least 1 char to become ready for
// reading (from buf or for direct reading).
// Returns true if something available, false if not.
STATIC bool uart_rx_wait (pyb_uart_obj_t *self) {
    int timeout = PYBUART_RX_TIMEOUT_US(self->baudrate);
    for ( ; ; ) {
        if (uart_rx_any(self)) {
            return true; // we have at least 1 char ready for reading
        }
        if (timeout > 0) {
            UtilsDelay(UTILS_DELAY_US_TO_COUNT(1));
            timeout--;
        }
        else {
            return false;
        }
    }
}

STATIC mp_obj_t uart_irq_new (pyb_uart_obj_t *self, byte trigger, mp_int_t priority, mp_obj_t handler) {
    // disable the uart interrupts before updating anything
    uart_irq_disable (self);

    if (self->uart_id == PYB_UART_0) {
        MAP_IntPrioritySet(INT_UARTA0, priority);
        MAP_UARTIntRegister(self->reg, UART0IntHandler);
    } else {
        MAP_IntPrioritySet(INT_UARTA1, priority);
        MAP_UARTIntRegister(self->reg, UART1IntHandler);
    }

    // create the callback
    mp_obj_t _irq = mp_irq_new ((mp_obj_t)self, handler, &uart_irq_methods);

    // enable the interrupts now
    self->irq_trigger = trigger;
    uart_irq_enable (self);
    return _irq;
}

STATIC void UARTGenericIntHandler(uint32_t uart_id) {
    pyb_uart_obj_t *self;
    uint32_t status;

    self = &pyb_uart_obj[uart_id];
    status = MAP_UARTIntStatus(self->reg, true);
    // receive interrupt
    if (status & (UART_INT_RX | UART_INT_RT)) {
        // set the flags
        self->irq_flags = UART_TRIGGER_RX_ANY;
        MAP_UARTIntClear(self->reg, UART_INT_RX | UART_INT_RT);
        while (UARTCharsAvail(self->reg)) {
            int data = MAP_UARTCharGetNonBlocking(self->reg);
            if (MP_STATE_PORT(os_term_dup_obj) && MP_STATE_PORT(os_term_dup_obj)->stream_o == self && data == mp_interrupt_char) {
                // raise an exception when interrupts are finished
                mp_sched_keyboard_interrupt();
            } else { // there's always a read buffer available
                uint16_t next_head = (self->read_buf_head + 1) % PYBUART_RX_BUFFER_LEN;
                if (next_head != self->read_buf_tail) {
                    // only store data if room in buf
                    self->read_buf[self->read_buf_head] = data;
                    self->read_buf_head = next_head;
                }
            }
        }
    }

    // check the flags to see if the user handler should be called
    if ((self->irq_trigger & self->irq_flags) && self->irq_enabled) {
        // call the user defined handler
        mp_irq_handler(mp_irq_find(self));
    }

    // clear the flags
    self->irq_flags = 0;
}

STATIC void uart_check_init(pyb_uart_obj_t *self) {
    // not initialized
    if (!self->baudrate) {
        mp_raise_OSError(MP_EPERM);
    }
}

STATIC void UART0IntHandler(void) {
    UARTGenericIntHandler(0);
}

STATIC void UART1IntHandler(void) {
    UARTGenericIntHandler(1);
}

STATIC void uart_irq_enable (mp_obj_t self_in) {
    pyb_uart_obj_t *self = self_in;
    // check for any of the rx interrupt types
    if (self->irq_trigger & (UART_TRIGGER_RX_ANY | UART_TRIGGER_RX_HALF | UART_TRIGGER_RX_FULL)) {
        MAP_UARTIntClear(self->reg, UART_INT_RX | UART_INT_RT);
        MAP_UARTIntEnable(self->reg, UART_INT_RX | UART_INT_RT);
    }
    self->irq_enabled = true;
}

STATIC void uart_irq_disable (mp_obj_t self_in) {
    pyb_uart_obj_t *self = self_in;
    self->irq_enabled = false;
}

STATIC int uart_irq_flags (mp_obj_t self_in) {
    pyb_uart_obj_t *self = self_in;
    return self->irq_flags;
}

/******************************************************************************/
/* MicroPython bindings                                                      */

STATIC void pyb_uart_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
    pyb_uart_obj_t *self = self_in;
    if (self->baudrate > 0) {
        mp_printf(print, "UART(%u, baudrate=%u, bits=", self->uart_id, self->baudrate);
        switch (self->config & UART_CONFIG_WLEN_MASK) {
        case UART_CONFIG_WLEN_5:
            mp_print_str(print, "5");
            break;
        case UART_CONFIG_WLEN_6:
            mp_print_str(print, "6");
            break;
        case UART_CONFIG_WLEN_7:
            mp_print_str(print, "7");
            break;
        case UART_CONFIG_WLEN_8:
            mp_print_str(print, "8");
            break;
        default:
            break;
        }
        if ((self->config & UART_CONFIG_PAR_MASK) == UART_CONFIG_PAR_NONE) {
            mp_print_str(print, ", parity=None");
        } else {
            mp_printf(print, ", parity=UART.%q", (self->config & UART_CONFIG_PAR_MASK) == UART_CONFIG_PAR_EVEN ? MP_QSTR_EVEN : MP_QSTR_ODD);
        }
        mp_printf(print, ", stop=%u)", (self->config & UART_CONFIG_STOP_MASK) == UART_CONFIG_STOP_ONE ? 1 : 2);
    }
    else {
        mp_printf(print, "UART(%u)", self->uart_id);
    }
}

STATIC mp_obj_t pyb_uart_init_helper(pyb_uart_obj_t *self, const mp_arg_val_t *args) {
    // get the baudrate
    if (args[0].u_int <= 0) {
        goto error;
    }
    uint baudrate = args[0].u_int;
    uint config;
    switch (args[1].u_int) {
    case 5:
        config = UART_CONFIG_WLEN_5;
        break;
    case 6:
        config = UART_CONFIG_WLEN_6;
        break;
    case 7:
        config = UART_CONFIG_WLEN_7;
        break;
    case 8:
        config = UART_CONFIG_WLEN_8;
        break;
    default:
        goto error;
        break;
    }
    // parity
    if (args[2].u_obj == mp_const_none) {
        config |= UART_CONFIG_PAR_NONE;
    } else {
        uint parity = mp_obj_get_int(args[2].u_obj);
        if (parity == 0) {
            config |= UART_CONFIG_PAR_EVEN;
        } else if (parity == 1) {
            config |= UART_CONFIG_PAR_ODD;
        } else {
            goto error;
        }
    }
    // stop bits
    config |= (args[3].u_int == 1 ? UART_CONFIG_STOP_ONE : UART_CONFIG_STOP_TWO);

    // assign the pins
    mp_obj_t pins_o = args[4].u_obj;
    uint flowcontrol = UART_FLOWCONTROL_NONE;
    if (pins_o != mp_const_none) {
        mp_obj_t *pins;
        size_t n_pins = 2;
        if (pins_o == MP_OBJ_NULL) {
            // use the default pins
            pins = (mp_obj_t *)pyb_uart_def_pin[self->uart_id];
        } else {
            mp_obj_get_array(pins_o, &n_pins, &pins);
            if (n_pins != 2 && n_pins != 4) {
                goto error;
            }
            if (n_pins == 4) {
                if (pins[PIN_TYPE_UART_RTS] != mp_const_none && pins[PIN_TYPE_UART_RX] == mp_const_none) {
                    goto error;  // RTS pin given in TX only mode
                } else if (pins[PIN_TYPE_UART_CTS] != mp_const_none && pins[PIN_TYPE_UART_TX] == mp_const_none) {
                    goto error;  // CTS pin given in RX only mode
                } else {
                    if (pins[PIN_TYPE_UART_RTS] != mp_const_none) {
                        flowcontrol |= UART_FLOWCONTROL_RX;
                    }
                    if (pins[PIN_TYPE_UART_CTS] != mp_const_none) {
                        flowcontrol |= UART_FLOWCONTROL_TX;
                    }
                }
            }
        }
        pin_assign_pins_af (pins, n_pins, PIN_TYPE_STD_PU, PIN_FN_UART, self->uart_id);
    }

    self->baudrate = baudrate;
    self->config = config;
    self->flowcontrol = flowcontrol;

    // initialize and enable the uart
    uart_init (self);
    // register it with the sleep module
    pyb_sleep_add ((const mp_obj_t)self, (WakeUpCB_t)uart_init);
    // enable the callback
    uart_irq_new (self, UART_TRIGGER_RX_ANY, INT_PRIORITY_LVL_3, mp_const_none);
    // disable the irq (from the user point of view)
    uart_irq_disable(self);

    return mp_const_none;

error:
    mp_raise_ValueError(MP_ERROR_TEXT("invalid argument(s) value"));
}

STATIC const mp_arg_t pyb_uart_init_args[] = {
    { MP_QSTR_id,                             MP_ARG_OBJ,  {.u_obj = MP_OBJ_NULL} },
    { MP_QSTR_baudrate,                       MP_ARG_INT,  {.u_int = 9600} },
    { MP_QSTR_bits,                           MP_ARG_INT,  {.u_int = 8} },
    { MP_QSTR_parity,                         MP_ARG_OBJ,  {.u_obj = mp_const_none} },
    { MP_QSTR_stop,                           MP_ARG_INT,  {.u_int = 1} },
    { MP_QSTR_pins,         MP_ARG_KW_ONLY  | MP_ARG_OBJ,  {.u_obj = MP_OBJ_NULL} },
};
STATIC mp_obj_t pyb_uart_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) {
    // parse args
    mp_map_t kw_args;
    mp_map_init_fixed_table(&kw_args, n_kw, all_args + n_args);
    mp_arg_val_t args[MP_ARRAY_SIZE(pyb_uart_init_args)];
    mp_arg_parse_all(n_args, all_args, &kw_args, MP_ARRAY_SIZE(args), pyb_uart_init_args, args);

    // work out the uart id
    uint uart_id;
    if (args[0].u_obj == MP_OBJ_NULL) {
        if (args[5].u_obj != MP_OBJ_NULL) {
            mp_obj_t *pins;
            size_t n_pins = 2;
            mp_obj_get_array(args[5].u_obj, &n_pins, &pins);
            // check the Tx pin (or the Rx if Tx is None)
            if (pins[0] == mp_const_none) {
                uart_id = pin_find_peripheral_unit(pins[1], PIN_FN_UART, PIN_TYPE_UART_RX);
            } else {
                uart_id = pin_find_peripheral_unit(pins[0], PIN_FN_UART, PIN_TYPE_UART_TX);
            }
        } else {
            // default id
            uart_id = 0;
        }
    } else {
        uart_id = mp_obj_get_int(args[0].u_obj);
    }

    if (uart_id > PYB_UART_1) {
        mp_raise_OSError(MP_ENODEV);
    }

    // get the correct uart instance
    pyb_uart_obj_t *self = &pyb_uart_obj[uart_id];
    self->base.type = &pyb_uart_type;
    self->uart_id = uart_id;

    // start the peripheral
    pyb_uart_init_helper(self, &args[1]);

    return self;
}

STATIC mp_obj_t pyb_uart_init(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
    // parse args
    mp_arg_val_t args[MP_ARRAY_SIZE(pyb_uart_init_args) - 1];
    mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(args), &pyb_uart_init_args[1], args);
    return pyb_uart_init_helper(pos_args[0], args);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_uart_init_obj, 1, pyb_uart_init);

STATIC mp_obj_t pyb_uart_deinit(mp_obj_t self_in) {
    pyb_uart_obj_t *self = self_in;

    // unregister it with the sleep module
    pyb_sleep_remove (self);
    // invalidate the baudrate
    self->baudrate = 0;
    // free the read buffer
    m_del(byte, self->read_buf, PYBUART_RX_BUFFER_LEN);
    MAP_UARTIntDisable(self->reg, UART_INT_RX | UART_INT_RT);
    MAP_UARTDisable(self->reg);
    MAP_PRCMPeripheralClkDisable(self->peripheral, PRCM_RUN_MODE_CLK | PRCM_SLP_MODE_CLK);
    return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_uart_deinit_obj, pyb_uart_deinit);

STATIC mp_obj_t pyb_uart_any(mp_obj_t self_in) {
    pyb_uart_obj_t *self = self_in;
    uart_check_init(self);
    return mp_obj_new_int(uart_rx_any(self));
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_uart_any_obj, pyb_uart_any);

STATIC mp_obj_t pyb_uart_sendbreak(mp_obj_t self_in) {
    pyb_uart_obj_t *self = self_in;
    uart_check_init(self);
    // send a break signal for at least 2 complete frames
    MAP_UARTBreakCtl(self->reg, true);
    UtilsDelay(UTILS_DELAY_US_TO_COUNT(PYBUART_2_FRAMES_TIME_US(self->baudrate)));
    MAP_UARTBreakCtl(self->reg, false);
    return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_uart_sendbreak_obj, pyb_uart_sendbreak);

/// \method irq(trigger, priority, handler, wake)
STATIC mp_obj_t pyb_uart_irq(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
    mp_arg_val_t args[mp_irq_INIT_NUM_ARGS];
    mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, mp_irq_INIT_NUM_ARGS, mp_irq_init_args, args);

    // check if any parameters were passed
    pyb_uart_obj_t *self = pos_args[0];
    uart_check_init(self);

    // convert the priority to the correct value
    uint priority = mp_irq_translate_priority (args[1].u_int);

    // check the power mode
    uint8_t pwrmode = (args[3].u_obj == mp_const_none) ? PYB_PWR_MODE_ACTIVE : mp_obj_get_int(args[3].u_obj);
    if (PYB_PWR_MODE_ACTIVE != pwrmode) {
        goto invalid_args;
    }

    // check the trigger
    uint trigger = mp_obj_get_int(args[0].u_obj);
    if (!trigger || trigger > (UART_TRIGGER_RX_ANY | UART_TRIGGER_RX_HALF | UART_TRIGGER_RX_FULL | UART_TRIGGER_TX_DONE)) {
        goto invalid_args;
    }

    // register a new callback
    return uart_irq_new (self, trigger, priority, args[2].u_obj);

invalid_args:
    mp_raise_ValueError(MP_ERROR_TEXT("invalid argument(s) value"));
}
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_uart_irq_obj, 1, pyb_uart_irq);

STATIC const mp_rom_map_elem_t pyb_uart_locals_dict_table[] = {
    // instance methods
    { MP_ROM_QSTR(MP_QSTR_init),        MP_ROM_PTR(&pyb_uart_init_obj) },
    { MP_ROM_QSTR(MP_QSTR_deinit),      MP_ROM_PTR(&pyb_uart_deinit_obj) },
    { MP_ROM_QSTR(MP_QSTR_any),         MP_ROM_PTR(&pyb_uart_any_obj) },
    { MP_ROM_QSTR(MP_QSTR_sendbreak),   MP_ROM_PTR(&pyb_uart_sendbreak_obj) },
    { MP_ROM_QSTR(MP_QSTR_irq),         MP_ROM_PTR(&pyb_uart_irq_obj) },

    /// \method read([nbytes])
    { MP_ROM_QSTR(MP_QSTR_read),        MP_ROM_PTR(&mp_stream_read_obj) },
    /// \method readline()
    { MP_ROM_QSTR(MP_QSTR_readline),    MP_ROM_PTR(&mp_stream_unbuffered_readline_obj) },
    /// \method readinto(buf[, nbytes])
    { MP_ROM_QSTR(MP_QSTR_readinto),    MP_ROM_PTR(&mp_stream_readinto_obj) },
    /// \method write(buf)
    { MP_ROM_QSTR(MP_QSTR_write),       MP_ROM_PTR(&mp_stream_write_obj) },

    // class constants
    { MP_ROM_QSTR(MP_QSTR_RX_ANY),      MP_ROM_INT(UART_TRIGGER_RX_ANY) },
};

STATIC MP_DEFINE_CONST_DICT(pyb_uart_locals_dict, pyb_uart_locals_dict_table);

STATIC mp_uint_t pyb_uart_read(mp_obj_t self_in, void *buf_in, mp_uint_t size, int *errcode) {
    pyb_uart_obj_t *self = self_in;
    byte *buf = buf_in;
    uart_check_init(self);

    // make sure we want at least 1 char
    if (size == 0) {
        return 0;
    }

    // wait for first char to become available
    if (!uart_rx_wait(self)) {
        // return MP_EAGAIN error to indicate non-blocking (then read() method returns None)
        *errcode = MP_EAGAIN;
        return MP_STREAM_ERROR;
    }

    // read the data
    byte *orig_buf = buf;
    for ( ; ; ) {
        *buf++ = uart_rx_char(self);
        if (--size == 0 || !uart_rx_wait(self)) {
            // return number of bytes read
            return buf - orig_buf;
        }
    }
}

STATIC mp_uint_t pyb_uart_write(mp_obj_t self_in, const void *buf_in, mp_uint_t size, int *errcode) {
    pyb_uart_obj_t *self = self_in;
    const char *buf = buf_in;
    uart_check_init(self);

    // write the data
    if (!uart_tx_strn(self, buf, size)) {
        mp_raise_OSError(MP_EIO);
    }
    return size;
}

STATIC mp_uint_t pyb_uart_ioctl(mp_obj_t self_in, mp_uint_t request, mp_uint_t arg, int *errcode) {
    pyb_uart_obj_t *self = self_in;
    mp_uint_t ret;
    uart_check_init(self);

    if (request == MP_STREAM_POLL) {
        mp_uint_t flags = arg;
        ret = 0;
        if ((flags & MP_STREAM_POLL_RD) && uart_rx_any(self)) {
            ret |= MP_STREAM_POLL_RD;
        }
        if ((flags & MP_STREAM_POLL_WR) && MAP_UARTSpaceAvail(self->reg)) {
            ret |= MP_STREAM_POLL_WR;
        }
    } else {
        *errcode = MP_EINVAL;
        ret = MP_STREAM_ERROR;
    }
    return ret;
}

STATIC const mp_stream_p_t uart_stream_p = {
    .read = pyb_uart_read,
    .write = pyb_uart_write,
    .ioctl = pyb_uart_ioctl,
    .is_text = false,
};

STATIC const mp_irq_methods_t uart_irq_methods = {
    .init = pyb_uart_irq,
    .enable = uart_irq_enable,
    .disable = uart_irq_disable,
    .flags = uart_irq_flags
};

const mp_obj_type_t pyb_uart_type = {
    { &mp_type_type },
    .name = MP_QSTR_UART,
    .print = pyb_uart_print,
    .make_new = pyb_uart_make_new,
    .getiter = mp_identity_getiter,
    .iternext = mp_stream_unbuffered_iter,
    .protocol = &uart_stream_p,
    .locals_dict = (mp_obj_t)&pyb_uart_locals_dict,
};


text:
<?xml version="1.0"?>
<System name="Authenticated">
  <Has name="server" value="/"/>
  <Has name="title" value="Authenticated"/>
  <Has name="version" value="0.0.0"/>
  <Function name="GET_resource">
    <Has name="operation" value="GET"/>
    <Has name="path" value="/resource"/>
    <Input type="implicit">
      <VarSet name="None">
        <Var name="Defined">
          <Value name="No"/>
        </Var>
      </VarSet>
    </Input>
  </Function>
  <Function name="POST_resource">
    <Has name="operation" value="POST"/>
    <Has name="path" value="/resource"/>
    <Input type="request">
      <VarSet name="Body">
        <Var name="Defined">
          <Value name="Yes" property="bodyContent"/>
          <Value name="No" failure="true"/>
        </Var>
        <Var name="Media-Type" when="bodyContent">
          <Value name="application-json" property="bodyApplication-json">
            <Has name="mediaType" value="application/json"/>
          </Value>
          <Value name="Other" failure="true">
            <Has name="excluded" value="'application/json'"/>
          </Value>
        </Var>
        <VarSet name="application-json" when="bodyApplication-json">
          <Var name="Type">
            <Value name="integer" property="bodyApplication-jsonValue"/>
            <Value name="null" failure="true"/>
            <Value name="Not integer" failure="true"/>
          </Var>
          <VarSet name="Value" when="bodyApplication-jsonValue">
            <Var name="Is">
              <Value name="-1" failure="true"/>
              <Value name="0"/>
              <Value name="> 0"/>
            </Var>
          </VarSet>
        </VarSet>
      </VarSet>
    </Input>
    <Input type="security">
      <VarSet name="Auth">
        <VarSet name="opKeyQuery">
          <Var name="Defined">
            <Value name="Yes" property="secRecOpKeyQuery"/>
            <Value name="No" failure="true">
              <Has name="authFailure" value="true"/>
            </Value>
          </Var>
          <Var name="Type" when="secRecOpKeyQuery">
            <Value name="apiKey"/>
          </Var>
          <Var name="Location" when="secRecOpKeyQuery">
            <Value name="query"/>
          </Var>
          <Var name="Name" when="secRecOpKeyQuery">
            <Value name="opKey"/>
          </Var>
        </VarSet>
      </VarSet>
    </Input>
  </Function>
  <Function name="DELETE_resource">
    <Has name="operation" value="DELETE"/>
    <Has name="path" value="/resource"/>
    <Input type="query">
      <VarSet name="id">
        <Has name="paramName" value="id"/>
        <Var name="Defined">
          <Has name="style" value="form"/>
          <Value name="Yes" property="id"/>
          <Value name="No"/>
        </Var>
        <Var name="Type" when="id">
          <Value name="integer" property="idValue"/>
          <Value name="null" failure="true"/>
          <Value name="Not integer" failure="true"/>
        </Var>
        <VarSet name="Value" when="idValue">
          <Var name="Is">
            <Value name="-1" failure="true"/>
            <Value name="0"/>
            <Value name="> 0"/>
          </Var>
        </VarSet>
      </VarSet>
    </Input>
    <Input type="security">
      <VarSet name="Auth">
        <Var name="Satisfied">
          <Value name="Yes">
            <When>
              <Equals property="secRec" count="1"/>
            </When>
          </Value>
          <Value name="No" failure="true">
            <Has name="authFailure" value="true"/>
            <When>
              <Equals property="secRec" count="0"/>
            </When>
          </Value>
        </Var>
        <VarSet name="0">
          <Var name="Defined">
            <Value name="Yes" property="secRec, secRec0"/>
            <Value name="No"/>
          </Var>
          <VarSet name="apiHttpBasic" when="secRec0">
            <Var name="Type">
              <Value name="http"/>
            </Var>
            <Var name="Scheme">
              <Value name="basic"/>
            </Var>
          </VarSet>
        </VarSet>
        <VarSet name="1">
          <Var name="Defined">
            <Value name="Yes" property="secRec, secRec1"/>
            <Value name="No"/>
          </Var>
          <VarSet name="apiHttpBearer" when="secRec1">
            <Var name="Defined">
              <Value name="Yes" property="secRec1ApiHttpBearer"/>
              <Value name="No" failure="true">
                <Has name="authFailure" value="true"/>
              </Value>
            </Var>
            <Var name="Type" when="secRec1ApiHttpBearer">
              <Value name="http"/>
            </Var>
            <Var name="Scheme" when="secRec1ApiHttpBearer">
              <Value name="bearer"/>
            </Var>
          </VarSet>
          <VarSet name="apiKeyCookie" when="secRec1">
            <Var name="Defined">
              <Value name="Yes" property="secRec1ApiKeyCookie"/>
              <Value name="No" failure="true">
                <Has name="authFailure" value="true"/>
              </Value>
            </Var>
            <Var name="Type" when="secRec1ApiKeyCookie">
              <Value name="apiKey"/>
            </Var>
            <Var name="Location" when="secRec1ApiKeyCookie">
              <Value name="cookie"/>
            </Var>
            <Var name="Name" when="secRec1ApiKeyCookie">
              <Value name="apiKey"/>
            </Var>
          </VarSet>
        </VarSet>
      </VarSet>
    </Input>
  </Function>
</System>

redpajama_set_name: RedPajamaGithub


text:
FROM ubuntu:18.04
ARG PIP_INDEX_URL=https://pypi.yelpcorp.com/simple
ENV PIP_INDEX_URL=$PIP_INDEX_URL
RUN apt-get update && apt-get install -y git python python-setuptools python-pip
RUN git clone https://github.com/Yelp/hacheck
RUN cd /hacheck && pip install .

RUN apt-get -y install socat

# Hacheck
EXPOSE 6666

# Run hacheck in background and dummy service in foreground
EXPOSE 1025
CMD /usr/local/bin/hacheck -p 6666 & socat TCP4-LISTEN:1025,fork SYSTEM:date


text:
#ifndef __MYREENTRANT_RANDOM__
#define __MYREENTRANT_RANDOM__

#include <cstdlib>

/**
 * Implemented thread-safe random number generator using random_r.
 */
class ReentrantRandom
{
	public:
		/**
		 * Initializes using: time() ^ (salt << 4).
		 */
		inline void init(unsigned int salt);

		/**
		 * Returns next random int.
		 */
		inline int next();

	private:
		struct random_data state;
		char buffer[32*sizeof(int32_t)];
};

#include "reentrant_random.inl"

#endif


text:
package tollBarrier.vehicule.vehiculesObjects;

import java.util.Random;
import java.util.Set;

import tollBarrier.vehicule.MoyenDePaiment;

public class Camion extends Vehicule
{

	public Camion(Set<MoyenDePaiment> mdp)
	{
		super(mdp);
		_amount = new Random().nextInt(51) +10;
	}

	public long getTimeMuliplier()
	{
		return 10;
	}

}


text:
package com.siyeh.ig.abstraction;

import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.ide.DataManager;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.PsiSearchHelper;
import com.intellij.psi.search.searches.MethodReferencesSearch;
import com.intellij.refactoring.RefactoringActionHandler;
import com.intellij.refactoring.RefactoringActionHandlerFactory;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.Processor;
import com.intellij.util.Query;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspection;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.InspectionGadgetsFix;
import com.siyeh.ig.psiutils.ClassUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public class StaticMethodOnlyUsedInOneClassInspection
        extends BaseInspection {

    @NotNull
    public String getDisplayName() {
        return InspectionGadgetsBundle.message(
                "static.method.only.used.in.one.class.display.name");
    }

    @NotNull
    protected String buildErrorString(Object... infos) {
        final PsiNamedElement element = (PsiNamedElement)infos[0];
        final String name = element.getName();
        if (infos.length > 1) {
            if (Boolean.TRUE.equals(infos[1])) {
                return InspectionGadgetsBundle.message(
                        "static.method.only.used.in.one.class.problem.descriptor.anonymous.extending",
                        name);
            }
            return InspectionGadgetsBundle.message(
                    "static.method.only.used.in.one.class.problem.descriptor.anonymous.implementing",
                    name);
        }
        return InspectionGadgetsBundle.message(
                "static.method.only.used.in.one.class.problem.descriptor", name);
    }

    @Nullable
    protected InspectionGadgetsFix buildFix(Object... infos) {
        return new StaticMethodOnlyUsedInOneClassFix();
    }

    private static class StaticMethodOnlyUsedInOneClassFix
            extends InspectionGadgetsFix {

        @NotNull
        public String getName() {
            return InspectionGadgetsBundle.message(
                    "static.method.only.used.in.one.class.quickfix");
        }

        protected void doFix(@NotNull final Project project,
                             ProblemDescriptor descriptor)
                throws IncorrectOperationException {
            final PsiElement location = descriptor.getPsiElement();
            final PsiMethod method = (PsiMethod)location.getParent();
            final Application application = ApplicationManager.getApplication();
            application.invokeLater(new Runnable() {
                public void run() {
                    final RefactoringActionHandlerFactory factory =
                            RefactoringActionHandlerFactory.getInstance();
                    final RefactoringActionHandler moveHandler =
                            factory.createMoveHandler();
                    final DataManager dataManager = DataManager.getInstance();
                    final DataContext dataContext =
                            dataManager.getDataContext();
                    moveHandler.invoke(project, new PsiElement[]{method},
                            dataContext);
                }
            });
        }
    }

    public BaseInspectionVisitor buildVisitor() {
        return new StaticmethodOnlyUsedInOneClassVisitor();
    }

    private static class StaticmethodOnlyUsedInOneClassVisitor
            extends BaseInspectionVisitor {

        @Override public void visitMethod(PsiMethod method) {
            super.visitMethod(method);
            if (!method.hasModifierProperty(PsiModifier.STATIC)) {
                return;
            }
            if (method.hasModifierProperty(PsiModifier.PRIVATE)) {
                return;
            }
            if (method.getNameIdentifier() == null) {
                return;
            }
            final UsageProcessor usageProcessor = new UsageProcessor();
            final PsiClass usageClass = usageProcessor.getUsageClass(method);
            if (usageClass == null) {
                return;
            }
            if (usageClass.equals(method.getContainingClass())) {
                return;
            }
            if (usageClass instanceof PsiAnonymousClass) {
                final PsiClass[] interfaces =
                        usageClass.getInterfaces();
                final PsiClass superClass;
                if (interfaces.length == 1) {
                    superClass = interfaces[0];
                    registerMethodError(method, superClass,
                            Boolean.valueOf(false));
                } else {
                    superClass = usageClass.getSuperClass();
                    if (superClass == null) {
                        return;
                    }
                    registerMethodError(method, superClass,
                            Boolean.valueOf(true));
                }
            } else {
                registerMethodError(method, usageClass);
            }
        }
    }

    private static class UsageProcessor implements Processor<PsiReference> {

        private PsiClass usageClass = null;

        public boolean process(PsiReference reference) {
            final ProgressManager progressManager =
                    ProgressManager.getInstance();
            progressManager.checkCanceled();
            final PsiElement element = reference.getElement();
            final PsiClass usageClass =
                    ClassUtils.getContainingClass(element);
            if (this.usageClass != null &&
                    !this.usageClass.equals(usageClass)) {
                this.usageClass = null;
                return false;
            }
            this.usageClass = usageClass;
            return true;
        }

        /**
         * @return the class the specified method is used from, or null if it is
         * used from 0 or more than 1 other classes.
         */
        @Nullable
        public PsiClass getUsageClass(final PsiMethod method) {
            final ProgressManager progressManager =
                    ProgressManager.getInstance();
            final PsiManager manager = method.getManager();
            final PsiSearchHelper searchHelper = manager.getSearchHelper();
            final String name = method.getName();
            final GlobalSearchScope scope =
                    GlobalSearchScope.allScope(method.getProject());
            final FindUsagesCostProcessor costProcessor =
                    new FindUsagesCostProcessor();
            searchHelper.processAllFilesWithWord(name, scope,
                    costProcessor, true);
            if (costProcessor.isCostTooHigh()) {
                return null;
            }
            progressManager.runProcess(new Runnable() {
                public void run() {
                    final Query<PsiReference> query =
                            MethodReferencesSearch.search(method);
                    query.forEach(UsageProcessor.this);
                }
            }, null);
            return usageClass;
        }

        private static class FindUsagesCostProcessor
                implements Processor<PsiFile> {

            private int counter = 0;
            private boolean costTooHigh = true;

            public boolean process(PsiFile psiFile) {
                counter++;
                if (counter < 10) {
                    costTooHigh = false;
                    return true;
                }
                costTooHigh = true;
                return false;
            }

            public boolean isCostTooHigh() {
                return costTooHigh;
            }
        }
    }
}


text:
<?php

namespace Codenetix\SocialMediaImporter\Support;

/**
 * @author Andrey Vorobiov<andrew.sprw@gmail.com>
 */
class TagsFromStringExtractor
{
    public static function extract($description)
    {
        if (preg_match_all('/#([\w]+)(?![\w])/i', $description, $matches)) {
            return $matches[1];
        }
        return [];
    }
}


text:
@import url('../Aqua/Stylesheet.css');

ul.tree-menu li div a.external_calendar, ul.tree-menu li div a.type_external_calendar,
	ul.tree-menu li div a.type_external_calendar_default {
	background-image: url(../../Images/Ruby/Logo/16.png);
}


text:
<?xml version='1.0' encoding='UTF-8'?>
<features name='gwtws-${project.version}'>

	<repository>mvn:org.apache.servicemix/apache-servicemix/${servicemix.version}/xml/features</repository>
	<repository>mvn:org.apache.camel.karaf/apache-camel/${camel.version}/xml/features</repository>

	<feature name="gwtws" version="${project.version}">

		<feature dependency="true">jetty</feature>
		<feature dependency="true">war</feature>

		<!--<bundle>mvn:com.google.gwt/gwt-servlet/${gwt.version}</bundle>-->
		<bundle>mvn:org.apache.servicemix.bundles/org.apache.servicemix.bundles.gwt-servlet/2.6.0_1-SNAPSHOT</bundle>

		<bundle>mvn:${project.groupId}/${project.artifactId}/${project.version}/war</bundle>
	</feature>
</features>


text:
package recursion1;

/*
 * Given a string, compute recursively a new string where identical chars
 * that are adjacent in the original string are separated from each other
 * by a "*".
 *
 * pairStar("hello") --> "hel*lo"
 * pairStar("xxyy") --> "x*xy*y"
 * pairStar("aaaa") --> "a*a*a*a"
 */

public class PairStarTest {
    public static void main(String[] args) {
		PairStarTest test = new PairStarTest();
		System.out.println(test.pairStar("hello"));
		System.out.println(test.pairStar("xxyy"));
		System.out.println(test.pairStar("aaaa"));
	}

    public String pairStar(String str) {
        if (str.length() <= 1) {
            return str;
        } else {
            if (str.charAt(0) == str.charAt(1)) {
                return str.charAt(0) + "*" + pairStar(str.substring(1));
            } else {
                return str.charAt(0) + pairStar(str.substring(1));
            }
        }
    }
}


text:
!-------------------------------------------------------------
! Copyright (c) 2013-2014 Yuta Kawai. All rights reserved.
!-------------------------------------------------------------
!> @brief a template module
!!
!! @author Yuta Kawai
!!
!!
module HexTriRectMesh_mod

  ! モジュール引用; Use statements
  !
  use dc_types, only: &
       & DP, TOKEN, STRING

  use dc_message, only: &
       & MessageNotify

  use VectorSpace_mod
  use SphericalCoord_mod
  use geometry_mod
  use PolyMesh_mod
  use fvMeshInfo_mod
  use GeometricField_mod

  ! 宣言文; Declareration statements
  !
  implicit none
  private

  ! 公開手続き
  ! Public procedure
  !
  public :: HexTriRectMesh_Init, HexTriRectMesh_Final

  type, public :: HexTriRectMesh
     type(PolyMesh), pointer :: mesh => null()
  end type HexTriRecMesh

  ! 非公開手続き
  ! Private procedure
  !

  ! 非公開変数
  ! Private variable
  !
  character(*), parameter:: module_name = 'HexTriRectMesh_mod' !< Module Name

contains

  !>
  !!
  !!
  subroutine HexTriRectMesh_Init(self, mesh)

    type(HexTriIcMesh), intent(inout) :: self
    type(PolyMesh), intent(in) :: mesh

    ! 実行文; Executable statements
    !

    self%mesh => mesh

  end subroutine HexTriRectMesh_Init

  !>
  !!
  !!
  subroutine HexTriRectMesh_Final()

    ! 実行文; Executable statements
    !

  end subroutine HexTriRectMesh_Final

  !> @brief
  !!
  !!
  subroutine HexTriRectMesh_generare(self, x0, x1, y0, y1, nx, ny)

    ! 宣言文; Declaration statement
    !
    type(HexTriRectMesh), intent(inout) :: self
    real(DP), intent(in) :: x0, x1, y0, y2
    integer, intent(in) :: NX, NY

    ! 局所変数
    ! Local variables
    !

    ! 実行文; Executable statement
    !

  end subroutine HexTriRectMesh_generare

end module HexTriRectMesh_mod


text:
layout: page
title: Harper - Acevedo Wedding
date: 2016-05-24
author: Deborah Nguyen
tags: weekly links, java
status: published
summary: Suspendisse in elementum ipsum. Fusce id hendrerit.
banner: images/banner/leisure-04.jpg
booking:
  startDate: 05/10/2019
  endDate: 05/11/2019
  ctyhocn: MNZHAHX
  groupCode: HAW
published: true
---
Sed dignissim eget ex ut vehicula. Nulla vel molestie augue. Sed blandit turpis ante, maximus eleifend urna fringilla varius. Nunc ut auctor velit. Fusce sed malesuada ante. Pellentesque eget sem accumsan nibh tempus pulvinar. Sed non blandit enim. Etiam aliquet nunc neque, quis iaculis elit finibus quis. In consectetur tellus nec massa imperdiet vehicula. Aenean pretium augue a sodales efficitur. Duis lobortis lorem erat, imperdiet facilisis sapien luctus nec.
Nam hendrerit mi vel consequat interdum. Nam eget dapibus turpis, eu maximus purus. Sed sit amet quam commodo, vulputate leo eu, dictum elit. Donec nec libero magna. Vestibulum eget enim vel augue cursus faucibus. Nam venenatis ante libero, quis lacinia velit ultrices sit amet. In at vestibulum lorem, a accumsan neque. Etiam sed lorem velit.

* Cras gravida ante sed libero sollicitudin eleifend
* Proin vitae diam eu nunc porta auctor
* Curabitur vitae ipsum scelerisque, feugiat metus vitae, pellentesque est
* Sed pulvinar tortor quis tortor pellentesque eleifend.

Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Proin pharetra vitae dolor a iaculis. Etiam malesuada non velit eget rhoncus. Integer felis nisl, cursus nec convallis eu, vulputate non diam. Nullam pretium, sapien ac fermentum bibendum, justo sem viverra sapien, vitae efficitur sapien metus eget massa. Morbi auctor tincidunt ex, in ullamcorper odio semper vel. Nulla facilisi.


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

<title>Constant Field Values (HappyBrackets API)</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Constant Field Values

Contents

net.happybrackets.*

net.happybrackets.*

net.happybrackets.core.OSCVocabulary.CONTROLLER

Modifier and Type
Constant Field
Value

public static final java.lang.String
CONTROLLER
"/hb/controller"

net.happybrackets.core.OSCVocabulary.Device

Modifier and Type
Constant Field
Value

public static final java.lang.String
ALIVE
"/device/alive"

public static final java.lang.String
BLEEP
"/device/bleep"

public static final java.lang.String
CLASS_LOADED
"/device/classloaded"

public static final java.lang.String
CLEAR_SOUND
"/device/clearsound"

public static final java.lang.String
DEVICE
"/device"

public static final java.lang.String
FADEOUT_CLEAR_SOUND
"/device/fadeout_clearsound"

public static final java.lang.String
FADEOUT_RESET
"/device/fadeout_reset"

public static final java.lang.String
FRIENDLY_NAME
"/device/friendly"

public static final java.lang.String
GAIN
"/device/gain"

public static final java.lang.String
GET_LOGS
"/device/get_logs"

public static final java.lang.String
LOG
"/device/log"

public static final java.lang.String
REBOOT
"/device/reboot"

public static final java.lang.String
RESET
"/device/reset"

public static final java.lang.String
RESET_SOUNDING
"/device/reset_sounding"

public static final java.lang.String
SET_ENCRYPTION
"/device/encrypt"

public static final java.lang.String
SET_ID
"/device/set_id"

public static final java.lang.String
SET_NAME
"/device/set_name"

public static final java.lang.String
SHUTDOWN
"/device/shutdown"

public static final java.lang.String
SIMULATOR_HOME_PATH
"/device/simulatorpath"

public static final java.lang.String
STATUS
"/device/status"

public static final java.lang.String
SYNC
"/device/sync"

public static final java.lang.String
VERSION
"/device/version"

net.happybrackets.core.OSCVocabulary.DeviceConfig

Modifier and Type
Constant Field
Value

public static final java.lang.String
CONFIG
"/device/config"

public static final java.lang.String
DELETE_CONFIG
"/device/config/delete"

public static final java.lang.String
PRINT_CONFIG
"/device/config/print"

net.happybrackets.core.OSCVocabulary.DynamicControlMessage

Modifier and Type
Constant Field
Value

public static final java.lang.String
CONTROL
"/cont"

public static final java.lang.String
CREATE
"/cont/create"

public static final java.lang.String
DESTROY
"/cont/destroy"

public static final java.lang.String
DEVICE_NAME
"/cont/device"

public static final java.lang.String
GET
"/cont/get"

public static final java.lang.String
GLOBAL
"/cont/global"

public static final java.lang.String
REQUEST_NAME
"/cont/request"

public static final java.lang.String
TARGET
"/cont/target"

public static final java.lang.String
UPDATE
"/cont/up"

net.happybrackets.core.OSCVocabulary.FileSendMessage

Modifier and Type
Constant Field
Value

public static final java.lang.String
CANCEL
"/file/cancel"

public static final java.lang.String
COMPLETE
"/file/complete"

public static final java.lang.String
CONTROL
"/file"

public static final java.lang.String
ERROR
"/file/error"

public static final java.lang.String
START
"/file/start"

public static final java.lang.String
WRITE
"/file/write"

net.happybrackets.core.OSCVocabulary.SchedulerMessage

Modifier and Type
Constant Field
Value

public static final java.lang.String
ADJUST
"/time/adj"

public static final java.lang.String
CURRENT
"/time/cur"

public static final java.lang.String
SET
"/time/set"

public static final java.lang.String
STRATUM
"/time/strat"

public static final java.lang.String
TIME
"/time"

net.happybrackets.core.config.DefaultConfig

Modifier and Type
Constant Field
Value

public static final int
ALIVE_INTERVAL
1000

public static final java.lang.String
AUDIO_DIRECTORY
"/audio"

public static final int
BROADCAST_PORT
2222

public static final int
CLOCK_SYNC_PORT
2224

public static final int
CODE_TO_DEVICE_PORT
2225

public static final java.lang.String
CONFIG_DIRECTORY
"/config"

public static final int
CONTROL_TO_DEVICE_PORT
2226

public static final int
CONTROLLER_DISCOVERY_PORT
2227

public static final int
CONTROLLER_HTTP_PORT
2228

public static final java.lang.String
ENCRYPTION_KEY
"CHANGE ME!"

public static final java.lang.String
KNOWN_DEVICES_FILE
"/known_devices"

public static final java.lang.String
MULTICAST_ADDRESS
"::FFFF:225.2.2.5"

public static final int
SECONDARY_BROADCAST_PORT
2229

public static final int
STATUS_FROM_DEVICE_PORT
2223

public static final java.lang.String
WORKING_DIRECTORY
"."

net.happybrackets.core.instruments.SampleModule

Modifier and Type
Constant Field
Value

public final java.lang.String
EXAMPLE_SAMPLE_NAME
"data/audio/Roje/i-write.wav"

net.happybrackets.device.DeviceMain

Modifier and Type
Constant Field
Value

public static final java.lang.String
EXAMPLES_FOLDER
"examples"

net.happybrackets.device.MuteControl

Modifier and Type
Constant Field
Value

public static final int
DEFAULT_MUTE_OUTPUT
27

net.happybrackets.device.StartupClasses

Modifier and Type
Constant Field
Value

public static final java.lang.String
STARTUP_FOLDER
"data/classes/"

net.happybrackets.device.config.ConfigFiles

Modifier and Type
Constant Field
Value

public static final java.lang.String
COMMON_CONFIG
"common.config"

public static final java.lang.String
CONFIG_EXT
".config"

public static final java.lang.String
JARS_FOLDER
"data/jars"

net.happybrackets.device.sensors.HTS221.I2CConstants

Modifier and Type
Constant Field
Value

public static final int
MULTI_BYTE_READ_MASK
128

net.happybrackets.device.sensors.LPS25H

Modifier and Type
Constant Field
Value

public static final byte
CTRL_REG1
32

public static final byte
CTRL_REG2
33

public static final byte
CTRL_REG3
34

public static final byte
CTRL_REG4
35

public static final byte
FIFO_CTRL
46

public static final byte
FIFO_STATUS
47

public static final byte
INT_CFG
36

public static final byte
INT_SOURCE
37

public static final byte
LPS25H_ADDRESS
92

public static final byte
PRESS_OUT_H
42

public static final byte
PRESS_OUT_L
41

public static final byte
PRESS_POUT_XL
40

public static final byte
REF_P_H
10

public static final byte
REF_P_L
9

public static final byte
REF_P_XL
8

public static final byte
RES_CONF
16

public static final byte
RPDS_H
58

public static final byte
RPDS_L
57

public static final byte
STATUS_REG
39

public static final byte
TEMP_OUT_H
44

public static final byte
TEMP_OUT_L
43

public static final byte
THS_P_H
49

public static final byte
THS_P_L
48

public static final byte
WHO_AM_I
15

net.happybrackets.device.sensors.LPS25H.I2CConstants

Modifier and Type
Constant Field
Value

public static final int
MULTI_BYTE_READ_MASK
128

net.happybrackets.device.sensors.LSM9DS1

Modifier and Type
Constant Field
Value

public static final int
ACC_DEVICE
0

public static final float
ACC_SCALE_16G
7.319999858736992E-4f

public static final float
ACC_SCALE_2G
6.0999998822808266E-5f

public static final float
ACC_SCALE_4G
1.2199999764561653E-4f

public static final float
ACC_SCALE_8G
2.4399999529123306E-4f

public static final float
ACC_ZERO
0.05000000074505806f

public static final float
ACCEL_CAL_MAX_X
1.006410002708435f

public static final float
ACCEL_CAL_MAX_Y
1.00497305393219f

public static final float
ACCEL_CAL_MAX_Z
1.0012439489364624f

public static final float
ACCEL_CAL_MIN_X
-0.9885119795799255f

public static final float
ACCEL_CAL_MIN_Y
-1.0115000009536743f

public static final float
ACCEL_CAL_MIN_Z
-1.012328028678894f

public static final int
ACT_DUR
5

public static final int
ACT_THS
4

public static final float
COMPASS_ALPHA
0.20000000298023224f

public static final float
COMPASS_ELLIPSOID_CORR_11
0.9732940196990967f

public static final float
COMPASS_ELLIPSOID_CORR_12
-0.014069000259041786f

public static final float
COMPASS_ELLIPSOID_CORR_13
-0.02142300084233284f

public static final float
COMPASS_ELLIPSOID_CORR_21
-0.014069000259041786f

public static final float
COMPASS_ELLIPSOID_CORR_22
0.9656919836997986f

public static final float
COMPASS_ELLIPSOID_CORR_23
-0.0027459999546408653f

public static final float
COMPASS_ELLIPSOID_CORR_31
-0.02142300084233284f

public static final float
COMPASS_ELLIPSOID_CORR_32
-0.0027459999546408653f

public static final float
COMPASS_ELLIPSOID_CORR_33
0.9801030158996582f

public static final float
COMPASS_ELLIPSOID_OFFSET_X
0.2689400017261505f

public static final float
COMPASS_ELLIPSOID_OFFSET_Y
0.5303450226783752f

public static final float
COMPASS_ELLIPSOID_OFFSET_Z
-0.12090799957513809f

public static final float
COMPASS_MAX_X
49.599647521972656f

public static final float
COMPASS_MAX_Y
70.56722259521484f

public static final float
COMPASS_MAX_Z
55.16642379760742f

public static final float
COMPASS_MIN_X
-26.074535369873047f

public static final float
COMPASS_MIN_Y
-2.03456711769104f

public static final float
COMPASS_MIN_Z
-14.253132820129395f

public static final int
CTRL_REG1_G
16

public static final int
CTRL_REG1_M
32

public static final int
CTRL_REG10
36

public static final int
CTRL_REG2_G
17

public static final int
CTRL_REG2_M
33

public static final int
CTRL_REG3_G
18

public static final int
CTRL_REG3_M
34

public static final int
CTRL_REG4
30

public static final int
CTRL_REG4_M
35

public static final int
CTRL_REG5_M
36

public static final int
CTRL_REG5_XL
31

public static final int
CTRL_REG6_XL
32

public static final int
CTRL_REG7_XL
33

public static final int
CTRL_REG8
34

public static final int
CTRL_REG9
35

public static final int
FIFO_CTRL
46

public static final int
FIFO_SRC
47

public static final float
GYRO_BIAS_X_INIT
0.02464199997484684f

public static final float
GYRO_BIAS_Y_INIT
0.02025499939918518f

public static final float
GYRO_BIAS_Z_INIT
-0.011904999613761902f

public static final float
GYRO_CONTINIOUS_ALPHA
0.009999999776482582f

public static final float
GYRO_LEARNING_ALPHA
2.0f

public static final float
GYRO_SCALE_2000
0.0012217304902151227f

public static final float
GYRO_SCALE_250
1.5271631127689034E-4f

public static final float
GYRO_SCALE_500
3.054326225537807E-4f

public static final float
GYRO_ZERO
0.20000000298023224f

public static final int
INT_CFG_M
48

public static final int
INT_GEN_CFG_G
48

public static final int
INT_GEN_CFG_XL
6

public static final int
INT_GEN_DUR_G
55

public static final int
INT_GEN_DUR_XL
10

public static final int
INT_GEN_SRC_G
20

public static final int
INT_GEN_SRC_XL
38

public static final int
INT_GEN_THS_X_XL
7

public static final int
INT_GEN_THS_XH_G
49

public static final int
INT_GEN_THS_XL_G
50

public static final int
INT_GEN_THS_Y_XL
8

public static final int
INT_GEN_THS_YH_G
51

public static final int
INT_GEN_THS_YL_G
52

public static final int
INT_GEN_THS_Z_XL
9

public static final int
INT_GEN_THS_ZH_G
53

public static final int
INT_GEN_THS_ZL_G
54

public static final int
INT_SRC_M
49

public static final int
INT_THS_H_M
51

public static final int
INT_THS_L_M
50

public static final int
INT1_CTRL
12

public static final int
INT2_CTRL
13

public static final int
LSM9DS1_ACCADDRESS
106

public static final int
LSM9DS1_MAGADDRESS
28

public static final int
MAG_DEVICE
1

public static final float
MAG_SCALE_12
0.0430000014603138f

public static final float
MAG_SCALE_16
0.057999998331069946f

public static final float
MAG_SCALE_4
0.014000000432133675f

public static final float
MAG_SCALE_8
0.028999999165534973f

public static final int
OFFSET_X_REG_H_M
6

public static final int
OFFSET_X_REG_L_M
5

public static final int
OFFSET_Y_REG_H_M
8

public static final int
OFFSET_Y_REG_L_M
7

public static final int
OFFSET_Z_REG_H_M
10

public static final int
OFFSET_Z_REG_L_M
9

public static final int
ORIENT_CFG_G
19

public static final int
OUT_TEMP_H
22

public static final int
OUT_TEMP_L
21

public static final int
OUT_X_H_G
25

public static final int
OUT_X_H_M
41

public static final int
OUT_X_H_XL
41

public static final int
OUT_X_L_G
24

public static final int
OUT_X_L_M
40

public static final int
OUT_X_L_XL
40

public static final int
OUT_Y_H_G
27

public static final int
OUT_Y_H_M
43

public static final int
OUT_Y_H_XL
43

public static final int
OUT_Y_L_G
26

public static final int
OUT_Y_L_M
42

public static final int
OUT_Y_L_XL
42

public static final int
OUT_Z_H_G
29

public static final int
OUT_Z_H_M
45

public static final int
OUT_Z_H_XL
45

public static final int
OUT_Z_L_G
28

public static final int
OUT_Z_L_M
44

public static final int
OUT_Z_L_XL
44

public static final int
REFERENCE_G
11

public static final int
STATUS_REG_0
23

public static final int
STATUS_REG_1
39

public static final int
STATUS_REG_M
39

public static final int
WHO_AM_I_AG_ID
104

public static final int
WHO_AM_I_M
15

public static final int
WHO_AM_I_M_ID
61

public static final int
WHO_AM_I_XG
15

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
// import redux-saga deps
import { takeEvery } from 'redux-saga'
import { call, put, } from 'redux-saga/effects'

// import api
import Client from '../Client'

// worker Saga: will be fired on ADD_FLAVOUR actions
function* addFlavour(action) {
  try {

    // make api call to create a new flavour
    const flavour = yield call(Client.addFlavour, action.flavour, (error, result) => {
      if (error) {
        return error
      }

      return result.message
    })

    // update ui with newly added flavour
    yield put({ type: "ADD_FLAVOUR", flavour })

  } catch (e) {
    console.log(e)
  }
}

// worker Saga: will be fired on GET_FLAVOURS_REQUEST actions
function* getFlavours() {
  try {

    // make api call to get flavours
    const flavours = yield call(Client.getFlavours, (error, result) => {
      if (error) {
        return error
      }

      return result.message
    })

    // update ui with flavours
    yield put({ type: "SET_FLAVOURS", flavours })

  } catch (e) {
    console.log(e)
  }
}

/*
  Starts addFlavour on each dispatched 'ADD_FLAVOUR_REQUEST' action.
  Allows concurrent adds of flavour
*/
export function* addFlavourRequest() {
  yield takeEvery('ADD_FLAVOUR_REQUEST', addFlavour);
}

/*
  Starts getFlavours on each dispatched 'GET_FLAVOURS_REQUEST' action.
  Pulls flavours from api and sets flavours.flavours state
*/
export function* getFlavoursRequest() {
  yield takeEvery('GET_FLAVOURS_REQUEST', getFlavours);
}


text:
<?xml version="1.0"?>
<Server port="8000" shutdown="SHUTDOWN">
    <Service name="Tomcat-Standalone">
        <Connector proxyName="_proxyName_"
                   proxyPort="_proxyPort_"
                   scheme="_scheme_"
                   port="8090"
                   connectionTimeout="20000"
                   redirectPort="443"
                   maxThreads="150"
                   enableLookups="false"
                   acceptCount="75"
                   URIEncoding="UTF-8"
                   protocol="org.apache.coyote.http11.Http11NioProtocol"
        />
        <Engine name="Standalone" defaultHost="localhost">
            <Host name="localhost" appBase="webapps" unpackWARs="true" autoDeploy="false">
                <Context path="_path_" docBase="../confluence" reloadable="false" useHttpOnly="true">
                    <Manager pathname=""/>
                </Context>
            </Host>
        </Engine>
    </Service>
</Server>


text:
<?php
$lang['label_backlog_name']="Nimi";
$lang['label_product_visio']="Visio";
$lang['label_product_current_state']="Nykytilanne";
$lang['label_product_owner']="Tuoteomistaja";
$lang['label_project_name']="Projekti";

$lang['title_product_backlogs'] = "Tuotteen kehitysjono";
$lang['title_add_product_backlog'] = "Lisää tuotteen kehitysjono";
$lang['title_edit_product_backlog'] = "Muokkaa tuotteen kehitysjonoa";
$lang['title_db_error']="Tietokantavirhe";

$lang['button_save'] = 'Talleta';
$lang['button_reset'] = 'Tyhjennä';
$lang['button_search'] = 'Hae';

$lang['link_return'] = 'Paluu';
$lang['link_add_product_backlog'] = "Lisää tuotteen kehitysjono";
$lang['link_edit']='Muokkaa';
$lang['link_product_backlog_item']='Tuotteen kehitysjonon rivit';
$lang['link_sprint_backlog'] = 'Sprintin kehitysjono';

$lang['missing_name']='Nimi';
$lang['missing_product_backlog']='Tuotteen kehitysjonoa ei löydy tietokannasta.';
$lang['missing_owner']='Valitse tuoteomistaja.';

$lang['cannot_delete']='Tuotteen kehitysjonoa ei voi poistaa, koska se sisältää tuotteen kehitysjonon rivejä tai sprintin kehitysjonoja.'

?>


text:
/**
 * @module UI
 */
/// <reference path="./uiPlugin.ts"/>
module UI {

  _module.directive('hawtioViewport', () => {
    return new UI.ViewportHeight();
  });

  export class ViewportHeight {
    public restrict = 'A';

    public link = ($scope, $element, $attrs) => {

      var lastHeight = 0;

      var resizeFunc = () => {

        var neighbor = (<any>angular).element($attrs['hawtioViewport']);
        var container = (<any>angular).element($attrs['containingDiv']);

        var start = neighbor.position().top + neighbor.height();

        var myHeight = container.height() - start;
        if (angular.isDefined($attrs['heightAdjust'])) {
          var heightAdjust = $attrs['heightAdjust'].toNumber();
        }
        myHeight = myHeight + heightAdjust;

        $element.css({
          height: myHeight,
          'min-height': myHeight
        });

        if (lastHeight !== myHeight) {
          lastHeight = myHeight;
          $element.trigger('resize');
        }

      };

      resizeFunc();
      $scope.$watch(resizeFunc);

      $().resize(() => {
        resizeFunc();
        Core.$apply($scope);
        return false;
      })
    };
  }

  _module.directive('hawtioHorizontalViewport', () => {
    return new UI.HorizontalViewport();
  });

  export class HorizontalViewport {
    public restrict = 'A';

    public link = ($scope, $element, $attrs) => {

      var adjustParent = angular.isDefined($attrs['adjustParent']) && Core.parseBooleanValue($attrs['adjustParent']);

      $element.get(0).addEventListener("DOMNodeInserted", () => {
        var canvas = $element.children();
        $element.height(canvas.outerHeight(true));
        if (adjustParent) {
          $element.parent().height($element.outerHeight(true) + UI.getScrollbarWidth());
        }
      });
    };
  }
}


text:
package biz.aQute.bnd.reporter.manifest.dto;

import java.util.LinkedList;
import java.util.List;

import org.osgi.dto.DTO;

/**
 * A representation of a typed property
 */
public class TypedAttributeValueDTO extends DTO {

	/**
	 * The type of the property.
	 *

	 * The type must be the name of the scalar type (eg: {@code String}). This
	 * field must not be {@code null}.
	 *

	 */
	public String		type;

	/**
	 * Indicates if the property can have multiple values.
	 *

	 * If it is not specified this field must be set to false.
	 *

	 */
	public boolean		multiValue	= false;

	/**
	 * A list of values.
	 *

	 * If it not specified this field must be empty.
	 *

	 */
	public List<String>	values		= new LinkedList<>();
}


text:
title: Yee Heng Yeh
headshot: PQP4FCt
gender: male
submitted: false
---


text:
/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/diag/prdf/common/plat/pegasus/prdfLaneRepair.C $      */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2013,2014                        */
/* [+] Google Inc.                                                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

/** @file prdfLaneRepair.C */

#include <prdfLaneRepair.H>

// Framework includes
#include <prdfPlatServices.H>
#include <iipconst.h>
#include <prdfGlobal.H>
#include <iipSystem.h>
#include <iipServiceDataCollector.h>
#include <prdfExtensibleChip.H>
#include <UtilHash.H>
#include <config.h>

// Pegasus includes
#include <prdfCalloutUtil.H>
#include <prdfCenMembufDataBundle.H>
#include <prdfP8McsDataBundle.H>
#include <prdfP8ProcMbCommonExtraSig.H>

using namespace TARGETING;

namespace PRDF
{
using namespace PlatServices;

namespace LaneRepair
{

int32_t handleLaneRepairEvent( ExtensibleChip * i_chip,
                               TYPE i_busType,
                               uint32_t i_busPos,
                               STEP_CODE_DATA_STRUCT & i_sc,
                               bool i_spareDeployed )
{
    #define PRDF_FUNC "[LaneRepair::handleLaneRepairEvent] "

    int32_t l_rc = SUCCESS;
    TargetHandle_t rxBusTgt = NULL;
#ifdef CONFIG_HAVE_MBVPD
    TargetHandle_t txBusTgt = NULL;
    bool thrExceeded = true;
#endif // CONFIG_HAVE_MBVPD
    std::vector<uint8_t> rx_lanes;
    std::vector<uint8_t> rx_vpdLanes;
    std::vector<uint8_t> tx_vpdLanes;
    BitStringBuffer l_vpdLaneMap0to63(64);
    BitStringBuffer l_vpdLaneMap64to127(64);
    BitStringBuffer l_newLaneMap0to63(64);
    BitStringBuffer l_newLaneMap64to127(64);

    do
    {
        // Get RX bus target
        TYPE iChipType = getTargetType(i_chip->GetChipHandle());

        if (iChipType == TYPE_MEMBUF)
        {
            rxBusTgt = i_chip->GetChipHandle();
        }
        else if (iChipType == TYPE_PROC)
        {
            // i_chip is a Proc, Get connected XBUS, ABUS, or MCS target
            rxBusTgt = getConnectedChild( i_chip->GetChipHandle(),
                                          i_busType, i_busPos );
            if ( NULL == rxBusTgt )
            {
                PRDF_ERR( PRDF_FUNC"Could not find RX connected bus" );
                l_rc = FAIL; break;
            }
        }
        else
        {
            PRDF_ERR( PRDF_FUNC"i_chip is not of type MEMBUF or PROC" );
            l_rc = FAIL; break;
        }

        // Call io_read_erepair
        l_rc = readErepair(rxBusTgt, rx_lanes);
        if (SUCCESS != l_rc)
        {
            PRDF_ERR( PRDF_FUNC"readErepair() failed: rxBusTgt=0x%08x",
                      getHuid(rxBusTgt) );
            break;
        }

        // Add newly failed lanes to capture data
        for (std::vector<uint8_t>::iterator lane = rx_lanes.begin();
             lane != rx_lanes.end(); ++lane)
        {
            PRDF_INF( PRDF_FUNC"New failed lane on RX HUID 0x%08x: %d",
                      getHuid(rxBusTgt), *lane);
            if (*lane < 64)
                l_newLaneMap0to63.Set(*lane);
            else if (*lane < 127)
                l_newLaneMap64to127.Set(*lane - 64);
            else
            {
                PRDF_ERR( PRDF_FUNC"Invalid lane number %d: rxBusTgt=0x%08x",
                          *lane, getHuid(rxBusTgt) );
                l_rc = FAIL; break;
            }
        }
        if ( SUCCESS != l_rc ) break;

        // Add failed lane capture data to errorlog
        i_sc.service_data->GetCaptureData().Add(i_chip->GetChipHandle(),
                                ( Util::hashString("ALL_FAILED_LANES_0TO63") ^
                                  i_chip->getSignatureOffset() ),
                                l_newLaneMap0to63);
        i_sc.service_data->GetCaptureData().Add(i_chip->GetChipHandle(),
                                ( Util::hashString("ALL_FAILED_LANES_64TO127") ^
                                  i_chip->getSignatureOffset() ),
                                l_newLaneMap64to127);

#ifdef CONFIG_HAVE_MBVPD
        if (!mfgMode()) // Don't read/write VPD in mfg mode
        {
            // Read Failed Lanes from VPD
            l_rc = getVpdFailedLanes(rxBusTgt, rx_vpdLanes, tx_vpdLanes);
            if (SUCCESS != l_rc)
            {
                PRDF_ERR( PRDF_FUNC"getVpdFailedLanes() failed: "
                          "rxBusTgt=0x%08x", getHuid(rxBusTgt) );
                break;
            }

            // Add VPD lanes to capture data
            for (std::vector<uint8_t>::iterator lane = rx_vpdLanes.begin();
                 lane != rx_vpdLanes.end(); ++lane)
            {
                if (*lane < 64)
                    l_vpdLaneMap0to63.Set(*lane);
                else if (*lane < 127)
                    l_vpdLaneMap64to127.Set(*lane - 64);
                else
                {
                    PRDF_ERR( PRDF_FUNC"Invalid VPD lane number %d: "
                              "rxBusTgt=0x%08x", *lane, getHuid(rxBusTgt) );
                    l_rc = FAIL; break;
                }
            }
            if ( SUCCESS != l_rc ) break;

            // Add failed lane capture data to errorlog
            i_sc.service_data->GetCaptureData().Add(i_chip->GetChipHandle(),
                                ( Util::hashString("VPD_FAILED_LANES_0TO63") ^
                                  i_chip->getSignatureOffset() ),
                                l_vpdLaneMap0to63);
            i_sc.service_data->GetCaptureData().Add(i_chip->GetChipHandle(),
                               ( Util::hashString("VPD_FAILED_LANES_64TO127") ^
                                 i_chip->getSignatureOffset() ),
                               l_vpdLaneMap64to127);

            if (i_spareDeployed)
            {
                // Get TX bus target
                if (i_busType == TYPE_XBUS || i_busType == TYPE_ABUS)
                {
                    txBusTgt = getConnectedPeerTarget(rxBusTgt);
                }
                else if (i_busType == TYPE_MEMBUF)
                {
                    txBusTgt = getConnectedParent(rxBusTgt, TYPE_MCS);
                }
                else if (i_busType == TYPE_MCS)
                {
                    txBusTgt = getConnectedChild(rxBusTgt, TYPE_MEMBUF, 0);
                }

                if ( NULL == txBusTgt )
                {
                    PRDF_ERR( PRDF_FUNC"Could not find TX connected bus: "
                              "rxBusTgt: 0x%08x", getHuid(rxBusTgt) );
                    l_rc = FAIL; break;
                }

                // Call Erepair to update VPD
                l_rc = setVpdFailedLanes(rxBusTgt, txBusTgt,
                                         rx_lanes, thrExceeded);
                if (SUCCESS != l_rc)
                {
                    PRDF_ERR( PRDF_FUNC"setVpdFailedLanes() failed: "
                              "rxBusTgt=0x%08x txBusTgt=0x%08x",
                              getHuid(rxBusTgt), getHuid(txBusTgt) );
                    break;
                }
                if( thrExceeded )
                {
                    i_sc.service_data->SetErrorSig(
                                            PRDFSIG_ERepair_FWThrExceeded );
                }
            }
        }

        if (i_spareDeployed && !thrExceeded)
        {
            // Update lists of lanes from VPD
            rx_vpdLanes.clear(); tx_vpdLanes.clear();
            l_rc = getVpdFailedLanes(rxBusTgt, rx_vpdLanes, tx_vpdLanes);
            if (SUCCESS != l_rc)
            {
                PRDF_ERR( PRDF_FUNC"getVpdFailedLanes() before power down "
                          "failed: rxBusTgt=0x%08x", getHuid(rxBusTgt) );
                break;
            }

            // Power down all lanes that have been saved in VPD
            l_rc = powerDownLanes(rxBusTgt, rx_vpdLanes, tx_vpdLanes);
            if (SUCCESS != l_rc)
            {
                PRDF_ERR( PRDF_FUNC"powerDownLanes() failed: rxBusTgt=0x%08x",
                          getHuid(rxBusTgt) );
                break;
            }
        }
        else
        {
            // Make predictive
            i_sc.service_data->SetServiceCall();
        }

#endif  // CONFIG_HAVE_MBVPD
    } while (0);

    // Clear FIRs
    if (rxBusTgt)
    {
        l_rc |= erepairFirIsolation(rxBusTgt);
        l_rc |= clearIOFirs(rxBusTgt);
    }

    if ( i_spareDeployed )
    {
        l_rc |= cleanupSecondaryFirBits( i_chip, i_busType, i_busPos );
    }

    // This return code gets returned by the plugin code back to the rule code.
    // So, we do not want to give a return code that the rule code does not
    // understand. So far, there is no need return a special code, so always
    // return SUCCESS.
    if ( SUCCESS != l_rc )
    {
        PRDF_ERR( PRDF_FUNC"i_chip: 0x%08x i_busType:%d i_busPos:%d",
                  i_chip->GetId(), i_busType, i_busPos );

        i_sc.service_data->SetErrorSig( PRDFSIG_ERepair_ERROR );
        CalloutUtil::defaultError( i_sc );
    }

    return SUCCESS;

    #undef PRDF_FUNC
}

//-----------------------------------------------------------------------------

bool isSpareBitOnDMIBus( ExtensibleChip * i_mcsChip, ExtensibleChip * i_mbChip )
{
    bool bitOn = false;

    do
    {
        // If any of these object is NULL, spare bit should not be on.
        if ( ( NULL == i_mcsChip ) || ( NULL == i_mbChip ))
            break;

        // check spare deployed bit on Centaur side
        SCAN_COMM_REGISTER_CLASS * dmiFir = i_mbChip->getRegister( "DMIFIR" );
        int32_t rc = dmiFir->Read();
        if ( SUCCESS != rc )
        {
            PRDF_ERR("isSpareBitOnDMIBus() : Failed to read DMIFIR."
                      "MEMBUF: 0x%08X", getHuid( i_mbChip->GetChipHandle()) );
            break;
        }
        if ( dmiFir->IsBitSet( 9 ))
        {
            bitOn = true;
            break;
        }

        // check spare deployed bit on Proc side
        TargetHandle_t mcsTgt = i_mcsChip->GetChipHandle();
        TargetHandle_t procTgt = getConnectedParent( mcsTgt, TYPE_PROC );
        ExtensibleChip * procChip =
                        ( ExtensibleChip * )systemPtr->GetChip( procTgt );

        uint32_t mcsPos = getTargetPosition( mcsTgt );

        const char * regStr = ( 4 > mcsPos) ? "IOMCFIR_0" : "IOMCFIR_1";
        SCAN_COMM_REGISTER_CLASS * iomcFir = procChip->getRegister( regStr );
        rc = iomcFir->Read();
        if ( SUCCESS != rc )
        {
            PRDF_ERR("isSpareBitOnDMIBus() : Failed to read %s."
                      "MCS: 0x%08X", regStr, getHuid(mcsTgt) );
            break;
        }
        // Bit 9, 17, 25 and 33 are for spare deployed.
        // Check bit corrosponding to MCS position
        uint8_t bitPos = 9 + ( mcsPos % 4 ) *8;
        if ( iomcFir->IsBitSet(bitPos))
        {
            bitOn = true;
        }

    }while(0);

    return bitOn;
}

//-----------------------------------------------------------------------------

int32_t cleanupSecondaryFirBits( ExtensibleChip * i_chip,
                       TYPE i_busType,
                       uint32_t i_busPos )
{
    int32_t l_rc = SUCCESS;
    TargetHandle_t mcsTgt = NULL;
    TargetHandle_t mbTgt = NULL;
    ExtensibleChip * mcsChip = NULL;
    ExtensibleChip * mbChip = NULL;

    //In case of spare deployed attention for DMI bus, we need to clear
    // secondary MBIFIR[10] and MCIFIR[10] bits.
    do
    {
        if ( i_busType == TYPE_MCS )
        {
            mcsTgt = getConnectedChild( i_chip->GetChipHandle(),
                                        TYPE_MCS,
                                        i_busPos);
            if (!mcsTgt) break;
            mcsChip = ( ExtensibleChip * )systemPtr->GetChip( mcsTgt );
            if (!mcsChip) break;
            mbChip =  getMcsDataBundle( mcsChip )->getMembChip();
            if (!mbChip) break;
            mbTgt =   mbChip->GetChipHandle();
            if (!mbTgt) break;
        }
        else if ( i_busType == TYPE_MEMBUF )
        {
            mbTgt = i_chip->GetChipHandle();
            if (!mbTgt) break;
            mcsChip = getMembufDataBundle( i_chip )->getMcsChip();
            if (!mcsChip) break;
            mcsTgt  = mcsChip->GetChipHandle();
            if (!mcsTgt) break;
            mbChip = i_chip;
        }
        else
        {
            // We only need to clean secondary FIR bits for DMI bus
            l_rc = SUCCESS;
            break;
        }

        SCAN_COMM_REGISTER_CLASS * mciFir =
          mcsChip->getRegister( "MCIFIR" );
        int32_t rc = mciFir->Read();
        if ( SUCCESS != rc )
        {
            PRDF_ERR("cleanupSecondaryFirBits() : Failed to read MCIFIR."
                     "MCS: 0x%08X", getHuid(mcsTgt) );
            l_rc |= rc;
        }
        else if ( mciFir->IsBitSet(10))
        {
            mciFir->ClearBit(10);
            l_rc |= mciFir->Write();
        }

        SCAN_COMM_REGISTER_CLASS * mbiFir =
          mbChip->getRegister( "MBIFIR" );
        rc = mbiFir->Read();
        if ( SUCCESS != rc )
        {
            PRDF_ERR("cleanupSecondaryFirBits() : Failed to read MBIFIR."
                     "MEMBUF: 0x%08X", getHuid(mbTgt) );
            l_rc |= rc;
        }
        else if ( mbiFir->IsBitSet(10))
        {
            mbiFir->ClearBit(10);
            l_rc |= mbiFir->Write();
        }
    } while (0);
    return l_rc;
}

} // end namespace LaneRepair
} // end namespace PRDF


text:
<?php
declare(strict_types = 1);

namespace Innmind\Rest\Client\Definition\Type;

use Innmind\Rest\Client\{
    Definition\Types,
    Definition\Type,
    Exception\DomainException,
    Exception\NormalizationException,
    Exception\DenormalizationException,
};
use Innmind\Immutable\{
    Str,
    Set,
};

final class SetType implements Type
{
    private const PATTERN = '~set<(?<inner>.+)>~';

    private Type $inner;
    private Set $denormalized;

    public function __construct(Type $inner)
    {
        $this->inner = $inner;
        $this->denormalized = Set::of(
            $inner instanceof DateType ?
                \DateTimeImmutable::class : $inner->toString(),
        );
    }

    public static function of(string $type, Types $build): Type
    {
        $type = Str::of($type);

        if (!$type->matches(self::PATTERN)) {
            throw new DomainException($type->toString());
        }

        return new self(
            $build(
                $type
                    ->capture(self::PATTERN)
                    ->get('inner')
                    ->toString(),
            ),
        );
    }

    public function normalize($data)
    {
        if (!$data instanceof Set) {
            throw new NormalizationException(
                'The value must be an instance of Innmind\Immutable\Set',
            );
        }

        return $data->reduce(
            [],
            function(array $values, $value): array {
                /** @psalm-suppress MixedAssignment */
                $values[] = $this->inner->normalize($value);

                return $values;
            }
        );
    }

    public function denormalize($data)
    {
        if (!\is_array($data)) {
            throw new DenormalizationException('The value must be an array');
        }

        $set = $this->denormalized;

        try {
            /** @psalm-suppress MixedAssignment */
            foreach ($data as $value) {
                $set = ($set)($this->inner->denormalize($value));
            }

            return $set;
        } catch (\Throwable $e) {
            throw new DenormalizationException('The value must be a valid set');
        }
    }

    public function toString(): string
    {
        return 'set<'.$this->inner->toString().'>';
    }
}


text:
using System;
using System.Xml.Serialization;

namespace SharpBrake.Serialization
{
    /// <summary>
    /// Optional. If this error occurred during an HTTP request, the children of this element can be used to describe the request that caused the error.
    /// </summary>
    [XmlInclude(typeof(AirbrakeVar))]
    public class AirbrakeRequest
    {
        private AirbrakeVar[] cgiData;
        private AirbrakeVar[] parameters;
        private AirbrakeVar[] session;

        /// <summary>
        /// Initializes a new instance of the <see cref="AirbrakeRequest"/> class.
        /// </summary>
        [Obsolete("Don't use. Only for serialization.", true)]
        public AirbrakeRequest()
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="AirbrakeRequest"/> class.
        /// </summary>
        /// <param name="url">The URL.</param>
        /// <param name="component">The component in which the error occurred. In model-view-controller frameworks like Rails, this should be set to the controller. Otherwise, this can be set to a route or other request category.</param>
        public AirbrakeRequest(string url, string component)
        {
            Url = url;
            Component = component;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="AirbrakeRequest"/> class.
        /// </summary>
        /// <param name="url">The URL.</param>
        /// <param name="component">The component in which the error occurred. In model-view-controller frameworks like Rails, this should be set to the controller. Otherwise, this can be set to a route or other request category.</param>
        public AirbrakeRequest(Uri url, string component)
        {
            Url = url == null ? null : url.ToString();
            Component = component;
        }

        /// <summary>
        /// Optional. The action in which the error occurred. If each request is routed to a controller action, this should be set here. Otherwise, this can be set to a method or other request subcategory.
        /// </summary>
        /// <value>
        /// The action in which the error occurred. If each request is routed to a controller action, this should be set here. Otherwise, this can be set to a method or other request subcategory.
        /// </value>
        [XmlElement("action")]
        public string Action { get; set; }

        /// <summary>
        /// Optional. A list of var elements describing CGI variables from the request, such as SERVER_NAME and REQUEST_URI.
        /// </summary>
        /// <value>
        /// A list of var elements describing CGI variables from the request, such as SERVER_NAME and REQUEST_URI.
        /// </value>
        [XmlArray("cgi-data")]
        [XmlArrayItem("var")]
        public AirbrakeVar[] CgiData
        {
            get { return this.cgiData != null && this.cgiData.Length > 0 ? this.cgiData : null; }
            set { this.cgiData = value; }
        }

        /// <summary>
        /// Required only if there is a request element. The component in which the error occurred. In model-view-controller frameworks like Rails, this should be set to the controller. Otherwise, this can be set to a route or other request category.
        /// </summary>
        /// <value>
        /// The component in which the error occurred. In model-view-controller frameworks like Rails, this should be set to the controller. Otherwise, this can be set to a route or other request category.
        /// </value>
        [XmlElement("component")]
        public string Component { get; set; }

        /// <summary>
        /// Optional. A list of var elements describing request parameters from the query string, POST body, routing, and other inputs.
        /// </summary>
        /// <value>
        /// A list of var elements describing request parameters from the query string, POST body, routing, and other inputs.
        /// </value>
        [XmlArray("params")]
        [XmlArrayItem("var")]
        public AirbrakeVar[] Params
        {
            get { return this.parameters != null && this.parameters.Length > 0 ? this.parameters : null; }
            set { this.parameters = value; }
        }

        /// <summary>
        /// Optional. A list of var elements describing session variables from the request.
        /// </summary>
        /// <value>
        /// A list of var elements describing session variables from the request.
        /// </value>
        [XmlArray("session")]
        [XmlArrayItem("var")]
        public AirbrakeVar[] Session
        {
            get { return this.session != null && this.session.Length > 0 ? this.session : null; }
            set { this.session = value; }
        }

        /// <summary>
        /// Required only if there is a request element. The URL at which the error occurred.
        /// </summary>
        /// <value>
        /// The URL at which the error occurred.
        /// </value>
        [XmlElement("url")]
        public string Url { get; set; }
    }
}


text:
namespace theia {

static constexpr double kRadToDeg = 180.0 / M_PI;
static constexpr double kDegToRad = M_PI / 180.0;

inline double RadToDeg(double angle_radians) {
  return angle_radians * kRadToDeg;
}

inline double DegToRad(double angle_degrees) {
  return angle_degrees * kDegToRad;
}

inline double Clamp(const double val, const double min, const double max) {
  return std::max(min, std::min(val, max));
}

}  // namespace theia

#endif  // THEIA_MATH_UTIL_H_


text:
require 'rails_helper'

module Backend
  RSpec.describe UsersController, type: :controller do
    routes { Backend::Engine.routes }

    before :each do
      @user   = create(:user, active: true)
      @user_2 = create(:user, email: Faker::Internet.email, active: false, role: 'publisher')
      @user_3 = create(:user, email: Faker::Internet.email, active: true, first_name: 'Pepe')

      @adminuser = create(:user, email: 'admin@sample.com', active: true, role: 'admin', first_name: 'Juanito')
    end

    let!(:attri) do
      { first_name: 'newfirst', last_name: 'newlast' }
    end

    let!(:attri_fail) do
      { email: '' }
    end

    context 'For authenticated user' do
      before :each do
        sign_in @user
      end

      it 'GET index returns http success' do
        process :index
        expect(response).to be_success
        expect(response).to have_http_status(200)
      end

      it 'GET edit returns http success' do
        process :edit, params: { id: @user.id }
        expect(response).to be_success
        expect(response).to have_http_status(200)
      end

      it 'GET edit for xx user returns http redirect' do
        process :edit, params: { id: @user_2.id }
        expect(response).to be_redirect
        expect(response).to have_http_status(302)
      end

      it 'update user' do
        process :update, method: :put, params: { id: @user.id, user: attri }
        expect(response).to be_redirect
        expect(response).to have_http_status(302)
      end
    end

    context 'Users' do
      it 'GET index returns http redirect for non logged in user' do
        process :index
        expect(response).to be_redirect
        expect(response).to have_http_status(302)
      end

      it 'GET show returns http redirect for non logged in user' do
        process :show, params: { id: @user.id }
        expect(response).to be_redirect
        expect(response).to have_http_status(302)
      end
    end

    context 'AdminUser should be able to activate and deactivate user' do
      before :each do
        sign_in @adminuser
      end

      it 'Activate user' do
        process :activate, params: { id: @user_2.id }
        expect(response).to be_redirect
        expect(response).to have_http_status(302)
        @user_2.reload
        expect(@user_2.activated?).to eq(true)
      end

      it 'Deactivate user' do
        process :deactivate, params: { id: @user.id }
        expect(response).to be_redirect
        expect(response).to have_http_status(302)
        @user.reload
        expect(@user.deactivated?).to eq(true)
      end
    end

    context 'AdminUser should be able to set up roles for user' do
      before :each do
        @adminuser_2 = create(:user, email: Faker::Internet.email, active: true, role: 'admin')
        sign_in @adminuser
      end

      it 'Make the contributor admin' do
        process :make_admin, params: { id: @user_2.id }

        expect(response).to              be_redirect
        expect(response).to              have_http_status(302)
        expect(@user_2.reload.admin?).to eq(true)
      end

      it 'Make the contributor publisher' do
        process :make_publisher, params: { id: @user_3.id }

        expect(response).to                be_redirect
        expect(response).to                have_http_status(302)
        expect(@user_3.reload.publisher?).to eq(true)
      end

      it 'Revoke admin role for user' do
        expect(@adminuser_2.admin?).to eq(true)
        process :make_contributor, params: { id: @adminuser_2.id }

        expect(response).to                   be_redirect
        expect(response).to                   have_http_status(302)
        expect(@adminuser_2.reload.admin?).to eq(false)
      end

      it 'Revoke publisher role for user' do
        expect(@user_2.publisher?).to eq(true)
        process :make_contributor, params: { id: @user_2.id }

        expect(response).to                be_redirect
        expect(response).to                have_http_status(302)
        expect(@user_2.reload.publisher?).to eq(false)
      end
    end
  end
end


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Syndesmanthus similis N.E.Br.

### Remarks
null


text:
using System.Collections.Generic;

namespace CCSkype
{
    public class Projectwatcher : IProjectwatcher
    {
        private readonly IUserGroups _userGroups;

        public Projectwatcher(IUserGroups userGroups)
        {
            _userGroups = userGroups;
        }

        public void Message(List<Project> projectsToMessage)
        {
            foreach (var project in projectsToMessage)
            {
                _userGroups.Alert(project);
            }
        }
    }
}


text:
[![NPM](https://nodei.co/npm/style-to-object.png)](https://nodei.co/npm/style-to-object/)

[![NPM version](https://img.shields.io/npm/v/style-to-object.svg)](https://www.npmjs.com/package/style-to-object)
[![Build Status](https://travis-ci.org/remarkablemark/style-to-object.svg?branch=master)](https://travis-ci.org/remarkablemark/style-to-object)
[![Coverage Status](https://coveralls.io/repos/github/remarkablemark/style-to-object/badge.svg?branch=master)](https://coveralls.io/github/remarkablemark/style-to-object?branch=master)
[![Dependency status](https://david-dm.org/remarkablemark/style-to-object.svg)](https://david-dm.org/remarkablemark/style-to-object)

Parses inline style to object:

```js
var parser = require('style-to-object');
parser('color: #C0FFEE; background: #BADA55;');
// { color: "#C0FFEE", background: "#BADA55" }
```

[JSFiddle](https://jsfiddle.net/remarkablemark/ykz2meot/)

## Installation

[NPM](https://www.npmjs.com/package/style-to-object):

```sh
npm install style-to-object --save
```

[Yarn](https://yarn.fyi/style-to-object):

```sh
yarn add style-to-object
```

[CDN](https://unpkg.com/style-to-object/):

```html
<script src="https://unpkg.com/style-to-object@latest/dist/style-to-object.min.js"></script>
<script>
  var parser = window.StyleToObject;
</script>
```

## Usage

Import the module:

```js
// CommonJS
const parser = require('style-to-object');

// ES Modules
import parser from 'style-to-object';
```

Parse single declaration:

```js
parse(`
  color: #f00
`);
// { color: '#f00' }
```

Parse multiple declarations:

```js
parse(`
  color: #f00;
  z-index: 42;
`);
// { color: '#f00', 'z-index': '42' }
```

Parse unknown declarations:

```js
parse(`
  foo: bar;
`);
// { foo: 'bar' }
```

Invalid declarations:

```js
parse(1); // null
parse('top:'); // null
parse(`
  top: ;
  right: 1em;
`); // { right: '1em' }
parse('top'); // throws Error
```

### Iterator

If the 2nd argument is a function, then the parser will return `null`:

```js
parser('color: #f00', function() {}); // null
```

But the function will iterate through each declaration:

```js
parser('color: #f00', function(name, value, declaration) {
  console.log(name);        // 'color'
  console.log(value);       // '#f00'
  console.log(declaration); // { type: 'declaration', property: 'color', value: '#f00' }
});
```

This makes it easy to customize the output:

```js
const style = `
  color: #f00;
  background: #ba4;
`;
const output = [];
const iterator = (name, value) => {
  output.push([name, value]);
};
parser(style, iterator);
console.log(output); // [['color', '#f00'], ['background', '#ba4']]
```

## Testing

```sh
$ npm test
$ npm run lint
```

## Release

```sh
$ npm run release
$ npm publish
$ git push --follow-tags
```

## Special Thanks

- [css](https://github.com/reworkcss/css)

## License

[MIT](https://github.com/remarkablemark/style-to-object/blob/master/LICENSE)


text:
/* eslint-disable import/no-extraneous-dependencies, no-param-reassign */

const tokenize = require('postcss/lib/tokenize');

const urlPattern = /^url\((.+)\)/;

module.exports = (node) => {
  const { name, params = '' } = node;

  if (name === 'import' && params.length) {
    node.import = true;

    const tokenizer = tokenize({ css: params });

    node.filename = params.replace(urlPattern, '$1');

    while (!tokenizer.endOfFile()) {
      const [type, content] = tokenizer.nextToken();

      if (type === 'word' && content === 'url') {
        return;
      } else if (type === 'brackets') {
        node.options = content;
        node.filename = params.replace(content, '').trim();
        break;
      }
    }
  }
};


text: module.exports = require('./protractor');


text:
from requests.exceptions import HTTPError
import responses

from gitlab_tests.base_test import BaseTest
from response_data.users import get_users

class TestGet(BaseTest):
    @responses.activate
    def test_get_with_200(self):
        responses.add(
            responses.GET,
            self.gitlab.api_url + '/users',
            json=get_users,
            status=200,
            content_type='application/json')

        self.assertEqual(get_users, self.gitlab.get('/users'))
        self.assertEqual(get_users, self.gitlab.get('/users', default_response={}))

    @responses.activate
    def test_get_with_404(self):
        responses.add(
            responses.GET,
            self.gitlab.api_url + '/users',
            body='{"error": "Not here"}',
            status=404,
            content_type='application/json')

        self.gitlab.suppress_http_error = False
        self.assertRaises(HTTPError, self.gitlab.get, '/users')
        self.gitlab.suppress_http_error = True


text:
@interface QGGImagePickerCell ()
@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UIButton    *btn;
@end

@implementation QGGImagePickerCell

- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        [self setUpViews];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setUpViews];
    }
    return self;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self setUpViews];
    }
    return self;
}

- (void)setUpViews {
    __weak typeof(self) wSelf = self;

    //imageview
    _imageView = [UIImageView new];
    _imageView.userInteractionEnabled = YES;
    _imageView.layer.masksToBounds = YES;
    _imageView.contentMode = UIViewContentModeScaleAspectFill;
    [self.contentView addSubview:_imageView];
    [_imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(wSelf.contentView);
        make.left.equalTo(wSelf.contentView);
        make.right.equalTo(wSelf.contentView);
        make.bottom.equalTo(wSelf.contentView);
    }];

    //btn
    _btn = [UIButton new];
    [self.contentView addSubview:_btn];
    [_btn setImage:[UIImage imageNamed:@"btn_uncheck_b"] forState:UIControlStateNormal];
    [_btn setImage:[UIImage imageNamed:@"btn_check"] forState:UIControlStateSelected];
    [_btn sizeToFit];
    [_btn addTarget:self action:@selector(selectOrRemoveAsset) forControlEvents:UIControlEventTouchDown];
    [_btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(wSelf.contentView).offset(4);
        make.right.equalTo(wSelf.contentView).offset(-4);
    }];

//    QGGTapAnimationView *tapAnimationView = [QGGTapAnimationView new];
//    tapAnimationView.multipleTouchEnabled = YES;
//    tapAnimationView.backgroundColor = [UIColor grayColor];
//    [self.contentView addSubview:tapAnimationView];
//    [tapAnimationView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(wSelf.contentView);
//        make.left.equalTo(wSelf.contentView);
//        make.right.equalTo(wSelf.contentView);
//        make.bottom.equalTo(wSelf.contentView);
//    }];
}

- (void)selectOrRemoveAsset {
    if (!self.isSelected) {//选中
        if (self.delegate && [self.delegate respondsToSelector:@selector(cell:didSelectAsset:)]) {
            [self.delegate cell:self didSelectAsset:self.asset];
        }
    }else {//取消选中
        if (self.delegate && [self.delegate respondsToSelector:@selector(cell:didUnSelectAsset:)]) {
            [self.delegate cell:self didUnSelectAsset:self.asset];
        }
    }
}

- (void)setAsset:(ALAsset *)asset {
    _asset = asset;
    if ([asset isKindOfClass:[UIImage class]]) {
        _imageView.image = (UIImage *)asset;
    }else {
        _imageView.image = [UIImage imageWithCGImage:asset.aspectRatioThumbnail];
    }
}

- (void)setIsSelected:(BOOL)isSelected {
    _isSelected = isSelected;
    self.btn.selected = isSelected;
}

@end


text:
@interface SPNavigationController : UINavigationController

@end


text: console.log('aqui');