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

#include "py/mpstate.h"
#include MICROPY_HAL_H
#include "py/runtime.h"
#include "bufhelper.h"
#include "inc/hw_types.h"
#include "inc/hw_i2c.h"
#include "inc/hw_ints.h"
#include "inc/hw_memmap.h"
#include "rom_map.h"
#include "pin.h"
#include "prcm.h"
#include "i2c.h"
#include "pybi2c.h"
#include "mpexception.h"
#include "pybsleep.h"
#include "utils.h"

/// \moduleref pyb
/// \class I2C - a two-wire serial protocol
///
/// I2C is a two-wire protocol for communicating between devices.  At the physical
/// level it consists of 2 wires: SCL and SDA, the clock and data lines respectively.
///
/// I2C objects are created attached to a specific bus.  They can be initialised
/// when created, or initialised later on:
///
///     from pyb import I2C
///
///     i2c = I2C()                          # create
///     i2c = I2C(50000)                     # create and init with a 50KHz baudrate
///     i2c.init(100000)                     # init with a 100KHz baudrate
///     i2c.deinit()                         # turn off the peripheral
///
/// Printing the i2c object gives you information about its configuration.
///
/// Basic methods for slave are send and recv:
///
///     i2c.send('abc')      # send 3 bytes
///     i2c.send(0x42)       # send a single byte, given by the number
///     data = i2c.recv(3)   # receive 3 bytes
///
/// To receive inplace, first create a bytearray:
///
///     data = bytearray(3)  # create a buffer
///     i2c.recv(data)       # receive 3 bytes, writing them into data
///
/// A master must specify the recipient's address:
///
///     i2c.init(100000)
///     i2c.send('123', 0x42)        # send 3 bytes to slave with address 0x42
///     i2c.send(b'456', addr=0x42)  # keyword for address
///
/// Master also has other methods:
///
///     i2c.is_ready(0x42)              # check if slave 0x42 is ready
///     i2c.scan()                      # scan for slaves on the bus, returning
///                                     #   a list of valid addresses
///     i2c.mem_read(3, 0x42, 2)        # read 3 bytes from memory of slave 0x42,
///                                     #   starting at address 2 in the slave
///     i2c.mem_write('abc', 0x42, 2)   # write 3 bytes to memory of slave 0x42,
///                                     #   starting at address 2 in the slave

typedef struct _pyb_i2c_obj_t {
    mp_obj_base_t base;
    uint baudrate;
} pyb_i2c_obj_t;

/******************************************************************************
 DEFINE CONSTANTS
 ******************************************************************************/
#define PYBI2C_MIN_BAUD_RATE_HZ                (50000)
#define PYBI2C_MAX_BAUD_RATE_HZ                (400000)

#define PYBI2C_TRANSC_TIMEOUT_MS               (10)
#define PYBI2C_TRANSAC_WAIT_DELAY_US           (10)

#define PYBI2C_TIMEOUT_TO_COUNT(to_us, baud)   (((baud) * to_us) / 16000000)

#define RET_IF_ERR(Func)                        {                           \
                                                    if (!Func) {            \
                                                        return  false;      \
                                                    }                       \
                                                }

/******************************************************************************
 DECLARE PRIVATE DATA
 ******************************************************************************/
STATIC pyb_i2c_obj_t pyb_i2c_obj = {.baudrate = 0};

/******************************************************************************
 DEFINE PRIVATE FUNCTIONS
 ******************************************************************************/
// only master mode is available for the moment
STATIC void i2c_init (pyb_i2c_obj_t *self) {
    // Enable the I2C Peripheral
    MAP_PRCMPeripheralClkEnable(PRCM_I2CA0, PRCM_RUN_MODE_CLK | PRCM_SLP_MODE_CLK);
    MAP_PRCMPeripheralReset(PRCM_I2CA0);
    // Configure I2C module with the specified baudrate
    MAP_I2CMasterInitExpClk(I2CA0_BASE, self->baudrate);
}

STATIC bool pyb_i2c_transaction(uint cmd) {
    // Convert the timeout to microseconds
    int32_t timeout = PYBI2C_TRANSC_TIMEOUT_MS * 1000;
    // Sanity check, t_timeout must be between 1 and 255
    uint t_timeout = MIN(PYBI2C_TIMEOUT_TO_COUNT(timeout, pyb_i2c_obj.baudrate), 255);
    // Clear all interrupts
    MAP_I2CMasterIntClearEx(I2CA0_BASE, MAP_I2CMasterIntStatusEx(I2CA0_BASE, false));
    // Set the time-out in terms of clock cycles. Not to be used with breakpoints.
    MAP_I2CMasterTimeoutSet(I2CA0_BASE, t_timeout);
    // Initiate the transfer.
    MAP_I2CMasterControl(I2CA0_BASE, cmd);
    // Wait until the current byte has been transferred.
    // Poll on the raw interrupt status.
    while ((MAP_I2CMasterIntStatusEx(I2CA0_BASE, false) & (I2C_MASTER_INT_DATA | I2C_MASTER_INT_TIMEOUT)) == 0) {
        // wait for a few microseconds
        UtilsDelay(UTILS_DELAY_US_TO_COUNT(PYBI2C_TRANSAC_WAIT_DELAY_US));
        timeout -= PYBI2C_TRANSAC_WAIT_DELAY_US;
        if (timeout < 0) {
            // the peripheral is not responding, so stop
            return false;
        }
    }

    // Check for any errors in the transfer
    if (MAP_I2CMasterErr(I2CA0_BASE) != I2C_MASTER_ERR_NONE) {
        switch(cmd) {
        case I2C_MASTER_CMD_BURST_SEND_START:
        case I2C_MASTER_CMD_BURST_SEND_CONT:
        case I2C_MASTER_CMD_BURST_SEND_STOP:
            MAP_I2CMasterControl(I2CA0_BASE, I2C_MASTER_CMD_BURST_SEND_ERROR_STOP);
            break;
        case I2C_MASTER_CMD_BURST_RECEIVE_START:
        case I2C_MASTER_CMD_BURST_RECEIVE_CONT:
        case I2C_MASTER_CMD_BURST_RECEIVE_FINISH:
            MAP_I2CMasterControl(I2CA0_BASE, I2C_MASTER_CMD_BURST_RECEIVE_ERROR_STOP);
            break;
        default:
            break;
        }
        return false;
    }
    return true;
}

STATIC bool pyb_i2c_write(byte devAddr, byte *data, uint len, bool stop) {
    // Set I2C codec slave address
    MAP_I2CMasterSlaveAddrSet(I2CA0_BASE, devAddr, false);
    // Write the first byte to the controller.
    MAP_I2CMasterDataPut(I2CA0_BASE, *data++);
    // Initiate the transfer.
    RET_IF_ERR(pyb_i2c_transaction(I2C_MASTER_CMD_BURST_SEND_START));

    // Loop until the completion of transfer or error
    while (--len) {
        // Write the next byte of data
        MAP_I2CMasterDataPut(I2CA0_BASE, *data++);
        // Transact over I2C to send the byte
        RET_IF_ERR(pyb_i2c_transaction(I2C_MASTER_CMD_BURST_SEND_CONT));
    }

    // If a stop bit is to be sent, send it.
    if (stop) {
        RET_IF_ERR(pyb_i2c_transaction(I2C_MASTER_CMD_BURST_SEND_STOP));
    }

    return true;
}

STATIC bool pyb_i2c_read(byte devAddr, byte *data, uint len) {
    uint cmd;

    // Set I2C codec slave address
    MAP_I2CMasterSlaveAddrSet(I2CA0_BASE, devAddr, true);

    // Check if its a single receive or burst receive
    if (len > 1) {
        // Initiate a burst receive sequence
        cmd = I2C_MASTER_CMD_BURST_RECEIVE_START;
    }
    else {
        // Configure for a single receive
        cmd = I2C_MASTER_CMD_SINGLE_RECEIVE;
    }

    // Initiate the transfer.
    RET_IF_ERR(pyb_i2c_transaction(cmd));
    // Decrement the count
    len--;
    // Loop until the completion of reception or error
    while (len) {
        // Receive the byte over I2C
        *data++ = MAP_I2CMasterDataGet(I2CA0_BASE);
        if (--len) {
            // Continue with reception
            RET_IF_ERR(pyb_i2c_transaction(I2C_MASTER_CMD_BURST_RECEIVE_CONT));
        }
        else {
            // Complete the last reception
            RET_IF_ERR(pyb_i2c_transaction(I2C_MASTER_CMD_BURST_RECEIVE_FINISH));
        }
    }

    // Receive the last byte over I2C
    *data = MAP_I2CMasterDataGet(I2CA0_BASE);

    return true;
}

STATIC bool pyb_i2c_scan_device(byte devAddr) {
    // Set I2C codec slave address
    MAP_I2CMasterSlaveAddrSet(I2CA0_BASE, devAddr, true);
    // Initiate the transfer.
    RET_IF_ERR(pyb_i2c_transaction(I2C_MASTER_CMD_SINGLE_RECEIVE));
    // Since this is a hack, send the stop bit anyway
    MAP_I2CMasterControl(I2CA0_BASE, I2C_MASTER_CMD_BURST_SEND_ERROR_STOP);

    return true;
}

/******************************************************************************/
/* Micro Python bindings                                                      */
/******************************************************************************/

/// \method init(100000)
///
/// Initialise the I2C bus as a master with the given baudrate.
///
STATIC mp_obj_t pyb_i2c_init_helper(pyb_i2c_obj_t *self_in, mp_obj_t baudrate) {
    pyb_i2c_obj_t *self = self_in;

    // make sure the baudrate is between the valid range
    self->baudrate = MIN(MAX(mp_obj_get_int(baudrate), PYBI2C_MIN_BAUD_RATE_HZ), PYBI2C_MAX_BAUD_RATE_HZ);

    // init the I2C bus
    i2c_init(self);

    // register it with the sleep module
    pybsleep_add ((const mp_obj_t)self, (WakeUpCB_t)i2c_init);

    return mp_const_none;
}

/// \classmethod \constructor(bus, ...)
///
/// Construct an I2C object on the given bus.  `bus` can only be 0.
/// With no additional parameters, the I2C object is created but not
/// initialised (it has the settings from the last initialisation of
/// the bus, if any).  If extra arguments are given, the bus is initialised.
/// See `init` for parameters of initialisation.
STATIC mp_obj_t pyb_i2c_make_new(mp_obj_t type_in, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *args) {
    // check arguments
    mp_arg_check_num(n_args, n_kw, 1, MP_OBJ_FUN_ARGS_MAX, true);

    // setup the object
    pyb_i2c_obj_t *self = &pyb_i2c_obj;
    self->base.type = &pyb_i2c_type;

    if (n_args > 0) {
        // start the peripheral
        pyb_i2c_init_helper(self, *args);
    }

    return (mp_obj_t)self;
}

STATIC void pyb_i2c_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t self_in, mp_print_kind_t kind) {
    pyb_i2c_obj_t *self = self_in;
    if (self->baudrate > 0) {
        print(env, "<I2C0, I2C.MASTER, baudrate=%u>)", self->baudrate);
    }
    else {
        print(env, "<I2C0>");
    }
}

STATIC mp_obj_t pyb_i2c_init(mp_obj_t self_in, mp_obj_t baudrate) {
    return pyb_i2c_init_helper(self_in, baudrate);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(pyb_i2c_init_obj, pyb_i2c_init);

/// \method deinit()
/// Turn off the I2C bus.
STATIC mp_obj_t pyb_i2c_deinit(mp_obj_t self_in) {
    // disable the peripheral
    MAP_I2CMasterDisable(I2CA0_BASE);
    MAP_PRCMPeripheralClkDisable(PRCM_I2CA0, PRCM_RUN_MODE_CLK | PRCM_SLP_MODE_CLK);
    // invalidate the baudrate
    pyb_i2c_obj.baudrate = 0;
    // unregister it with the sleep module
    pybsleep_remove ((const mp_obj_t)self_in);
    return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_i2c_deinit_obj, pyb_i2c_deinit);

/// \method is_ready(addr)
/// Check if an I2C device responds to the given address.  Only valid when in master mode.
STATIC mp_obj_t pyb_i2c_is_ready(mp_obj_t self_in, mp_obj_t i2c_addr_o) {
    mp_uint_t i2c_addr = mp_obj_get_int(i2c_addr_o);
    for (int i = 0; i < 7; i++) {
        if (pyb_i2c_scan_device(i2c_addr)) {
            return mp_const_true;
        }
    }
    return mp_const_false;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(pyb_i2c_is_ready_obj, pyb_i2c_is_ready);

/// \method scan()
/// Scan all I2C addresses from 0x01 to 0x7f and return a list of those that respond.
/// Only valid when in master mode.
STATIC mp_obj_t pyb_i2c_scan(mp_obj_t self_in) {
    mp_obj_t list = mp_obj_new_list(0, NULL);
    for (uint addr = 1; addr <= 127; addr++) {
        for (int i = 0; i < 7; i++) {
            if (pyb_i2c_scan_device(addr)) {
                mp_obj_list_append(list, mp_obj_new_int(addr));
                break;
            }
        }
    }

    return list;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_i2c_scan_obj, pyb_i2c_scan);

/// \method send(send, addr=0x00)
/// Send data on the bus:
///
///   - `send` is the data to send (an integer to send, or a buffer object)
///   - `addr` is the address to send to (only required in master mode)
/// Return value: `None`.
STATIC const mp_arg_t pyb_i2c_send_args[] = {
    { MP_QSTR_send,    MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
    { MP_QSTR_addr,                      MP_ARG_INT, {.u_int = 0} },
};
#define PYB_I2C_SEND_NUM_ARGS MP_ARRAY_SIZE(pyb_i2c_send_args)

STATIC mp_obj_t pyb_i2c_send(mp_uint_t n_args, const mp_obj_t *args, mp_map_t *kw_args) {
    // parse args
    mp_arg_val_t vals[PYB_I2C_SEND_NUM_ARGS];
    mp_arg_parse_all(n_args - 1, args + 1, kw_args, PYB_I2C_SEND_NUM_ARGS, pyb_i2c_send_args, vals);

    // get the buffer to send from
    mp_buffer_info_t bufinfo;
    uint8_t data[1];
    pyb_buf_get_for_send(vals[0].u_obj, &bufinfo, data);

    // send the data
    if (!pyb_i2c_write(vals[1].u_int, bufinfo.buf, bufinfo.len, true)) {
        nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, mpexception_os_operation_failed));
    }

    return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_i2c_send_obj, 1, pyb_i2c_send);

/// \method recv(recv, addr=0x00)
///
/// Receive data on the bus:
///
///   - `recv` can be an integer, which is the number of bytes to receive,
///     or a mutable buffer, which will be filled with received bytes
///   - `addr` is the address to receive from (only required in master mode)
///
/// Return value: if `recv` is an integer then a new buffer of the bytes received,
/// otherwise the same buffer that was passed in to `recv`.
STATIC const mp_arg_t pyb_i2c_recv_args[] = {
    { MP_QSTR_recv,    MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
    { MP_QSTR_addr,                      MP_ARG_INT, {.u_int = 0} },
};
#define PYB_I2C_RECV_NUM_ARGS MP_ARRAY_SIZE(pyb_i2c_recv_args)

STATIC mp_obj_t pyb_i2c_recv(mp_uint_t n_args, const mp_obj_t *args, mp_map_t *kw_args) {
    // parse args
    mp_arg_val_t vals[PYB_I2C_RECV_NUM_ARGS];
    mp_arg_parse_all(n_args - 1, args + 1, kw_args, PYB_I2C_RECV_NUM_ARGS, pyb_i2c_recv_args, vals);

    // get the buffer to receive into
    vstr_t vstr;
    mp_obj_t o_ret = pyb_buf_get_for_recv(vals[0].u_obj, &vstr);

    // receive the data
    if (!pyb_i2c_read(vals[1].u_int, (byte *)vstr.buf, vstr.len)) {
        nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, mpexception_os_operation_failed));
    }

    // return the received data
    if (o_ret != MP_OBJ_NULL) {
        return o_ret;
    }
    else {
        return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
    }
}
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_i2c_recv_obj, 1, pyb_i2c_recv);

/// \method mem_read(data, addr, memaddr, addr_size=8)
///
/// Read from the memory of an I2C device:
///
///   - `data` can be an integer or a buffer to read into
///   - `addr` is the I2C device address
///   - `memaddr` is the memory location within the I2C device
///   - `addr_size` selects the width of memaddr: 8 or 16 bits
///
/// Returns the read data.
/// This is only valid in master mode.
STATIC const mp_arg_t pyb_i2c_mem_read_args[] = {
    { MP_QSTR_data,      MP_ARG_REQUIRED  | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
    { MP_QSTR_addr,      MP_ARG_REQUIRED  | MP_ARG_INT, {.u_int = 0} },
    { MP_QSTR_memaddr,   MP_ARG_REQUIRED  | MP_ARG_INT, {.u_int = 0} },
    { MP_QSTR_addr_size, MP_ARG_KW_ONLY   | MP_ARG_INT, {.u_int = 8} },
};
#define PYB_I2C_MEM_READ_NUM_ARGS MP_ARRAY_SIZE(pyb_i2c_mem_read_args)

STATIC mp_obj_t pyb_i2c_mem_read(mp_uint_t n_args, const mp_obj_t *args, mp_map_t *kw_args) {
    // parse args
    mp_arg_val_t vals[PYB_I2C_MEM_READ_NUM_ARGS];
    mp_arg_parse_all(n_args - 1, args + 1, kw_args, PYB_I2C_MEM_READ_NUM_ARGS, pyb_i2c_mem_read_args, vals);

    // get the buffer to read into
    vstr_t vstr;
    mp_obj_t o_ret = pyb_buf_get_for_recv(vals[0].u_obj, &vstr);

    // get the addresses
    mp_uint_t i2c_addr = vals[1].u_int;
    mp_uint_t mem_addr = vals[2].u_int;
    // determine the width of mem_addr (1 or 2 bytes)
    mp_uint_t mem_addr_size = vals[3].u_int >> 3;

    // Write the register address to be read from.
    if (pyb_i2c_write (i2c_addr, (byte *)&mem_addr, mem_addr_size, false)) {
        // Read the specified length of data
        if (pyb_i2c_read (i2c_addr, (byte *)vstr.buf, vstr.len)) {
            // return the read data
            if (o_ret != MP_OBJ_NULL) {
                return o_ret;
            } else {
                return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
            }
        }
    }

    nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, mpexception_os_operation_failed));

    return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_i2c_mem_read_obj, 1, pyb_i2c_mem_read);

/// \method mem_write(data, addr, memaddr, addr_size=8)
///
/// Write to the memory of an I2C device:
///
///   - `data` can be an integer or a buffer to write from
///   - `addr` is the I2C device address
///   - `memaddr` is the memory location within the I2C device
///   - `addr_size` selects the width of memaddr: 8 or 16 bits
///
/// Returns `None`.
/// This is only valid in master mode.
STATIC mp_obj_t pyb_i2c_mem_write(mp_uint_t n_args, const mp_obj_t *args, mp_map_t *kw_args) {
    // parse args (same as mem_read)
    mp_arg_val_t vals[PYB_I2C_MEM_READ_NUM_ARGS];
    mp_arg_parse_all(n_args - 1, args + 1, kw_args, PYB_I2C_MEM_READ_NUM_ARGS, pyb_i2c_mem_read_args, vals);

    // get the buffer to write from
    mp_buffer_info_t bufinfo;
    uint8_t data[1];
    pyb_buf_get_for_send(vals[0].u_obj, &bufinfo, data);

    // get the addresses
    mp_uint_t i2c_addr = vals[1].u_int;
    mp_uint_t mem_addr = vals[2].u_int;
    // determine the width of mem_addr (1 or 2 bytes)
    mp_uint_t mem_addr_size = vals[3].u_int >> 3;

    // Write the register address to write to.
    if (pyb_i2c_write (i2c_addr, (byte *)&mem_addr, mem_addr_size, false)) {
        // Write the specified length of data
        if (pyb_i2c_write (i2c_addr, bufinfo.buf, bufinfo.len, true)) {
            return mp_const_none;
        }
    }

    nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, mpexception_os_operation_failed));

    return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_i2c_mem_write_obj, 1, pyb_i2c_mem_write);

STATIC const mp_map_elem_t pyb_i2c_locals_dict_table[] = {
    // instance methods
    { MP_OBJ_NEW_QSTR(MP_QSTR_init),            (mp_obj_t)&pyb_i2c_init_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_deinit),          (mp_obj_t)&pyb_i2c_deinit_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_is_ready),        (mp_obj_t)&pyb_i2c_is_ready_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_scan),            (mp_obj_t)&pyb_i2c_scan_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_send),            (mp_obj_t)&pyb_i2c_send_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_recv),            (mp_obj_t)&pyb_i2c_recv_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_mem_read),        (mp_obj_t)&pyb_i2c_mem_read_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_mem_write),       (mp_obj_t)&pyb_i2c_mem_write_obj },
};

STATIC MP_DEFINE_CONST_DICT(pyb_i2c_locals_dict, pyb_i2c_locals_dict_table);

const mp_obj_type_t pyb_i2c_type = {
    { &mp_type_type },
    .name = MP_QSTR_I2C,
    .print = pyb_i2c_print,
    .make_new = pyb_i2c_make_new,
    .locals_dict = (mp_obj_t)&pyb_i2c_locals_dict,
};


text:
import { DOCUMENT } from '@angular/common';
import {
  AfterViewInit,
  ChangeDetectorRef,
  Component,
  Inject,
  OnDestroy,
  OnInit,
  ViewEncapsulation,
} from '@angular/core';
import {
  SkyAgGridRowDeleteConfirmArgs,
  SkyAgGridService,
  SkyCellType,
} from '@skyux/ag-grid';
import { SkyDockLocation, SkyDockService } from '@skyux/core';
import { SkyThemeService, SkyThemeSettings } from '@skyux/theme';

import { GridOptions, RowNode, RowSelectedEvent } from 'ag-grid-community';
import { BehaviorSubject, Observable, Subscription, combineLatest } from 'rxjs';
import { delay, filter, map } from 'rxjs/operators';

import { columnDefinitions, data } from '../shared/baseball-players-data';
import { FontLoadingService } from '../shared/font-loading/font-loading.service';

import { ContextMenuComponent } from './context-menu.component';

type DataSet = { id: string; data: any[] };

@Component({
  selector: 'app-ag-grid-stories',
  templateUrl: './ag-grid-stories.component.html',
  styleUrls: ['./ag-grid-stories.component.scss'],
  encapsulation: ViewEncapsulation.None,
})
export class AgGridStoriesComponent
  implements OnInit, AfterViewInit, OnDestroy
{
  public dataSets: DataSet[] = [
    {
      id: 'back-to-top',
      data: data.slice(40, 48),
    },
    {
      id: 'row-delete',
      data: data.slice(50, 53),
    },
    {
      id: 'validation',
      data: data.slice(60, 63),
    },
  ];
  public gridOptions: { [_: string]: GridOptions } = {};
  public isActive$ = new BehaviorSubject(true);
  public addPreviewWrapper$ = new BehaviorSubject(false);
  public ready = new BehaviorSubject(false);
  public rowDeleteIds: string[] = [];
  public skyTheme: SkyThemeSettings;

  readonly #gridsReady = new Map<string, Observable<boolean>>();
  readonly #agGridService: SkyAgGridService;
  readonly #themeSvc: SkyThemeService;
  readonly #changeDetectorRef: ChangeDetectorRef;
  readonly #dockService: SkyDockService;
  readonly #doc: Document;
  readonly #ngUnsubscribe: Subscription;
  readonly #fontLoadingService: FontLoadingService;

  constructor(
    agGridService: SkyAgGridService,
    themeSvc: SkyThemeService,
    changeDetectorRef: ChangeDetectorRef,
    dockService: SkyDockService,
    @Inject(DOCUMENT) doc: Document,
    fontLoadingService: FontLoadingService
  ) {
    this.#agGridService = agGridService;
    this.#themeSvc = themeSvc;
    this.#changeDetectorRef = changeDetectorRef;
    this.#dockService = dockService;
    this.#doc = doc;
    this.#ngUnsubscribe = new Subscription();
    this.#fontLoadingService = fontLoadingService;
  }

  public ngOnInit(): void {
    this.#dockService.setDockOptions({
      location: SkyDockLocation.ElementBottom,
      referenceEl: this.#doc.querySelector('#back-to-top'),
    });
    this.dataSets.forEach((dataSet) =>
      this.#gridsReady.set(dataSet.id, new BehaviorSubject(false))
    );
    this.#gridsReady.set(
      'theme',
      this.#themeSvc.settingsChange.pipe(map(() => true))
    );
    this.#gridsReady.set('font', this.#fontLoadingService.ready());
    this.#ngUnsubscribe.add(
      this.#themeSvc.settingsChange.subscribe((settings) => {
        this.skyTheme = settings.currentSettings;
        this.isActive$.next(true);
      })
    );
    this.dataSets.forEach((dataSet) => {
      this.gridOptions[dataSet.id] = this.#agGridService.getGridOptions({
        gridOptions: {
          columnDefs: [
            ...(() =>
              dataSet.id === 'row-delete'
                ? [
                    {
                      field: 'select',
                      headerName: '',
                      sortable: false,
                      width: 30,
                      type: SkyCellType.RowSelector,
                    },
                    {
                      colId: 'contextMenu',
                      headerName: '',
                      sortable: false,
                      cellRenderer: ContextMenuComponent,
                      maxWidth: 55,
                    },
                  ]
                : [])(),
            ...columnDefinitions
              .slice(0, 10)
              .filter(
                (col) => col.field !== 'birthday' || dataSet.id !== 'validation'
              )
              .map((colDef) => {
                const additionalType =
                  colDef.field === 'seasons_played' &&
                  dataSet.id === 'validation'
                    ? [SkyCellType.NumberValidator]
                    : [];
                const cellRendererParams =
                  colDef.field === 'seasons_played' &&
                  dataSet.id === 'validation'
                    ? {
                        skyComponentProperties: {
                          validator: (value: unknown) =>
                            !!value && value < 18 && value > 0,
                          validatorMessage:
                            'Expected a number between 1 and 18.',
                        },
                      }
                    : undefined;
                return {
                  ...colDef,
                  type: [
                    ...(Array.isArray(colDef.type)
                      ? colDef.type
                      : [colDef.type]),
                    ...additionalType,
                  ].filter((type) => !!type),
                  cellRendererParams,
                };
              }),
          ],
          context: {
            rowDeleteIds: [],
          },
          suppressColumnVirtualisation: true,
          suppressHorizontalScroll: true,
          suppressRowVirtualisation: true,
          onGridReady: (params) => {
            if (dataSet.id === 'row-delete') {
              params.api.addEventListener(
                RowNode.EVENT_ROW_SELECTED,
                ($event: RowSelectedEvent) => {
                  if ($event.node.isSelected()) {
                    this.rowDeleteIds = this.rowDeleteIds.concat([
                      $event.node.id,
                    ]);
                  } else {
                    this.rowDeleteIds = this.rowDeleteIds.filter(
                      (id) => id !== $event.node.id
                    );
                  }
                }
              );
            }
          },
          onFirstDataRendered: () => {
            (this.#gridsReady.get(dataSet.id) as BehaviorSubject<boolean>).next(
              true
            );
          },
          rowData: dataSet.data,
        },
      });
    });
  }

  public ngAfterViewInit(): void {
    this.#ngUnsubscribe.add(
      combineLatest(Array.from(this.#gridsReady.values()))
        .pipe(
          filter((gridsReady) => gridsReady.every((ready) => ready)),
          delay(1000)
        )
        .subscribe(() => {
          // Scroll down to show the back-to-top button.
          this.#doc
            .querySelector(
              '#back-to-top .sky-ag-grid-row-johnsra05 [col-id="name"]'
            )
            .scrollIntoView();

          setTimeout(() => {
            // Select a row to show the row delete button.
            this.#doc
              .querySelector(
                '#row-delete .sky-ag-grid-row-killeha01 [col-id="select"] label'
              )
              .dispatchEvent(new MouseEvent('click'));

            setTimeout(() => {
              // Trigger validation popover to show up.
              this.#doc
                .querySelector(
                  '#validation .sky-ag-grid-row-martipe02 [col-id="seasons_played"]'
                )
                .dispatchEvent(new KeyboardEvent('keyup', { key: 'ArrowUp' }));

              // Tell Cypress we're ready.
              setTimeout(() => this.ready.next(true), 100);
            });
          });
        })
    );
    if (!this.skyTheme) {
      this.isActive$.next(false);
      this.addPreviewWrapper$.next(true);
      setTimeout(() => {
        this.#changeDetectorRef.markForCheck();
      });
    }
  }

  public ngOnDestroy(): void {
    this.#ngUnsubscribe.unsubscribe();
  }

  public deleteConfirm($event: SkyAgGridRowDeleteConfirmArgs) {
    console.log(`Delete ${$event.id}`);
  }
}

redpajama_set_name: RedPajamaGithub


text:
package org.jboss.as.quickstarts.bean_validation_custom_constraint;

import java.util.Set;

import javax.inject.Inject;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;

import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.quickstarts.bean_validation_custom_constraint.Address;
import org.jboss.as.quickstarts.bean_validation_custom_constraint.AddressValidator;
import org.jboss.as.quickstarts.bean_validation_custom_constraint.Person;
import org.jboss.as.quickstarts.bean_validation_custom_constraint.PersonAddress;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;

/**
 * Simple tests for Bean Validator using custom constraints. Arquillian deploys an WAR archive to the application server, which
 * constructs Validator object.
 *
 * This object is injected into the tests so user can verify the validators are working. This example does not touch validation
 * on database layer, e.g. it is not validating uniqueness constraint for email field.
 *
 *
 * @author Giriraj Sharma
 *
 */
@RunWith(Arquillian.class)
public class MyPersonTest {

    /**
     * Constructs a deployment archive
     *
     * @return the deployment archive
     */
    @Deployment
    public static Archive<?> createTestArchive() {
        return ShrinkWrap.create(WebArchive.class, "test.war").addClasses(Person.class, PersonAddress.class, Address.class, AddressValidator.class)
            // enable JPA
            .addAsResource("META-INF/test-persistence.xml", "META-INF/persistence.xml")
            // add sample data
            .addAsResource("import.sql")
            // enable CDI
            .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
            // Deploy our test datasource
            .addAsWebInfResource("test-ds.xml", "test-ds.xml");
    }

    // Get configured validator directly from JBoss EAP environment
    @Inject
    Validator validator;

    /**
     * Tests an empty member registration, e.g. violation of:
     *
     *

     *
@NotNull

     *
@Size

     *
@Address

     *

     */

    /**
     * Tests a valid Person and correct address
     */
    @Test
    public void testCorrectAddress() {
        Set<ConstraintViolation<Person>> violations = validator.validate(createValidPerson());

        Assert.assertEquals("No violations were found", 0, violations.size());
    }

    /**
     * Validating the model data which has correct values. Tests {@code @Address} constraint
     */
    @Test
    public void testAddressViolation() {
        Person person = createValidPerson();
        validateAddressConstraints(person);

        // Setting city field of address.
        person.getPersonAddress().setCity("Carolina");
        validateAddressConstraints(person);

        // Setting pin code equal to valid length of 6 characters.
        person.getPersonAddress().setPinCode("123456");
        person.getPersonAddress().setCity("Auckland");
        validateAddressConstraints(person);

        // Setting country name with valid length of more than 4 characters
        person.getPersonAddress().setPinCode("123456");
        person.getPersonAddress().setCountry("Mexico");
        validateAddressConstraints(person);

    }

    private void validateAddressConstraints(Person person) {
        Set<ConstraintViolation<Person>> violations = validator.validate(person);

        for (ConstraintViolation<Person> violation : violations) {
            Assert.assertEquals("One violation was found", 1, violations.size());
            Assert.assertEquals("Address Field  was invalid", violation.getMessage(), violation.getInvalidValue());
        }
    }

    private Person createValidPerson() {
        PersonAddress address = new PersonAddress("#12, 4th Main", "XYZ Layout", "Bangalore", "Karnataka", "India", "56004554");
        Person person = new Person("John", "Smith", address);
        return person;
    }
}


text:
Arduino based temperature surface monitor

# Hardware
* 5 Thermocouples
* AREF pull up resistor
* Push Button
* Debounce resistor
* LCD
* Potentiometer
* Arduino Module

# State Machine
* Initialize
* Scan Channels
* Idle
* Settings
* DAQ
* Error

#Intialize

Purpose: To configure the Arduino I/O and setup the serial communication protocol

# Scan Channels

Purpose: To scan all the thermocouple channels and to determine which ones are connected and ready for use and which ones are not.

# Idle

Purpose: Waits for a button press or serial command to trigger a state change.  Possible next states are scan channel, settings or DAQ.

# Settings

Purpose: The settings for the DAQ.  This includes the type of averaging, average sample size, average frequency and units.

# DAQ

Purpose: This gets the thermocouple data, converts it to data, updates the display and sends the result over serial communication.

# Error

Purpose: To catch errors and update the user on the controller status.


text:
package ti.modules.titanium.xml;

import org.appcelerator.kroll.annotations.Kroll;
import org.w3c.dom.DOMException;
import org.w3c.dom.ProcessingInstruction;

@Kroll.proxy(parentModule=XMLModule.class)
public class ProcessingInstructionProxy extends NodeProxy {

	private ProcessingInstruction pi;

	public ProcessingInstructionProxy(ProcessingInstruction pi)
	{
		super(pi);
		this.pi = pi;
	}

	@Kroll.getProperty @Kroll.method
	public String getData() {
		return pi.getData();
	}

	@Kroll.getProperty @Kroll.method
	public String getTarget() {
		return pi.getTarget();
	}

	@Kroll.setProperty @Kroll.method
	public void setData(String data) throws DOMException {
		pi.setData(data);
	}

	@Override
	public String getApiName()
	{
		return "Ti.XML.ProcessingInstruction";
	}
}


text:
package org.springframework.cloud.vault.util;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;

import org.junit.rules.ExternalResource;

import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.util.Assert;
import org.springframework.vault.authentication.SessionManager;
import org.springframework.vault.client.VaultEndpoint;
import org.springframework.vault.core.VaultTemplate;
import org.springframework.vault.support.SslConfiguration;
import org.springframework.vault.support.VaultToken;

/**
 * Vault rule to ensure a running and prepared Vault.
 *
 * @author Mark Paluch
 */
public class VaultRule extends ExternalResource {

	public static final Version VERSIONING_INTRODUCED_WITH = Version.parse("0.10.0");

	private final VaultEndpoint vaultEndpoint;

	private final PrepareVault prepareVault;

	private VaultToken token;

	/**
	 * Create a new {@link VaultRule} with default SSL configuration and endpoint.
	 *
	 * @see Settings#createSslConfiguration()
	 * @see VaultEndpoint
	 */
	public VaultRule() {
		this(Settings.createSslConfiguration(),
				TestRestTemplateFactory.TEST_VAULT_ENDPOINT);
	}

	/**
	 * Create a new {@link VaultRule} with the given {@link SslConfiguration} and
	 * {@link VaultEndpoint}.
	 * @param sslConfiguration must not be {@literal null}.
	 * @param vaultEndpoint must not be {@literal null}.
	 */
	public VaultRule(SslConfiguration sslConfiguration, VaultEndpoint vaultEndpoint) {

		Assert.notNull(sslConfiguration, "SslConfiguration must not be null");
		Assert.notNull(vaultEndpoint, "VaultEndpoint must not be null");

		ClientHttpRequestFactory requestFactory = TestRestTemplateFactory
				.create(sslConfiguration).getRequestFactory();

		VaultTemplate vaultTemplate = new VaultTemplate(vaultEndpoint, requestFactory,
				new PreparingSessionManager());

		this.token = Settings.token();
		this.prepareVault = new PrepareVault(vaultTemplate);
		this.vaultEndpoint = vaultEndpoint;
	}

	@Override
	public void before() {

		try (Socket socket = new Socket()) {

			socket.connect(new InetSocketAddress(InetAddress.getByName("localhost"),
					this.vaultEndpoint.getPort()));
		}
		catch (Exception ex) {
			throw new IllegalStateException(String.format(
					"Vault is not running on localhost:%d which is required to run a test using @Rule %s",
					this.vaultEndpoint.getPort(), getClass().getSimpleName()));
		}

		if (!this.prepareVault.isAvailable()) {

			this.token = this.prepareVault.initializeVault();
			this.prepareVault.createToken(Settings.token().getToken(), "root");

			if (this.prepareVault.getVersion()
					.isGreaterThanOrEqualTo(VERSIONING_INTRODUCED_WITH)) {
				this.prepareVault.disableGenericVersioning();
				this.prepareVault.mountVersionedKvBackend();
			}

			this.token = Settings.token();
		}
	}

	public PrepareVault prepare() {
		return this.prepareVault;
	}

	private class PreparingSessionManager implements SessionManager {

		@Override
		public VaultToken getSessionToken() {
			return VaultRule.this.token;
		}

	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <listener>
        <listener-class>com.nsysmon.AShutdownServletContextListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>nsysmon</servlet-name>
        <servlet-class>com.nsysmon.servlet.NSysMonServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>nsysmon</servlet-name>
        <url-pattern>/nsysmon/*</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>content</servlet-name>
        <servlet-class>com.nsysmon.demo.AppServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>content</servlet-name>
        <url-pattern>content/*</url-pattern>
    </servlet-mapping>

    <filter>
        <filter-name>nsysmon-filter</filter-name>
        <filter-class>com.nsysmon.measure.http.AHttpRequestMeasuringFilter</filter-class>
        <init-param>
            <param-name>nsysmon.http-analyzer</param-name>
            <param-value>com.nsysmon.demo.NullHttpRequestAnalyzer</param-value>
        </init-param>
    </filter>

    <filter>
        <filter-name>GzipFilter</filter-name>
        <filter-class>org.eclipse.jetty.servlets.GzipFilter</filter-class>
        <init-param>
            <param-name>mimeTypes</param-name>
            <param-value>text/json,text/html,text/plain,text/xml,application/xhtml+xml,text/css,application/javascript,application/json,image/svg+xml</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>GzipFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <filter-mapping>
        <filter-name>nsysmon-filter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>


text:
"use strict";;
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var core_1 = tslib_1.__importDefault(require("./core"));
var types_1 = tslib_1.__importDefault(require("../lib/types"));
var shared_1 = tslib_1.__importDefault(require("../lib/shared"));
function default_1(fork) {
    fork.use(core_1.default);
    var types = fork.use(types_1.default);
    var def = types.Type.def;
    var or = types.Type.or;
    var defaults = fork.use(shared_1.default).defaults;
    def("Function")
        .field("generator", Boolean, defaults["false"])
        .field("expression", Boolean, defaults["false"])
        .field("defaults", [or(def("Expression"), null)], defaults.emptyArray)
        // Legacy
        .field("rest", or(def("Identifier"), null), defaults["null"]);
    // The ESTree way of representing a ...rest parameter.
    def("RestElement")
        .bases("Pattern")
        .build("argument")
        .field("argument", def("Pattern"))
        .field("typeAnnotation", // for Babylon. Flow parser puts it on the identifier
    or(def("TypeAnnotation"), def("TSTypeAnnotation"), null), defaults["null"]);
    def("SpreadElementPattern")
        .bases("Pattern")
        .build("argument")
        .field("argument", def("Pattern"));
    def("FunctionDeclaration")
        .build("id", "params", "body", "generator", "expression")
        // May be `null` in the context of `export default function () {}`
        .field("id", or(def("Identifier"), null));
    def("FunctionExpression")
        .build("id", "params", "body", "generator", "expression");
    def("ArrowFunctionExpression")
        .bases("Function", "Expression")
        .build("params", "body", "expression")
        // The forced null value here is compatible with the overridden
        // definition of the "id" field in the Function interface.
        .field("id", null, defaults["null"])
        // Arrow function bodies are allowed to be expressions.
        .field("body", or(def("BlockStatement"), def("Expression")))
        // The current spec forbids arrow generators, so I have taken the
        // liberty of enforcing that. TODO Report this.
        .field("generator", false, defaults["false"]);
    def("ForOfStatement")
        .bases("Statement")
        .build("left", "right", "body")
        .field("left", or(def("VariableDeclaration"), def("Pattern")))
        .field("right", def("Expression"))
        .field("body", def("Statement"));
    def("YieldExpression")
        .bases("Expression")
        .build("argument", "delegate")
        .field("argument", or(def("Expression"), null))
        .field("delegate", Boolean, defaults["false"]);
    def("GeneratorExpression")
        .bases("Expression")
        .build("body", "blocks", "filter")
        .field("body", def("Expression"))
        .field("blocks", [def("ComprehensionBlock")])
        .field("filter", or(def("Expression"), null));
    def("ComprehensionExpression")
        .bases("Expression")
        .build("body", "blocks", "filter")
        .field("body", def("Expression"))
        .field("blocks", [def("ComprehensionBlock")])
        .field("filter", or(def("Expression"), null));
    def("ComprehensionBlock")
        .bases("Node")
        .build("left", "right", "each")
        .field("left", def("Pattern"))
        .field("right", def("Expression"))
        .field("each", Boolean);
    def("Property")
        .field("key", or(def("Literal"), def("Identifier"), def("Expression")))
        .field("value", or(def("Expression"), def("Pattern")))
        .field("method", Boolean, defaults["false"])
        .field("shorthand", Boolean, defaults["false"])
        .field("computed", Boolean, defaults["false"]);
    def("ObjectProperty")
        .field("shorthand", Boolean, defaults["false"]);
    def("PropertyPattern")
        .bases("Pattern")
        .build("key", "pattern")
        .field("key", or(def("Literal"), def("Identifier"), def("Expression")))
        .field("pattern", def("Pattern"))
        .field("computed", Boolean, defaults["false"]);
    def("ObjectPattern")
        .bases("Pattern")
        .build("properties")
        .field("properties", [or(def("PropertyPattern"), def("Property"))]);
    def("ArrayPattern")
        .bases("Pattern")
        .build("elements")
        .field("elements", [or(def("Pattern"), null)]);
    def("SpreadElement")
        .bases("Node")
        .build("argument")
        .field("argument", def("Expression"));
    def("ArrayExpression")
        .field("elements", [or(def("Expression"), def("SpreadElement"), def("RestElement"), null)]);
    def("NewExpression")
        .field("arguments", [or(def("Expression"), def("SpreadElement"))]);
    def("CallExpression")
        .field("arguments", [or(def("Expression"), def("SpreadElement"))]);
    // Note: this node type is *not* an AssignmentExpression with a Pattern on
    // the left-hand side! The existing AssignmentExpression type already
    // supports destructuring assignments. AssignmentPattern nodes may appear
    // wherever a Pattern is allowed, and the right-hand side represents a
    // default value to be destructured against the left-hand side, if no
    // value is otherwise provided. For example: default parameter values.
    def("AssignmentPattern")
        .bases("Pattern")
        .build("left", "right")
        .field("left", def("Pattern"))
        .field("right", def("Expression"));
    def("MethodDefinition")
        .bases("Declaration")
        .build("kind", "key", "value", "static")
        .field("kind", or("constructor", "method", "get", "set"))
        .field("key", def("Expression"))
        .field("value", def("Function"))
        .field("computed", Boolean, defaults["false"])
        .field("static", Boolean, defaults["false"]);
    var ClassBodyElement = or(def("MethodDefinition"), def("VariableDeclarator"), def("ClassPropertyDefinition"), def("ClassProperty"));
    def("ClassProperty")
        .bases("Declaration")
        .build("key")
        .field("key", or(def("Literal"), def("Identifier"), def("Expression")))
        .field("computed", Boolean, defaults["false"]);
    def("ClassPropertyDefinition") // static property
        .bases("Declaration")
        .build("definition")
        // Yes, Virginia, circular definitions are permitted.
        .field("definition", ClassBodyElement);
    def("ClassBody")
        .bases("Declaration")
        .build("body")
        .field("body", [ClassBodyElement]);
    def("ClassDeclaration")
        .bases("Declaration")
        .build("id", "body", "superClass")
        .field("id", or(def("Identifier"), null))
        .field("body", def("ClassBody"))
        .field("superClass", or(def("Expression"), null), defaults["null"]);
    def("ClassExpression")
        .bases("Expression")
        .build("id", "body", "superClass")
        .field("id", or(def("Identifier"), null), defaults["null"])
        .field("body", def("ClassBody"))
        .field("superClass", or(def("Expression"), null), defaults["null"]);
    def("Super")
        .bases("Expression")
        .build();
    // Specifier and ModuleSpecifier are abstract non-standard types
    // introduced for definitional convenience.
    def("Specifier").bases("Node");
    // This supertype is shared/abused by both def/babel.js and
    // def/esprima.js. In the future, it will be possible to load only one set
    // of definitions appropriate for a given parser, but until then we must
    // rely on default functions to reconcile the conflicting AST formats.
    def("ModuleSpecifier")
        .bases("Specifier")
        // This local field is used by Babel/Acorn. It should not technically
        // be optional in the Babel/Acorn AST format, but it must be optional
        // in the Esprima AST format.
        .field("local", or(def("Identifier"), null), defaults["null"])
        // The id and name fields are used by Esprima. The id field should not
        // technically be optional in the Esprima AST format, but it must be
        // optional in the Babel/Acorn AST format.
        .field("id", or(def("Identifier"), null), defaults["null"])
        .field("name", or(def("Identifier"), null), defaults["null"]);
    // import {<id [as name]>} from ...;
    def("ImportSpecifier")
        .bases("ModuleSpecifier")
        .build("imported", "local")
        .field("imported", def("Identifier"));
    // import <id> from ...;
    def("ImportDefaultSpecifier")
        .bases("ModuleSpecifier")
        .build("local");
    // import <* as id> from ...;
    def("ImportNamespaceSpecifier")
        .bases("ModuleSpecifier")
        .build("local");
    def("ImportDeclaration")
        .bases("Declaration")
        .build("specifiers", "source", "importKind")
        .field("specifiers", [or(def("ImportSpecifier"), def("ImportNamespaceSpecifier"), def("ImportDefaultSpecifier"))], defaults.emptyArray)
        .field("source", def("Literal"))
        .field("importKind", or("value", "type"), function () {
        return "value";
    });
    def("ExportNamedDeclaration")
        .bases("Declaration")
        .build("declaration", "specifiers", "source")
        .field("declaration", or(def("Declaration"), null))
        .field("specifiers", [def("ExportSpecifier")], defaults.emptyArray)
        .field("source", or(def("Literal"), null), defaults["null"]);
    def("ExportSpecifier")
        .bases("ModuleSpecifier")
        .build("local", "exported")
        .field("exported", def("Identifier"));
    def("ExportDefaultDeclaration")
        .bases("Declaration")
        .build("declaration")
        .field("declaration", or(def("Declaration"), def("Expression")));
    def("ExportAllDeclaration")
        .bases("Declaration")
        .build("source")
        .field("source", def("Literal"));
    def("TaggedTemplateExpression")
        .bases("Expression")
        .build("tag", "quasi")
        .field("tag", def("Expression"))
        .field("quasi", def("TemplateLiteral"));
    def("TemplateLiteral")
        .bases("Expression")
        .build("quasis", "expressions")
        .field("quasis", [def("TemplateElement")])
        .field("expressions", [def("Expression")]);
    def("TemplateElement")
        .bases("Node")
        .build("value", "tail")
        .field("value", { "cooked": String, "raw": String })
        .field("tail", Boolean);
    def("MetaProperty")
        .bases("Expression")
        .build("meta", "property")
        .field("meta", def("Identifier"))
        .field("property", def("Identifier"));
}
exports.default = default_1;
module.exports = exports["default"];


text:
package com.deleidos.rtws.commons.util.expression;

import java.util.LinkedList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.deleidos.rtws.commons.util.expression.Literal.LIST;
import static com.deleidos.rtws.commons.util.expression.Literal.LITERAL;

/**
 * Utility class for parsing simple expressions. Given a regular expression containing
 * capturing groups, this class matches the pattern against a given text string, and if
 * it matches extracts each captured group as a term.
 *
 * As a convenience, this class adds two additional character groups to the standard ones
 * available in the Pattern class. The sequence \l and \L can be used to match a java style
 * literal value or a comma separated list of literal values.
 */
public class Parser {

	/** The pattern to be matched. */
	private Pattern pattern;

	/**
	 * Constructor.
	 */
	private Parser(String pattern) {
		this.pattern = Pattern.compile(substituteLiteralPlaceholders(pattern));
	}

	/**
	 * Factory style instantiation.
	 */
	public static Parser compile(String pattern) {
		return new Parser(pattern);
	}

	/**
	 * Parses the given expression using the configured pattern, and returns the matching groups.
	 */
	public TermList parse(String expression) {
		LinkedList<String> buffer = new LinkedList<String>();
		Matcher matcher = pattern.matcher(expression);
		if(matcher.matches()) {
			for(int i = 1; i <= matcher.groupCount(); i++) {
				buffer.add(matcher.group(i));
			}
			return new TermList(buffer.toArray(new String[buffer.size()]));
		} else {
			throw new IllegalArgumentException("Invalid expression syntax '" + expression + "'.");
		}
	}

	/**
	 * Replace any instances of \l or \L within the given patter with the full patterns.
	 */
	protected static String substituteLiteralPlaceholders(String expression) {
		return expression.replaceAll("\\\\l", Matcher.quoteReplacement(LITERAL)).replaceAll("\\\\L", Matcher.quoteReplacement(LIST));
	}

}


text:
import simplejson as json
import base64, hashlib, os, sys, time
import decimal, math, getpass, operator, random
from collections import namedtuple

# Enum: codes for p2p msg names.
IDENT, TAG, MARKET, OFFER, ORDER, CONF, PAY, REC, FINAL, FEEDBACK, CAST, SYNC, BURN, REG, CANCEL = range(15)
Msg = namedtuple('Msg', 'obj sig hash msgname')
MultiMsg = namedtuple('MultiMsg', 'msg hash msgnum total')

btcd = bm = None

# Returns a packed, signed and hashed MM msgstr given any
# dict, msgname, and BTC addr. Requires bitcoind to create BTC sig.
def MM_dumps(btc_addr, msgname, obj):
    b64 = base64.b64encode( json.dumps(obj, sort_keys=True) )
    sig = btcd.signmessage(btc_addr, b64)
    hash = hashlib.sha256(b64).hexdigest()
    msgobj = Msg( b64, sig, hash, msgname )
    return json.dumps(msgobj)

# Returns a verified Msg( dict, sig, hash, msgname ) given a MM objstr
# and BTC addr. Verifies sha256; requires bitcoind to verify BTC sig.
def MM_loads(btc_addr, str, checksig=True):
    msg = Msg(**json.loads(str))
    if msg.hash != hashlib.sha256(msg.obj).hexdigest():
        print "Hash failed to verify..."
        return None
    if checksig and not btcd.verifymessage(btc_addr, msg.sig, msg.obj):
        print "BTC Signature failed to verify..."
        return None
    r = json.loads( base64.b64decode(msg.obj) )
    return Msg( r, msg.sig, msg.hash, msg.msgname )

# Returns the value of a single element of the underlying
# dict, given the key string. VERIFIES NUSSING.
def MM_extract(name, str):
    msg = Msg(**json.loads(str))
    obj = json.loads( base64.b64decode(msg.obj) )
    return obj[name]

# Takes  a Msg string. Writes Msg to a file in msg dir,
# named hash.dat where hash is the Msg hash.
def MM_writefile(obj):
    hash = Msg( **json.loads(obj) ).hash

    dir = 'msg'
    if not os.path.isdir(dir):
        os.makedirs(dir)
    path = os.path.join(dir, hash + '.dat')
    if not os.path.exists(path):
        ofile = open( path, 'w' )
        ofile.write(obj)
        ofile.close()

    return hash

# Takes an index name and Msg hash.
# Renames the Msg file with a backup extension.
# Deletes hash from the named index.
def MM_backupfile(name, hash):
    fname = os.path.join('msg', hash + '.dat')
    os.rename( fname, fname + '.bak' )
    deletefromindex(name, hash)

# Takes an entity name eg. 'vendorid' and a Msg string,
# extracts the associated Ident, and returns the
# BTC address associated with said Ident.
def btcfrommsg(entity, msgstr):
    idhash = MM_extract(entity, msgstr)
    ids = loadlist('ident')
    return searchlistbyhash( ids, idhash ).obj['btcaddr']

# Takes a verified "OrderMsg" and returns the associated Offer.
def offerfromordermsg( msg, getorder=False ):
    offerlist = loadlist('offer')
    orderlist = loadlist('order')
    conflist = loadlist('conf')
    paylist = loadlist('pay')
    reclist = loadlist('rec')

    if msg.msgname == ORDER:
        return searchlistbyhash(offerlist, msg.obj['offerhash'])
    elif msg.msgname == CONF:
        order = searchlistbyhash(orderlist, msg.obj['orderhash'])
        return searchlistbyhash(offerlist, order.obj['offerhash'])
    elif msg.msgname == PAY:
        conf = searchlistbyhash(conflist, msg.obj['confhash'])
        order = searchlistbyhash(orderlist, conf.obj['orderhash'])
        return searchlistbyhash(offerlist, order.obj['offerhash'])
    elif msg.msgname == REC:
        pay = searchlistbyhash(paylist, msg.obj['payhash'])
        conf = searchlistbyhash(conflist, pay.obj['confhash'])
        order = searchlistbyhash(orderlist, conf.obj['orderhash'])
        return searchlistbyhash(offerlist, order.obj['offerhash'])
    elif msg.msgname == FINAL:
        rec = searchlistbyhash(reclist, msg.obj['rechash'])
        pay = searchlistbyhash(paylist, rec.obj['payhash'])
        conf = searchlistbyhash(conflist, pay.obj['confhash'])
        order = searchlistbyhash(orderlist, conf.obj['orderhash'])
        if getorder:
            return order
        return searchlistbyhash(offerlist, order.obj['offerhash'])

# Takes an unverified msg string of any type,
# Uses btcfrommsg() to extract the associated btc address,
# Returns a verifed version of the Msg.
def readmsg( msgstr ):
    msgname = Msg(**json.loads(msgstr)).msgname
    if msgname == IDENT:
        btc = MM_extract('btcaddr', msgstr)
    elif msgname == TAG or msgname == OFFER or msgname == CONF or msgname == REC:
        btc = btcfrommsg('vendorid', msgstr)
    elif msgname == ORDER or msgname == PAY or msgname == FINAL:
        btc = btcfrommsg('buyerid', msgstr)
    elif msgname == MARKET or msgname == CAST:
        btc = btcfrommsg('modid', msgstr)
    elif msgname == FEEDBACK or msgname == CANCEL:
        btc = btcfrommsg('fromid', msgstr)
    elif msgname == SYNC or msgname == BURN:
        btc = btcfrommsg('userid', msgstr)
    elif msgname == REG:
        return MM_loads(None, msgstr, False)
    return MM_loads(btc, msgstr)

# Takes a list, an index filename, and an entity name.
# Loads the index from file. Loads all associated Msgs
# from their files into the given list. Verifies everything.
def loadlist( fname ):
    list = []
    for i in loadindex(fname):
        msgstr = open( os.path.join('msg', i + '.dat') ).read()
        list.append( readmsg(msgstr) )
    return list

# Returns a list entry by it's hash.
def searchlistbyhash(list, hash):
    for entry in list:
        if entry.hash == hash:
            return entry
    else:
        return None

# Packs a list of Msgs into a b64 string for CASTing.
def packlistforcast( name, list ):
    newlist = []
    for msg in list:
        b64 = base64.b64encode( json.dumps(msg.obj, sort_keys=True) )
        msgobj = Msg(b64, msg.sig, msg.hash, msg.msgname)
        msgstr = json.dumps(msgobj)
        newlist.append(msgstr)
#        MM_backupfile(name, msg.hash)
    return base64.b64encode( json.dumps(newlist) )

# Unpacks a list of msgs from a CAST,
# writes/indexes msgs to files without verification.
def unpackcastlist( caststr, index ):
    if not caststr:
        return
    list = json.loads( base64.b64decode(caststr) )
    for msg in list:
        hash = MM_writefile(msg)
        appendindex(index, hash)

# Asks user yes or no, returns boolean
def yorn( ):
    yorn = raw_input("[Y or N]: ")
    return yorn in ('Y', 'y', 'yes', 'YES', 'Yes')

# Breaks up a list/string into chunks of a given size.
def chunks(seq, n):
    return (seq[i:i+n] for i in xrange(0, len(seq), n))

# Breaks a b64 string down into b64 encoded MultiMsgs.
def breakdownbmmsg( b64msg ):
    newlist = []
    CHUNKSIZE = 5000 #250 * 1024
    chunk_list = list( chunks(b64msg, CHUNKSIZE) )
    hash = hashlib.sha256(b64msg).hexdigest()
    total = len(chunk_list)

    for i in range(total):
        msgobj = MultiMsg( chunk_list[i], hash, i, total )
        newlist.append( base64.b64encode(json.dumps(msgobj, sort_keys=True)) )
    return newlist

# Reconstructs a b64 string from a list of MultiMsgs.
def reconstructmsg(mmsg_list):
    mmsg_list = sorted(mmsg_list, key=operator.attrgetter('msgnum'))
    b64msg = ''
    for mmsg in mmsg_list:
        b64msg += mmsg.msg
    return base64.b64decode(b64msg)

# Accepts a BM address, Msg string and prompt flag.
# Sends any raw Msg to any BM address.
def sendmsgviabm(to_addr, from_addr, msgstr, prompt, subject='Msg'):
    MAXBMOBJSIZE = 5000 #256*1024 - 20
    if prompt:
        print "Are you sure you want to send this Message?"
    if not prompt or yorn():
        b64msg = base64.b64encode(msgstr)
        if sys.getsizeof(b64msg) > MAXBMOBJSIZE:
            multimsgs = breakdownbmmsg(b64msg)
            random.shuffle(multimsgs)
            for msg in multimsgs:
                bm.sendMessage(to_addr, from_addr, base64.b64encode('MultiMsg'), msg)
        else:
            bm.sendMessage(to_addr, from_addr, base64.b64encode(subject), b64msg)
        print "Message sent!"

# Writes and index to file.
def writeindex( index_set, name ):
    indfile = open( name + '.dat', 'w' )
    json.dump(list(index_set), indfile)
    indfile.close()

# Loads an index from file.
# Creates an empty index if none exists.
def loadindex( name ):
    fname = name + '.dat'
    if not os.path.exists(fname):
        writeindex([], name)
    indfile = open( fname, 'r' )
    index_set = set( json.load(indfile) )
    indfile.close()
    return index_set

# Loads an index from file, appends
# a new hash, and writes it back.
def appendindex( name, newhash ):
    index = loadindex(name)
    index.add(newhash)
    writeindex( index, name )

# Loads and index from file, deletes
# an existing hash, and writes it back.
def deletefromindex( name, hash ):
    index = loadindex(name)
    index.remove(hash)
    writeindex( index, name )

# Creates a new Ident Msg and returns its string representation.
def createidentmsgstr( btc_addr, bm_addr, user_name ):
    ident = { 'name': user_name,
                'btcaddr': btc_addr,
                'bmaddr': bm_addr }
    return MM_dumps(btc_addr, IDENT, ident)

# Creates a new Register Msg and returns its string representation.
def createregmsgstr( btc_addr, modid, userid, reg_fee_txid ):
    reg = { 'modid': modid,
                'userid': userid,
                'txid': reg_fee_txid }
    return MM_dumps(btc_addr, REG, reg)

def createburnmsgstr(btc_addr, userid, txid):
    burn = { 'userid': userid,
                'txid': txid }
    return MM_dumps(btc_addr, BURN, burn)

# Creates a new Tag Msg and returns its string representation.
def createtagmsgstr( btc_addr, vendorid, tagname, desc ):
    tag = { 'vendorid': vendorid,
            'tagname': tagname,
            'description': desc }
    return MM_dumps(btc_addr, TAG, tag)

# Creates a new Market Msg and returns its string representation.
def createmarketmsgstr( btc_addr, modid, marketname, desc, reg_fee, burn_mult ):
    market = { 'modid': modid,
                'marketname': marketname,
                'description': desc,
                'fee': reg_fee,
                'multiplier': burn_mult }
    return MM_dumps(btc_addr, MARKET, market)

# Creates a new Offer Msg and returns its string representation.
def createoffermsgstr( btc_addr, markethash, vendorid, vendor_pubkey, \
                        name, locale, desc, amount, price, refund_ratio, \
                        locktime, minrep, tags ):
    offer = { 'vendorid': vendorid,
                'markethash': markethash,
                'pubkey': vendor_pubkey,
                'name': name,
                'locale': locale,
                'description': desc,
                'amount': amount,
                'price': price,
                'ratio': refund_ratio,
                'locktime': locktime,
                'minrep': minrep,
                'tags': tags }
    return MM_dumps(btc_addr, OFFER, offer)

# Creates a new Order Msg and returns its string representation.
def createordermsgstr( btc_addr, offerhash, vendorid, buyerid, buyer_pubkey, \
                        multisig, crypt_fundingtx, funding_txid, vout, spk ):
    order = { 'offerhash': offerhash,
                'vendorid': vendorid,
                'buyerid': buyerid,
                'pubkey': buyer_pubkey,
                'multisig': multisig,
                'crypt_fundingtx': crypt_fundingtx,
                'txid': funding_txid,
                'vout': vout,
                'spk': spk }
    return MM_dumps(btc_addr, ORDER, order)

# Creates a new Confirmation Msg and returns its string representation.
def createconfmsgstr( btc_addr, orderhash, vendorid, buyerid, refundtx, prevtx ):
    conf = { 'orderhash': orderhash,
                'vendorid': vendorid,
                'buyerid': buyerid,
                'refundtx': refundtx,
                'prevtx': prevtx }
    return MM_dumps(btc_addr, CONF, conf)

# Creates a new Payment Msg and returns its string representation.
def createpaymsgstr( btc_addr, confhash, vendorid, buyerid, refundhex, address ):
    pay = { 'confhash': confhash,
            'vendorid': vendorid,
            'buyerid': buyerid,
            'refundhex': refundhex,
            'address': address }
    return MM_dumps(btc_addr, PAY, pay)

# Creates a new Reciept Msg and returns its string representation.
def createrecmsgstr( btc_addr, payhash, vendorid, buyerid, finaltx, prevtx ):
    rec = { 'payhash': payhash,
            'vendorid': vendorid,
            'buyerid': buyerid,
            'finaltx': finaltx,
            'prevtx': prevtx }
    return MM_dumps(btc_addr, REC, rec)

# Creates a new Finalize Msg and returns its string representation.
def createfinalmsgstr(btc_addr, rechash, vendorid, buyerid, finaltxid):
    final = { 'rechash': rechash,
                'vendorid': vendorid,
                'buyerid': buyerid,
                'finaltxid': finaltxid }
    return MM_dumps(btc_addr, FINAL, final)

# Creates a new Feedback Msg and returns its string representation.
def createfeedbackmsgstr( btc_addr, markethash, finalhash, fromid, toid, finaltxid, redeemscript, upvote, message ):
    feedback = { 'markethash': markethash,
                    'finalhash': finalhash,
                    'fromid': fromid,
                    'toid': toid,
                    'finaltxid': finaltxid,
                    'redeemscript': redeemscript,
                    'upvote': upvote,
                    'message': message }
    return MM_dumps(btc_addr, FEEDBACK, feedback)

# Creates a new Broadcast Msg and returns its string representation.
def createcastmsgstr( btc_addr, modid, identlist, burnlist, taglist, offerlist, feedbacklist ):
    cast = { 'modid': modid,
                'identlist': packlistforcast('ident', identlist),
                'burnlist': packlistforcast('burn', burnlist),
                'taglist': packlistforcast('tags', taglist),
                'offerlist': packlistforcast('offer', offerlist),
                'feedbacklist': packlistforcast('feedback', feedbacklist) }
    return MM_dumps(btc_addr, CAST, cast)

# Creates a new Synchronize Msg and returns its string representation.
def createsyncmsgstr( btc_addr, modid, userid ):
    sync = { 'modid': modid,
                'userid': userid }
    return MM_dumps(btc_addr, SYNC, sync)

# Creates a new Cancel Order Msg and returns its string representation.
def createcancelmsgstr(btc_addr, fromid, toid, orderhash):
    cancel = { 'fromid': fromid,
                'toid': toid,
                'orderhash': orderhash }
    return MM_dumps(btc_addr, CANCEL, cancel)

# Takes an amount, destination address, change address,
# and optionally customizeable fee, and minimum confirms.
# Uses btcd createrawtransaction. To create a tx,
# payable by the user's btc core wallet.
def mktx(price, addr, chg_addr, fee, confs=1):

    dust_threshold = decimal.Decimal('0.00005430')
    collected = decimal.Decimal(0)
    utxos = btcd.listunspent(confs)
    ops = []

    #search for single utxo above price + fee
    single = None
    for op in utxos:
        amount = op['amount']
        if amount >= price + fee:
            single = op
            collected = amount

    #if not, accumulate sequentially up to price + fee
    if not single:
        for op in utxos:
            ops.append(op)
            amount = op['amount']
            collected += amount
            if collected >= price + fee:
                break
        else:
            raise Exception("Insufficient funds!")
    else:
        ops.append(single)

    #convert from tx format
    newops = []
    for op in ops:
        newops.append( dict((key, op[key]) for key in ("txid", "vout")) )

    change = collected - (price + fee)

    addresses = { addr: price }
    if change > dust_threshold:
        addresses[chg_addr] = change

    return btcd.createrawtransaction( newops, addresses )

# Takes a tx hexstring and returns a more appropriate fee..
def calc_fee( hex_str ):
    size_bytes = len(hex_str) / 2
    size_rounded = int(math.ceil(size_bytes / 1000.0)) * 1000
    return size_rounded / decimal.Decimal('10000000.0')

# Takes a number and truncates it to 8 decimal places.
def truncate(num):
    strnum = str(num)
    if '.' in strnum:
        i = strnum.index('.')
        if len( strnum[i+1:] ) >= 8:
            return decimal.Decimal( strnum[:i+9] )
    return num

# Takes a ratio and amount, returns a tuple containing
# two portions of the amounts based on the given ratio.
def getamounts(ratio, amount):
    stratio = str(ratio)

    i = stratio.index('.')
    sp = len( stratio[i+1:] )

    denom = decimal.Decimal( '1'+'0'*sp )
    numer = ratio*denom
    total = numer+denom

    bper = numer/total
    vper = denom/total

    bbtc = truncate(amount*bper)
    vbtc = truncate(amount*vper)

    return ( bbtc, vbtc )

# Asks user for their wallet encryption passphrase.
# unlocks core wallet for 10min.
def unlockwallet( wp=None ):
    if not wp:
        wp = getpass.getpass("Please enter your wallet encryption passphrase: ")
    btcd.walletpassphrase(wp, 600)


text:
"""
Definition of the config-container type.
"""

import json

from .misc import Struct, merge_dicts, deep_getattr, deep_setattr

################################################################################

class ConfigContainerMixin:
    """
    A mixin-baseclass of the `ConfigContainer <#figura.container.ConfigContainer>`_ class.
    """

    INDENT_LEN = 2

    DEFAULT_JSON_DUMP_KWARGS = {
        'indent': INDENT_LEN,
        'ensure_ascii': False,
    }

    # ============================================================================================
    # attribute access
    # ============================================================================================

    def deep_getattr(self, attr_path, *args):
        """
        See deep_getattr_.

        .. _deep_getattr:
        """
        return deep_getattr(self, attr_path, *args)

    def deep_setattr(self, attr_path, value):
        """
        See deep_setattr_.

        .. _deep_setattr:
        """
        return deep_setattr(self, attr_path, value)

    def apply_overrides(self, overrides, **kwargs):
        """
        A convenience method, simply calling apply_overrides_to_config_.

        :note: this method modifies the config container in-place.

        .. _apply_overrides_to_config: #figura.override.apply_overrides_to_config
        """
        from figura.override import apply_overrides_to_config  # avoid circular import
        apply_overrides_to_config(self, overrides, **kwargs)

    # ============================================================================================
    # serialization
    # ============================================================================================

    def to_string(self, **kwargs):
        """
        A JSON-string representation of the config container.
        """
        return self.to_json(**kwargs)

    def __str__(self):
        return self.to_string()

    def __repr__(self):
        return '%s(%s)' % (
            self.__class__.__name__,
            super().__repr__())

    def to_json(self, **kwargs):
        """
        :param args+kwargs: extra args to pass to ``json.dumps``.
        :return: the json string representation of self.
        """
        kw = dict(self.DEFAULT_JSON_DUMP_KWARGS)
        kw.update(kwargs)
        return json.dumps(self, **kw)

    @classmethod
    def from_json(cls, json_str):
        """
        Create a ConfigContainer from a json string.
        """
        return cls.from_dict(json.loads(json_str))

    def to_dict(self):
        """
        deep-conversion of self to a dict.
        """
        return json.loads(self.to_json())

    @classmethod
    def from_dict(cls, x):
        """
        deep-conversion of a dict to a ConfigContainer
        """
        return get_config_container_from_dict(x, cls=cls)

    def to_python_string(self):
        """
        A python-string representation of the config container.
        """
        lines = self._to_python_lines(self, 0)
        return '\n'.join(lines)

    def _to_python_lines(self, x, indent_level=0):
        indent = ' ' * (self.INDENT_LEN * indent_level)
        lines = []
        for k, v in x.items():
            if isinstance(v, ConfigContainer):
                lines.append('%sclass %s:' % (indent, k))
                if len(v) > 0:
                    lines.extend(self._to_python_lines(v, indent_level + 1))
                else:
                    lines.append('%s%spass' % (indent, ' ' * self.INDENT_LEN))
            else:
                lines.append('%s%s = %r' % (indent, k, v))
        return lines

class ConfigContainer(Struct, ConfigContainerMixin):
    """
    A `Struct <#figura.misc.Struct>`_-like (recursive) container holding the configuration data.
    """

    DEFAULT_METADATA = Struct(
        is_override_set=False,
        is_opaque=False,
        is_opaque_override=False,
        doc=None,
        name=None,
        file=None,
        package=None,
    )

    def __init__(self, *args, **kwargs):
        metadata = kwargs.pop('metadata', None)
        super().__init__(*args, **kwargs)
        # not doing self._metadata=x because that results with self['_metadata']=x,
        # i.e. adding a new key to the container
        if metadata is not None:
            metadata = merge_dicts(self.DEFAULT_METADATA, metadata)
        else:
            metadata = Struct(self.DEFAULT_METADATA)
        self.__dict__['_metadata'] = metadata

    def get_metadata(self):
        return self._metadata

    def copy(self):
        return type(self)(self)

    @property
    def __doc__(self):
        return self._metadata.doc

    @property
    def __name__(self):
        return self._metadata.name

    @property
    def __file__(self):
        return self._metadata.file

    @property
    def __package__(self):
        return self._metadata.package

    def _add_module_metadata(self, module):
        metadata = self._metadata
        for attr in ['name', 'file', 'package']:
            try:
                metadata[attr] = getattr(module, '__%s__' % attr)
            except AttributeError:
                pass
        for attr in ['doc']:
            if metadata[attr]:
                continue
            try:
                metadata[attr] = getattr(module, '__%s__' % attr)
            except AttributeError:
                pass

################################################################################

def get_config_container_from_dict(x, cls=ConfigContainer):
    """
    Deep-conversion of a dict to a ConfigContainer.
    """
    if isinstance(x, dict):
        # convert recursively, and preserve dict type
        y = type(x)(
            (k, get_config_container_from_dict(v, cls=cls))
            for k, v in x.items()
        )
        return cls(y)
    else:
        # assume an atomic value
        return x

################################################################################


text:
package edu.duke.cabig.c3pr.xml;

import org.apache.log4j.Logger;
import org.exolab.castor.mapping.FieldHandler;
import org.exolab.castor.mapping.ValidityException;

import edu.duke.cabig.c3pr.domain.ScheduledEpoch;

/**
 * Created by IntelliJ IDEA. User: kherm Date: Sep 19, 2007 Time: 3:29:25 PM To change this template
 * use File | Settings | File Templates.
 */
public class StratumGroupFieldHandler implements FieldHandler {

    Logger log = Logger.getLogger(StratumGroupFieldHandler.class);

    public Object getValue(Object object) throws IllegalStateException {
        ScheduledEpoch scheduledEpoch = (ScheduledEpoch) object;
        Integer stratumGroupNumber = scheduledEpoch.getStratumGroupNumber();
        if(stratumGroupNumber != null && !stratumGroupNumber.toString().equals("")){
        	return stratumGroupNumber.toString();
        }
    	try {
    		return scheduledEpoch.getStratumGroup().toString();
    	}catch (Exception e) {
    		log.warn("Cannot get stratum group number. Exception thrown while computing stratuum group number.");
    		log.warn(e);
            return null;
        }
    }

    public void setValue(Object object, Object value) throws IllegalStateException,
                    IllegalArgumentException {
    	if(value==null){
    		log.warn("Cannot set stratum group number to null.");
    		return;
    	}
    	ScheduledEpoch scheduledEpoch = (ScheduledEpoch) object;
        String s = (String) value;
        int i = Integer.parseInt(s.split(":")[0].trim());
        scheduledEpoch.setStratumGroupNumber(i);

    }

    public void resetValue(Object object) throws IllegalStateException, IllegalArgumentException {
        // To change body of implemented methods use File | Settings | File Templates.
    }

    /**
     * @deprecated
     */
    public void checkValidity(Object object) throws ValidityException, IllegalStateException {
        // To change body of implemented methods use File | Settings | File Templates.
    }

    public Object newInstance(Object object) throws IllegalStateException {
        return null; // To change body of implemented methods use File | Settings | File
                        // Templates.
    }
}


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/cloud/tasks/v2/target.proto

namespace Google\Cloud\Tasks\V2;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * HTTP request.
 * The task will be pushed to the worker as an HTTP request. If the worker
 * or the redirected worker acknowledges the task by returning a successful HTTP
 * response code ([`200` - `299`]), the task will be removed from the queue. If
 * any other HTTP response code is returned or no response is received, the
 * task will be retried according to the following:
 * * User-specified throttling: [retry configuration][google.cloud.tasks.v2.Queue.retry_config],
 *   [rate limits][google.cloud.tasks.v2.Queue.rate_limits], and the [queue's state][google.cloud.tasks.v2.Queue.state].
 * * System throttling: To prevent the worker from overloading, Cloud Tasks may
 *   temporarily reduce the queue's effective rate. User-specified settings
 *   will not be changed.
 *  System throttling happens because:
 *   * Cloud Tasks backs off on all errors. Normally the backoff specified in
 *     [rate limits][google.cloud.tasks.v2.Queue.rate_limits] will be used. But if the worker returns
 *     `429` (Too Many Requests), `503` (Service Unavailable), or the rate of
 *     errors is high, Cloud Tasks will use a higher backoff rate. The retry
 *     specified in the `Retry-After` HTTP response header is considered.
 *   * To prevent traffic spikes and to smooth sudden increases in traffic,
 *     dispatches ramp up slowly when the queue is newly created or idle and
 *     if large numbers of tasks suddenly become available to dispatch (due to
 *     spikes in create task rates, the queue being unpaused, or many tasks
 *     that are scheduled at the same time).
 *
 * Generated from protobuf message google.cloud.tasks.v2.HttpRequest
 */
class HttpRequest extends \Google\Protobuf\Internal\Message
{
    /**
     * Required. The full url path that the request will be sent to.
     * This string must begin with either "http://" or "https://". Some examples
     * are: `http://acme.com` and `https://acme.com/sales:8080`. Cloud Tasks will
     * encode some characters for safety and compatibility. The maximum allowed
     * URL length is 2083 characters after encoding.
     * The `Location` header response from a redirect response [`300` - `399`]
     * may be followed. The redirect is not counted as a separate attempt.
     *
     * Generated from protobuf field string url = 1 [(.google.api.field_behavior) = REQUIRED];
     */
    private $url = '';
    /**
     * The HTTP method to use for the request. The default is POST.
     *
     * Generated from protobuf field .google.cloud.tasks.v2.HttpMethod http_method = 2;
     */
    private $http_method = 0;
    /**
     * HTTP request headers.
     * This map contains the header field names and values.
     * Headers can be set when the
     * [task is created][google.cloud.tasks.v2beta3.CloudTasks.CreateTask].
     * These headers represent a subset of the headers that will accompany the
     * task's HTTP request. Some HTTP request headers will be ignored or replaced.
     * A partial list of headers that will be ignored or replaced is:
     * * Host: This will be computed by Cloud Tasks and derived from
     *   [HttpRequest.url][google.cloud.tasks.v2.HttpRequest.url].
     * * Content-Length: This will be computed by Cloud Tasks.
     * * User-Agent: This will be set to `"Google-Cloud-Tasks"`.
     * * `X-Google-*`: Google use only.
     * * `X-AppEngine-*`: Google use only.
     * `Content-Type` won't be set by Cloud Tasks. You can explicitly set
     * `Content-Type` to a media type when the
     *  [task is created][google.cloud.tasks.v2beta3.CloudTasks.CreateTask].
     *  For example, `Content-Type` can be set to `"application/octet-stream"` or
     *  `"application/json"`.
     * Headers which can have multiple values (according to RFC2616) can be
     * specified using comma-separated values.
     * The size of the headers must be less than 80KB.
     *
     * Generated from protobuf field map<string, string> headers = 3;
     */
    private $headers;
    /**
     * HTTP request body.
     * A request body is allowed only if the
     * [HTTP method][google.cloud.tasks.v2.HttpRequest.http_method] is POST, PUT, or PATCH. It is an
     * error to set body on a task with an incompatible [HttpMethod][google.cloud.tasks.v2.HttpMethod].
     *
     * Generated from protobuf field bytes body = 4;
     */
    private $body = '';
    protected $authorization_header;

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type string $url
     *           Required. The full url path that the request will be sent to.
     *           This string must begin with either "http://" or "https://". Some examples
     *           are: `http://acme.com` and `https://acme.com/sales:8080`. Cloud Tasks will
     *           encode some characters for safety and compatibility. The maximum allowed
     *           URL length is 2083 characters after encoding.
     *           The `Location` header response from a redirect response [`300` - `399`]
     *           may be followed. The redirect is not counted as a separate attempt.
     *     @type int $http_method
     *           The HTTP method to use for the request. The default is POST.
     *     @type array|\Google\Protobuf\Internal\MapField $headers
     *           HTTP request headers.
     *           This map contains the header field names and values.
     *           Headers can be set when the
     *           [task is created][google.cloud.tasks.v2beta3.CloudTasks.CreateTask].
     *           These headers represent a subset of the headers that will accompany the
     *           task's HTTP request. Some HTTP request headers will be ignored or replaced.
     *           A partial list of headers that will be ignored or replaced is:
     *           * Host: This will be computed by Cloud Tasks and derived from
     *             [HttpRequest.url][google.cloud.tasks.v2.HttpRequest.url].
     *           * Content-Length: This will be computed by Cloud Tasks.
     *           * User-Agent: This will be set to `"Google-Cloud-Tasks"`.
     *           * `X-Google-*`: Google use only.
     *           * `X-AppEngine-*`: Google use only.
     *           `Content-Type` won't be set by Cloud Tasks. You can explicitly set
     *           `Content-Type` to a media type when the
     *            [task is created][google.cloud.tasks.v2beta3.CloudTasks.CreateTask].
     *            For example, `Content-Type` can be set to `"application/octet-stream"` or
     *            `"application/json"`.
     *           Headers which can have multiple values (according to RFC2616) can be
     *           specified using comma-separated values.
     *           The size of the headers must be less than 80KB.
     *     @type string $body
     *           HTTP request body.
     *           A request body is allowed only if the
     *           [HTTP method][google.cloud.tasks.v2.HttpRequest.http_method] is POST, PUT, or PATCH. It is an
     *           error to set body on a task with an incompatible [HttpMethod][google.cloud.tasks.v2.HttpMethod].
     *     @type \Google\Cloud\Tasks\V2\OAuthToken $oauth_token
     *           If specified, an
     *           [OAuth token](https://developers.google.com/identity/protocols/OAuth2)
     *           will be generated and attached as an `Authorization` header in the HTTP
     *           request.
     *           This type of authorization should generally only be used when calling
     *           Google APIs hosted on *.googleapis.com.
     *     @type \Google\Cloud\Tasks\V2\OidcToken $oidc_token
     *           If specified, an
     *           [OIDC](https://developers.google.com/identity/protocols/OpenIDConnect)
     *           token will be generated and attached as an `Authorization` header in the
     *           HTTP request.
     *           This type of authorization can be used for many scenarios, including
     *           calling Cloud Run, or endpoints where you intend to validate the token
     *           yourself.
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Cloud\Tasks\V2\Target::initOnce();
        parent::__construct($data);
    }

    /**
     * Required. The full url path that the request will be sent to.
     * This string must begin with either "http://" or "https://". Some examples
     * are: `http://acme.com` and `https://acme.com/sales:8080`. Cloud Tasks will
     * encode some characters for safety and compatibility. The maximum allowed
     * URL length is 2083 characters after encoding.
     * The `Location` header response from a redirect response [`300` - `399`]
     * may be followed. The redirect is not counted as a separate attempt.
     *
     * Generated from protobuf field string url = 1 [(.google.api.field_behavior) = REQUIRED];
     * @return string
     */
    public function getUrl()
    {
        return $this->url;
    }

    /**
     * Required. The full url path that the request will be sent to.
     * This string must begin with either "http://" or "https://". Some examples
     * are: `http://acme.com` and `https://acme.com/sales:8080`. Cloud Tasks will
     * encode some characters for safety and compatibility. The maximum allowed
     * URL length is 2083 characters after encoding.
     * The `Location` header response from a redirect response [`300` - `399`]
     * may be followed. The redirect is not counted as a separate attempt.
     *
     * Generated from protobuf field string url = 1 [(.google.api.field_behavior) = REQUIRED];
     * @param string $var
     * @return $this
     */
    public function setUrl($var)
    {
        GPBUtil::checkString($var, True);
        $this->url = $var;

        return $this;
    }

    /**
     * The HTTP method to use for the request. The default is POST.
     *
     * Generated from protobuf field .google.cloud.tasks.v2.HttpMethod http_method = 2;
     * @return int
     */
    public function getHttpMethod()
    {
        return $this->http_method;
    }

    /**
     * The HTTP method to use for the request. The default is POST.
     *
     * Generated from protobuf field .google.cloud.tasks.v2.HttpMethod http_method = 2;
     * @param int $var
     * @return $this
     */
    public function setHttpMethod($var)
    {
        GPBUtil::checkEnum($var, \Google\Cloud\Tasks\V2\HttpMethod::class);
        $this->http_method = $var;

        return $this;
    }

    /**
     * HTTP request headers.
     * This map contains the header field names and values.
     * Headers can be set when the
     * [task is created][google.cloud.tasks.v2beta3.CloudTasks.CreateTask].
     * These headers represent a subset of the headers that will accompany the
     * task's HTTP request. Some HTTP request headers will be ignored or replaced.
     * A partial list of headers that will be ignored or replaced is:
     * * Host: This will be computed by Cloud Tasks and derived from
     *   [HttpRequest.url][google.cloud.tasks.v2.HttpRequest.url].
     * * Content-Length: This will be computed by Cloud Tasks.
     * * User-Agent: This will be set to `"Google-Cloud-Tasks"`.
     * * `X-Google-*`: Google use only.
     * * `X-AppEngine-*`: Google use only.
     * `Content-Type` won't be set by Cloud Tasks. You can explicitly set
     * `Content-Type` to a media type when the
     *  [task is created][google.cloud.tasks.v2beta3.CloudTasks.CreateTask].
     *  For example, `Content-Type` can be set to `"application/octet-stream"` or
     *  `"application/json"`.
     * Headers which can have multiple values (according to RFC2616) can be
     * specified using comma-separated values.
     * The size of the headers must be less than 80KB.
     *
     * Generated from protobuf field map<string, string> headers = 3;
     * @return \Google\Protobuf\Internal\MapField
     */
    public function getHeaders()
    {
        return $this->headers;
    }

    /**
     * HTTP request headers.
     * This map contains the header field names and values.
     * Headers can be set when the
     * [task is created][google.cloud.tasks.v2beta3.CloudTasks.CreateTask].
     * These headers represent a subset of the headers that will accompany the
     * task's HTTP request. Some HTTP request headers will be ignored or replaced.
     * A partial list of headers that will be ignored or replaced is:
     * * Host: This will be computed by Cloud Tasks and derived from
     *   [HttpRequest.url][google.cloud.tasks.v2.HttpRequest.url].
     * * Content-Length: This will be computed by Cloud Tasks.
     * * User-Agent: This will be set to `"Google-Cloud-Tasks"`.
     * * `X-Google-*`: Google use only.
     * * `X-AppEngine-*`: Google use only.
     * `Content-Type` won't be set by Cloud Tasks. You can explicitly set
     * `Content-Type` to a media type when the
     *  [task is created][google.cloud.tasks.v2beta3.CloudTasks.CreateTask].
     *  For example, `Content-Type` can be set to `"application/octet-stream"` or
     *  `"application/json"`.
     * Headers which can have multiple values (according to RFC2616) can be
     * specified using comma-separated values.
     * The size of the headers must be less than 80KB.
     *
     * Generated from protobuf field map<string, string> headers = 3;
     * @param array|\Google\Protobuf\Internal\MapField $var
     * @return $this
     */
    public function setHeaders($var)
    {
        $arr = GPBUtil::checkMapField($var, \Google\Protobuf\Internal\GPBType::STRING, \Google\Protobuf\Internal\GPBType::STRING);
        $this->headers = $arr;

        return $this;
    }

    /**
     * HTTP request body.
     * A request body is allowed only if the
     * [HTTP method][google.cloud.tasks.v2.HttpRequest.http_method] is POST, PUT, or PATCH. It is an
     * error to set body on a task with an incompatible [HttpMethod][google.cloud.tasks.v2.HttpMethod].
     *
     * Generated from protobuf field bytes body = 4;
     * @return string
     */
    public function getBody()
    {
        return $this->body;
    }

    /**
     * HTTP request body.
     * A request body is allowed only if the
     * [HTTP method][google.cloud.tasks.v2.HttpRequest.http_method] is POST, PUT, or PATCH. It is an
     * error to set body on a task with an incompatible [HttpMethod][google.cloud.tasks.v2.HttpMethod].
     *
     * Generated from protobuf field bytes body = 4;
     * @param string $var
     * @return $this
     */
    public function setBody($var)
    {
        GPBUtil::checkString($var, False);
        $this->body = $var;

        return $this;
    }

    /**
     * If specified, an
     * [OAuth token](https://developers.google.com/identity/protocols/OAuth2)
     * will be generated and attached as an `Authorization` header in the HTTP
     * request.
     * This type of authorization should generally only be used when calling
     * Google APIs hosted on *.googleapis.com.
     *
     * Generated from protobuf field .google.cloud.tasks.v2.OAuthToken oauth_token = 5;
     * @return \Google\Cloud\Tasks\V2\OAuthToken|null
     */
    public function getOauthToken()
    {
        return $this->readOneof(5);
    }

    public function hasOauthToken()
    {
        return $this->hasOneof(5);
    }

    /**
     * If specified, an
     * [OAuth token](https://developers.google.com/identity/protocols/OAuth2)
     * will be generated and attached as an `Authorization` header in the HTTP
     * request.
     * This type of authorization should generally only be used when calling
     * Google APIs hosted on *.googleapis.com.
     *
     * Generated from protobuf field .google.cloud.tasks.v2.OAuthToken oauth_token = 5;
     * @param \Google\Cloud\Tasks\V2\OAuthToken $var
     * @return $this
     */
    public function setOauthToken($var)
    {
        GPBUtil::checkMessage($var, \Google\Cloud\Tasks\V2\OAuthToken::class);
        $this->writeOneof(5, $var);

        return $this;
    }

    /**
     * If specified, an
     * [OIDC](https://developers.google.com/identity/protocols/OpenIDConnect)
     * token will be generated and attached as an `Authorization` header in the
     * HTTP request.
     * This type of authorization can be used for many scenarios, including
     * calling Cloud Run, or endpoints where you intend to validate the token
     * yourself.
     *
     * Generated from protobuf field .google.cloud.tasks.v2.OidcToken oidc_token = 6;
     * @return \Google\Cloud\Tasks\V2\OidcToken|null
     */
    public function getOidcToken()
    {
        return $this->readOneof(6);
    }

    public function hasOidcToken()
    {
        return $this->hasOneof(6);
    }

    /**
     * If specified, an
     * [OIDC](https://developers.google.com/identity/protocols/OpenIDConnect)
     * token will be generated and attached as an `Authorization` header in the
     * HTTP request.
     * This type of authorization can be used for many scenarios, including
     * calling Cloud Run, or endpoints where you intend to validate the token
     * yourself.
     *
     * Generated from protobuf field .google.cloud.tasks.v2.OidcToken oidc_token = 6;
     * @param \Google\Cloud\Tasks\V2\OidcToken $var
     * @return $this
     */
    public function setOidcToken($var)
    {
        GPBUtil::checkMessage($var, \Google\Cloud\Tasks\V2\OidcToken::class);
        $this->writeOneof(6, $var);

        return $this;
    }

    /**
     * @return string
     */
    public function getAuthorizationHeader()
    {
        return $this->whichOneof("authorization_header");
    }

}


text:
namespace UniLua
{
	using System;
	using System.Diagnostics;
	using System.IO;

	internal class LuaOSLib
	{
		public const string LIB_NAME = "os";

		public static int OpenLib( ILuaState lua )
		{
			NameFuncPair[] define = new NameFuncPair[]
			{
				new NameFuncPair("clock", 	OS_Clock),
				new NameFuncPair("time", 	OS_Time),
				new NameFuncPair("setlocale", OS_SetLocale),
				new NameFuncPair("execute", OS_Execute),
				new NameFuncPair("tmpname", OS_TmpName),
				new NameFuncPair("remove", OS_Remove),
			};

			lua.L_NewLib( define );
			return 1;
		}

		private static int OS_Clock( ILuaState lua )
		{
			lua.PushNumber( Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds );
			return 1;
		}

		private static int OS_Time( ILuaState lua )
		{
			// TODO:
			lua.PushNumber(DateTime.Now.Ticks / 1000000000);
			return 1;
		}

		private static int OS_SetLocale( ILuaState lua )
		{
			lua.PushNumber( Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds );
			return 1;
		}

		private static int OS_Execute( ILuaState lua )
		{
			var cmd = lua.L_OptString(1, null);
			if (cmd == null)
			{
				lua.PushBoolean(true);
			}
			else
			{
				throw new NotImplementedException();
			}
			return 1;
		}

		private static int OS_TmpName( ILuaState lua )
		{
			lua.PushString( Path.GetTempFileName() );
			return 1;
		}

		private static int OS_Remove( ILuaState lua )
		{
			var file = lua.L_CheckString(1);
			File.Delete(file);
			return 1;
		}
	}
}


text:
package org.kuali.mobility.events.entity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class DayImpl implements Serializable, Comparable<Day>, Day {

	private static final long serialVersionUID = -1626066050656327429L;

	private Date date;

	private List<EventImpl> events;

	public DayImpl() {
		events = new ArrayList<EventImpl>();
	}

	/* (non-Javadoc)
	 * @see org.kuali.mobility.events.entity.Day#compareTo(org.kuali.mobility.events.entity.DayImpl)
	 */
	public int compareTo(Day that) {
		if (getDate() != null && that.getDate() != null) {
			if (getDate().equals(that.getDate())) {
				return 0;
			}
			return getDate().before(that.getDate()) ? -1 : 1;
		}
		return -1;
	}

	/* (non-Javadoc)
	 * @see org.kuali.mobility.events.entity.Day#getDate()
	 */
	@Override
	public Date getDate() {
		return date;
	}

	/* (non-Javadoc)
	 * @see org.kuali.mobility.events.entity.Day#setDate(java.util.Date)
	 */
	@Override
	public void setDate(Date date) {
		this.date = date;
	}

	@Override
	public List<EventImpl> getEvents() {
		return events;
	}

	@Override
	public void setEvents(List<? extends Event> events) {
		this.events = (List<EventImpl>) (List<?>) events;
	}

}


text:
package com.rmrobotics.library.hardware;

import com.qualcomm.robotcore.hardware.Servo;
import com.qualcomm.robotcore.util.Range;

/**
 * Created by Simon on 11/23/2015.
 */

public class rServo {

    private static final double MAX_POSITION = 1.0;
    private static final double MIN_POSITION = 0.01;

    private Servo parent;
    private Servo.Direction defaultDirection;
    private double minPosition;
    private double maxPosition;
    private double desiredPosition;
    private double currentPosition;
    private double initPos;

    public rServo(Servo s, Servo.Direction x, double min, double max, double init){
        parent = s;
        defaultDirection = x;
        minPosition = min;
        maxPosition = max;
        initPos = init;
        desiredPosition = init;
        parent.setDirection(defaultDirection);
    }

    public void setDesiredPosition(double d){
        desiredPosition = d;
    }

    public void updateCurrentPosition(){
        desiredPosition = Range.clip(desiredPosition, minPosition, maxPosition);
        currentPosition = desiredPosition;
    }

    public void setPosition(){
        parent.setPosition(currentPosition);
    }

    public double getPosition() {
        return parent.getPosition();
    }

    public void setInitPos() {parent.setPosition(initPos);}

}